lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
Samples/NiUserSelection/DefaultTrackingInitializer.cpp
Wessi/OpenNI
613b0a43e66e1e97488624dec285341bc047d6d4
#include "DefaultTrackingInitializer.h" DefaultTrackingInitializer::DefaultTrackingInitializer(xn::UserGenerator *pUserGenerator) : TrackingInitializer(pUserGenerator), m_hCalibrationStartCallback(NULL), m_hCalibrationCompleteCallback(NULL), m_hInProgressCallback(NULL) { if(m_pUserGenerator->IsCapabilitySupported(XN_CAPABILITY_SKELETON)==FALSE) { m_bValid=FALSE; return; } XnStatus res=m_pUserGenerator->GetSkeletonCap().RegisterToCalibrationStart(CalibrationStartCallback,this,m_hCalibrationStartCallback); if(res!=XN_STATUS_OK) { m_hCalibrationStartCallback=NULL; m_bValid=FALSE; return; } res=m_pUserGenerator->GetSkeletonCap().RegisterToCalibrationComplete(CalibrationCompleteCallback,this,m_hCalibrationStartCallback); if(res!=XN_STATUS_OK) { m_hCalibrationStartCallback=NULL; m_bValid=FALSE; return; } res=m_pUserGenerator->GetSkeletonCap().RegisterToCalibrationInProgress(CalibrationInProgressCallback,this,m_hInProgressCallback); if(res!=XN_STATUS_OK) { m_hInProgressCallback=NULL; m_bValid=FALSE; return; } } DefaultTrackingInitializer::~DefaultTrackingInitializer() { if(m_pUserGenerator==NULL) return; if(m_hCalibrationStartCallback!=NULL) { m_pUserGenerator->GetSkeletonCap().UnregisterFromCalibrationStart(m_hCalibrationStartCallback); m_hCalibrationStartCallback=NULL; } if(m_hCalibrationCompleteCallback!=NULL) { m_pUserGenerator->GetSkeletonCap().UnregisterFromCalibrationComplete(m_hCalibrationCompleteCallback); m_hCalibrationCompleteCallback=NULL; } if(m_hInProgressCallback!=NULL) { m_pUserGenerator->GetSkeletonCap().UnregisterFromCalibrationInProgress(m_hInProgressCallback); m_hInProgressCallback=NULL; } } XnStatus DefaultTrackingInitializer::StartTracking(XnUserID nUserId, XnBool bForce) { if(m_pUserGenerator->GetSkeletonCap().IsTracking(nUserId)==TRUE) { if(m_pUserSelector!=NULL) { return m_pUserSelector->UpdateUserTracking(nUserId,TRUE,0); } else return XN_STATUS_OK; } return m_pUserGenerator->GetSkeletonCap().RequestCalibration(nUserId,bForce); } XnStatus DefaultTrackingInitializer::AbortTracking(XnUserID nUserId) { if(m_pUserGenerator->GetSkeletonCap().IsTracking(nUserId)==TRUE) { XnStatus res=m_pUserGenerator->GetSkeletonCap().StopTracking(nUserId); return res; } return m_pUserGenerator->GetSkeletonCap().AbortCalibration(nUserId); } XnStatus DefaultTrackingInitializer::CalibrationStart(XnUserID ) { return XN_STATUS_OK; } XnStatus DefaultTrackingInitializer::CalibrationComplete(XnUserID nUserId,XnCalibrationStatus eStatus) { XnBool retVal=FALSE; if (eStatus == XN_CALIBRATION_STATUS_OK) { if(m_pUserGenerator->GetSkeletonCap().StartTracking(nUserId)==XN_STATUS_OK) { retVal=TRUE; } } if(m_pUserSelector!=NULL) { return m_pUserSelector->UpdateUserTracking(nUserId,retVal,eStatus); } return XN_STATUS_OK; } XnStatus DefaultTrackingInitializer::CalibrationInProgress(XnUserID nUserId,XnCalibrationStatus eStatus) { if(m_pUserSelector!=NULL) return m_pUserSelector->UpdateUserTrackingProgress(nUserId,eStatus); return XN_STATUS_OK; } void XN_CALLBACK_TYPE DefaultTrackingInitializer::CalibrationStartCallback(xn::SkeletonCapability& , XnUserID nUserId, void* pCookie) { DefaultTrackingInitializer *pDefaultTrackingInitializer=(DefaultTrackingInitializer *)pCookie; pDefaultTrackingInitializer->CalibrationStart(nUserId); } void XN_CALLBACK_TYPE DefaultTrackingInitializer::CalibrationCompleteCallback(xn::SkeletonCapability& , XnUserID nUserId, XnCalibrationStatus eStatus, void* pCookie) { DefaultTrackingInitializer *pDefaultTrackingInitializer=(DefaultTrackingInitializer *)pCookie; pDefaultTrackingInitializer->CalibrationComplete(nUserId,eStatus); } void XN_CALLBACK_TYPE DefaultTrackingInitializer::CalibrationInProgressCallback(xn::SkeletonCapability& , XnUserID nUserId, XnCalibrationStatus eStatus, void* pCookie) { DefaultTrackingInitializer *pDefaultTrackingInitializer=(DefaultTrackingInitializer *)pCookie; pDefaultTrackingInitializer->CalibrationInProgress(nUserId,eStatus); }
#include "DefaultTrackingInitializer.h" DefaultTrackingInitializer::DefaultTrackingInitializer(xn::UserGenerator *pUserGenerator) : TrackingInitializer(pUserGenerator), m_hCalibrationStartCallback(NULL), m_hCalibrationCompleteCallback(NULL), m_hInProgressCallback(NULL) { if(m_pUserGenerator->IsCapabilitySupported(XN_CAPABILITY_SKELETON)==FALSE) { m_bValid=FALSE; return; } XnStatus res=m_pUserGenerator->GetSkeletonCap().RegisterToCalibrationStart(CalibrationStartCallback,this,m_hCalibrationStartCallback); if(res!=XN_STATUS_OK) { m_hCalibrationStartCallback=NULL; m_bValid=FALSE; return; } res=m_pUserGenerator->GetSkeletonCap().RegisterToCalibrationComplete(CalibrationCompleteCallback,this,m_hCalibrationStartCallback); if(res!=XN_STATUS_OK) { m_hCalibrationStartCallback=NULL; m_bValid=FALSE; return; } res=m_pUserGenerator->GetSkeletonCap().RegisterToCalibrationInProgress(CalibrationInProgressCallback,this,m_hInProgressCallback); if(res!=XN_STATUS_OK) { m_hInProgressCallback=NULL; m_bValid=FALSE; return; } } DefaultTrackingInitializer::~DefaultTrackingInitializer() { if(m_pUserGenerator==NULL) return; if(m_hCalibrationStartCallback!=NULL) { m_pUserGenerator->GetSkeletonCap().UnregisterFromCalibrationStart(m_hCalibrationStartCallback); m_hCalibrationStartCallback=NULL; } if(m_hCalibrationCompleteCallback!=NULL) { m_pUserGenerator->GetSkeletonCap().UnregisterFromCalibrationComplete(m_hCalibrationCompleteCallback); m_hCalibrationCompleteCallback=NULL; } if(m_hInProgressCallback!=NULL) { m_pUserGenerator->GetSkeletonCap().UnregisterFromCalibrationInProgress(m_hInProgressCallback); m_hInProgressCallback=NULL; } } XnStatus DefaultTrackingInitializer::StartTracking(XnUserID nUserId, XnBool bForce) { if(m_pUserGenerator->GetSkeletonCap().IsTracking(nUserId)==TRUE) { if(m_pUserSelector!=NULL) { return m_pUserSelector->UpdateUserTracking(nUserId,TRUE,0); } else return XN_STATUS_OK; } return m_pUserGenerator->GetSkeletonCap().RequestCalibration(nUserId,bForce); } XnStatus DefaultTrackingInitializer::AbortTracking(XnUserID nUserId) {
XnStatus DefaultTrackingInitializer::CalibrationStart(XnUserID ) { return XN_STATUS_OK; } XnStatus DefaultTrackingInitializer::CalibrationComplete(XnUserID nUserId,XnCalibrationStatus eStatus) { XnBool retVal=FALSE; if (eStatus == XN_CALIBRATION_STATUS_OK) { if(m_pUserGenerator->GetSkeletonCap().StartTracking(nUserId)==XN_STATUS_OK) { retVal=TRUE; } } if(m_pUserSelector!=NULL) { return m_pUserSelector->UpdateUserTracking(nUserId,retVal,eStatus); } return XN_STATUS_OK; } XnStatus DefaultTrackingInitializer::CalibrationInProgress(XnUserID nUserId,XnCalibrationStatus eStatus) { if(m_pUserSelector!=NULL) return m_pUserSelector->UpdateUserTrackingProgress(nUserId,eStatus); return XN_STATUS_OK; } void XN_CALLBACK_TYPE DefaultTrackingInitializer::CalibrationStartCallback(xn::SkeletonCapability& , XnUserID nUserId, void* pCookie) { DefaultTrackingInitializer *pDefaultTrackingInitializer=(DefaultTrackingInitializer *)pCookie; pDefaultTrackingInitializer->CalibrationStart(nUserId); } void XN_CALLBACK_TYPE DefaultTrackingInitializer::CalibrationCompleteCallback(xn::SkeletonCapability& , XnUserID nUserId, XnCalibrationStatus eStatus, void* pCookie) { DefaultTrackingInitializer *pDefaultTrackingInitializer=(DefaultTrackingInitializer *)pCookie; pDefaultTrackingInitializer->CalibrationComplete(nUserId,eStatus); } void XN_CALLBACK_TYPE DefaultTrackingInitializer::CalibrationInProgressCallback(xn::SkeletonCapability& , XnUserID nUserId, XnCalibrationStatus eStatus, void* pCookie) { DefaultTrackingInitializer *pDefaultTrackingInitializer=(DefaultTrackingInitializer *)pCookie; pDefaultTrackingInitializer->CalibrationInProgress(nUserId,eStatus); }
if(m_pUserGenerator->GetSkeletonCap().IsTracking(nUserId)==TRUE) { XnStatus res=m_pUserGenerator->GetSkeletonCap().StopTracking(nUserId); return res; } return m_pUserGenerator->GetSkeletonCap().AbortCalibration(nUserId); }
function_block-function_prefix_line
[ { "content": "XN_C_API XnBool XN_C_DECL xnProfilingIsActive();\n", "file_path": "Include/XnProfiling.h", "rank": 0, "score": 107637.93107806591 }, { "content": "XN_C_API XnBool XN_C_DECL xnLoggerIsEnabled(XnLogger* pLogger, XnLogSeverity severity);\n", "file_path": "Include/XnLog.h", "rank": 1, "score": 107631.2904144281 }, { "content": "XN_C_API XnBool XN_C_DECL xnGetGlobalMirror(XnContext* pContext);\n", "file_path": "Include/XnContext.h", "rank": 2, "score": 107631.2904144281 }, { "content": "XN_C_API XnBool XN_C_DECL xnOSWasKeyboardHit();\n", "file_path": "Include/XnOS.h", "rank": 3, "score": 107631.2904144281 }, { "content": "XN_C_API XnBool XN_C_DECL xnIsTypeDerivedFrom(XnProductionNodeType type, XnProductionNodeType base);\n", "file_path": "Include/XnUtils.h", "rank": 4, "score": 107631.2904144281 }, { "content": "XN_C_API XnBool XN_C_DECL xnLogIsDumpMaskEnabled(const XnChar* strDumpMask);\n", "file_path": "Include/XnDump.h", "rank": 5, "score": 107631.2904144281 }, { "content": "XN_C_API XnBool XN_C_DECL xnIsGenerating(XnNodeHandle hInstance);\n", "file_path": "Include/XnPrdNode.h", "rank": 6, "score": 106333.35121743499 }, { "content": "XN_C_API XnBool XN_C_DECL xnUSBDeviceIsControlRequestPending(XnUSBDevice* pDevice);\n", "file_path": "Include/XnUSBDevice.h", "rank": 7, "score": 106327.26818441981 }, { "content": "XN_C_API XnBool XN_C_DECL xnEnumerationErrorsIteratorIsValid(XnEnumerationErrorsIterator it);\n", "file_path": "Include/XnEnumerationErrors.h", "rank": 8, "score": 106327.26818441981 }, { "content": "XN_C_API XnBool XN_C_DECL xnNodeInfoListIteratorIsValid(XnNodeInfoListIterator it);\n", "file_path": "Include/XnPrdNodeInfoList.h", "rank": 9, "score": 103892.44682259709 }, { "content": "#ifndef _XN_LIST_H\n\n#define _XN_LIST_H\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnDataTypes.h>\n\n#include <IXnNodeAllocator.h>\n\n#include <XnNodeAllocator.h>\n\n#include <XnNode.h>\n\n#include <XnStatusCodes.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\n\n\n/**\n\n * The linked list\n\n */\n", "file_path": "Include/XnList.h", "rank": 10, "score": 65638.63217454305 }, { "content": "#ifndef __XN_EVENT_H__\n\n#define __XN_EVENT_H__\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include \"XnCallback.h\"\n\n#include \"XnList.h\"\n\n#include \"XnTypes.h\"\n\n#include \"XnOSCpp.h\"\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n", "file_path": "Include/XnEvent.h", "rank": 11, "score": 65638.62538292339 }, { "content": "#ifndef _XN_NODE_H_\n\n#define _XN_NODE_H_\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnDataTypes.h>\n\n#include <XnBaseNode.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\n/**\n\n * The building block of the data types - XnNode\n\n */\n", "file_path": "Include/XnNode.h", "rank": 12, "score": 65638.02646327356 }, { "content": "#ifndef _XN_STACK_H\n\n#define _XN_STACK_H\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include \"XnList.h\"\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\n/**\n\n* The stack\n\n*/\n", "file_path": "Include/XnStack.h", "rank": 13, "score": 65637.78883193768 }, { "content": "#ifndef __XNARRAY_H__\n\n#define __XNARRAY_H__\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnOS.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\ntemplate <typename T>\n", "file_path": "Include/XnArray.h", "rank": 14, "score": 65637.78883193768 }, { "content": "#ifndef _XN_QUEUE_H\n\n#define _XN_QUEUE_H\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include \"XnList.h\"\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\n/**\n\n* The queue\n\n*/\n", "file_path": "Include/XnQueue.h", "rank": 15, "score": 65637.78883193768 }, { "content": "#ifndef __XN_ALGORITHMS_H__\n\n#define __XN_ALGORITHMS_H__\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnPlatform.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\ntemplate<class T>\n\nXnBool DefaultComparer(const T& arg1, const T& arg2)\n\n{\n\n\treturn arg1 < arg2;\n\n}\n\n\n", "file_path": "Include/XnAlgorithms.h", "rank": 16, "score": 65637.30747077153 }, { "content": "#ifndef _XN_HASH_H\n\n#define _XN_HASH_H\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include \"XnList.h\"\n\n\n\n//---------------------------------------------------------------------------\n\n// Defines\n\n//---------------------------------------------------------------------------\n\n#define XN_HASH_LAST_BIN 256\n\n#define XN_HASH_NUM_BINS (XN_HASH_LAST_BIN + 1)\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\n/**\n\n* The key to the hash\n\n*/\n\ntypedef XnValue XnKey;\n", "file_path": "Include/XnHash.h", "rank": 17, "score": 65636.92127015685 }, { "content": "\n\n\t/** Resets the data of this array and sets its size to 0. **/\n\n\tvoid Clear()\n\n\t{\n\n\t\tXN_DELETE_ARR(m_pData);\n\n\t\tInit();\n\n\t}\n\n\n\n\t/** Element access operator. Returns a modifiable reference to the element at specified index. **/\n\n\tT& operator[](XnUInt32 nIndex)\n\n\t{\n\n\t\tXN_ASSERT(nIndex < m_nSize);\n\n\t\treturn m_pData[nIndex];\n\n\t}\n\n\n\n\t/** Element access operator. Returns a const reference to the element at specified index. **/\n\n\tconst T& operator[](XnUInt32 nIndex) const\n\n\t{\n\n\t\tXN_ASSERT(nIndex < m_nSize);\n\n\t\treturn m_pData[nIndex];\n", "file_path": "Include/XnArray.h", "rank": 18, "score": 65636.29276090616 }, { "content": "\t/**\n\n\t* Destructor. Destroys internal representations.\n\n\t*/\n\n\tvirtual ~XnHash()\n\n\t{\n\n\t\tif (m_Bins != NULL)\n\n\t\t{\n\n\t\t\tfor (int i = 0; i < XN_HASH_NUM_BINS; ++i)\n\n\t\t\t{\n\n\t\t\t\tXN_DELETE(m_Bins[i]);\n\n\t\t\t}\n\n\t\t\tXN_DELETE_ARR(m_Bins);\n\n\t\t}\n\n\t}\n\n\n\n\t/**\n\n\t* Returns the status of the initialization of the hash.\n\n\t* @returns XN_STATUS_OK if the hash was initialized successfully, or an error code otherwise \n\n\t* (e.g. if memory could not be allocated).\n\n\t*/\n", "file_path": "Include/XnHash.h", "rank": 19, "score": 65635.3446334186 }, { "content": "\t*/\n\n\tvirtual XnStatus Remove(ConstIterator where)\n\n\t{\n\n\t\t// Verify iterator is valid\n\n\t\tif (where == end())\n\n\t\t{\n\n\t\t\treturn XN_STATUS_ILLEGAL_POSITION;\n\n\t\t}\n\n\t\tif (IsEmpty())\n\n\t\t{\n\n\t\t\treturn XN_STATUS_IS_EMPTY;\n\n\t\t}\n\n\n\n\t\tXnNode* pToRemove = where.m_pCurrent;\n\n\n\n\t\t// Connect other nodes to bypass the one removed\n\n\t\tpToRemove->Previous()->Next() = pToRemove->Next();\n\n\t\tpToRemove->Next()->Previous() = pToRemove->Previous();\n\n\n\n\t\t// Return removed node to the pool\n", "file_path": "Include/XnList.h", "rank": 20, "score": 65635.18162996309 }, { "content": "\t\t// Return base node to the pool\n\n\t\tm_pNodeAllocator->Deallocate(m_pBase);\n\n\n\n\t\tif (m_bOwnsAllocator)\n\n\t\t{\n\n\t\t\t//We created the allocator in this object, so we must release it\n\n\t\t\tXN_DELETE(m_pNodeAllocator);\n\n\t\t}\n\n\t}\n\n\n\n\t/**\n\n\t* Add a new value at the beginning of list\n\n\t* \n\n\t* @param\tvalue\t[in]\tThe value to add to the head of the list\n\n\t*\n\n\t* @return\tXN_STATUS_ALLOC_FAILED\tFailed to add to the list because no nodes are available.\n\n\t*/\n\n\tXnStatus AddFirst(const XnValue& value)\n\n\t{\n\n\t\treturn Add(m_pBase, value);\n", "file_path": "Include/XnList.h", "rank": 21, "score": 65634.88588600274 }, { "content": "\n\n\t\tXnNode* pKeyNode = (XnNode*)(pNode->Data());\n\n\t\tXnNode* pValueNode = pKeyNode->Next();\n\n\n\n\t\t// Return the nodes to the pool\n\n\t\tXnNode::Deallocate(pKeyNode);\n\n\t\tXnNode::Deallocate(pValueNode);\n\n\n\n\t\tpNode->Previous()->Next() = pNode->Next();\n\n\t\tpNode->Next()->Previous() = pNode->Previous();\n\n\n\n\t\tXnNode::Deallocate(pNode);\n\n\n\n\t\treturn XN_STATUS_OK;\n\n\t}\n\n\n\n\n\n\t/**\n\n\t* Remove all entries from the XnHash.\n\n\t*/\n", "file_path": "Include/XnHash.h", "rank": 22, "score": 65634.85147203156 }, { "content": "\t\t/** The hash to which the iterator belongs */\n\n\t\tconst XnHash* m_pHash;\n\n\t\t/** The bin of the current object */\n\n\t\tXnUInt16 m_nCurrentBin;\n\n\t\t/** Iterator for the specific bin */\n\n\t\tXnList::Iterator m_Iterator;\n\n\t};\n\n\n\n\t/**\n\n\t* Iterator to the XnHash\n\n\t*/\n", "file_path": "Include/XnHash.h", "rank": 23, "score": 65630.40278787183 }, { "content": "\t\t\t// OZOZ: Allocation failed in ctor...\n\n\t\t}\n\n\n\n\t\tm_pBase->Next() = m_pBase->Previous() = m_pBase;\n\n\t}\n\n\n\n\t/**\n\n\t* Add a new value to the list\n\n\t* \n\n\t* @param\tpWhere\t[in]\tThe XnNode after which to add the new value\n\n\t* @param\tval\t\t[in]\tThe value to add to the list\n\n\t*\n\n\t* @return\tXN_STATUS_ALLOC_FAILED\t\tFailed to add to the list because no nodes are available,\n\n\t*/\n\n\tXnStatus Add(XnNode* pWhere, const XnValue& val)\n\n\t{\n\n\t\t// Get a node from the pool for the entry\n\n\t\tXnNode* pNewNode = m_pNodeAllocator->Allocate();\n\n\t\tif (pNewNode == NULL)\n\n\t\t{\n", "file_path": "Include/XnList.h", "rank": 24, "score": 65630.40278787183 }, { "content": "\n\n\t/**\n\n\t* An iterator to the end of the list (const version). The position is invalid.\n\n\t*/\n\n\tConstIterator end() const\n\n\t{\n\n\t\treturn ConstIterator(m_pBase);\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator to the last entry of the list (non-const version)\n\n\t*/\n\n\tIterator rbegin()\n\n\t{\n\n\t\treturn Iterator(m_pBase->Previous());\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator to the last entry of the list (const version)\n\n\t*/\n", "file_path": "Include/XnList.h", "rank": 25, "score": 65630.40278787183 }, { "content": "\t\tm_pNodeAllocator->Deallocate(pToRemove);\n\n\n\n\t\treturn XN_STATUS_OK;\n\n\t}\n\n\n\n\n\n\t/**\n\n\t* Remove all entries from the list\n\n\t*/\n\n\tXnStatus Clear()\n\n\t{\n\n\t\twhile (!IsEmpty())\n\n\t\t\tRemove(begin());\n\n\n\n\t\treturn XN_STATUS_OK;\n\n\t}\n\n\n\n\t/**\n\n\t* Check if list is empty\n\n\t*/\n", "file_path": "Include/XnList.h", "rank": 26, "score": 65630.40278787183 }, { "content": "\t\t\t\treturn (nRetVal);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline XnStatus AddAfter(ConstIterator where, Type const& value)\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue val = Translator::CreateValueCopy(value);\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnStatus nRetVal = XnList::AddAfter(where, val);\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tif (nRetVal != XN_STATUS_OK)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\tTranslator::FreeValue(val);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\treturn (nRetVal);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline XnStatus AddBefore(ConstIterator where, Type const& value)\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue val = Translator::CreateValueCopy(value);\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnStatus nRetVal = XnList::AddBefore(where, val);\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tif (nRetVal != XN_STATUS_OK)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n", "file_path": "Include/XnList.h", "rank": 27, "score": 65630.40278787183 }, { "content": "\t{\n\n\t\treturn m_List.AddFirst(value);\n\n\t}\n\n\n\n\t/**\n\n\t* Pop the value at the top of the stack\n\n\t* \n\n\t* @param\tvalue\t[out]\tThe value that was at the top of the stack\n\n\t*\n\n\t* @return\tXN_STATUS_IS_EMPTY\tThe stack is empty\n\n\t*/\n\n\tXnStatus Pop(XnValue& value)\n\n\t{\n\n\t\tif (IsEmpty())\n\n\t\t{\n\n\t\t\treturn XN_STATUS_IS_EMPTY;\n\n\t\t}\n\n\n\n\t\tvalue = *(m_List.begin());\n\n\t\treturn m_List.Remove(m_List.begin());\n", "file_path": "Include/XnStack.h", "rank": 28, "score": 65630.40278787183 }, { "content": "\t\t\tif (nRetVal != XN_STATUS_OK) return (nRetVal);\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tTranslator::FreeValue(val);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline XnStatus Remove(Type const& value)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tIterator it = Find(value);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn Remove(it);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline Iterator begin() { return XnList::begin(); }\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline ConstIterator begin() const { return XnList::begin(); }\t\t\t\t\t\t\t\\\n\n\t\tinline Iterator end() { return XnList::end(); }\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline ConstIterator end() const { return XnList::end(); }\t\t\t\t\t\t\t\t\\\n\n\t\tinline Iterator rbegin() { return XnList::rbegin(); }\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline ConstIterator rbegin() const { return XnList::rbegin(); }\t\t\t\t\t\t\\\n\n\t\tinline Iterator rend() { return XnList::rend(); }\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline ConstIterator rend() const { return XnList::rend(); }\t\t\t\t\t\t\t\\\n\n\tprotected:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tvirtual XnStatus Remove(XnList::ConstIterator where)\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n", "file_path": "Include/XnList.h", "rank": 29, "score": 65630.40278787183 }, { "content": "\t\t* Operator to check if 2 iterators point to different objects\n\n\t\t* \n\n\t\t* @param\tother\t[in]\tinstance to compare with\n\n\t\t*/\n\n\t\tXnBool operator!=(const ConstIterator& other) const\n\n\t\t{\n\n\t\t\treturn m_pCurrent != other.m_pCurrent;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Get the value of the current object (const version)\n\n\t\t*/\n\n\t\tconst XnValue& operator*() const\n\n\t\t{\n\n\t\t\treturn m_pCurrent->Data();\n\n\t\t}\n\n\n\n\n\n\t\t/**\n\n\t\t* Get the entire current object (const version)\n", "file_path": "Include/XnList.h", "rank": 30, "score": 65630.40278787183 }, { "content": "/*****************************************************************************\n\n* *\n\n* OpenNI 1.x Alpha *\n\n* Copyright (C) 2012 PrimeSense Ltd. *\n\n* *\n\n* This file is part of OpenNI. *\n\n* *\n\n* Licensed under the Apache License, Version 2.0 (the \"License\"); *\n\n* you may not use this file except in compliance with the License. *\n\n* You may obtain a copy of the License at *\n\n* *\n\n* http://www.apache.org/licenses/LICENSE-2.0 *\n\n* *\n\n* Unless required by applicable law or agreed to in writing, software *\n\n* distributed under the License is distributed on an \"AS IS\" BASIS, *\n\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n\n* See the License for the specific language governing permissions and *\n\n* limitations under the License. *\n\n* *\n\n*****************************************************************************/\n", "file_path": "Include/XnStack.h", "rank": 31, "score": 65630.40278787183 }, { "content": "\n\n\t\t/**\n\n\t\t* Get the entire current object (const version)\n\n\t\t*/\n\n\t\tconst XnNode* GetNode() const\n\n\t\t{\n\n\t\t\treturn m_Iterator.GetNode();\n\n\t\t}\n\n\n\n\tprotected:\n\n\t\t/**\n\n\t\t* constructor to be used from inside the XnHash\n\n\t\t* \n\n\t\t* @param\tpHash\t\t\t[in]\tThe hash to which the iterator belongs\n\n\t\t* @param\tnBin\t\t\t[in]\tThe bin of the current object\n\n\t\t* @param\tlistIterator\t[in]\tIterator on the bin (each bin is a XnList)\n\n\t\t*/\n\n\t\tConstIterator(const XnHash* pHash, XnUInt16 nBin, XnList::Iterator listIterator) :\n\n\t\t\t m_pHash(pHash), m_nCurrentBin(nBin), m_Iterator(listIterator)\n\n\t\t\t {\n", "file_path": "Include/XnHash.h", "rank": 32, "score": 65630.40278787183 }, { "content": "\n\n\t\t/**\n\n\t\t* Support iterator++, go to the next object in the list, returning the old value\n\n\t\t*/\n\n\t\tConstIterator operator++(int)\n\n\t\t{\n\n\t\t\tConstIterator other(m_pCurrent);\n\n\t\t\tm_pCurrent = m_pCurrent->Next();\n\n\t\t\treturn other;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Support --iterator, go to the next object in the list\n\n\t\t*/\n\n\t\tConstIterator& operator--()\n\n\t\t{\n\n\t\t\tm_pCurrent = m_pCurrent->Previous();\n\n\t\t\treturn *this;\n\n\t\t}\n\n\n", "file_path": "Include/XnList.h", "rank": 33, "score": 65630.40278787183 }, { "content": "\n\n\t/** The internal XnList with which the stack is implemented. */\n\n\tXnList m_List;\n\n};\n\n\n\n/**\n\n* Declares a stack of type @a Type, named @a ClassName. The class uses @a Translator for translating\n\n* from @a Type to XnValue. It is declared using the declspec @a decl.\n\n*/ \n\n#define XN_DECLARE_STACK_WITH_TRANSLATOR_DECL(decl, Type, ClassName, Translator)\t\t\\\n\n\t/* Note: we use queue declaration, as this is the same interface. */\t\t\t\t\\\n\n\tXN_DECLARE_QUEUE_WITH_TRANSLATOR_DECL(decl, Type, ClassName, Translator, XnStack)\n\n\n\n/**\n\n* Declares a stack of type @a Type, named @a ClassName. The class uses @a Translator for translating\n\n* from @a Type to XnValue.\n\n*/ \n\n#define XN_DECLARE_STACK_WITH_TRANSLATOR(Type, ClassName, Translator)\t\\\n\n\tXN_DECLARE_STACK_WITH_TRANSLATOR_DECL(, ClassName, Translator)\n\n\n", "file_path": "Include/XnStack.h", "rank": 34, "score": 65630.40278787183 }, { "content": "\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tXnStatus Pop(Type& value)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue val;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnStatus nRetVal = base::Pop(val);\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tif (nRetVal != XN_STATUS_OK) return (nRetVal);\t\t\t\t\t\t\t\t\\\n\n\t\t\tvalue = Translator::GetFromValue(val);\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tTranslator::FreeValue(val);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline Type const& Top() const { return Translator::GetFromValue(base::Top()); }\\\n\n\t\tinline Type& Top() { return Translator::GetFromValue(base::Top()); }\t\t\t\\\n\n\tprivate:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tXN_DISABLE_COPY_AND_ASSIGN(ClassName);\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t};\n\n\n\n/**\n\n* Declares a queue of type @a Type, named @a ClassName. The class uses @a Translator for translating\n\n* from @a Type to XnValue.\n", "file_path": "Include/XnQueue.h", "rank": 35, "score": 65630.40278787183 }, { "content": "\t};\n\n\n\npublic:\n\n\t/**\n\n\t* Constructor. Initialize internal representations\n\n\t*/\n\n\tXnList()\n\n\t{\n\n\t\t//Default node allocator is XnNodeAllocator\n\n\t\tInit(XN_NEW(XnNodeAllocator));\n\n\t\tm_bOwnsAllocator = TRUE;\n\n\t}\n\n\n\n\t/**\n\n\t* Destructor. Destroy internal representations\n\n\t*/\n\n\tvirtual ~XnList()\n\n\t{\n\n\t\tClear();\n\n\n", "file_path": "Include/XnList.h", "rank": 36, "score": 65630.40278787183 }, { "content": "\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline ConstIterator operator--(int)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\tConstIterator result = *this;\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\t--*this;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\treturn result;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline Type const& operator*() const\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\treturn Translator::GetFromValue(**((XnList::ConstIterator*)this));\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline Type const* operator->() const { return (&**this); }\t\t\t\t\t\t\t\\\n\n\t\tprotected:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline ConstIterator(XnNode* pNode) : XnList::ConstIterator(pNode) {}\t\t\t\t\\\n\n\t\t\tinline ConstIterator(const XnList::ConstIterator& other) :\t\t\t\t\t\t\t\\\n\n\t\t\t\tXnList::ConstIterator(other) \t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t};\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n", "file_path": "Include/XnList.h", "rank": 37, "score": 65630.40278787183 }, { "content": "\t}\n\n\n\n\t/**\n\n\t* Get the value at the top of the queue (it is user responsibility to check queue is not empty)\n\n\t* \n\n\t* @return\ta reference to the object at head of the queue.\n\n\t*/\n\n\tXnValue const& Top() const\n\n\t{\n\n\t\treturn *(m_List.begin());\n\n\t}\n\n\n\n\t/**\n\n\t* Get the value at the top of the queue (it is user responsibility to check queue is not empty)\n\n\t* \n\n\t* @return\ta reference to the object at head of the queue.\n\n\t*/\n\n\tXnValue& Top()\n\n\t{\n\n\t\treturn *(m_List.begin());\n", "file_path": "Include/XnStack.h", "rank": 38, "score": 65630.40278787183 }, { "content": "\t\t/**\n\n\t\t* Support iterator++, go to the next object in the list, returning the old value\n\n\t\t*/\n\n\t\tinline Iterator operator++(int) \n\n\t\t{ \n\n\t\t\tIterator result = *this;\n\n\t\t\t++*this;\n\n\t\t\treturn (result);\n\n\t\t}\n\n\t\t\n\n\t\t/**\n\n\t\t* Support --iterator, go to the next object in the list\n\n\t\t*/\n\n\t\tinline Iterator& operator--() \n\n\t\t{ \n\n\t\t\t--(*(ConstIterator*)this); \n\n\t\t\treturn (*this);\n\n\t\t}\n\n\t\t/**\n\n\t\t* Support iterator--, go to the next object in the list, returning the old value\n", "file_path": "Include/XnHash.h", "rank": 39, "score": 65630.40278787183 }, { "content": "\t/**\n\n\t* Push a new value to the queue\n\n\t* \n\n\t* @param\tvalue\t[in]\tThe value to add to the queue\n\n\t*\n\n\t* @return\tXN_STATUS_ALLOC_FAILED\tFailed to add to the queue because no nodes are available.\n\n\t*/\n\n\tvirtual XnStatus Push(XnValue const& value)\n\n\t{\n\n\t\tXnStatus nRetVal = XN_STATUS_OK;\n\n\n\n\t\tnRetVal = m_List.AddLast(value);\n\n\t\tXN_IS_STATUS_OK(nRetVal);\n\n\n\n\t\treturn (XN_STATUS_OK);\n\n\t}\n\n\t/**\n\n\t* Pop the value at the top of the queue\n\n\t* \n\n\t* @param\tvalue\t[out]\tThe value that was at the top of the queue\n", "file_path": "Include/XnQueue.h", "rank": 40, "score": 65630.40278787183 }, { "content": "\t\t\t\t // Find the first valid\n\n\t\t\t\t while (m_Iterator == m_pHash->m_Bins[m_nCurrentBin]->end() &&\n\n\t\t\t\t\t m_Iterator != m_pHash->m_Bins[XN_HASH_LAST_BIN]->end())\n\n\t\t\t\t {\n\n\t\t\t\t\t do\n\n\t\t\t\t\t {\n\n\t\t\t\t\t\t m_nCurrentBin++;\n\n\t\t\t\t\t } while (m_pHash->m_Bins[m_nCurrentBin] == NULL);\n\n\t\t\t\t\t m_Iterator = m_pHash->m_Bins[m_nCurrentBin]->begin();\n\n\t\t\t\t }\n\n\t\t\t }\n\n\n\n\t\t/**\n\n\t\t* constructor to be used from inside the XnHash. It points to the first value in the hash.\n\n\t\t* \n\n\t\t* @param\tpHash\t[in]\tThe hash to which the iterator belongs\n\n\t\t*/\n\n\t\tConstIterator(const XnHash* pHash) : \n\n\t\t\t m_pHash(pHash), m_nCurrentBin(0), m_Iterator(m_pHash->m_Bins[XN_HASH_LAST_BIN]->end()) {}\n\n\n", "file_path": "Include/XnHash.h", "rank": 41, "score": 65630.40278787183 }, { "content": "/**\n\n* Declares a stack of type @a Type, named @a ClassName, that uses the default translator.\n\n* It is declared using the declspec @a decl.\n\n*/ \n\n#define XN_DECLARE_STACK_DECL(decl, Type, ClassName)\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\tXN_DECLARE_DEFAULT_VALUE_TRANSLATOR_DECL(decl, Type, XN_DEFAULT_TRANSLATOR_NAME(ClassName))\t\t\t\\\n\n\tXN_DECLARE_STACK_WITH_TRANSLATOR_DECL(decl, Type, ClassName, XN_DEFAULT_TRANSLATOR_NAME(ClassName))\n\n\n\n/**\n\n* Declares a stack of type @a Type, named @a ClassName, that uses the default translator.\n\n*/ \n\n#define XN_DECLARE_STACK(Type, ClassName)\t\t\t\\\n\n\tXN_DECLARE_STACK_DECL(, Type, ClassName)\n\n\n\n\n\n#endif // _XN_STACK_H\n", "file_path": "Include/XnStack.h", "rank": 42, "score": 65630.40278787183 }, { "content": "* It inherits from @a base. Note that @a base must be a derivative of XnQueue.\n\n*/ \n\n#define XN_DECLARE_QUEUE_WITH_TRANSLATOR(Type, ClassName, Translator, base)\t\t\t\t\\\n\n\tXN_DECLARE_QUEUE_WITH_TRANSLATOR_DECL(, Type, ClassName, Translator, base)\n\n\n\n/**\n\n* Declares a queue of type @a Type, named @a ClassName, that uses the default translator.\n\n* It is declared using the declspec @a decl.\n\n*/ \n\n#define XN_DECLARE_QUEUE_DECL(decl, Type, ClassName)\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\tXN_DECLARE_DEFAULT_VALUE_TRANSLATOR_DECL(decl, Type, XN_DEFAULT_TRANSLATOR_NAME(ClassName))\t\t\t\\\n\n\tXN_DECLARE_QUEUE_WITH_TRANSLATOR_DECL(decl, Type, ClassName, XN_DEFAULT_TRANSLATOR_NAME(ClassName), XnQueue)\n\n\n\n/**\n\n* Declares a queue of type @a Type, named @a ClassName, that uses the default translator.\n\n*/ \n\n#define XN_DECLARE_QUEUE(Type, ClassName)\t\t\\\n\n\tXN_DECLARE_QUEUE_DECL(, Type, ClassName)\n\n\n\n#endif // _XN_QUEUE_H\n", "file_path": "Include/XnQueue.h", "rank": 43, "score": 65630.40278787183 }, { "content": "\n\n/**\n\n* The hash value - the output of the hash function\n\n*/\n\ntypedef XnUInt8 XnHashValue;\n\n\n\n/**\n\n* Default Hash function\n\n*/\n\nstatic XnHashValue XnDefaultHashFunction(const XnKey& key)\n\n{\n\n\treturn (XnSizeT(key) & 0xff);\n\n}\n\n\n\n/**\n\n* Default Compare function\n\n*/\n\nstatic XnInt32 XnDefaultCompareFunction(const XnKey& key1, const XnKey& key2)\n\n{\n\n\treturn XnInt32(XnSizeT(key1)-XnSizeT(key2));\n\n}\n\n\n\n/**\n\n * The hash - associative array\n\n */\n", "file_path": "Include/XnHash.h", "rank": 44, "score": 65630.40278787183 }, { "content": "\t\t\treturn XN_STATUS_ALLOC_FAILED;\n\n\t\t}\n\n\t\t// push new node to position\n\n\t\tpNewNode->Data() = val;\n\n\t\tpNewNode->Next() = pWhere->Next();\n\n\t\tpNewNode->Previous() = pWhere;\n\n\t\tpWhere->Next()->Previous() = pNewNode;\n\n\t\tpWhere->Next() = pNewNode;\n\n\n\n\t\treturn XN_STATUS_OK;\n\n\t}\n\n\n\n\n\n\t/** The base node for the list */\n\n\tXnNode* m_pBase;\n\n\t\n\n\tINiNodeAllocator* m_pNodeAllocator;\n\n\tXnBool m_bOwnsAllocator;\n\n\n\nprivate:\n\n\tXN_DISABLE_COPY_AND_ASSIGN(XnList);\n\n};\n\n\n\n/**\n\n* Declares a list of type @a Type, which is named @a ClassName. The list uses translator @a Translator,\n\n* and is declared using the @a decl declspec.\n\n*/\n", "file_path": "Include/XnList.h", "rank": 45, "score": 65630.40278787183 }, { "content": "/*****************************************************************************\n\n* *\n\n* OpenNI 1.x Alpha *\n\n* Copyright (C) 2012 PrimeSense Ltd. *\n\n* *\n\n* This file is part of OpenNI. *\n\n* *\n\n* Licensed under the Apache License, Version 2.0 (the \"License\"); *\n\n* you may not use this file except in compliance with the License. *\n\n* You may obtain a copy of the License at *\n\n* *\n\n* http://www.apache.org/licenses/LICENSE-2.0 *\n\n* *\n\n* Unless required by applicable law or agreed to in writing, software *\n\n* distributed under the License is distributed on an \"AS IS\" BASIS, *\n\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n\n* See the License for the specific language governing permissions and *\n\n* limitations under the License. *\n\n* *\n\n*****************************************************************************/\n", "file_path": "Include/XnList.h", "rank": 46, "score": 65630.40278787183 }, { "content": "\tXnBool IsEmpty() const\n\n\t{\n\n\t\treturn (begin() == end());\n\n\t}\n\n\n\n\t/**\n\n\t* Current size of the list\n\n\t*/\n\n\tXnUInt32 Size() const\n\n\t{\n\n\t\tXnUInt32 nSize = 0;\n\n\t\tfor (ConstIterator iter = begin(); iter != end(); ++iter, ++nSize)\n\n\t\t\t;\n\n\n\n\t\treturn nSize;\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator to the first entry of the list (non-const version)\n\n\t*/\n", "file_path": "Include/XnList.h", "rank": 47, "score": 65630.40278787183 }, { "content": "\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline Iterator operator--(int)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\tIterator result = *this;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\t--*this;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\treturn result;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline Type& operator*() const { return ((Type&)**(ConstIterator*)this); }\t\t\t\\\n\n\t\t\tinline Type* operator->() const { return (&**this); }\t\t\t\t\t\t\t\t\\\n\n\t\tprotected:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tinline Iterator(XnNode* pNode) : ConstIterator(pNode) {}\t\t\t\t\t\t\t\\\n\n\t\t\tinline Iterator(const XnList::Iterator& other) : ConstIterator(other) {}\t\t\t\\\n\n\t\t};\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\tpublic:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tClassName()\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t~ClassName()\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\twhile (!IsEmpty())\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n", "file_path": "Include/XnList.h", "rank": 48, "score": 65630.40278787183 }, { "content": "\t\n\nprotected:\n\n\tfriend class XnNodeManager;\n\n\t\n\n\t/**\n\n\t* Constructor. Initialize internal representations\n\n\t*/\n\n\tXnList(INiNodeAllocator* pNodeAllocator)\n\n\t{\n\n\t\tInit(pNodeAllocator);\n\n\t\tm_bOwnsAllocator = FALSE;\n\n\t}\n\n\t\n\n\tvoid Init(INiNodeAllocator* pNodeAllocator)\n\n\t{\n\n\t\tm_pNodeAllocator = pNodeAllocator;\n\n\t\t// Allocate a node to act as base node.\n\n\t\tm_pBase = m_pNodeAllocator->Allocate();\n\n\t\tif (m_pBase == NULL)\n\n\t\t{\n", "file_path": "Include/XnList.h", "rank": 49, "score": 65630.40278787183 }, { "content": "\t\t/**\n\n\t\t* Support iterator++, go to the next object in the list, returning the old value\n\n\t\t*/\n\n\t\tinline Iterator operator++(int) \n\n\t\t{ \n\n\t\t\tIterator result = *this;\n\n\t\t\t++*this;\n\n\t\t\treturn (result);\n\n\t\t}\n\n\t\t\n\n\t\t/**\n\n\t\t* Support --iterator, go to the next object in the list\n\n\t\t*/\n\n\t\tinline Iterator& operator--() \n\n\t\t{ \n\n\t\t\t--(*(ConstIterator*)this); \n\n\t\t\treturn (*this);\n\n\t\t}\n\n\t\t/**\n\n\t\t* Support iterator--, go to the next object in the list, returning the old value\n", "file_path": "Include/XnList.h", "rank": 50, "score": 65630.40278787183 }, { "content": "/*****************************************************************************\n\n* *\n\n* OpenNI 1.x Alpha *\n\n* Copyright (C) 2012 PrimeSense Ltd. *\n\n* *\n\n* This file is part of OpenNI. *\n\n* *\n\n* Licensed under the Apache License, Version 2.0 (the \"License\"); *\n\n* you may not use this file except in compliance with the License. *\n\n* You may obtain a copy of the License at *\n\n* *\n\n* http://www.apache.org/licenses/LICENSE-2.0 *\n\n* *\n\n* Unless required by applicable law or agreed to in writing, software *\n\n* distributed under the License is distributed on an \"AS IS\" BASIS, *\n\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n\n* See the License for the specific language governing permissions and *\n\n* limitations under the License. *\n\n* *\n\n*****************************************************************************/\n", "file_path": "Include/XnHash.h", "rank": 51, "score": 65630.40278787183 }, { "content": "\t* @return\tXN_STATUS_ALLOC_FAILED\t\tFailed to add to the list because no nodes are available,\n\n\t*\t\t\tXN_STATUS_ILLEGAL_POSITION\titerator is invalid\n\n\t*/\n\n\tXnStatus AddAfter(ConstIterator where, const XnValue& val)\n\n\t{\n\n\t\tif (where == end())\n\n\t\t{\n\n\t\t\treturn XN_STATUS_ILLEGAL_POSITION;\n\n\t\t}\n\n\n\n\t\treturn Add(where.m_pCurrent, val);\n\n\t}\n\n\n\n\t/**\n\n\t* Add a new value before the object pointed to by the iterator\n\n\t* \n\n\t* @param\twhere\t[in]\titerator to the position before which to add the new value\n\n\t* @param\tval\t\t[in]\tThe value to add to the list\n\n\t*\n\n\t* @return\tXN_STATUS_ALLOC_FAILED\t\tFailed to add to the list because no nodes are available,\n", "file_path": "Include/XnList.h", "rank": 52, "score": 65630.40278787183 }, { "content": "\tIterator begin()\n\n\t{\n\n\t\treturn Iterator(m_pBase->Next());\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator to the first entry of the list (const version)\n\n\t*/\n\n\tConstIterator begin() const\n\n\t{\n\n\t\treturn ConstIterator(m_pBase->Next());\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator 1to the end of the list (non-const version). The position is invalid.\n\n\t*/\n\n\tIterator end()\n\n\t{\n\n\t\treturn Iterator(m_pBase);\n\n\t}\n", "file_path": "Include/XnList.h", "rank": 53, "score": 65630.40278787183 }, { "content": "\t\t*/\n\n\t\tconst XnNode* GetNode() const\n\n\t\t{\n\n\t\t\treturn m_pCurrent;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Get the entire current object (non-const version)\n\n\t\t*/\n\n\t\tXnNode* GetNode()\n\n\t\t{\n\n\t\t\treturn m_pCurrent;\n\n\t\t}\n\n\n\n\tprotected:\n\n\t\t/**\n\n\t\t* constructor to be used from inside the XnList. It points to the node supplied.\n\n\t\t* \n\n\t\t* @param\tpNode\t[in]\tThe XnNode to which to currently point\n\n\t\t*/\n\n\t\tConstIterator(XnNode* pNode) : m_pCurrent(pNode) {}\n\n\n\n\t\t/** The current XnNode */\n\n\t\tXnNode* m_pCurrent;\n\n\t};\n\n\n\n\t/**\n\n \t * Iterator to the XnList\n\n\t */\n", "file_path": "Include/XnList.h", "rank": 54, "score": 65630.40278787183 }, { "content": "\t{\n\n\t\treturn *(m_List.begin());\n\n\t}\n\n\n\n\t/**\n\n\t* Get the value at the top of the queue (it is user responsibility to check queue is not empty)\n\n\t* \n\n\t* @return\ta reference to the object at head of the queue.\n\n\t*/\n\n\tXnValue& Top()\n\n\t{\n\n\t\treturn *(m_List.begin());\n\n\t}\n\n\n\n\t/**\n\n\t* Check if queue is empty\n\n\t*/\n\n\tXnBool IsEmpty() const\n\n\t{\n\n\t\treturn m_List.IsEmpty();\n", "file_path": "Include/XnQueue.h", "rank": 55, "score": 65630.40278787183 }, { "content": "\t\t*/\n\n\t\tinline Iterator operator--(int)\n\n\t\t{ \n\n\t\t\tIterator result = *this;\n\n\t\t\t--*this;\n\n\t\t\treturn (result);\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Get the value of the current object\n\n\t\t*/\n\n\t\tinline XnValue& operator*() const { return ((XnValue&)**(ConstIterator*)this); }\n\n\n\n\tprotected:\n\n\t\t/**\n\n\t\t* constructor to be used from inside the XnList. It points to the node supplied.\n\n\t\t* \n\n\t\t* @param\tpNode\t[in]\tThe XnNode to which to currently point\n\n\t\t*/\n\n\t\tinline Iterator(XnNode* pNode) : ConstIterator(pNode) {}\n", "file_path": "Include/XnList.h", "rank": 56, "score": 65630.40278787183 }, { "content": "\tConstIterator rbegin() const\n\n\t{\n\n\t\treturn ConstIterator(m_pBase->Previous());\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator to the beginning of the list (non-const version). This position is invalid\n\n\t*/\n\n\tIterator rend()\n\n\t{\n\n\t\treturn Iterator(m_pBase);\n\n\t}\n\n\n\n\t/**\n\n\t* An iterator to the beginning of the list (const version). This position is invalid\n\n\t*/\n\n\tConstIterator rend() const\n\n\t{\n\n\t\treturn ConstIterator(m_pBase);\n\n\t}\n", "file_path": "Include/XnList.h", "rank": 57, "score": 65630.40278787183 }, { "content": "\t\t\twhile (m_Iterator == m_pHash->m_Bins[m_nCurrentBin]->end() &&\n\n\t\t\t\tm_Iterator != m_pHash->m_Bins[XN_HASH_LAST_BIN]->end())\n\n\t\t\t{\n\n\t\t\t\tdo\n\n\t\t\t\t{\n\n\t\t\t\t\tm_nCurrentBin++;\n\n\t\t\t\t} while (m_pHash->m_Bins[m_nCurrentBin] == NULL);\n\n\t\t\t\tm_Iterator = m_pHash->m_Bins[m_nCurrentBin]->begin();\n\n\t\t\t}\n\n\t\t\treturn *this;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Support iterator++, go to the next object in the hash, returning the old value\n\n\t\t*/\n\n\t\tConstIterator operator++(int)\n\n\t\t{\n\n\t\t\tXnHash::ConstIterator other(*this);\n\n\t\t\t++*this;\n\n\t\t\treturn other;\n", "file_path": "Include/XnHash.h", "rank": 58, "score": 65630.40278787183 }, { "content": "\t\t\t\t\tm_nCurrentBin--;\n\n\t\t\t\t} while (m_pHash->m_Bins[m_nCurrentBin] == NULL);\n\n\t\t\t\tm_Iterator = m_pHash->m_Bins[m_nCurrentBin]->rbegin();\n\n\t\t\t}\n\n\t\t\treturn *this;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Support iterator--, go to the previous object in the hash, returning the old value\n\n\t\t*/\n\n\t\tConstIterator operator--(int)\n\n\t\t{\n\n\t\t\tConstIterator other(*this);\n\n\t\t\t--*this;\n\n\t\t\treturn other;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Operator to check if 2 iterators point to the same object\n\n\t\t* \n", "file_path": "Include/XnHash.h", "rank": 59, "score": 65630.40278787183 }, { "content": "\t}\n\n\n\n\t/**\n\n\t* Add a new value at the end of the list\n\n\t* \n\n\t* @param\tvalue\t[in]\tThe value to add to the tail of the list\n\n\t*\n\n\t* @return\tXN_STATUS_ALLOC_FAILED\tFailed to add to the list because no nodes are available.\n\n\t*/\n\n\tXnStatus AddLast(const XnValue& value)\n\n\t{\n\n\t\treturn Add(rbegin().m_pCurrent, value);\n\n\t}\n\n\n\n\t/**\n\n\t* Add a new value after the object pointed to by the iterator\n\n\t* \n\n\t* @param\twhere\t[in]\titerator to the position after which to add the new value\n\n\t* @param\tval\t\t[in]\tThe value to add to the list\n\n\t*\n", "file_path": "Include/XnList.h", "rank": 60, "score": 65630.40278787183 }, { "content": "\t\tconst XnKey& Key() const\n\n\t\t{\n\n\t\t\treturn ((XnNode*)(*m_Iterator))->Data();\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Get the value of the current object (const version)\n\n\t\t*/\n\n\t\tconst XnValue& Value() const\n\n\t\t{\n\n\t\t\treturn ((XnNode*)(*m_Iterator))->Next()->Data();\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Get the entire current object (non-const version)\n\n\t\t*/\n\n\t\tXnNode* GetNode()\n\n\t\t{\n\n\t\t\treturn m_Iterator.GetNode();\n\n\t\t}\n", "file_path": "Include/XnHash.h", "rank": 61, "score": 65630.40278787183 }, { "content": "\t{\n\n\t\tif (IsEmpty())\n\n\t\t{\n\n\t\t\treturn end();\n\n\t\t}\n\n\n\n\t\tIterator iter = begin();\n\n\t\tfor (; iter != end(); ++iter)\n\n\t\t{\n\n\t\t\tif (*iter == value)\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\treturn iter;\n\n\t}\n\n\n\n\n\n\t/**\n\n\t* Get an iterator pointing to a value in the list.\n\n\t* \n\n\t* @param\tvalue\t[in]\tThe searched value \n", "file_path": "Include/XnList.h", "rank": 62, "score": 65630.40278787183 }, { "content": "\t\t/**\n\n\t\t* Support iterator--, go to the next object in the list, returning the old value\n\n\t\t*/\n\n\t\tConstIterator operator--(int)\n\n\t\t{\n\n\t\t\tConstIterator other = *this;\n\n\t\t\t--*this;\n\n\t\t\treturn other;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Operator to check if 2 iterators point to the same object\n\n\t\t* \n\n\t\t* @param\tother\t[in]\tinstance to compare with\n\n\t\t*/\n\n\t\tXnBool operator==(const ConstIterator& other) const\n\n\t\t{\n\n\t\t\treturn m_pCurrent == other.m_pCurrent;\n\n\t\t}\n\n\t\t/**\n", "file_path": "Include/XnList.h", "rank": 63, "score": 65630.40278787183 }, { "content": "\t\t}\n\n\n\n\t\t/**\n\n\t\t* Support --iterator, go to the previous object in the hash\n\n\t\t*/\n\n\t\tConstIterator& operator--()\n\n\t\t{\n\n\t\t\t--m_Iterator;\n\n\n\n\t\t\twhile (m_Iterator == m_pHash->m_Bins[m_nCurrentBin]->end() &&\n\n\t\t\t\tm_Iterator != m_pHash->m_Bins[XN_HASH_LAST_BIN]->end())\n\n\t\t\t{\n\n\t\t\t\tdo \n\n\t\t\t\t{\n\n\t\t\t\t\tif (m_nCurrentBin == 0)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tm_nCurrentBin = XN_HASH_LAST_BIN;\n\n\t\t\t\t\t\tm_Iterator = m_pHash->m_Bins[XN_HASH_LAST_BIN]->end();\n\n\t\t\t\t\t\treturn *this;\n\n\t\t\t\t\t}\n", "file_path": "Include/XnHash.h", "rank": 64, "score": 65630.40278787183 }, { "content": "\t*\n\n\t* @return\tXN_STATUS_IS_EMPTY\tThe queue is empty\n\n\t*/\n\n\tvirtual XnStatus Pop(XnValue& value)\n\n\t{\n\n\t\tif (IsEmpty())\n\n\t\t{\n\n\t\t\treturn XN_STATUS_IS_EMPTY;\n\n\t\t}\n\n\n\n\t\tvalue = *(m_List.begin());\n\n\t\treturn m_List.Remove(m_List.begin());\n\n\t}\n\n\n\n\t/**\n\n\t* Get the value at the top of the queue (it is user responsibility to check queue is not empty)\n\n\t* \n\n\t* @return\ta reference to the object at head of the queue.\n\n\t*/\n\n\tXnValue const& Top() const\n", "file_path": "Include/XnQueue.h", "rank": 65, "score": 65630.40278787183 }, { "content": "\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\tTranslator::FreeValue(val);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\treturn (nRetVal);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline ConstIterator Find(Type const& value) const\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue _value = Translator::GetAsValue(value);\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XnList::Find(_value);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline Iterator Find(Type const& value)\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue _value = Translator::GetAsValue(value);\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XnList::Find(_value);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline XnStatus Remove(ConstIterator where)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue val = Translator::GetAsValue(*where);\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnStatus nRetVal = XnList::Remove(where);\t\t\t\t\t\t\t\t\t\t\t\\\n", "file_path": "Include/XnList.h", "rank": 66, "score": 65630.40278787183 }, { "content": "\t\t\t\tRemove(begin());\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline XnStatus AddFirst(Type const& value)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue val = Translator::CreateValueCopy(value);\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnStatus nRetVal = XnList::AddFirst(val);\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tif (nRetVal != XN_STATUS_OK)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\tTranslator::FreeValue(val);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\treturn (nRetVal);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\treturn XN_STATUS_OK;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tinline XnStatus AddLast(Type const& value)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnValue val = Translator::CreateValueCopy(value);\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tXnStatus nRetVal = XnList::AddLast(val);\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\tif (nRetVal != XN_STATUS_OK)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t\t\tTranslator::FreeValue(val);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n", "file_path": "Include/XnList.h", "rank": 67, "score": 65630.40278787183 }, { "content": "\t*/\n\n\tXnStatus AddBefore(ConstIterator where, const XnValue& val)\n\n\t{\n\n\t\tif (where == end())\n\n\t\t{\n\n\t\t\treturn XN_STATUS_ILLEGAL_POSITION;\n\n\t\t}\n\n\n\n\t\treturn Add(where.m_pCurrent->Previous(), val);\n\n\t}\n\n\n\n\n\n\t/**\n\n\t* Get an iterator pointing to a value in the list.\n\n\t* \n\n\t* @param\tvalue\t[in]\tThe searched value \n\n\t*\n\n\t* @return\tend()\tif value doesn't exist\n\n\t*/\n\n\tIterator Find(const XnValue& value)\n", "file_path": "Include/XnList.h", "rank": 68, "score": 65630.40278787183 }, { "content": "\t\t* @param\tother\t[in]\tinstance to compare with\n\n\t\t*/\n\n\t\tXnBool operator==(const ConstIterator& other) const\n\n\t\t{\n\n\t\t\treturn m_Iterator == other.m_Iterator;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Operator to check if 2 iterators point to different objects\n\n\t\t* \n\n\t\t* @param\tother\t[in]\tinstance to compare with\n\n\t\t*/\n\n\t\tXnBool operator!=(const ConstIterator& other) const\n\n\t\t{\n\n\t\t\treturn m_Iterator != other.m_Iterator;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t* Get the key of the current object (const version)\n\n\t\t*/\n", "file_path": "Include/XnHash.h", "rank": 69, "score": 65630.40278787183 }, { "content": "\t\t\treturn Remove(ConstIterator(where));\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\tprivate:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t\tXN_DISABLE_COPY_AND_ASSIGN(ClassName);\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\t};\n\n\n\n/**\n\n* Declares a list of type @a Type, which is named @a ClassName. The list uses translator @a Translator.\n\n*/\n\n#define XN_DECLARE_LIST_WITH_TRANSLATOR(Type, ClassName, Translator)\t\t\t\t\t\t\t\\\n\n\tXN_DECLARE_LIST_WITH_TRANSLATOR_DECL(, Type, ClassName, Translator)\n\n\n\n/**\n\n* Declares a list of type @a Type, which is named @a ClassName. The list uses creates a default translator\n\n* and is declared using the @a decl declspec.\n\n*/\n\n#define XN_DECLARE_LIST_DECL(decl, Type, ClassName)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\n\tXN_DECLARE_DEFAULT_VALUE_TRANSLATOR_DECL(decl, Type, XN_DEFAULT_TRANSLATOR_NAME(ClassName))\t\t\t\\\n\n\tXN_DECLARE_LIST_WITH_TRANSLATOR_DECL(decl, Type, ClassName, XN_DEFAULT_TRANSLATOR_NAME(ClassName))\n\n\n\n/**\n\n* Declares a list of type @a Type, which is named @a ClassName. The list uses creates a default translator.\n\n*/\n\n#define XN_DECLARE_LIST(Type, ClassName)\t\t\\\n\n\tXN_DECLARE_LIST_DECL(, Type, ClassName)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n#endif // _XN_LIST_H\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n", "file_path": "Include/XnList.h", "rank": 70, "score": 65630.40278787183 }, { "content": "\t*\n\n\t* @return\tend()\tif value doesn't exist\n\n\t*/\n\n\tConstIterator Find(const XnValue& value) const\n\n\t{\n\n\t\tif (IsEmpty())\n\n\t\t{\n\n\t\t\treturn end();\n\n\t\t}\n\n\n\n\t\tConstIterator iter = begin();\n\n\t\tfor (; iter != end(); ++iter)\n\n\t\t{\n\n\t\t\tif (*iter == value)\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\treturn iter;\n\n\t}\n\n\n\n\n", "file_path": "Include/XnList.h", "rank": 71, "score": 65630.40278787183 }, { "content": "\t/**\n\n\t* Remove a value from the list\n\n\t* \n\n\t* @param\twhere\t[in]\tIterator pointing to an entry in the list\n\n\t* @param\tvalue\t[out]\tThe value that was in the removed entry\n\n\t*\n\n\t* @return XN_STATUS_ILLEGAL_POSITION\titerator was invalid\n\n\t*/\n\n\tXnStatus Remove(ConstIterator where, XnValue& value)\n\n\t{\n\n\t\tvalue = *where;\n\n\t\treturn Remove(where);\n\n\t}\n\n\n\n\t/**\n\n\t* Remove a value from the list\n\n\t* \n\n\t* @param\twhere\t[in]\tIterator pointing to an entry in the list\n\n\t*\n\n\t* @return XN_STATUS_ILLEGAL_POSITION\titerator was invalid\n", "file_path": "Include/XnList.h", "rank": 72, "score": 65630.40278787183 }, { "content": "\t}\n\n\n\n\t/**\n\n\t* Get current size of queue\n\n\t*/\n\n\tvirtual XnUInt32 Size() const\n\n\t{\n\n\t\treturn m_List.Size();\n\n\t}\n\n\n\nprivate:\n\n\tXN_DISABLE_COPY_AND_ASSIGN(XnQueue);\n\n\n\n\t/** The internal XnList with which the queue is implemented. */\n\n\tXnList m_List;\n\n};\n\n\n\n/**\n\n* Declares a queue of type @a Type, named @a ClassName. The class uses @a Translator for translating\n\n* from @a Type to XnValue. It is declared using the declspec @a decl.\n\n* It inherits from @a base. Note that @a base must be a derivative of XnQueue.\n\n*/ \n", "file_path": "Include/XnQueue.h", "rank": 73, "score": 65630.40278787183 }, { "content": "\t}\n\n\n\n\t/**\n\n\t* Check if stack is empty\n\n\t*/\n\n\tXnBool IsEmpty() const\n\n\t{\n\n\t\treturn m_List.IsEmpty();\n\n\t}\n\n\n\n\t/**\n\n\t* Get current size of the stack\n\n\t*/\n\n\tXnUInt32 Size() const\n\n\t{\n\n\t\treturn m_List.Size();\n\n\t}\n\n\n\nprivate:\n\n\tXN_DISABLE_COPY_AND_ASSIGN(XnStack);\n", "file_path": "Include/XnStack.h", "rank": 74, "score": 65630.40278787183 }, { "content": "/*****************************************************************************\n\n* *\n\n* OpenNI 1.x Alpha *\n\n* Copyright (C) 2012 PrimeSense Ltd. *\n\n* *\n\n* This file is part of OpenNI. *\n\n* *\n\n* Licensed under the Apache License, Version 2.0 (the \"License\"); *\n\n* you may not use this file except in compliance with the License. *\n\n* You may obtain a copy of the License at *\n\n* *\n\n* http://www.apache.org/licenses/LICENSE-2.0 *\n\n* *\n\n* Unless required by applicable law or agreed to in writing, software *\n\n* distributed under the License is distributed on an \"AS IS\" BASIS, *\n\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n\n* See the License for the specific language governing permissions and *\n\n* limitations under the License. *\n\n* *\n\n*****************************************************************************/\n", "file_path": "Include/XnQueue.h", "rank": 75, "score": 65630.40278787183 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include \"SampleManager.h\"\n\n#include \"SceneDrawer.h\"\n\n#include \"DefaultTrackingInitializer.h\"\n\n#include \"SinglePoseUserSelector.h\"\n\n#include \"PoseToggleUserSelector.h\"\n\n#include \"ClosestUserSelector.h\"\n\n\n\n// Utility macro. This calls cleanup, prints a message and returns.\n\n#define RETURN_WITH_CLEANUP(returnCode,errorMsg) \\\n\n Cleanup(); \\\n\n printf(\"Failed to start sample: %s\\n\", errorMsg); \\\n\n return returnCode; \n\n\n\n\n\nSampleManager::SampleManager() : m_pUserTracker(NULL), \n\n m_pTrackingInitializer(NULL), \n\n m_pUserSelector(NULL)\n", "file_path": "Samples/NiUserSelection/SampleManager.cpp", "rank": 76, "score": 12.091277144221792 }, { "content": "#ifndef __OPEN_NI_VIDEO_H__\n\n#define __OPEN_NI_VIDEO_H__\n\n\n\n//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <streams.h>\n\n#include <XnCppWrapper.h>\n\n#include \"Guids.h\"\n\n#include <XnLog.h>\n\n#include \"IAdditionalControls.h\"\n\n\n\n//---------------------------------------------------------------------------\n\n// Macros\n\n//---------------------------------------------------------------------------\n\n#define XN_METHOD_START\t\t\t\txnDumpFileWriteString(m_Dump, \"%s was called\\n\", __FUNCTION__)\n\n\n\n#define XN_METHOD_RETURN(hr)\t\t\\\n\n\t{\t\t\t\t\t\t\t\t\\\n\n\t\txnDumpFileWriteString(m_Dump, \"\\t%s returned %s (%d)\\n\", __FUNCTION__, XN_STRINGIFY(hr), hr);\t\\\n", "file_path": "Platform/Win32/Build/Utils/OpenNIFilter/XnVideoSource.h", "rank": 77, "score": 12.042164299268531 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n// NOTE: you must define XN_OS_IMPL before including xnOS.h, otherwise, when mem profiling this file will not compile.\n\n#define XN_OS_IMPL\n\n#include <XnOS.h>\n\n#if (XN_PLATFORM == XN_PLATFORM_MACOSX)\n\n\t#include <sys/malloc.h>\n\n#else\n\n\t#include <malloc.h>\n\n#endif\n\n#include <XnLog.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Code\n\n//---------------------------------------------------------------------------\n\nXN_C_API void* xnOSMalloc(const XnSizeT nAllocSize)\n\n{\n\n\t// Return a pointer to the requested allocation size\n\n\treturn (malloc(nAllocSize));\n", "file_path": "Source/OpenNI/Linux/LinuxMemory.cpp", "rank": 78, "score": 11.946095200870925 }, { "content": " Return the position of the object added, NULL if it failed.\n\n Existing POSITIONs in *this are undisturbed, including p.\n\n */\n\nprotected:\n\n __out_opt POSITION AddAfterI(__in_opt POSITION p, __in void * pObj);\n\npublic:\n\n\n\n /* Add the list *pList to *this after position p in *this\n\n AddAfter(NULL,x) adds x to the start - equivalent to AddHead\n\n Return TRUE if it all worked, FALSE if it didn't.\n\n If it fails, some of the objects may be added\n\n Existing POSITIONs in *this are undisturbed, including p.\n\n */\n\n BOOL AddAfter(__in_opt POSITION p, __in CBaseList *pList);\n\n\n\n\n\n /* Mirror images:\n\n Add the object *pObj to this-List after position p in *this.\n\n AddBefore(NULL,x) adds x to the end - equivalent to AddTail\n\n Return the position of the new object, NULL if it fails\n", "file_path": "Platform/Win32/Build/Utils/OpenNIFilter/DirectShowBaseClasses/wxlist.h", "rank": 79, "score": 11.940062227372787 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n// NOTE: you must define XN_OS_IMPL before including xnOS.h, otherwise, when mem profiling this file will not compile.\n\n#define XN_OS_IMPL\n\n#include <XnOS.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Code\n\n//---------------------------------------------------------------------------\n\nXN_C_API void* xnOSMalloc(const XnSizeT nAllocSize)\n\n{\n\n\t// Return a pointer to the requested allocation size\n\n\treturn (malloc(nAllocSize));\n\n}\n\n\n\nXN_C_API void* xnOSMallocAligned(const XnSizeT nAllocSize, const XnSizeT nAlignment)\n\n{\n\n\t// Return a pointer to the aligned requested allocation size \n\n\treturn (_aligned_malloc(nAllocSize, nAlignment));\n", "file_path": "Source/OpenNI/Win32/Win32Memory.cpp", "rank": 80, "score": 11.652739803242078 }, { "content": "public class StatusException extends GeneralException\n\n{\n\n\t/**\n\n\t * \n\n\t */\n\n\tprivate static final long serialVersionUID = 1L;\n\n\n\n\t/**\n\n\t * Constructor - creates a new StatusException with the given integer code,\n\n\t * and looks up the error message corresponding to that code.\n\n\t * @param status\n\n\t */\n\n\tpublic StatusException(int status)\n\n\t{\n\n\t\tsuper(WrapperUtils.getErrorMessage(status));\n\n\t}\n", "file_path": "Wrappers/OpenNI.java/src/org/openni/StatusException.java", "rank": 81, "score": 10.539900789901706 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n// NOTE: you must define XN_OS_IMPL before including XnOS.h, otherwise, when mem profiling this file will not compile.\n\n#define XN_OS_IMPL\n\n#undef XN_CROSS_PLATFORM\n\n#include <XnOS.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Code\n\n//---------------------------------------------------------------------------\n\nXN_C_API void* xnOSMalloc(const XnSizeT nAllocSize)\n\n{\n\n\t// Return a pointer to the requested allocation size\n\n\treturn (malloc(nAllocSize));\n\n}\n\n\n\nXN_C_API void* xnOSMallocAligned(const XnSizeT nAllocSize, const XnSizeT nAlignment)\n\n{\n\n\t// TODO: fix alignment\n", "file_path": "Source/OpenNI/FilesOnly/FilesOnlyMemory.cpp", "rank": 82, "score": 10.304912297964355 }, { "content": " // Returns a pointer to the last occurence of a valid path separator in\n\n // the FilePath. On Windows, for example, both '/' and '\\' are valid path\n\n // separators. Returns NULL if no path separator was found.\n\n const char* FindLastPathSeparator() const;\n\n\n\n String pathname_;\n\n}; // class FilePath\n\n\n\n} // namespace internal\n\n} // namespace testing\n\n\n\n#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_\n\n// This file was GENERATED by command:\n\n// pump.py gtest-type-util.h.pump\n\n// DO NOT EDIT BY HAND!!!\n\n\n\n// Copyright 2008 Google Inc.\n\n// All Rights Reserved.\n\n//\n\n// Redistribution and use in source and binary forms, with or without\n", "file_path": "Externals/PSCommon/Testing/gtest/gtest.h", "rank": 83, "score": 9.81240826221795 }, { "content": " Existing POSITIONs in *this are undisturbed, including p.\n\n */\n\n protected:\n\n __out_opt POSITION AddBeforeI(__in_opt POSITION p, __in void * pObj);\n\n public:\n\n\n\n /* Add the list *pList to *this before position p in *this\n\n AddAfter(NULL,x) adds x to the start - equivalent to AddHead\n\n Return TRUE if it all worked, FALSE if it didn't.\n\n If it fails, some of the objects may be added\n\n Existing POSITIONs in *this are undisturbed, including p.\n\n */\n\n BOOL AddBefore(__in_opt POSITION p, __in CBaseList *pList);\n\n\n\n\n\n /* Note that AddAfter(p,x) is equivalent to AddBefore(Next(p),x)\n\n even in cases where p is NULL or Next(p) is NULL.\n\n Similarly for mirror images etc.\n\n This may make it easier to argue about programs.\n\n */\n", "file_path": "Platform/Win32/Build/Utils/OpenNIFilter/DirectShowBaseClasses/wxlist.h", "rank": 84, "score": 9.708244643327246 }, { "content": "\n\n // Similar to ShowWideCString(), except that this function encloses\n\n // the converted string in double quotes.\n\n static String ShowWideCStringQuoted(const wchar_t* wide_c_str);\n\n\n\n // Compares two wide C strings. Returns true iff they have the same\n\n // content.\n\n //\n\n // Unlike wcscmp(), this function can handle NULL argument(s). A\n\n // NULL C string is considered different to any non-NULL C string,\n\n // including the empty string.\n\n static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);\n\n\n\n // Compares two C strings, ignoring case. Returns true iff they\n\n // have the same content.\n\n //\n\n // Unlike strcasecmp(), this function can handle NULL argument(s).\n\n // A NULL C string is considered different to any non-NULL C string,\n\n // including the empty string.\n\n static bool CaseInsensitiveCStringEquals(const char* lhs,\n", "file_path": "Externals/PSCommon/Testing/gtest/gtest.h", "rank": 85, "score": 9.693954426685087 }, { "content": "\t\t\t{\n\n\t\t\t\treturn Iterator(xnEnumerationErrorsGetNext(m_it));\n\n\t\t\t}\n\n\n\n\t\t\t/**\n\n\t\t\t * @brief Returns the description data of the failing node the iterator points to.\n\n\t\t\t *\n\n\t\t\t * <b>Remarks</b>\n\n\t\t\t *\n\n\t\t\t * The description data returned in the @ref XnProductionNodeDescription struct\n\n\t\t\t * includes the node name, the vendor, and the version.\n\n\t\t\t */\n\n\t\t\tinline const XnProductionNodeDescription& Description() { return *xnEnumerationErrorsGetCurrentDescription(m_it); }\n\n\n\n\t\t\t/**\n\n\t\t\t * @brief Returns the failure error code of the failing node the iterator points to.\n\n\t\t\t * For a string representation of this error, call @ref xnGetStatusString().\n\n\t\t\t */\n\n\t\t\tinline XnStatus Error() { return xnEnumerationErrorsGetCurrentError(m_it); }\n\n\n", "file_path": "Include/XnCppWrapper.h", "rank": 86, "score": 9.37649861900223 }, { "content": " OsStackTraceGetterInterface* os_stack_trace_getter();\n\n\n\n // Returns the current OS stack trace as a String.\n\n //\n\n // The maximum number of stack frames to be included is specified by\n\n // the gtest_stack_trace_depth flag. The skip_count parameter\n\n // specifies the number of top frames to be skipped, which doesn't\n\n // count against the number of frames to be included.\n\n //\n\n // For example, if Foo() calls Bar(), which in turn calls\n\n // CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n\n // trace but Bar() and CurrentOsStackTraceExceptTop() won't.\n\n String CurrentOsStackTraceExceptTop(int skip_count);\n\n\n\n // Finds and returns a TestCase with the given name. If one doesn't\n\n // exist, creates one and returns it.\n\n //\n\n // Arguments:\n\n //\n\n // test_case_name: name of the test case\n", "file_path": "Externals/PSCommon/Testing/gmock-gtest-all.cc", "rank": 87, "score": 9.283513900104587 }, { "content": "// Implements the RE class.\n\n\n\nRE::~RE() {\n\n free(const_cast<char*>(pattern_));\n\n free(const_cast<char*>(full_pattern_));\n\n}\n\n\n\n// Returns true iff regular expression re matches the entire str.\n\nbool RE::FullMatch(const char* str, const RE& re) {\n\n return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);\n\n}\n\n\n\n// Returns true iff regular expression re matches a substring of str\n\n// (including str itself).\n\nbool RE::PartialMatch(const char* str, const RE& re) {\n\n return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);\n\n}\n\n\n\n// Initializes an RE from its string representation.\n\nvoid RE::Init(const char* regex) {\n", "file_path": "Externals/PSCommon/Testing/gmock-gtest-all.cc", "rank": 88, "score": 9.12375028674235 }, { "content": "#define ValidateReadWritePtr(p,cb) 0\n\n#define ValidateStringPtr(p) 0\n\n#define ValidateStringPtrA(p) 0\n\n#define ValidateStringPtrW(p) 0\n\n\n\n\n\n#ifdef _OBJBASE_H_\n\n\n\n // Outputting GUID names. If you want to include the name\n\n // associated with a GUID (eg CLSID_...) then\n\n //\n\n // GuidNames[yourGUID]\n\n //\n\n // Returns the name defined in uuids.h as a string\n\n\n\n typedef struct {\n\n CHAR *szName;\n\n GUID guid;\n\n } GUID_STRING_ENTRY;\n\n\n", "file_path": "Platform/Win32/Build/Utils/OpenNIFilter/DirectShowBaseClasses/wxdebug.h", "rank": 89, "score": 8.921734819121529 }, { "content": "GLOBAL(JDIMENSION)\n\njpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,\n\n\t\t JDIMENSION max_lines)\n\n{\n\n JDIMENSION row_ctr;\n\n\n\n if (cinfo->global_state != DSTATE_SCANNING)\n\n ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);\n\n if (cinfo->output_scanline >= cinfo->output_height) {\n\n WARNMS(cinfo, JWRN_TOO_MUCH_DATA);\n\n return 0;\n\n }\n\n\n\n /* Call progress monitor hook if present */\n\n if (cinfo->progress != NULL) {\n\n cinfo->progress->pass_counter = (long) cinfo->output_scanline;\n\n cinfo->progress->pass_limit = (long) cinfo->output_height;\n\n (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);\n\n }\n\n\n\n /* Process some data */\n\n row_ctr = 0;\n\n (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);\n\n cinfo->output_scanline += row_ctr;\n\n return row_ctr;\n", "file_path": "Externals/LibJPEG/jdapistd.c", "rank": 90, "score": 8.786832661247391 }, { "content": " // Example: FilePath(\"dir/file.exe\").RemoveExtension(\"EXE\") returns\n\n // FilePath(\"dir/file\"). If a case-insensitive extension is not\n\n // found, returns a copy of the original FilePath.\n\n FilePath RemoveExtension(const char* extension) const;\n\n\n\n // Creates directories so that path exists. Returns true if successful or if\n\n // the directories already exist; returns false if unable to create\n\n // directories for any reason. Will also return false if the FilePath does\n\n // not represent a directory (that is, it doesn't end with a path separator).\n\n bool CreateDirectoriesRecursively() const;\n\n\n\n // Create the directory so that path exists. Returns true if successful or\n\n // if the directory already exists; returns false if unable to create the\n\n // directory for any reason, including if the parent directory does not\n\n // exist. Not named \"CreateDirectory\" because that's a macro on Windows.\n\n bool CreateFolder() const;\n\n\n\n // Returns true if FilePath describes something in the file-system,\n\n // either a file, directory, or whatever, and that something exists.\n\n bool FileOrDirectoryExists() const;\n", "file_path": "Externals/PSCommon/Testing/gtest/gtest.h", "rank": 91, "score": 8.783264205294756 }, { "content": " return internal::NotMatcher<InnerMatcher>(m);\n\n}\n\n\n\n// Returns a matcher that matches anything that satisfies the given\n\n// predicate. The predicate can be any unary function or functor\n\n// whose return type can be implicitly converted to bool.\n\ntemplate <typename Predicate>\n\ninline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >\n\nTruly(Predicate pred) {\n\n return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));\n\n}\n\n\n\n// Returns a matcher that matches an equal container.\n\n// This matcher behaves like Eq(), but in the event of mismatch lists the\n\n// values that are included in one container but not the other. (Duplicate\n\n// values and order differences are not explained.)\n\ntemplate <typename Container>\n\ninline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT\n\n GTEST_REMOVE_CONST_(Container)> >\n\n ContainerEq(const Container& rhs) {\n", "file_path": "Externals/PSCommon/Testing/gmock/gmock.h", "rank": 92, "score": 8.70241962294351 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include \"XnModuleLoader.h\"\n\n#include \"XnRecorderImpl.h\"\n\n#include \"XnPlayerImpl.h\"\n\n#include <XnOpenNI.h>\n\n#include <XnOS.h>\n\n#include <XnLog.h>\n\n#include <XnVersion.h>\n\n#include \"XnXml.h\"\n\n#include \"XnEnum.h\"\n\n#include \"XnInternalTypes.h\"\n\n#include <XnInternalDefs.h>\n\n#include <XnCppWrapper.h>\n\n#include <XnCodecIDs.h>\n\n#include \"XnLicensingInternal.h\"\n\n#include \"XnMockNotifier.h\"\n\n#include \"XnNodeWatcher.h\"\n\n#include \"xnInternalFuncs.h\"\n", "file_path": "Source/OpenNI/XnOpenNI.cpp", "rank": 93, "score": 8.682463351288417 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnUSB.h>\n\n#include \"../xnUSBInternal.h\"\n\n#include \"XnUSBWin32.h\"\n\n#include <XnLog.h>\n\n#include <setupapi.h>\n\n#include <strsafe.h>\n\n#include <process.h>\n\n#include <dbt.h>\n\n#include \"devioctl.h\"\n\n#include \"usb.h\"\n\n#include \"XnListT.h\"\n\n\n\n//---------------------------------------------------------------------------\n\n// Types\n\n//---------------------------------------------------------------------------\n\ntypedef struct XnUSBEventCallback\n\n{\n", "file_path": "Source/OpenNI/Win32/XnUSBWin32.cpp", "rank": 94, "score": 8.67616268635485 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnOS.h>\n\n#include <sys/types.h>\n\n#include <sys/socket.h>\n\n#include <netdb.h>\n\n#include <ctype.h>\n\n#include <netinet/in.h>\n\n#include <netinet/tcp.h>\n\n#include <arpa/inet.h>\n\n#include <errno.h>\n\n#include <XnLog.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Structs\n\n//---------------------------------------------------------------------------\n\n/** The Xiron OS network socket structure. */ \n\ntypedef struct xnOSSocket\n\n{\n", "file_path": "Source/OpenNI/Linux/LinuxNetwork.cpp", "rank": 95, "score": 8.633551934029606 }, { "content": "#pragma warning(push, 3)\n\n#include <glh/glh_obs.h>\n\n#include <glh/glh_glut2.h>\n\n#pragma warning(pop)\n\n\n\nusing namespace glh;\n\n\n\n#include <XnLog.h>\n\n#include \"Device.h\"\n\n#include \"Capture.h\"\n\n#include \"Draw.h\"\n\n#include \"Audio.h\"\n\n#include \"Keyboard.h\"\n\n#include \"Menu.h\"\n\n#include \"Statistics.h\"\n\n#include \"MouseInput.h\"\n\n\n\n#if (XN_PLATFORM == XN_PLATFORM_WIN32)\n\n\t#include <conio.h>\n\n\t#include <direct.h>\t\n", "file_path": "Samples/NiViewer/NiViewer.cpp", "rank": 96, "score": 8.63311282906703 }, { "content": "// --------------------------------\n\n// Includes\n\n// --------------------------------\n\n#include \"Draw.h\"\n\n#include \"Device.h\"\n\n#include \"Keyboard.h\"\n\n#include \"Capture.h\"\n\n#if (XN_PLATFORM == XN_PLATFORM_MACOSX)\n\n\t#include <GLUT/glut.h>\n\n\t#include <OpenGL/gl.h>\n\n#else\n\n\t#include <GL/gl.h>\n\n\t#include <GL/glut.h>\n\n#endif\n\n#include \"Statistics.h\"\n\n#include \"MouseInput.h\"\n\n\n\n#if (XN_PLATFORM == XN_PLATFORM_WIN32)\n\n\t#ifdef __INTEL_COMPILER\n\n\t\t#include <ia32intrin.h>\n", "file_path": "Samples/NiViewer/Draw.cpp", "rank": 97, "score": 8.622667976394567 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnPlatform.h>\n\n\n\n#if (XN_PLATFORM == XN_PLATFORM_LINUX_ARM)\n\n\n\n#include <XnUSBDevice.h>\n\n#include <linux/usb/gadgetfs.h>\n\n#include <asm/byteorder.h>\n\n#include <poll.h>\n\n#include <errno.h>\n\n#include <XnLog.h>\n\n#include <XnOSCpp.h>\n\n#include <XnDump.h>\n\n#include <aio.h>\n\n\n\n//---------------------------------------------------------------------------\n\n// Defines\n\n//---------------------------------------------------------------------------\n", "file_path": "Source/OpenNI/Linux/LinuxUSBDevice.cpp", "rank": 98, "score": 8.610356597229998 }, { "content": "//---------------------------------------------------------------------------\n\n// Includes\n\n//---------------------------------------------------------------------------\n\n#include <XnUSB.h>\n\n\n\n#if (XN_PLATFORM == XN_PLATFORM_ANDROID_ARM)\n\n#include <libusb.h>\n\n#else\n\n#include <libusb-1.0/libusb.h>\n\n#endif\n\n\n\n#include \"XnUSBLinux.h\"\n\n#include \"../XnUSBInternal.h\"\n\n#include <XnOS.h>\n\n#include <XnLog.h>\n\n#include <XnOSCpp.h>\n\n#include \"XnListT.h\"\n\n\n\n\n\n//---------------------------------------------------------------------------\n", "file_path": "Source/OpenNI/Linux/XnUSBLinux.cpp", "rank": 99, "score": 8.557757843524652 } ]
C++
src/game/scenes/GameScene.cpp
rkolovanov/game-sapper
b59b6a8ac56b5337c880ba26dbabf0200318dd93
#include "GameScene.h" #include "../Game.h" #include "../audio/MusicManager.h" #include "MainMenuScene.h" #include <random> #include <iostream> Game::Scenes::GameScene::GameScene(Game& game, size_t sizeX, size_t sizeY, size_t minesNumber) : Scene(game), m_field(sizeX, sizeY) { this->m_minesNumber = minesNumber; generateMines(minesNumber); calculateNearbyMinesCount(); Audio::MusicManager::getInstance().playMusic("resources/music/game-theme.ogg"); } void Game::Scenes::GameScene::onEvent(const sf::Event& event) { if (event.type == sf::Event::MouseButtonPressed) { float rectangleSizeX = static_cast<float>(m_game.getWindow().getSize().x) / static_cast<float>(m_field.getSizeX()); float rectangleSizeY = static_cast<float>(m_game.getWindow().getSize().y) / static_cast<float>(m_field.getSizeY()); size_t cellX = event.mouseButton.x / rectangleSizeX; size_t cellY = event.mouseButton.y / rectangleSizeY; Cell& cell = m_field.get(cellX, cellY); if (event.mouseButton.button == sf::Mouse::Left) { if (!cell.isChecked) { checkCell(cellX, cellY); } } else if (event.mouseButton.button == sf::Mouse::Right) { if (!cell.isChecked) { cell.isMarked = !cell.isMarked; } } if (getFieldStatus() == Field::FieldStatus::Lose) { m_game.changeScene(std::make_unique<MainMenuScene>(m_game)); } else if (getFieldStatus() == Field::FieldStatus::Win) { m_game.changeScene(std::make_unique<MainMenuScene>(m_game)); } } } void Game::Scenes::GameScene::onUpdate(const sf::Time& elapsedTime) { float rectangleSizeX = static_cast<float>(m_game.getWindow().getSize().x) / static_cast<float>(m_field.getSizeX()); float rectangleSizeY = static_cast<float>(m_game.getWindow().getSize().y) / static_cast<float>(m_field.getSizeY()); sf::RectangleShape shape(sf::Vector2f(rectangleSizeX, rectangleSizeY)); sf::Font font; sf::Text text; font.loadFromFile("resources/fonts/arial.ttf"); shape.setOutlineThickness(1.0); shape.setOutlineColor(sf::Color::Black); text.setFont(font); text.setCharacterSize(std::min(rectangleSizeX, rectangleSizeY) / 2); text.setFillColor(sf::Color::Black); for (size_t y = 0; y < m_field.getSizeY(); ++y) { for (size_t x = 0; x < m_field.getSizeX(); ++x) { Cell& cell = m_field.get(x, y); shape.setPosition(x * rectangleSizeX, y * rectangleSizeY); text.setPosition(x * rectangleSizeX, y * rectangleSizeY); if (cell.isChecked) { if (cell.isMine) { shape.setFillColor(sf::Color::Red); } else { shape.setFillColor(sf::Color::White); } text.setString(std::to_string(cell.nearbyMinesNumber)); } else if (cell.isMarked) { shape.setFillColor(sf::Color::Yellow); } else { shape.setFillColor(sf::Color(100, 100, 100)); } m_game.getWindow().draw(shape); m_game.getWindow().draw(text); text.setString(""); } } } void Game::Scenes::GameScene::generateMines(size_t minesNumber) { std::random_device rd; std::mt19937 mersenne(rd()); size_t sizeX = m_field.getSizeX(); size_t sizeY = m_field.getSizeX(); if (minesNumber > sizeX * sizeY) { throw std::invalid_argument("Mines count greater than cells count."); } for (size_t i = 0; i < minesNumber; ++i) { size_t generatedX = mersenne() % sizeX; size_t generatedY = mersenne() % sizeY; while (m_field.get(generatedX, generatedY).isMine) { generatedX = mersenne() % sizeX; generatedY = mersenne() % sizeY; } Cell& cell = m_field.get(generatedX, generatedY); cell.isMine = true; } } void Game::Scenes::GameScene::calculateNearbyMinesCount() { for (size_t y = 0; y < m_field.getSizeY(); ++y) { for (size_t x = 0; x < m_field.getSizeX(); ++x) { size_t minesCount = 0; std::vector<std::pair<size_t, size_t>> shifts = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; for (const auto& shift : shifts) { try { if (m_field.get(x + shift.first, y + shift.second).isMine) { ++minesCount; } } catch (const std::invalid_argument&) { } } m_field.get(x, y).nearbyMinesNumber = minesCount; } } } void Game::Scenes::GameScene::checkCell(size_t x, size_t y) { Cell& cell = m_field.get(x, y); if (cell.isChecked) { return; } cell.isChecked = true; if (cell.nearbyMinesNumber == 0) { std::vector<std::pair<size_t, size_t>> shifts = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; for (const auto& shift : shifts) { try { checkCell(x + shift.first, y + shift.second); } catch (const std::invalid_argument&) { } } } } Game::Field::FieldStatus Game::Scenes::GameScene::getFieldStatus() { size_t markedCells = 0; size_t markedMines = 0; size_t uncheckedCells = 0; for (size_t y = 0; y < m_field.getSizeY(); ++y) { for (size_t x = 0; x < m_field.getSizeX(); ++x) { try { Cell& cell = m_field.get(x, y); if (cell.isChecked) { if (cell.isMine) { return Field::FieldStatus::Lose; } } else { if (cell.isMarked) { if (cell.isMine) { ++markedMines; } else { ++markedCells; } } else { ++uncheckedCells; } } } catch (const std::invalid_argument&) { } } } if (markedMines == m_minesNumber && markedCells == 0 && uncheckedCells == 0) { return Field::FieldStatus::Win; } return Field::FieldStatus::Unknown; }
#include "GameScene.h" #include "../Game.h" #include "../audio/MusicManager.h" #include "MainMenuScene.h" #include <random> #include <iostream> Game::Scenes::GameScene::GameScene(Game& game, size_t sizeX, size_t sizeY, size_t minesNumber) : Scene(game), m_field(sizeX, sizeY) { this->m_minesNumber = minesNumber; generateMines(minesNumber); calculateNearbyMinesCount(); Audio::MusicManager::getInstance().playMusic("resources/music/game-theme.ogg"); } void Game::Scenes::GameScene::onEvent(const sf::Event& event) { if (event.type == sf::Event::MouseButtonPressed) { float rectangleSizeX = static_cast<float>(m_game.getWindow().getSize().x) / static_cast<float>(m_field.getSizeX()); float rectangleSizeY = static_cast<float>(m_game.getWindow().getSize().y) / static_cast<float>(m_field.getSizeY()); size_t cellX = event.mouseButton.x / rectangleSizeX; size_t cellY = event.mouseButton.y / rectangleSizeY; Cell& cell = m_field.get(cellX, cellY); if (event.mouseButton.button == sf::Mouse::Left) { if (!cell.isChecked) { checkCell(cellX, cellY); } } else if (event.mouseButton.button == sf::Mouse::Right) { if (!cell.isChecked) { cell.isMarked = !cell.isMarked; } } if (getFieldStatus() == Field::FieldStatus::Lose) { m_game.changeScene(std::make_unique<MainMenuScene>(m_game)); } else if (getFieldStatus() == Field::FieldStatus::Win) { m_game.changeScene(std::make_unique<MainMenuScene>(m_game)); } } } void Game::Scenes::GameScene::onUpdate(const sf::Time& elapsedTime) { float rectangleSizeX = static_cast<float>(m_game.getWindow().getSize().x) / static_cast<float>(m_field.getSizeX()); float rectangleSizeY = static_cast<float>(m_game.getWindow().getSize().y) / static_cast<float>(m_field.getSizeY()); sf::RectangleShape shape(sf::Vector2f(rectangleSizeX, rectangleSizeY)); sf::Font font; sf::Text text; font.loadFromFile("resources/fonts/arial.ttf"); shape.setOutlineThickness(1.0); shape.setOutlineColor(sf::Color::Black); text.setFont(font); text.setCharacterSize(std::min(rectangleSizeX, rectangleSizeY) / 2); text.setFillColor(sf::Color::Black); for (size_t y = 0; y < m_field.getSizeY(); ++y) { for (size_t x = 0; x < m_field.getSizeX(); ++x) { Cell& cell = m_field.get(x, y); shape.setPosition(x * rectangleSizeX, y * rectangleSizeY); text.setPosition(x * rectangleSizeX, y * rectangleSizeY); if (cell.isChecked) { if (cell.isMine) { shape.setFillColor(sf::Color::Red); } else { shape.setFillColor(sf::Color::White); } text.setString(std::to_string(cell.nearbyMinesNumber)); } else if (cell.isMarked) { shape.setFillColor(sf::Color::Yellow); } else { shape.setFillColor(sf::Color(100, 100, 100)); } m_game.getWindow().draw(shape); m_game.getWindow().draw(text); text.setString(""); } } } void Game::Scenes::GameScene::generateMines(size_t minesNumber) { std::random_device rd; std::mt19937 mersenne(rd()); size_t sizeX = m_field.getSizeX(); size_t sizeY = m_field.getSizeX(); if (minesNumber > sizeX * sizeY) { throw std::invalid_argument("Mines count greater than cells count."); } for (size_t i = 0; i < minesNumber; ++i) { size_t generatedX = mersenne() % sizeX; size_t generatedY = mersenne() % sizeY; while (m_field.get(generatedX, generatedY).isMine) { generatedX = mersenne() % sizeX; generatedY = mersenne() % sizeY; } Cell& cell = m_field.get(generatedX, generatedY); cell.isMine = true; } } void Game::Scenes::GameScene::calculateNearbyMinesCount() { for (size_t y = 0; y < m_field.getSizeY(); ++y) { for (size_t x = 0; x < m_field.getSizeX(); ++x) { size_t minesCount = 0; std::vector<std::pair<size_t, size_t>> shifts = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; for (const auto& shift : shifts) { try { if (m_field.get(x + shift.first, y + shift.second).isMine) { ++minesCount; } } catch (const std::invalid_argument&) { } } m_field.get(x, y).nearbyMinesNumber = minesCount; } } } void Game::Scenes::GameScene::checkCell(size_t x, size_t y) { Cell& cell = m_field.get(x, y);
} else { ++markedCells; } } else { ++uncheckedCells; } } } catch (const std::invalid_argument&) { } } } if (markedMines == m_minesNumber && markedCells == 0 && uncheckedCells == 0) { return Field::FieldStatus::Win; } return Field::FieldStatus::Unknown; }
if (cell.isChecked) { return; } cell.isChecked = true; if (cell.nearbyMinesNumber == 0) { std::vector<std::pair<size_t, size_t>> shifts = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; for (const auto& shift : shifts) { try { checkCell(x + shift.first, y + shift.second); } catch (const std::invalid_argument&) { } } } } Game::Field::FieldStatus Game::Scenes::GameScene::getFieldStatus() { size_t markedCells = 0; size_t markedMines = 0; size_t uncheckedCells = 0; for (size_t y = 0; y < m_field.getSizeY(); ++y) { for (size_t x = 0; x < m_field.getSizeX(); ++x) { try { Cell& cell = m_field.get(x, y); if (cell.isChecked) { if (cell.isMine) { return Field::FieldStatus::Lose; } } else { if (cell.isMarked) { if (cell.isMine) { ++markedMines;
random
[ { "content": "#ifndef GAME_SAPPER_SRC_GAME_FIELD_CELL_H\n\n#define GAME_SAPPER_SRC_GAME_FIELD_CELL_H\n\n\n\n#include <cstddef>\n\n\n\n\n\nstruct Cell {\n\n size_t nearbyMinesNumber;\n\n bool isMine;\n\n bool isChecked;\n\n bool isMarked;\n\n};\n\n\n\n\n", "file_path": "src/game/field/Cell.h", "rank": 0, "score": 46954.04158532312 }, { "content": "class TextButton : public sf::Text {\n\npublic:\n\n explicit TextButton(const sf::FloatRect& rect);\n\n bool isInButtonRect(float x, float y);\n\n\n\nprivate:\n\n sf::FloatRect m_rect;\n\n};\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_GUI_TEXT_BUTTON_H\n", "file_path": "src/game/gui/TextButton.h", "rank": 1, "score": 40263.98259814439 }, { "content": " class FontManager {\n\n public:\n\n FontManager(const FontManager&) = delete;\n\n FontManager(FontManager&&) = delete;\n\n FontManager& operator=(const FontManager&) = delete;\n\n FontManager& operator=(FontManager&&) = delete;\n\n\n\n static FontManager& getInstance();\n\n bool loadFont(const std::string& path, const std::string& name);\n\n sf::Font& getFont(const std::string& name);\n\n\n\n private:\n\n FontManager() = default;\n\n\n\n std::map<std::string, sf::Font> m_fonts;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_GUI_FONT_MANAGER_H\n", "file_path": "src/game/gui/FontManager.h", "rank": 2, "score": 29773.870939884397 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_GUI_FONT_MANAGER_H\n\n#define GAME_SAPPER_SRC_GAME_GUI_FONT_MANAGER_H\n\n\n\n#include <SFML/Graphics.hpp>\n\n#include <map>\n\n\n\n\n\nnamespace Game {\n\n namespace Gui {\n", "file_path": "src/game/gui/FontManager.h", "rank": 3, "score": 25759.549113108013 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_GUI_TEXT_BUTTON_H\n\n#define GAME_SAPPER_SRC_GAME_GUI_TEXT_BUTTON_H\n\n\n\n#include <SFML/Graphics.hpp>\n\n\n", "file_path": "src/game/gui/TextButton.h", "rank": 4, "score": 25759.34864524881 }, { "content": "#include \"TextButton.h\"\n\n#include \"FontManager.h\"\n\n\n\nTextButton::TextButton(const sf::FloatRect& rect): sf::Text() {\n\n m_rect = rect;\n\n setPosition(rect.left, rect.top);\n\n setCharacterSize(rect.height);\n\n}\n\n\n\nbool TextButton::isInButtonRect(float x, float y) {\n\n return m_rect.contains(x, y);\n\n}\n", "file_path": "src/game/gui/TextButton.cpp", "rank": 5, "score": 24441.09946707865 }, { "content": "#include \"FontManager.h\"\n\n\n\nGame::Gui::FontManager& Game::Gui::FontManager::getInstance() {\n\n static FontManager fontManager;\n\n return fontManager;\n\n}\n\n\n\nbool Game::Gui::FontManager::loadFont(const std::string& path, const std::string& name) {\n\n sf::Font font;\n\n\n\n if (name.empty() || !font.loadFromFile(path)) {\n\n return false;\n\n }\n\n\n\n m_fonts[name] = font;\n\n\n\n return true;\n\n}\n\n\n\nsf::Font& Game::Gui::FontManager::getFont(const std::string &name) {\n\n if (m_fonts.count(name) == 0) {\n\n throw std::invalid_argument(\"Wrong font name.\");\n\n }\n\n\n\n return m_fonts[name];\n\n}\n", "file_path": "src/game/gui/FontManager.cpp", "rank": 6, "score": 24440.09336724717 }, { "content": "namespace Game {\n\n namespace Field {\n\n enum FieldStatus {\n\n Unknown,\n\n Win,\n\n Lose\n\n };\n\n }\n", "file_path": "src/game/field/FieldStatus.h", "rank": 7, "score": 24157.628753124736 }, { "content": " bool isMarked;\n", "file_path": "src/game/field/Cell.h", "rank": 8, "score": 22875.061010572394 }, { "content": " bool isMine;\n", "file_path": "src/game/field/Cell.h", "rank": 9, "score": 22875.061010572394 }, { "content": " bool isChecked;\n", "file_path": "src/game/field/Cell.h", "rank": 10, "score": 22875.061010572394 }, { "content": " class Game {\n\n public:\n\n Game();\n\n Game(const Game&) = delete;\n\n Game(Game&&) = delete;\n\n Game& operator=(const Game&) = delete;\n\n Game& operator=(Game&&) = delete;\n\n ~Game() = default;\n\n\n\n void onEvent(const sf::Event& event);\n\n void onUpdate(const sf::Time& elapsedTime);\n\n int execute();\n\n sf::RenderWindow& getWindow();\n\n void changeScene(std::unique_ptr<Scenes::Scene>&& scene);\n\n\n\n private:\n\n void replaceScene();\n\n\n\n sf::RenderWindow m_window;\n\n std::unique_ptr<Scenes::Scene> m_scene;\n\n std::unique_ptr<Scenes::Scene> m_replaceScene;\n\n };\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_GAME_H\n", "file_path": "src/game/Game.h", "rank": 11, "score": 22583.6930484281 }, { "content": " class Game;\n\n\n\n namespace Scenes {\n", "file_path": "src/game/scenes/Scene.h", "rank": 12, "score": 21466.706967739065 }, { "content": " size_t nearbyMinesNumber;\n", "file_path": "src/game/field/Cell.h", "rank": 13, "score": 21159.462143943787 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_GAME_H\n\n#define GAME_SAPPER_SRC_GAME_GAME_H\n\n\n\n#include \"scenes/Scene.h\"\n\n#include <SFML/Graphics.hpp>\n\n#include <SFML/Audio.hpp>\n\n#include <memory>\n\n\n\n\n\nnamespace Game {\n", "file_path": "src/game/Game.h", "rank": 14, "score": 8119.193323493916 }, { "content": "#include \"Game.h\"\n\n#include \"scenes/MainMenuScene.h\"\n\n#include <iostream>\n\n\n\nGame::Game::Game() {\n\n const std::string title = \"Sapper Game\";\n\n const sf::VideoMode videoMode(512, 512);\n\n const sf::Uint32 windowStyle = sf::Style::Close;\n\n\n\n m_window.create(videoMode, title, windowStyle);\n\n changeScene(std::make_unique<Scenes::MainMenuScene>(*this));\n\n}\n\n\n\nvoid Game::Game::onEvent(const sf::Event& event) {\n\n if (m_scene != nullptr) {\n\n m_scene->onEvent(event);\n\n }\n\n}\n\n\n\nvoid Game::Game::onUpdate(const sf::Time& elapsedTime) {\n", "file_path": "src/game/Game.cpp", "rank": 15, "score": 7823.714888178577 }, { "content": " if (m_scene != nullptr) {\n\n m_scene->onUpdate(elapsedTime);\n\n }\n\n}\n\n\n\nint Game::Game::execute() {\n\n sf::Clock clock;\n\n\n\n try {\n\n while (m_window.isOpen()) {\n\n sf::Event event {};\n\n\n\n while (m_window.pollEvent(event)) {\n\n if (event.type == sf::Event::Closed) {\n\n m_window.close();\n\n return 0;\n\n } else {\n\n onEvent(event);\n\n }\n\n }\n", "file_path": "src/game/Game.cpp", "rank": 16, "score": 7820.196591163002 }, { "content": "}\n\n\n\nsf::RenderWindow &Game::Game::getWindow() {\n\n return m_window;\n\n}\n\n\n\nvoid Game::Game::changeScene(std::unique_ptr<Scenes::Scene>&& scene) {\n\n m_replaceScene = std::move(scene);\n\n}\n\n\n\nvoid Game::Game::replaceScene() {\n\n m_scene = std::move(m_replaceScene);\n\n m_replaceScene.reset(nullptr);\n\n}\n", "file_path": "src/game/Game.cpp", "rank": 17, "score": 7819.452046949426 }, { "content": "\n\n m_window.clear();\n\n onUpdate(clock.getElapsedTime());\n\n m_window.display();\n\n\n\n if (m_replaceScene != nullptr) {\n\n replaceScene();\n\n }\n\n\n\n clock.restart();\n\n }\n\n } catch (const std::exception& e) {\n\n std::cerr << e.what() << \"\\n\";\n\n return 1;\n\n } catch (...) {\n\n std::cerr << \"Unknown error occurred!\\n\";\n\n return 1;\n\n }\n\n\n\n return 0;\n", "file_path": "src/game/Game.cpp", "rank": 18, "score": 7816.287124679907 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_SCENES_GAME_SCENE_H\n\n#define GAME_SAPPER_SRC_GAME_SCENES_GAME_SCENE_H\n\n\n\n#include \"Scene.h\"\n\n#include \"../field/Field.h\"\n\n#include \"../field/FieldStatus.h\"\n\n#include <iostream>\n\n\n\nnamespace Game {\n\n namespace Scenes {\n", "file_path": "src/game/scenes/GameScene.h", "rank": 19, "score": 7543.13674141888 }, { "content": " class GameScene final : public Scene {\n\n public:\n\n GameScene(Game& game, size_t sizeX, size_t sizeY, size_t minesNumber);\n\n void onEvent(const sf::Event& event) override;\n\n void onUpdate(const sf::Time& elapsedTime) override;\n\n ~GameScene() override = default;\n\n\n\n private:\n\n void generateMines(size_t minesNumber);\n\n void calculateNearbyMinesCount();\n\n void checkCell(size_t x, size_t y);\n\n Field::FieldStatus getFieldStatus();\n\n\n\n Field::Field m_field;\n\n size_t m_minesNumber;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_SCENES_GAME_SCENE_H\n", "file_path": "src/game/scenes/GameScene.h", "rank": 20, "score": 7439.845975943134 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_FIELD_FIELD_H\n\n#define GAME_SAPPER_SRC_GAME_FIELD_FIELD_H\n\n\n\n#include \"Cell.h\"\n\n\n\n#include <vector>\n\n\n\n\n\nnamespace Game {\n\n namespace Field {\n", "file_path": "src/game/field/Field.h", "rank": 31, "score": 6060.06425422604 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_SCENES_SCENE_H\n\n#define GAME_SAPPER_SRC_GAME_SCENES_SCENE_H\n\n\n\n#include <SFML/Graphics.hpp>\n\n\n\n\n\nnamespace Game {\n", "file_path": "src/game/scenes/Scene.h", "rank": 32, "score": 6058.222005758972 }, { "content": "#include \"Field.h\"\n\n#include <stdexcept>\n\n\n\nGame::Field::Field::Field(size_t sizeX, size_t sizeY) {\n\n m_fieldRows.resize(sizeY, FieldRow(sizeX));\n\n this->sizeX = sizeX;\n\n this->sizeY = sizeY;\n\n}\n\n\n\nCell& Game::Field::Field::get(size_t x, size_t y) {\n\n if (y >= m_fieldRows.size() || x >= m_fieldRows[y].cells.size()) {\n\n throw std::invalid_argument(\"Out of bounds.\");\n\n }\n\n\n\n return m_fieldRows[y].cells[x];\n\n}\n\n\n\nsize_t Game::Field::Field::getSizeX() {\n\n return sizeX;\n\n}\n\n\n\nsize_t Game::Field::Field::getSizeY() {\n\n return sizeY;\n\n}\n\n\n\nGame::Field::Field::FieldRow::FieldRow(size_t length) {\n\n cells.resize(length);\n\n}\n", "file_path": "src/game/field/Field.cpp", "rank": 33, "score": 5734.055060753057 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_TEXTURES_TEXTURE_MANAGER_H\n\n#define GAME_SAPPER_SRC_GAME_TEXTURES_TEXTURE_MANAGER_H\n\n\n\n#include <SFML/Graphics.hpp>\n\n#include <map>\n\n\n\n\n\nnamespace Game {\n\n namespace Textures {\n", "file_path": "src/game/textures/TextureManager.h", "rank": 34, "score": 5731.182924761095 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_AUDIO_MUSIC_MANAGER_H\n\n#define GAME_SAPPER_SRC_GAME_AUDIO_MUSIC_MANAGER_H\n\n\n\n#include <SFML/Audio.hpp>\n\n#include <string>\n\n\n\n\n\nnamespace Game {\n\n namespace Audio {\n", "file_path": "src/game/audio/MusicManager.h", "rank": 35, "score": 5731.182924761095 }, { "content": " class Scene {\n\n public:\n\n explicit Scene(Game& game): m_game(game) {}\n\n virtual void onEvent(const sf::Event& event) = 0;\n\n virtual void onUpdate(const sf::Time& elapsedTime) = 0;\n\n virtual ~Scene() = default;\n\n\n\n protected:\n\n Game& m_game;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_SCENES_SCENE_H\n", "file_path": "src/game/scenes/Scene.h", "rank": 36, "score": 5728.079501703705 }, { "content": "#ifndef GAME_SAPPER_SRC_GAME_SCENES_MAIN_MENU_SCENE_H\n\n#define GAME_SAPPER_SRC_GAME_SCENES_MAIN_MENU_SCENE_H\n\n\n\n#include \"Scene.h\"\n\n#include \"../gui/TextButton.h\"\n\n\n\n\n\nnamespace Game {\n\n namespace Scenes {\n", "file_path": "src/game/scenes/MainMenuScene.h", "rank": 37, "score": 5438.785764034773 }, { "content": "#include \"TextureManager.h\"\n\n\n\nGame::Textures::TextureManager& Game::Textures::TextureManager::getInstance() {\n\n static TextureManager textureManager;\n\n return textureManager;\n\n}\n\n\n\nbool Game::Textures::TextureManager::loadTexture(const std::string& path, const std::string &name) {\n\n sf::Texture texture;\n\n\n\n if (name.empty() || !texture.loadFromFile(path)) {\n\n return false;\n\n }\n\n\n\n m_textures[name] = texture;\n\n\n\n return true;\n\n}\n\n\n\nsf::Texture& Game::Textures::TextureManager::getTexture(const std::string &name) {\n\n if (m_textures.count(name) == 0) {\n\n throw std::invalid_argument(\"Wrong texture name.\");\n\n }\n\n\n\n return m_textures[name];\n\n}\n", "file_path": "src/game/textures/TextureManager.cpp", "rank": 38, "score": 5437.887964115445 }, { "content": "#include \"MusicManager.h\"\n\n\n\nGame::Audio::MusicManager &Game::Audio::MusicManager::getInstance() {\n\n static MusicManager musicManager;\n\n return musicManager;\n\n}\n\n\n\nbool Game::Audio::MusicManager::playMusic(const std::string &path) {\n\n m_music.stop();\n\n\n\n if (path.empty() || !m_music.openFromFile(path)) {\n\n return false;\n\n }\n\n\n\n m_music.setLoop(true);\n\n m_music.play();\n\n}\n", "file_path": "src/game/audio/MusicManager.cpp", "rank": 39, "score": 5437.520810942531 }, { "content": " class Field final {\n\n public:\n\n Field(size_t sizeX, size_t sizeY);\n\n Cell& get(size_t x, size_t y);\n\n size_t getSizeX();\n\n size_t getSizeY();\n\n\n\n private:\n\n struct FieldRow {\n\n std::vector<Cell> cells;\n\n explicit FieldRow(size_t length);\n\n };\n\n\n\n std::vector<FieldRow> m_fieldRows;\n\n size_t sizeX;\n\n size_t sizeY;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_FIELD_FIELD_H\n", "file_path": "src/game/field/Field.h", "rank": 40, "score": 5434.314754610865 }, { "content": "#include \"MainMenuScene.h\"\n\n#include \"GameScene.h\"\n\n#include \"../Game.h\"\n\n#include \"../audio/MusicManager.h\"\n\n#include \"../textures/TextureManager.h\"\n\n#include \"../gui/FontManager.h\"\n\n\n\nGame::Scenes::MainMenuScene::MainMenuScene(Game& game): Scene(game),\n\nm_newGameButton(sf::FloatRect(185, 200, 200, 25)),\n\nm_exitButton(sf::FloatRect(185, 250, 200, 25)) {\n\n m_newGameButton.setFont(Gui::FontManager::getInstance().getFont(\"arial\"));\n\n m_exitButton.setFont(Gui::FontManager::getInstance().getFont(\"arial\"));\n\n m_newGameButton.setFillColor(sf::Color::White);\n\n m_exitButton.setFillColor(sf::Color::White);\n\n m_newGameButton.setString(\"NEW GAME\");\n\n m_exitButton.setString(\"EXIT\");\n\n Audio::MusicManager::getInstance().playMusic(\"resources/music/main-menu-theme.ogg\");\n\n}\n\n\n\nvoid Game::Scenes::MainMenuScene::onEvent(const sf::Event &event) {\n", "file_path": "src/game/scenes/MainMenuScene.cpp", "rank": 41, "score": 5176.986141507735 }, { "content": " if (event.type == sf::Event::MouseButtonPressed) {\n\n if (event.mouseButton.button == sf::Mouse::Left) {\n\n if (m_newGameButton.isInButtonRect(event.mouseButton.x, event.mouseButton.y)) {\n\n m_game.changeScene(std::make_unique<GameScene>(m_game, 16, 16, 10));\n\n } else if (m_exitButton.isInButtonRect(event.mouseButton.x, event.mouseButton.y)) {\n\n m_game.getWindow().close();\n\n }\n\n }\n\n }\n\n}\n\n\n\nvoid Game::Scenes::MainMenuScene::onUpdate(const sf::Time& elapsedTime) {\n\n sf::RenderWindow& window = m_game.getWindow();\n\n sf::Texture& menuBackgroundTexture = Textures::TextureManager::getInstance().getTexture(\"main-menu\");\n\n sf::Sprite sprite(menuBackgroundTexture);\n\n sprite.setTextureRect(sf::IntRect(0, 0, 800, 800));\n\n\n\n window.draw(sprite);\n\n window.draw(m_newGameButton);\n\n window.draw(m_exitButton);\n\n}\n\n\n", "file_path": "src/game/scenes/MainMenuScene.cpp", "rank": 42, "score": 5173.178630259349 }, { "content": " class TextureManager {\n\n public:\n\n TextureManager(const TextureManager&) = delete;\n\n TextureManager(TextureManager&&) = delete;\n\n TextureManager& operator=(const TextureManager&) = delete;\n\n TextureManager& operator=(TextureManager&&) = delete;\n\n\n\n static TextureManager& getInstance();\n\n bool loadTexture(const std::string& path, const std::string& name);\n\n sf::Texture& getTexture(const std::string& name);\n\n\n\n private:\n\n TextureManager() = default;\n\n\n\n std::map<std::string, sf::Texture> m_textures;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_TEXTURES_TEXTURE_MANAGER_H\n", "file_path": "src/game/textures/TextureManager.h", "rank": 43, "score": 5169.211568019781 }, { "content": " class MusicManager {\n\n public:\n\n MusicManager(const MusicManager&) = delete;\n\n MusicManager(MusicManager&&) = delete;\n\n MusicManager& operator=(const MusicManager&) = delete;\n\n MusicManager& operator=(MusicManager&&) = delete;\n\n\n\n static MusicManager& getInstance();\n\n bool playMusic(const std::string& path);\n\n\n\n private:\n\n MusicManager() = default;\n\n\n\n sf::Music m_music;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_AUDIO_MUSIC_MANAGER_H\n", "file_path": "src/game/audio/MusicManager.h", "rank": 44, "score": 5169.211568019781 }, { "content": " class MainMenuScene final : public Scene {\n\n public:\n\n explicit MainMenuScene(Game& game);\n\n void onEvent(const sf::Event& event) override;\n\n void onUpdate(const sf::Time& elapsedTime) override;\n\n ~MainMenuScene() override = default;\n\n\n\n private:\n\n TextButton m_newGameButton;\n\n TextButton m_exitButton;\n\n };\n\n }\n\n}\n\n\n\n\n\n#endif // GAME_SAPPER_SRC_GAME_SCENES_MAIN_MENU_SCENE_H\n", "file_path": "src/game/scenes/MainMenuScene.h", "rank": 45, "score": 4155.595604704209 }, { "content": "# game-sapper\n\n\n\nИгра \"Сапёр\", написанная на языке С++ с использованием SFML.\n", "file_path": "README.md", "rank": 46, "score": 3854.6331110022056 }, { "content": "#include \"game/Game.h\"\n\n#include \"game/textures/TextureManager.h\"\n\n#include \"game/gui/FontManager.h\"\n\n#include <iostream>\n\n\n\nint main() {\n\n Game::Textures::TextureManager& textureManager = Game::Textures::TextureManager::getInstance();\n\n Game::Gui::FontManager& fontManager = Game::Gui::FontManager::getInstance();\n\n\n\n try {\n\n textureManager.loadTexture(\"resources/images/main-menu.jpg\", \"main-menu\");\n\n fontManager.loadFont(\"resources/fonts/arial.ttf\", \"arial\");\n\n } catch (const std::invalid_argument& e) {\n\n std::cerr << e.what() << \"\\n\";\n\n return 0;\n\n }\n\n\n\n Game::Game game;\n\n\n\n return game.execute();\n\n}\n", "file_path": "src/main.cpp", "rank": 47, "score": 6.329762931035064 } ]
C++
include/torquis/split.hpp
devfix/torquis
5d42ee8e6af332bbfc5aaa2741405e72109e3d14
#ifndef TORQUIS_INCLUDE_GUARD #error "Do not include this file directly, include tho torquis.hpp" #endif #ifndef TORQUIS_SPLIT_HPP #define TORQUIS_SPLIT_HPP namespace torquis { template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const CharT delim) { std::vector<std::basic_string_view<CharT>> parts; std::size_t prev = 0, curr; do { curr = str.find(delim, prev); if (curr == std::string::npos) { parts.push_back(str.substr(prev)); } else { parts.push_back(str.substr(prev, curr - prev)); } prev = curr + 1; } while (curr != std::string::npos); return parts; } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const std::basic_string_view<CharT> delim) { std::vector<std::basic_string_view<CharT>> parts; if (delim.length()) { std::size_t prev = 0, curr; do { curr = str.find(delim, prev); if (curr == std::string::npos) { parts.push_back(str.substr(prev)); } else { parts.push_back(str.substr(prev, curr - prev)); } prev = curr + delim.length(); } while (curr != std::string::npos && prev <= str.length()); } else { for (std::size_t i = 0; i < str.length(); i++) { parts.push_back(str.substr(i, 1)); } } return parts; } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const std::basic_string<CharT>& delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const CharT* delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string<CharT>& str, const std::basic_string_view<CharT> delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string<CharT>& str, const std::basic_string<CharT>& delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string<CharT>& str, const CharT* delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const CharT* str, const std::basic_string_view<CharT> delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const CharT* str, const std::basic_string<CharT>& delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const CharT* str, const CharT* delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } } #endif
#ifndef TORQUIS_INCLUDE_GUARD #error "Do not include this file directly, include tho torquis.hpp" #endif #ifndef TORQUIS_SPLIT_HPP #define TORQUIS_SPLIT_HPP namespace torquis { template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const CharT delim) { std::vector<st
()) { std::size_t prev = 0, curr; do { curr = str.find(delim, prev); if (curr == std::string::npos) { parts.push_back(str.substr(prev)); } else { parts.push_back(str.substr(prev, curr - prev)); } prev = curr + delim.length(); } while (curr != std::string::npos && prev <= str.length()); } else { for (std::size_t i = 0; i < str.length(); i++) { parts.push_back(str.substr(i, 1)); } } return parts; } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const std::basic_string<CharT>& delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const CharT* delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string<CharT>& str, const std::basic_string_view<CharT> delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string<CharT>& str, const std::basic_string<CharT>& delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string<CharT>& str, const CharT* delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const CharT* str, const std::basic_string_view<CharT> delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const CharT* str, const std::basic_string<CharT>& delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const CharT* str, const CharT* delim) { return split<CharT>(std::basic_string_view<CharT>(str), std::basic_string_view<CharT>(delim)); } } #endif
d::basic_string_view<CharT>> parts; std::size_t prev = 0, curr; do { curr = str.find(delim, prev); if (curr == std::string::npos) { parts.push_back(str.substr(prev)); } else { parts.push_back(str.substr(prev, curr - prev)); } prev = curr + 1; } while (curr != std::string::npos); return parts; } template<typename CharT> [[nodiscard]] std::vector<std::basic_string_view<CharT>> split(const std::basic_string_view<CharT> str, const std::basic_string_view<CharT> delim) { std::vector<std::basic_string_view<CharT>> parts; if (delim.length
random
[ { "content": "\n\n#define TORQUIS_INCLUDE_GUARD\n\n#include \"torquis/join.hpp\"\n\n#include \"torquis/replace.hpp\"\n\n#include \"torquis/split.hpp\"\n\n#include \"torquis/tolower.hpp\"\n\n#include \"torquis/toupper.hpp\"\n\n#undef TORQUIS_INCLUDE_GUARD\n\n\n\n#endif //TORQUIS_HPP\n", "file_path": "include/torquis.hpp", "rank": 0, "score": 39068.58589162868 }, { "content": "/*\n\n *\n\n * _______ _____ ______ _____ _ _ _____ _______\n\n * | | | |_____/ | __| | | | |______\n\n * | |_____| | \\_ |____\\| |_____| __|__ ______|\n\n *\n\n * c++ string library\n\n *\n\n * version 0.3\n\n * written by Tristan Krause aka. devfix\n\n * https://github.com/devfix/torquis\n\n *\n\n */\n\n\n\n#ifndef TORQUIS_HPP\n\n#define TORQUIS_HPP\n\n\n\n#include <string>\n\n#include <string_view>\n\n#include <vector>\n", "file_path": "include/torquis.hpp", "rank": 1, "score": 39067.84409207317 }, { "content": "//\n\n// Created by core on 05/03/2021.\n\n//\n\n\n\n#ifndef TORQUIS_INCLUDE_GUARD\n\n#error \"Do not include this file directly, include the torquis.hpp\"\n\n#endif\n\n\n\n#ifndef TORQUIS_JOIN_HPP\n\n#define TORQUIS_JOIN_HPP\n\n\n\nnamespace torquis\n\n{\n\n\n\n\t/**\n\n\t * \\brief takes all strings in a vector and joins them into one string\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\tparam StringT type of the string, must use CharT as character type\n\n\t * \\param vec vector of strings\n\n\t * \\param delim delimiter string between each string\n", "file_path": "include/torquis/join.hpp", "rank": 3, "score": 36493.163407162756 }, { "content": "//\n\n// Created by core on 05/03/2021.\n\n//\n\n\n\n#ifndef TORQUIS_INCLUDE_GUARD\n\n#error \"Do not include this file directly, include the torquis.hpp\"\n\n#endif\n\n\n\n#ifndef TORQUIS_TOLOWER_HPP\n\n#define TORQUIS_TOLOWER_HPP\n\n\n\nnamespace torquis\n\n{\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their lower case inplace\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t * \\param len input string length\n\n\t */\n", "file_path": "include/torquis/tolower.hpp", "rank": 4, "score": 36493.128985809526 }, { "content": "//\n\n// Created by core on 05/03/2021.\n\n//\n\n\n\n#ifndef TORQUIS_INCLUDE_GUARD\n\n#error \"Do not include this file directly, include the torquis.hpp\"\n\n#endif\n\n\n\n#ifndef TORQUIS_TOUPPER_HPP\n\n#define TORQUIS_TOUPPER_HPP\n\n\n\nnamespace torquis\n\n{\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their upper case inplace\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t * \\param len input string length\n\n\t */\n", "file_path": "include/torquis/toupper.hpp", "rank": 5, "score": 36493.128985809526 }, { "content": "//\n\n// Created by core on 05/03/2021.\n\n//\n\n\n\n#ifndef TORQUIS_INCLUDE_GUARD\n\n#error \"Do not include this file directly, include the torquis.hpp\"\n\n#endif\n\n\n\n#ifndef TORQUIS_REPLACE_HPP\n\n#define TORQUIS_REPLACE_HPP\n\n\n\nnamespace torquis\n\n{\n\n\ttemplate<typename CharT>\n\n\tusing sv = std::basic_string_view<CharT>;\n\n\n\n\ttemplate<typename CharT>\n\n\tusing cs = const CharT*;\n\n\n\n\ttemplate<typename CharT>\n", "file_path": "include/torquis/replace.hpp", "rank": 6, "score": 36491.930608814866 }, { "content": "\t */\n\n\ttemplate<typename CharT, typename StringT>\n\n\t[[nodiscard]] std::basic_string<CharT> join(const std::vector<StringT>& vec, const std::basic_string_view<CharT> delim)\n\n\t{\n\n\t\tif (vec.empty()) { return {}; }\n\n\t\telse\n\n\t\t{\n\n\t\t\tstd::basic_string<CharT> str(vec[0]);\n\n\t\t\tfor (std::size_t i = 1; i < vec.size(); i++)\n\n\t\t\t{\n\n\t\t\t\tstr += delim;\n\n\t\t\t\tstr += vec[i];\n\n\t\t\t}\n\n\t\t\treturn str;\n\n\t\t}\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief takes all strings in a vector and joins them into one string\n\n\t * \\tparam CharT underlying character type of the string\n", "file_path": "include/torquis/join.hpp", "rank": 13, "score": 36486.88301463295 }, { "content": "\t * \\tparam StringT type of the string, must use CharT as character type\n\n\t * \\param vec vector of strings\n\n\t * \\param delim delimiter string between each string\n\n\t */\n\n\ttemplate<typename CharT, typename StringT>\n\n\t[[nodiscard]] std::basic_string<CharT> join(const std::vector<StringT>& vec, const std::basic_string<CharT>& delim)\n\n\t{\n\n\t\treturn join<CharT, StringT>(vec, std::basic_string_view<CharT>(delim));\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief takes all strings in a vector and joins them into one string\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\tparam StringT type of the string, must use CharT as character type\n\n\t * \\param vec vector of strings\n\n\t * \\param delim delimiter string between each string\n\n\t */\n\n\ttemplate<typename CharT, typename StringT>\n\n\t[[nodiscard]] std::basic_string<CharT> join(const std::vector<StringT>& vec, const CharT* delim)\n\n\t{\n\n\t\treturn join<CharT, StringT>(vec, std::basic_string_view<CharT>(delim));\n\n\t}\n\n\n\n}\n\n\n\n#endif //TORQUIS_JOIN_HPP\n", "file_path": "include/torquis/join.hpp", "rank": 15, "score": 36486.30248281994 }, { "content": "\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const s<CharT>& oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const s<CharT>& oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const s<CharT>& oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n}\n\n\n\n#endif //TORQUIS_REPLACE_HPP\n", "file_path": "include/torquis/replace.hpp", "rank": 16, "score": 36486.15532386221 }, { "content": "\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const s<CharT>& oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const sv<CharT> oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const sv<CharT> oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const sv<CharT> oldval, const s<CharT>& newval)\n\n\t{\n", "file_path": "include/torquis/replace.hpp", "rank": 17, "score": 36485.351577246554 }, { "content": "\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const s<CharT>& oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const s<CharT>& oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const sv<CharT> oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const sv<CharT> oldval, const cs<CharT> newval)\n\n\t{\n", "file_path": "include/torquis/replace.hpp", "rank": 18, "score": 36485.31834608418 }, { "content": "\t\treturn repl;\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const sv<CharT> oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const sv<CharT> oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const cs<CharT> oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n", "file_path": "include/torquis/replace.hpp", "rank": 19, "score": 36485.127805808144 }, { "content": "\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const cs<CharT> oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const s<CharT>& oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const s<CharT>& oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n", "file_path": "include/torquis/replace.hpp", "rank": 20, "score": 36485.115242204505 }, { "content": "\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const cs<CharT> oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const cs<CharT> oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const s<CharT>& oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n", "file_path": "include/torquis/replace.hpp", "rank": 21, "score": 36485.10276043677 }, { "content": "\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const cs<CharT> oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const cs<CharT> oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const s<CharT>& str, const cs<CharT> oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n", "file_path": "include/torquis/replace.hpp", "rank": 22, "score": 36485.093473212226 }, { "content": "\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const sv<CharT> oldval, const s<CharT>& newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const cs<CharT> oldval, const sv<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>(str), sv<CharT>(oldval), sv<CharT>(newval));\n\n\t}\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const cs<CharT> str, const cs<CharT> oldval, const cs<CharT> newval)\n\n\t{\n\n\t\treturn replace(sv<CharT>{str}, sv<CharT>{oldval}, sv<CharT>{newval});\n\n\t}\n", "file_path": "include/torquis/replace.hpp", "rank": 23, "score": 36485.058955552195 }, { "content": "\ttemplate<typename CharT>\n\n\tvoid toupper(CharT* str, std::size_t len)\n\n\t{\n\n\t\tstatic_assert(!std::is_const_v<CharT>, \"no const type allowed\");\n\n\t\tfor (; len--; str++) { *str = std::toupper(*str); }\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their upper case inplace\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tvoid toupper(std::basic_string<CharT>& str)\n\n\t{\n\n\t\tif (!str.empty()) { toupper(&str[0], str.length()); }\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their upper case and returns it\n", "file_path": "include/torquis/toupper.hpp", "rank": 24, "score": 36484.786653514624 }, { "content": "\ttemplate<typename CharT>\n\n\tvoid tolower(CharT* str, std::size_t len)\n\n\t{\n\n\t\tstatic_assert(!std::is_const_v<CharT>, \"no const type allowed\");\n\n\t\tfor (; len--; str++) { *str = std::tolower(*str); }\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their lower case inplace\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tvoid tolower(std::basic_string<CharT>& str)\n\n\t{\n\n\t\tif (!str.empty()) { tolower(&str[0], str.length()); }\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their lower case and returns it\n", "file_path": "include/torquis/tolower.hpp", "rank": 25, "score": 36484.786653514624 }, { "content": "\tusing s = std::basic_string<CharT>;\n\n\n\n\ttemplate<typename CharT>\n\n\t[[nodiscard]] s<CharT> replace(const sv<CharT> str, const sv<CharT> oldval, const sv<CharT> newval)\n\n\t{\n\n\t\tstd::basic_string<CharT> repl;\n\n\n\n\t\tstd::size_t lpos = 0;\n\n\t\twhile (lpos != str.npos)\n\n\t\t{\n\n\t\t\tauto pos = str.find(oldval, lpos);\n\n\t\t\trepl += str.substr(lpos, pos - lpos);\n\n\t\t\tif (pos != str.npos)\n\n\t\t\t{\n\n\t\t\t\trepl += newval;\n\n\t\t\t\tlpos = pos + oldval.length();\n\n\t\t\t}\n\n\t\t\telse { lpos = str.npos; }\n\n\t\t}\n\n\n", "file_path": "include/torquis/replace.hpp", "rank": 26, "score": 36484.625720450065 }, { "content": "\t\ttoupper(copy);\n\n\t\treturn copy;\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their upper case and returns it\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tstd::basic_string<CharT> toupperc(const CharT* str)\n\n\t{\n\n\t\tstd::basic_string<CharT> copy(str);\n\n\t\ttoupper(copy);\n\n\t\treturn copy;\n\n\t}\n\n\n\n}\n\n\n\n#endif //TORQUIS_TOUPPER_HPP\n", "file_path": "include/torquis/toupper.hpp", "rank": 27, "score": 36484.28113645047 }, { "content": "\t\ttolower(copy);\n\n\t\treturn copy;\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their lower case and returns it\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tstd::basic_string<CharT> tolowerc(const CharT* str)\n\n\t{\n\n\t\tstd::basic_string<CharT> copy(str);\n\n\t\ttolower(copy);\n\n\t\treturn copy;\n\n\t}\n\n\n\n}\n\n\n\n#endif //TORQUIS_TOLOWER_HPP\n", "file_path": "include/torquis/tolower.hpp", "rank": 28, "score": 36484.28113645047 }, { "content": "\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tstd::basic_string<CharT> tolowerc(const std::basic_string_view<CharT> str)\n\n\t{\n\n\t\tstd::basic_string<CharT> copy(str);\n\n\t\ttolower(copy);\n\n\t\treturn copy;\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their lower case and returns it\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tstd::basic_string<CharT> tolowerc(const std::basic_string<CharT>& str)\n\n\t{\n\n\t\tstd::basic_string<CharT> copy(str);\n", "file_path": "include/torquis/tolower.hpp", "rank": 29, "score": 36483.01322297367 }, { "content": "\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tstd::basic_string<CharT> toupperc(const std::basic_string_view<CharT> str)\n\n\t{\n\n\t\tstd::basic_string<CharT> copy(str);\n\n\t\ttoupper(copy);\n\n\t\treturn copy;\n\n\t}\n\n\n\n\t/**\n\n\t * \\brief converts the ascii-characters of a string to their upper case and returns it\n\n\t * \\tparam CharT underlying character type of the string\n\n\t * \\param str input string\n\n\t */\n\n\ttemplate<typename CharT>\n\n\tstd::basic_string<CharT> toupperc(const std::basic_string<CharT>& str)\n\n\t{\n\n\t\tstd::basic_string<CharT> copy(str);\n", "file_path": "include/torquis/toupper.hpp", "rank": 30, "score": 36483.01322297367 }, { "content": "[torquis.hpp]: https://github.com/devfix/torquis/blob/main/include/torquis.hpp\n\n\n\n```\n\n_______ _____ ______ _____ _ _ _____ _______\n\n | | | |_____/ | __| | | | |______\n\n | |_____| | \\_ |____\\| |_____| __|__ ______|\n\n\n\n c++ string library\n\n```\n\n\n\n## Features\n\n* small header-only library\n\n* very lightweight, only one file\n\n* various function overloads for string-views, strings and c-strings\n\n* MIT license\n\n\n\n## Functions\n\n* split\n\n* join\n\n* tolower\n\n* toupper\n\n* replace\n\n\n\n## Simple usage\n\n* copy the content of the `include` directory and include `torquis.hpp`\n\n\n\n## CMake integration\n\n### With FetchContent\n\nIf you are using CMake version 1.14 or later you can use [FetchContent](https://cmake.org/cmake/help/latest/module/FetchContent.html) with `FetchContent_MakeAvailable`:\n\n```cmake\n\nInclude(FetchContent)\n\n\n\nFetchContent_Declare(\n\n torquis\n\n GIT_REPOSITORY https://github.com/devfix/torquis.git\n\n GIT_TAG v0.3)\n\nFetchContent_MakeAvailable(torquis)\n\n\n\nadd_executable(my_fancy_executable main.cpp)\n\ntarget_include_directories(my_fancy_executable PRIVATE ${torquis_SOURCE_DIR}/include)\n\n```\n\n### As subdirectory\n\nThis project is also provided when torquis is used as a subdirectory. Assuming that torquis has been cloned to `my_libs/torquis`:\n\n```cmake\n\nadd_subdirectory(my_libs/torquis)\n\nadd_executable(my_fancy_executable main.cpp)\n\ntarget_include_directories(my_fancy_executable PRIVATE ${torquis_SOURCE_DIR}/include)\n\n```\n", "file_path": "README.md", "rank": 31, "score": 11397.626391275442 }, { "content": "//\n\n// Created by core on 10/02/2021.\n\n//\n\n\n\n#include <catch2/catch.hpp>\n\n#include <include/torquis.hpp>\n\n#include <cstring>\n\n#define TORQUIS_INCLUDE_GUARD\n\n#include <include/torquis/tolower.hpp>\n\n#undef TORQUIS_INCLUDE_GUARD\n\n\n\n\n\n/*\n\n * tests for character type: char\n\n */\n\n\n\nTEST_CASE(\"tolower/char/by-cstring/0\")\n\n{\n\n\tstd::string str;\n\n\ttorquis::tolower(str); // call string type: string\n", "file_path": "test/test_tolower.cpp", "rank": 32, "score": 7.613569590209044 }, { "content": "//\n\n// Created by core on 10/02/2021.\n\n//\n\n\n\n#include <catch2/catch.hpp>\n\n#include <include/torquis.hpp>\n\n#include <cstring>\n\n#define TORQUIS_INCLUDE_GUARD\n\n#include <include/torquis/toupper.hpp>\n\n#undef TORQUIS_INCLUDE_GUARD\n\n\n\n\n\n/*\n\n * tests for character type: char\n\n */\n\n\n\nTEST_CASE(\"toupper/char/by-cstring/0\")\n\n{\n\n\tstd::string str;\n\n\ttorquis::toupper(str); // call string type: string\n", "file_path": "test/test_toupper.cpp", "rank": 33, "score": 7.613569590209044 }, { "content": "//\n\n// Created by core on 03/02/2021.\n\n//\n\n\n\n#include <catch2/catch.hpp>\n\n#define TORQUIS_INCLUDE_GUARD\n\n#include <include/torquis/split.hpp>\n\n#undef TORQUIS_INCLUDE_GUARD\n\n\n\n\n\n/*\n\n * tests for character type: char\n\n */\n\n\n\nTEST_CASE(\"split/char/by-character/0\")\n\n{\n\n\tconst auto str = \"\";\n\n\tconst auto split = torquis::split({ str }, '#');\n\n\tREQUIRE(split.size() == 1);\n\n\tCHECK(split[0] == \"\");\n", "file_path": "test/test_split.cpp", "rank": 34, "score": 7.36492653777922 }, { "content": "//\n\n// Created by core on 05/03/2021.\n\n//\n\n\n\n#include <catch2/catch.hpp>\n\n#include <cstring>\n\n\n\n#define TORQUIS_INCLUDE_GUARD\n\n#include <include/torquis/replace.hpp>\n\n#undef TORQUIS_INCLUDE_GUARD\n\n\n\n\n\nTEST_CASE(\"replace/char/0\")\n\n{\n\n\t{\n\n\t\tconst char* str(\"one one was a race horse, two two was one too.\");\n\n\t\tauto repl = torquis::replace(str, \"one\", \"three\");\n\n\t\tCHECK(repl == \"three three was a race horse, two two was three too.\");\n\n\t}\n\n\t{\n", "file_path": "test/test_replace.cpp", "rank": 35, "score": 7.149269422086025 }, { "content": "//\n\n// Created by core on 04/02/2021.\n\n//\n\n\n\n#include <catch2/catch.hpp>\n\n#include <include/torquis.hpp>\n\n\n\n/*\n\n * tests for character type: char\n\n */\n\n\n\nTEST_CASE(\"inter/char/split-join/0\")\n\n{\n\n\tconst std::string_view str(\"abc#def#ghi\");\n\n\tauto joined = torquis::join(torquis::split(str, '#'), \"#\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/char/split-join/1\")\n\n{\n", "file_path": "test/test_inter.cpp", "rank": 36, "score": 7.016285366781618 }, { "content": "//\n\n// Created by core on 03/02/2021.\n\n//\n\n\n\n#include <catch2/catch.hpp>\n\n#define TORQUIS_INCLUDE_GUARD\n\n#include <include/torquis/join.hpp>\n\n#undef TORQUIS_INCLUDE_GUARD\n\n\n\n/*\n\n * tests for character type: char\n\n */\n\n\n\nTEST_CASE(\"join/char/0\")\n\n{\n\n\tstd::vector<std::string> vec;\n\n\tauto join = torquis::join(vec, \"-\");\n\n\tCHECK(join.empty());\n\n}\n\n\n", "file_path": "test/test_join.cpp", "rank": 37, "score": 5.722501418441022 }, { "content": "\tconst std::string_view str(\"abc#def#ghi\");\n\n\tauto joined = torquis::join(torquis::split(str, \"#\"), \"#\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/char/split-join/2\")\n\n{\n\n\tconst std::string_view str(\"#abc#def#ghi#\");\n\n\tauto joined = torquis::join(torquis::split(str, \"#\"), \"#\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/char/split-join/3\")\n\n{\n\n\tconst std::string_view str(\"##abc#def#####ghi####\");\n\n\tauto joined = torquis::join(torquis::split(str, \"##\"), \"##\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/char/split-join/4\")\n", "file_path": "test/test_inter.cpp", "rank": 38, "score": 4.552992641746523 }, { "content": "{\n\n\tconst std::wstring_view str(L\"abc#def#ghi\");\n\n\tauto joined = torquis::join(torquis::split(str, L\"#\"), L\"#\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/wchar_t/split-join/2\")\n\n{\n\n\tconst std::wstring_view str(L\"#abc#def#ghi#\");\n\n\tauto joined = torquis::join(torquis::split(str, L\"#\"), L\"#\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/wchar_t/split-join/3\")\n\n{\n\n\tconst std::wstring_view str(L\"##abc#def#####ghi####\");\n\n\tauto joined = torquis::join(torquis::split(str, L\"##\"), L\"##\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/wchar_t/split-join/4\")\n\n{\n\n\tconst std::wstring_view str(L\"+-aa-++-++--bb+-\");\n\n\tauto joined = torquis::join(torquis::split(str, L\"+-\"), L\"+-\");\n\n\tCHECK(joined == str);\n\n}\n", "file_path": "test/test_inter.cpp", "rank": 39, "score": 4.546027489576324 }, { "content": "\t\tconst char* str(\"aaa\");\n\n\t\tauto repl = torquis::replace(str, \"a\", \"b\");\n\n\t\tCHECK(repl == \"bbb\");\n\n\t}\n\n\t{\n\n\t\tconst char* str(\"ababab\");\n\n\t\tauto repl = torquis::replace(str, \"ab\", \"b\");\n\n\t\tCHECK(repl == \"bbb\");\n\n\t}\n\n\t{\n\n\t\tconst char* str(\"aaa\");\n\n\t\tauto repl = torquis::replace(str, \"aa\", \"b\");\n\n\t\tCHECK(repl == \"ba\");\n\n\t}\n\n\t{\n\n\t\tconst char* str(\"abbbb\");\n\n\t\tauto repl = torquis::replace(str, \"abb\", \"a\");\n\n\t\tCHECK(repl == \"abb\");\n\n\t\tauto repl2 = torquis::replace(repl, \"abb\", \"a\");\n\n\t\tCHECK(repl2 == \"a\");\n", "file_path": "test/test_replace.cpp", "rank": 40, "score": 4.54256609716845 }, { "content": "{\n\n\tconst std::string_view str(\"+-aa-++-++--bb+-\");\n\n\tauto joined = torquis::join(torquis::split(str, \"+-\"), \"+-\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\n\n\n\n\n/*\n\n * tests for character type: wchar_t\n\n */\n\n\n\nTEST_CASE(\"inter/wchar_t/split-join/0\")\n\n{\n\n\tconst std::wstring_view str(L\"abc#def#ghi\");\n\n\tauto joined = torquis::join(torquis::split(str, L'#'), L\"#\");\n\n\tCHECK(joined == str);\n\n}\n\n\n\nTEST_CASE(\"inter/wchar_t/split-join/1\")\n", "file_path": "test/test_inter.cpp", "rank": 41, "score": 4.389119081367761 }, { "content": "\t{\n\n\t\tconst wchar_t* str(L\"aaa\");\n\n\t\tauto repl = torquis::replace(str, L\"aa\", L\"b\");\n\n\t\tCHECK(repl == L\"ba\");\n\n\t}\n\n\t{\n\n\t\tconst wchar_t* str(L\"abbbb\");\n\n\t\tauto repl = torquis::replace(str, L\"abb\", L\"a\");\n\n\t\tCHECK(repl == L\"abb\");\n\n\t\tauto repl2 = torquis::replace(repl, L\"abb\", L\"a\");\n\n\t\tCHECK(repl2 == L\"a\");\n\n\t}\n\n}\n", "file_path": "test/test_replace.cpp", "rank": 42, "score": 4.170327592593854 }, { "content": "\tauto lower = torquis::tolowerc(str); // call string type: string_view\n\n\tCHECK(lower == \"aöb?Ä#+ßq\");\n\n}\n\n\n\nTEST_CASE(\"tolower/char/by-cstring/4\")\n\n{\n\n\tstd::string str(\"aöB?Ä#+ßQ\");\n\n\tauto lower = torquis::tolowerc(str); // call string type: string\n\n\tCHECK(lower == \"aöb?Ä#+ßq\");\n\n}\n\n\n\nTEST_CASE(\"tolower/char/by-cstring/5\")\n\n{\n\n\tconst char* str = \"aöB?Ä#+ßQ\";\n\n\tauto lower = torquis::tolowerc(str); // call string type: c-string\n\n\tCHECK(lower == \"aöb?Ä#+ßq\");\n\n}\n\n\n\n\n\n\n", "file_path": "test/test_tolower.cpp", "rank": 43, "score": 4.065186315099487 }, { "content": "\tstd::wstring str(L\"aöB?Ä#+ßQ\");\n\n\ttorquis::tolower(&str[0], str.length()); // call string type: c-string\n\n\tCHECK(std::wstring(L\"aöb?Ä#+ßq\") == str);\n\n}\n\n\n\nTEST_CASE(\"tolower/wchar_t/by-cstring/3\")\n\n{\n\n\tstd::wstring_view str(L\"aöB?Ä#+ßQ\");\n\n\tauto lower = torquis::tolowerc(str); // call string type: string_view\n\n\tCHECK(lower == L\"aöb?Ä#+ßq\");\n\n}\n\n\n\nTEST_CASE(\"tolower/wchar_t/by-cstring/4\")\n\n{\n\n\tstd::wstring str(L\"aöB?Ä#+ßQ\");\n\n\tauto lower = torquis::tolowerc(str); // call string type: string\n\n\tCHECK(lower == L\"aöb?Ä#+ßq\");\n\n}\n\n\n\nTEST_CASE(\"tolower/wchar_t/by-cstring/5\")\n\n{\n\n\tconst wchar_t* str = L\"aöB?Ä#+ßQ\";\n\n\tauto lower = torquis::tolowerc(str); // call string type: c-string\n\n\tCHECK(lower == L\"aöb?Ä#+ßq\");\n\n}\n", "file_path": "test/test_tolower.cpp", "rank": 44, "score": 4.058299880258966 }, { "content": "\t}\n\n}\n\n\n\nTEST_CASE(\"replace/wchar_t/0\")\n\n{\n\n\t{\n\n\t\tconst wchar_t* str(L\"one one was a race horse, two two was one too.\");\n\n\t\tauto repl = torquis::replace(str, L\"one\", L\"three\");\n\n\t\tCHECK(repl == L\"three three was a race horse, two two was three too.\");\n\n\t}\n\n\t{\n\n\t\tconst wchar_t* str(L\"aaa\");\n\n\t\tauto repl = torquis::replace(str, L\"a\", L\"b\");\n\n\t\tCHECK(repl == L\"bbb\");\n\n\t}\n\n\t{\n\n\t\tconst wchar_t* str(L\"ababab\");\n\n\t\tauto repl = torquis::replace(str, L\"ab\", L\"b\");\n\n\t\tCHECK(repl == L\"bbb\");\n\n\t}\n", "file_path": "test/test_replace.cpp", "rank": 45, "score": 4.008637853962678 }, { "content": "\tstd::wstring str(L\"aöB?Äk#+ßl\");\n\n\ttorquis::toupper(&str[0], str.length()); // call string type: c-string\n\n\tCHECK(std::wstring(L\"AöB?ÄK#+ßL\") == str);\n\n}\n\n\n\nTEST_CASE(\"toupper/wchar_t/by-cstring/3\")\n\n{\n\n\tstd::wstring_view str(L\"aöB?Äk#+ßl\");\n\n\tauto lower = torquis::toupperc(str); // call string type: string_view\n\n\tCHECK(lower == L\"AöB?ÄK#+ßL\");\n\n}\n\n\n\nTEST_CASE(\"toupper/wchar_t/by-cstring/4\")\n\n{\n\n\tstd::wstring str(L\"aöB?Äk#+ßl\");\n\n\tauto lower = torquis::toupperc(str); // call string type: string\n\n\tCHECK(lower == L\"AöB?ÄK#+ßL\");\n\n}\n\n\n\nTEST_CASE(\"toupper/wchar_t/by-cstring/5\")\n\n{\n\n\tconst wchar_t* str = L\"aöB?Äk#+ßl\";\n\n\tauto lower = torquis::toupperc(str); // call string type: c-string\n\n\tCHECK(lower == L\"AöB?ÄK#+ßL\");\n\n}\n", "file_path": "test/test_toupper.cpp", "rank": 46, "score": 3.982004577069704 }, { "content": "\tauto lower = torquis::toupperc(str); // call string type: string_view\n\n\tCHECK(lower == \"AöB?ÄK#+ßL\");\n\n}\n\n\n\nTEST_CASE(\"toupper/char/by-cstring/4\")\n\n{\n\n\tstd::string str(\"aöB?Äk#+ßl\");\n\n\tauto lower = torquis::toupperc(str); // call string type: string\n\n\tCHECK(lower == \"AöB?ÄK#+ßL\");\n\n}\n\n\n\nTEST_CASE(\"toupper/char/by-cstring/5\")\n\n{\n\n\tconst char* str = \"aöB?Äk#+ßl\";\n\n\tauto lower = torquis::toupperc(str); // call string type: c-string\n\n\tCHECK(lower == \"AöB?ÄK#+ßL\");\n\n}\n\n\n\n\n\n\n", "file_path": "test/test_toupper.cpp", "rank": 47, "score": 3.9596494627046246 }, { "content": "/*\n\n * tests for character type: wchar_t\n\n */\n\n\n\nTEST_CASE(\"tolower/wchar_t/by-cstring/0\")\n\n{\n\n\tstd::wstring str;\n\n\ttorquis::tolower(str); // call string type: string\n\n\tCHECK(str.empty());\n\n}\n\n\n\nTEST_CASE(\"tolower/wchar_t/by-cstring/1\")\n\n{\n\n\tstd::wstring str(L\"aöB?Ä#+ßQ\");\n\n\ttorquis::tolower(str); // call string type: string\n\n\tCHECK(std::wstring(L\"aöb?Ä#+ßq\") == str);\n\n}\n\n\n\nTEST_CASE(\"tolower/wchar_t/by-cstring/2\")\n\n{\n", "file_path": "test/test_tolower.cpp", "rank": 48, "score": 3.9487204883111677 }, { "content": "/*\n\n * tests for character type: char\n\n */\n\n\n\nTEST_CASE(\"toupper/wchar_t/by-cstring/0\")\n\n{\n\n\tstd::wstring str;\n\n\ttorquis::toupper(str); // call string type: string\n\n\tCHECK(str.empty());\n\n}\n\n\n\nTEST_CASE(\"toupper/wchar_t/by-cstring/1\")\n\n{\n\n\tstd::wstring str(L\"aöB?Äk#+ßl\");\n\n\ttorquis::toupper(str); // call string type: string\n\n\tCHECK(std::wstring(L\"AöB?ÄK#+ßL\") == str);\n\n}\n\n\n\nTEST_CASE(\"toupper/wchar_t/by-cstring/2\")\n\n{\n", "file_path": "test/test_toupper.cpp", "rank": 49, "score": 3.915120902270492 }, { "content": "\tCHECK(str.empty());\n\n}\n\n\n\nTEST_CASE(\"tolower/char/by-cstring/1\")\n\n{\n\n\tstd::string str(\"aöB?Ä#+ßQ\");\n\n\ttorquis::tolower(str); // call string type: string\n\n\tCHECK(std::string(\"aöb?Ä#+ßq\") == str);\n\n}\n\n\n\nTEST_CASE(\"tolower/char/by-cstring/2\")\n\n{\n\n\tstd::string str(\"aöB?Ä#+ßQ\");\n\n\ttorquis::tolower(&str[0], str.length()); // call string type: c-string\n\n\tCHECK(std::string(\"aöb?Ä#+ßq\") == str);\n\n}\n\n\n\nTEST_CASE(\"tolower/char/by-cstring/3\")\n\n{\n\n\tstd::string_view str(\"aöB?Ä#+ßQ\");\n", "file_path": "test/test_tolower.cpp", "rank": 50, "score": 3.898389166062483 }, { "content": "\tCHECK(split[3] == \"ghi\");\n\n\tCHECK(split[4] == \"\");\n\n\tCHECK(split[5] == \"\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-character/3\")\n\n{\n\n\tconst auto str = \"###\";\n\n\tconst auto split = torquis::split({ str }, '#');\n\n\tREQUIRE(split.size() == 4);\n\n\tCHECK(split[0] == \"\");\n\n\tCHECK(split[1] == \"\");\n\n\tCHECK(split[2] == \"\");\n\n\tCHECK(split[3] == \"\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-string/0\")\n\n{\n\n\tconst std::string_view str = \"\";\n\n\tconst auto split = torquis::split(str, \"-#\");\n", "file_path": "test/test_split.cpp", "rank": 51, "score": 3.8792543438981255 }, { "content": "\tCHECK(str.empty());\n\n}\n\n\n\nTEST_CASE(\"toupper/char/by-cstring/1\")\n\n{\n\n\tstd::string str(\"aöB?Äk#+ßl\");\n\n\ttorquis::toupper(str); // call string type: string\n\n\tCHECK(std::string(\"AöB?ÄK#+ßL\") == str);\n\n}\n\n\n\nTEST_CASE(\"toupper/char/by-cstring/2\")\n\n{\n\n\tstd::string str(\"aöB?Äk#+ßl\");\n\n\ttorquis::toupper(&str[0], str.length()); // call string type: c-string\n\n\tCHECK(std::string(\"AöB?ÄK#+ßL\") == str);\n\n}\n\n\n\nTEST_CASE(\"toupper/char/by-cstring/3\")\n\n{\n\n\tstd::string_view str(\"aöB?Äk#+ßl\");\n", "file_path": "test/test_toupper.cpp", "rank": 52, "score": 3.8572125234726817 }, { "content": "\tconst auto split = torquis::split( str , std::string_view(\"-#\"));\n\n\tREQUIRE(split.size() == 4);\n\n\tCHECK(split[0] == \"\");\n\n\tCHECK(split[1] == \"\");\n\n\tCHECK(split[2] == \"\");\n\n\tCHECK(split[3] == \"\");\n\n}\n\n\n\n\n\n\n\n/*\n\n * tests for character type: wchar_t\n\n */\n\n\n\nTEST_CASE(\"split/wchar_t/by-character/0\")\n\n{\n\n\tconst auto str = L\"\";\n\n\tconst auto split = torquis::split({ str }, L'#');\n\n\tREQUIRE(split.size() == 1);\n\n\tCHECK(split[0] == L\"\");\n", "file_path": "test/test_split.cpp", "rank": 53, "score": 3.786300628815981 }, { "content": "}\n\n\n\nTEST_CASE(\"split/char/by-character/1\")\n\n{\n\n\tconst auto str = \"abc#def#ghi\";\n\n\tconst auto split = torquis::split({ str }, '#');\n\n\tREQUIRE(split.size() == 3);\n\n\tCHECK(split[0] == \"abc\");\n\n\tCHECK(split[1] == \"def\");\n\n\tCHECK(split[2] == \"ghi\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-character/2\")\n\n{\n\n\tconst auto str = \"#abc#def#ghi##\";\n\n\tconst auto split = torquis::split({ str }, '#');\n\n\tREQUIRE(split.size() == 6);\n\n\tCHECK(split[0] == \"\");\n\n\tCHECK(split[1] == \"abc\");\n\n\tCHECK(split[2] == \"def\");\n", "file_path": "test/test_split.cpp", "rank": 54, "score": 3.7844957403856823 }, { "content": "\tREQUIRE(split.size() == 1);\n\n\tCHECK(split[0] == \"\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-string/1\")\n\n{\n\n\tconst std::string str = \"abc\";\n\n\tconst auto split = torquis::split(str, \"\");\n\n\tREQUIRE(split.size() == 3);\n\n\tCHECK(split[0] == \"a\");\n\n\tCHECK(split[1] == \"b\");\n\n\tCHECK(split[2] == \"c\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-string/2\")\n\n{\n\n\tconst auto str = \"a-bc-#de#f-#g-h#i\";\n\n\tconst auto split = torquis::split(str, std::string(\"-#\"));\n\n\tREQUIRE(split.size() == 3);\n\n\tCHECK(split[0] == \"a-bc\");\n", "file_path": "test/test_split.cpp", "rank": 55, "score": 3.766126864875398 }, { "content": "\tCHECK(split[3] == L\"ghi\");\n\n\tCHECK(split[4] == L\"\");\n\n\tCHECK(split[5] == L\"\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-character/3\")\n\n{\n\n\tconst auto str = L\"###\";\n\n\tconst auto split = torquis::split({ str }, L'#');\n\n\tREQUIRE(split.size() == 4);\n\n\tCHECK(split[0] == L\"\");\n\n\tCHECK(split[1] == L\"\");\n\n\tCHECK(split[2] == L\"\");\n\n\tCHECK(split[3] == L\"\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-string/0\")\n\n{\n\n\tconst std::wstring_view str = L\"\";\n\n\tconst auto split = torquis::split(str, L\"-#\");\n", "file_path": "test/test_split.cpp", "rank": 56, "score": 3.6770294804836956 }, { "content": "\tREQUIRE(split.size() == 1);\n\n\tCHECK(split[0] == L\"\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-string/1\")\n\n{\n\n\tconst std::wstring str = L\"abc\";\n\n\tconst auto split = torquis::split(str, L\"\");\n\n\tREQUIRE(split.size() == 3);\n\n\tCHECK(split[0] == L\"a\");\n\n\tCHECK(split[1] == L\"b\");\n\n\tCHECK(split[2] == L\"c\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-string/2\")\n\n{\n\n\tconst auto str = L\"a-bc-#de#f-#g-h#i\";\n\n\tconst auto split = torquis::split(str, std::wstring(L\"-#\"));\n\n\tREQUIRE(split.size() == 3);\n\n\tCHECK(split[0] == L\"a-bc\");\n", "file_path": "test/test_split.cpp", "rank": 57, "score": 3.6088799737464736 }, { "content": "}\n\n\n\nTEST_CASE(\"split/wchar_t/by-character/1\")\n\n{\n\n\tconst auto str = L\"abc#def#ghi\";\n\n\tconst auto split = torquis::split({ str }, L'#');\n\n\tREQUIRE(split.size() == 3);\n\n\tCHECK(split[0] == L\"abc\");\n\n\tCHECK(split[1] == L\"def\");\n\n\tCHECK(split[2] == L\"ghi\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-character/2\")\n\n{\n\n\tconst auto str = L\"#abc#def#ghi##\";\n\n\tconst auto split = torquis::split({ str }, L'#');\n\n\tREQUIRE(split.size() == 6);\n\n\tCHECK(split[0] == L\"\");\n\n\tCHECK(split[1] == L\"abc\");\n\n\tCHECK(split[2] == L\"def\");\n", "file_path": "test/test_split.cpp", "rank": 58, "score": 3.6088799737464736 }, { "content": "\tCHECK(split[1] == L\"de#f\");\n\n\tCHECK(split[2] == L\"g-h#i\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-string/3\")\n\n{\n\n\tconst auto str = L\"-#abc--##def--##ghi-#-#\";\n\n\tconst auto split = torquis::split(str, std::wstring_view(L\"-#\"));\n\n\tREQUIRE(split.size() == 6);\n\n\tCHECK(split[0] == L\"\");\n\n\tCHECK(split[1] == L\"abc-\");\n\n\tCHECK(split[2] == L\"#def-\");\n\n\tCHECK(split[3] == L\"#ghi\");\n\n\tCHECK(split[4] == L\"\");\n\n\tCHECK(split[5] == L\"\");\n\n}\n\n\n\nTEST_CASE(\"split/wchar_t/by-string/4\")\n\n{\n\n\tconst auto str = L\"-#-#-#\";\n\n\tconst auto split = torquis::split( str , std::wstring_view(L\"-#\"));\n\n\tREQUIRE(split.size() == 4);\n\n\tCHECK(split[0] == L\"\");\n\n\tCHECK(split[1] == L\"\");\n\n\tCHECK(split[2] == L\"\");\n\n\tCHECK(split[3] == L\"\");\n\n}\n\n\n", "file_path": "test/test_split.cpp", "rank": 59, "score": 3.276736961752272 }, { "content": "\tCHECK(split[1] == \"de#f\");\n\n\tCHECK(split[2] == \"g-h#i\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-string/3\")\n\n{\n\n\tconst auto str = \"-#abc--##def--##ghi-#-#\";\n\n\tconst auto split = torquis::split( str , std::string_view(\"-#\"));\n\n\tREQUIRE(split.size() == 6);\n\n\tCHECK(split[0] == \"\");\n\n\tCHECK(split[1] == \"abc-\");\n\n\tCHECK(split[2] == \"#def-\");\n\n\tCHECK(split[3] == \"#ghi\");\n\n\tCHECK(split[4] == \"\");\n\n\tCHECK(split[5] == \"\");\n\n}\n\n\n\nTEST_CASE(\"split/char/by-string/4\")\n\n{\n\n\tconst auto str = \"-#-#-#\";\n", "file_path": "test/test_split.cpp", "rank": 60, "score": 3.176886151377772 }, { "content": "//\n\n// Created by core on 03/02/2021.\n\n//\n\n\n\n#define CATCH_CONFIG_EXTERNAL_INTERFACES\n\n#define CATCH_CONFIG_RUNNER\n\n#include <catch2/catch.hpp>\n\n\n\nint main(int argc, char* argv[])\n\n{\n\n\treturn Catch::Session().run(argc, argv);\n\n}\n", "file_path": "test/testrunner.cpp", "rank": 61, "score": 2.2198998666950045 }, { "content": "TEST_CASE(\"join/wchar_t/0\")\n\n{\n\n\tstd::vector<std::wstring> vec;\n\n\tauto join = torquis::join(vec, L\"-\");\n\n\tCHECK(join.empty());\n\n}\n\n\n\nTEST_CASE(\"join/wchar_t/1\")\n\n{\n\n\tstd::vector<std::wstring> vec = {{ L\"a\" }, { L\"b\" }, { L\"c\" }};\n\n\tauto join = torquis::join(vec, std::wstring(L\"\"));\n\n\tCHECK(join == L\"abc\");\n\n}\n\n\n\nTEST_CASE(\"join/wchar_t/2\")\n\n{\n\n\tstd::vector<std::wstring_view> vec = {{ L\"a\" }, { L\"b\" }, { L\"c\" }};\n\n\tauto join = torquis::join(vec, std::wstring_view(L\"-\"));\n\n\tCHECK(join == L\"a-b-c\");\n\n}\n", "file_path": "test/test_join.cpp", "rank": 62, "score": 2.0091755183153723 }, { "content": "TEST_CASE(\"join/char/1\")\n\n{\n\n\tstd::vector<std::string> vec = {{ \"a\" }, { \"b\" }, { \"c\" }};\n\n\tauto join = torquis::join(vec, std::string(\"\"));\n\n\tCHECK(join == \"abc\");\n\n}\n\n\n\nTEST_CASE(\"join/char/2\")\n\n{\n\n\tstd::vector<std::string_view> vec = {{ \"a\" }, { \"b\" }, { \"c\" }};\n\n\tauto join = torquis::join(vec, std::string_view(\"-\"));\n\n\tCHECK(join == \"a-b-c\");\n\n}\n\n\n\n\n\n\n\n/*\n\n * tests for character type: wchar_t\n\n */\n\n\n", "file_path": "test/test_join.cpp", "rank": 63, "score": 1.9785620599966753 } ]
C++
atlas_npu/ascendbase/src/Base/SingleOpProcess/SingleOpProcess.cpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
#include "SingleOpProcess.h" #include "acl/acl.h" SingleOpProcess::SingleOpProcess() : inputTensorNum_(0), outputTensorNum_(0), stream_(nullptr), attr_(nullptr), withHandle_(false), opHandle_(nullptr) {} SingleOpProcess::SingleOpProcess(const aclrtStream &stream) : inputTensorNum_(0), outputTensorNum_(0), attr_(nullptr), withHandle_(false), opHandle_(nullptr) { stream_ = stream; } SingleOpProcess::~SingleOpProcess() { if (withHandle_ == true) { aclopDestroyHandle(opHandle_); opHandle_ = nullptr; } stream_ = nullptr; } void SingleOpProcess::SetTypeName(std::string typeName) { typeName_ = typeName; } std::string SingleOpProcess::GetTypeName() { return typeName_; } APP_ERROR SingleOpProcess::SetInputTensor(std::vector<Tensor> tensors) { inputTensorDesc_.clear(); for (int i = 0; i < inputTensorNum_; i++) { std::shared_ptr<aclTensorDesc> tensorDesc(aclCreateTensorDesc(tensors[i].dataType, tensors[i].numDim, tensors[i].dims.data(), tensors[i].format), aclDestroyTensorDesc); if (tensorDesc == nullptr) { LogError << "Failed to create acl input tensor description."; return APP_ERR_COMM_INVALID_POINTER; } inputTensorDesc_.push_back(tensorDesc); } return APP_ERR_OK; } APP_ERROR SingleOpProcess::SetInputDataBuffer(std::vector<std::shared_ptr<void>> inputDataBuf, std::vector<size_t> inputBufSize) { inputDataBuf_.clear(); inputData_ = inputDataBuf; for (int i = 0; i < inputTensorNum_; i++) { std::shared_ptr<aclDataBuffer> dataBuffer(aclCreateDataBuffer(inputDataBuf[i].get(), inputBufSize[i]), aclDestroyDataBuffer); if (dataBuffer == nullptr) { LogError << "Failed to create acl input data buffer."; return APP_ERR_COMM_INVALID_POINTER; } inputDataBuf_.push_back(dataBuffer); } return APP_ERR_OK; } APP_ERROR SingleOpProcess::SetOutputTensor(std::vector<Tensor> tensors) { outputTensorDesc_.clear(); outputDataBuf_.clear(); outputData_.clear(); outputDataSize_.clear(); APP_ERROR ret = APP_ERR_OK; for (int i = 0; i < outputTensorNum_; i++) { std::shared_ptr<aclTensorDesc> tensorDesc(aclCreateTensorDesc(tensors[i].dataType, tensors[i].numDim, tensors[i].dims.data(), tensors[i].format), aclDestroyTensorDesc); if (tensorDesc == nullptr) { LogError << "Failed to create acl output tensor description."; return APP_ERR_COMM_INVALID_POINTER; } outputTensorDesc_.push_back(tensorDesc); void *outDevBuf = nullptr; size_t size = aclGetTensorDescSize(tensorDesc.get()); ret = aclrtMalloc(&outDevBuf, size, ACL_MEM_MALLOC_NORMAL_ONLY); if (ret != APP_ERR_OK) { LogError << "Failed to aclrtMalloc out result."; return ret; } std::shared_ptr<aclDataBuffer> dataBuf(aclCreateDataBuffer(outDevBuf, size), aclDestroyDataBuffer); if (dataBuf == nullptr) { LogError << "Failed to create acl output data buffer."; return APP_ERR_COMM_INVALID_POINTER; } outputDataBuf_.push_back(dataBuf); std::shared_ptr<void> data(outDevBuf, aclrtFree); outputData_.push_back(data); outputDataSize_.push_back(size); } return APP_ERR_OK; } void SingleOpProcess::SetInputTensorNum(int num) { inputTensorNum_ = num; } int SingleOpProcess::GetInputTensorNum() const { return inputTensorNum_; } void SingleOpProcess::SetOutputTensorNum(int num) { outputTensorNum_ = num; } int SingleOpProcess::GetOutputTensorNum() const { return outputTensorNum_; } std::vector<std::shared_ptr<void>> SingleOpProcess::GetOutputData() { return outputData_; } std::vector<size_t> SingleOpProcess::GetOutputDataSize() { return outputDataSize_; } APP_ERROR SingleOpProcess::SetOpAttr(std::shared_ptr<aclopAttr> attr, OpAttr attrDesc) { attr_ = attr; switch (attrDesc.type) { case BOOL: aclopSetAttrBool(attr.get(), attrDesc.name.c_str(), attrDesc.numBool); break; case INT: aclopSetAttrInt(attr.get(), attrDesc.name.c_str(), attrDesc.numInt); break; case FLOAT: aclopSetAttrFloat(attr.get(), attrDesc.name.c_str(), attrDesc.numFloat); break; case STRING: aclopSetAttrString(attr.get(), attrDesc.name.c_str(), attrDesc.numString.c_str()); break; case LIST_BOOL: aclopSetAttrListBool(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.valuesBool.data()); break; case LIST_INT: aclopSetAttrListInt(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.valuesInt.data()); break; case LIST_FLOAT: aclopSetAttrListFloat(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.valuesFloat.data()); break; case LIST_STRING: { const char **valuesString = new const char *[attrDesc.num]; for (int i = 0; i < attrDesc.num; i++) { valuesString[i] = attrDesc.valuesString[i].c_str(); } aclopSetAttrListString(attr.get(), attrDesc.name.c_str(), attrDesc.num, valuesString); delete[] valuesString; break; } case LIST_LIST_INT: { const int64_t **valuesListList = new const int64_t *[attrDesc.num]; for (int i = 0; i < attrDesc.num; i++) { valuesListList[i] = attrDesc.valuesListList[i].data(); } aclopSetAttrListListInt(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.numLists.data(), valuesListList); delete[] valuesListList; break; } default : break; } return APP_ERR_OK; } std::shared_ptr<aclopAttr> SingleOpProcess::GetOpAttr() { return attr_; } void SingleOpProcess::SetStream(aclrtStream stream) { stream_ = stream; } const aclrtStream& SingleOpProcess::GetStream() const { return stream_; } APP_ERROR SingleOpProcess::RunSingleOp(const bool &withHandle) { withHandle_ = withHandle; std::vector<aclTensorDesc *> inTensorDesc; for (auto tensor : inputTensorDesc_) { inTensorDesc.push_back(tensor.get()); } std::vector<aclDataBuffer *> inData; for (auto data : inputDataBuf_) { inData.push_back(data.get()); } std::vector<aclTensorDesc *> outTensorDesc; for (auto tensor : outputTensorDesc_) { outTensorDesc.push_back(tensor.get()); } std::vector<aclDataBuffer *> outData; for (auto data : outputDataBuf_) { outData.push_back(data.get()); } APP_ERROR ret = APP_ERR_OK; if (withHandle_ == true) { ret = aclopCreateHandle(typeName_.c_str(), inputTensorNum_, inTensorDesc.data(), outputTensorNum_, outTensorDesc.data(), attr_.get(), &opHandle_); if (ret != APP_ERR_OK) { LogError << typeName_ << "Failed to create handle, ret = " << ret; return ret; } ret = aclopExecWithHandle(opHandle_, inputTensorNum_, inData.data(), outputTensorNum_, outData.data(), stream_); if (ret != APP_ERR_OK) { LogError << typeName_ << "Failed to execute single operator with handle, ret = " << ret; return ret; } } else { ret = aclopExecute(typeName_.c_str(), inputTensorNum_, inTensorDesc.data(), inData.data(), outputTensorNum_, outTensorDesc.data(), outData.data(), attr_.get(), stream_); if (ret != APP_ERR_OK) { LogError << "Failed to execute singleOp: " << typeName_ << " ret = " << ret; return ret; } } return APP_ERR_OK; }
#include "SingleOpProcess.h" #include "acl/acl.h" SingleOpProcess::SingleOpProcess() : inputTensorNum_(0), outputTensorNum_(0), stream_(nullptr), attr_(nullptr), withHandle_(false), opHandle_(nullptr) {} SingleOpProcess::SingleOpProcess(const aclrtStream &stream) : inputTensorNum_(0), outputTensorNum_(0), attr_(nullptr), withHandle_(false), opHandle_(nullptr) { stream_ = stream; } SingleOpProcess::~SingleOpProcess() { if (withHandle_ == true) { aclopDestroyHandle(opHandle_); opHandle_ = nullptr; } s
e); } return APP_ERR_OK; } void SingleOpProcess::SetInputTensorNum(int num) { inputTensorNum_ = num; } int SingleOpProcess::GetInputTensorNum() const { return inputTensorNum_; } void SingleOpProcess::SetOutputTensorNum(int num) { outputTensorNum_ = num; } int SingleOpProcess::GetOutputTensorNum() const { return outputTensorNum_; } std::vector<std::shared_ptr<void>> SingleOpProcess::GetOutputData() { return outputData_; } std::vector<size_t> SingleOpProcess::GetOutputDataSize() { return outputDataSize_; } APP_ERROR SingleOpProcess::SetOpAttr(std::shared_ptr<aclopAttr> attr, OpAttr attrDesc) { attr_ = attr; switch (attrDesc.type) { case BOOL: aclopSetAttrBool(attr.get(), attrDesc.name.c_str(), attrDesc.numBool); break; case INT: aclopSetAttrInt(attr.get(), attrDesc.name.c_str(), attrDesc.numInt); break; case FLOAT: aclopSetAttrFloat(attr.get(), attrDesc.name.c_str(), attrDesc.numFloat); break; case STRING: aclopSetAttrString(attr.get(), attrDesc.name.c_str(), attrDesc.numString.c_str()); break; case LIST_BOOL: aclopSetAttrListBool(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.valuesBool.data()); break; case LIST_INT: aclopSetAttrListInt(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.valuesInt.data()); break; case LIST_FLOAT: aclopSetAttrListFloat(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.valuesFloat.data()); break; case LIST_STRING: { const char **valuesString = new const char *[attrDesc.num]; for (int i = 0; i < attrDesc.num; i++) { valuesString[i] = attrDesc.valuesString[i].c_str(); } aclopSetAttrListString(attr.get(), attrDesc.name.c_str(), attrDesc.num, valuesString); delete[] valuesString; break; } case LIST_LIST_INT: { const int64_t **valuesListList = new const int64_t *[attrDesc.num]; for (int i = 0; i < attrDesc.num; i++) { valuesListList[i] = attrDesc.valuesListList[i].data(); } aclopSetAttrListListInt(attr.get(), attrDesc.name.c_str(), attrDesc.num, attrDesc.numLists.data(), valuesListList); delete[] valuesListList; break; } default : break; } return APP_ERR_OK; } std::shared_ptr<aclopAttr> SingleOpProcess::GetOpAttr() { return attr_; } void SingleOpProcess::SetStream(aclrtStream stream) { stream_ = stream; } const aclrtStream& SingleOpProcess::GetStream() const { return stream_; } APP_ERROR SingleOpProcess::RunSingleOp(const bool &withHandle) { withHandle_ = withHandle; std::vector<aclTensorDesc *> inTensorDesc; for (auto tensor : inputTensorDesc_) { inTensorDesc.push_back(tensor.get()); } std::vector<aclDataBuffer *> inData; for (auto data : inputDataBuf_) { inData.push_back(data.get()); } std::vector<aclTensorDesc *> outTensorDesc; for (auto tensor : outputTensorDesc_) { outTensorDesc.push_back(tensor.get()); } std::vector<aclDataBuffer *> outData; for (auto data : outputDataBuf_) { outData.push_back(data.get()); } APP_ERROR ret = APP_ERR_OK; if (withHandle_ == true) { ret = aclopCreateHandle(typeName_.c_str(), inputTensorNum_, inTensorDesc.data(), outputTensorNum_, outTensorDesc.data(), attr_.get(), &opHandle_); if (ret != APP_ERR_OK) { LogError << typeName_ << "Failed to create handle, ret = " << ret; return ret; } ret = aclopExecWithHandle(opHandle_, inputTensorNum_, inData.data(), outputTensorNum_, outData.data(), stream_); if (ret != APP_ERR_OK) { LogError << typeName_ << "Failed to execute single operator with handle, ret = " << ret; return ret; } } else { ret = aclopExecute(typeName_.c_str(), inputTensorNum_, inTensorDesc.data(), inData.data(), outputTensorNum_, outTensorDesc.data(), outData.data(), attr_.get(), stream_); if (ret != APP_ERR_OK) { LogError << "Failed to execute singleOp: " << typeName_ << " ret = " << ret; return ret; } } return APP_ERR_OK; }
tream_ = nullptr; } void SingleOpProcess::SetTypeName(std::string typeName) { typeName_ = typeName; } std::string SingleOpProcess::GetTypeName() { return typeName_; } APP_ERROR SingleOpProcess::SetInputTensor(std::vector<Tensor> tensors) { inputTensorDesc_.clear(); for (int i = 0; i < inputTensorNum_; i++) { std::shared_ptr<aclTensorDesc> tensorDesc(aclCreateTensorDesc(tensors[i].dataType, tensors[i].numDim, tensors[i].dims.data(), tensors[i].format), aclDestroyTensorDesc); if (tensorDesc == nullptr) { LogError << "Failed to create acl input tensor description."; return APP_ERR_COMM_INVALID_POINTER; } inputTensorDesc_.push_back(tensorDesc); } return APP_ERR_OK; } APP_ERROR SingleOpProcess::SetInputDataBuffer(std::vector<std::shared_ptr<void>> inputDataBuf, std::vector<size_t> inputBufSize) { inputDataBuf_.clear(); inputData_ = inputDataBuf; for (int i = 0; i < inputTensorNum_; i++) { std::shared_ptr<aclDataBuffer> dataBuffer(aclCreateDataBuffer(inputDataBuf[i].get(), inputBufSize[i]), aclDestroyDataBuffer); if (dataBuffer == nullptr) { LogError << "Failed to create acl input data buffer."; return APP_ERR_COMM_INVALID_POINTER; } inputDataBuf_.push_back(dataBuffer); } return APP_ERR_OK; } APP_ERROR SingleOpProcess::SetOutputTensor(std::vector<Tensor> tensors) { outputTensorDesc_.clear(); outputDataBuf_.clear(); outputData_.clear(); outputDataSize_.clear(); APP_ERROR ret = APP_ERR_OK; for (int i = 0; i < outputTensorNum_; i++) { std::shared_ptr<aclTensorDesc> tensorDesc(aclCreateTensorDesc(tensors[i].dataType, tensors[i].numDim, tensors[i].dims.data(), tensors[i].format), aclDestroyTensorDesc); if (tensorDesc == nullptr) { LogError << "Failed to create acl output tensor description."; return APP_ERR_COMM_INVALID_POINTER; } outputTensorDesc_.push_back(tensorDesc); void *outDevBuf = nullptr; size_t size = aclGetTensorDescSize(tensorDesc.get()); ret = aclrtMalloc(&outDevBuf, size, ACL_MEM_MALLOC_NORMAL_ONLY); if (ret != APP_ERR_OK) { LogError << "Failed to aclrtMalloc out result."; return ret; } std::shared_ptr<aclDataBuffer> dataBuf(aclCreateDataBuffer(outDevBuf, size), aclDestroyDataBuffer); if (dataBuf == nullptr) { LogError << "Failed to create acl output data buffer."; return APP_ERR_COMM_INVALID_POINTER; } outputDataBuf_.push_back(dataBuf); std::shared_ptr<void> data(outDevBuf, aclrtFree); outputData_.push_back(data); outputDataSize_.push_back(siz
random
[ { "content": " uint8_t *data = nullptr; // Image data\n", "file_path": "atlas_npu/ascendbase/src/Base/CommonDataType/CommonDataType.h", "rank": 0, "score": 95849.1341938177 }, { "content": "template<typename T> FLATBUFFERS_CONSTEXPR inline bool IsConstTrue(T t) {\n\n return !!t;\n", "file_path": "tools/plugin/serializer/tf_lite/include/flatbuffers/base.h", "rank": 1, "score": 94599.07537217901 }, { "content": "", "file_path": "tests/model/cmdline.h", "rank": 2, "score": 80786.13377326139 }, { "content": "#include <iostream>\n\n#include <cstdlib>\n\n#include <string.h>\n\n\n\nnamespace TEngine {\n\n\n\nstatic inline std::string GetRealName(const char* name)\n\n{\n\n std::string result;\n\n\n\n char* real_name = abi::__cxa_demangle(name, nullptr, nullptr, nullptr);\n\n\n\n result = real_name;\n\n\n\n std::free(real_name);\n\n\n\n return result;\n\n}\n\n\n", "file_path": "include/any.hpp", "rank": 3, "score": 63985.22825560769 }, { "content": " void clear() noexcept\n\n {\n\n if(!empty())\n\n {\n\n this->vtable->destroy(storage);\n\n this->vtable = nullptr;\n\n }\n\n }\n\n\n\n /// Returns true if *this has no contained object, otherwise false.\n\n bool empty() const noexcept\n\n {\n\n return this->vtable == nullptr;\n\n }\n\n\n\n /// If *this has a contained object of type T, typeid(T); otherwise typeid(void).\n\n const std::type_info& type() const noexcept\n\n {\n\n return empty() ? typeid(void) : this->vtable->type();\n\n }\n", "file_path": "include/any.hpp", "rank": 4, "score": 63982.62558446608 }, { "content": " && !std::is_lvalue_reference<ValueType>::value>;\n\n#else\n\n using can_move = std::false_type;\n\n#endif\n\n\n\n auto p = any_cast<typename std::remove_reference<ValueType>::type>(&operand);\n\n if(p == nullptr) throw bad_any_cast(operand.type(),typeid(ValueType));\n\n return detail::any_cast_move_if_true<ValueType>(p, can_move());\n\n }\n\n\n\n /// If operand != nullptr && operand->type() == typeid(ValueType), a pointer to the object\n\n /// contained by operand, otherwise nullptr.\n\n template<typename T>\n\n inline const T* any_cast(const any* operand) noexcept\n\n {\n\n if(operand == nullptr || !operand->is_typed(typeid(T)))\n\n return nullptr;\n\n else\n\n return operand->cast<T>();\n\n }\n", "file_path": "include/any.hpp", "rank": 5, "score": 63982.25862811794 }, { "content": "\n\n /// If operand != nullptr && operand->type() == typeid(ValueType), a pointer to the object\n\n /// contained by operand, otherwise nullptr.\n\n template<typename T>\n\n inline T* any_cast(any* operand) noexcept\n\n {\n\n if(operand == nullptr || !operand->is_typed(typeid(T)))\n\n {\n\n if(operand != nullptr ) \n\n {\n\n std::cout << \"type is not same-----------------------\\n\";\n\n }\n\n return nullptr;\n\n }\n\n else\n\n return operand->cast<T>();\n\n }\n\n\n\n}\n\n\n\nnamespace std\n\n{\n\n inline void swap(TEngine::any& lhs, TEngine::any& rhs) noexcept\n\n {\n\n lhs.swap(rhs);\n\n }\n\n}\n", "file_path": "include/any.hpp", "rank": 6, "score": 63978.83896876326 }, { "content": "\n\n /// Exchange the states of *this and rhs.\n\n void swap(any& rhs) noexcept\n\n {\n\n if(this->vtable != rhs.vtable)\n\n {\n\n any tmp(std::move(rhs));\n\n\n\n // move from *this to rhs.\n\n rhs.vtable = this->vtable;\n\n if(this->vtable != nullptr)\n\n {\n\n this->vtable->move(this->storage, rhs.storage);\n\n // this->vtable = nullptr; -- uneeded, see below\n\n }\n\n\n\n // move from tmp (previously rhs) to *this.\n\n this->vtable = tmp.vtable;\n\n if(tmp.vtable != nullptr)\n\n {\n", "file_path": "include/any.hpp", "rank": 7, "score": 63978.24618443462 }, { "content": " inline ValueType any_cast_move_if_true(typename std::remove_reference<ValueType>::type* p, std::false_type)\n\n {\n\n return *p;\n\n }\n\n }\n\n \n\n /// Performs *any_cast<add_const_t<remove_reference_t<ValueType>>>(&operand), or throws bad_any_cast on failure.\n\n template<typename ValueType>\n\n inline ValueType any_cast(const any& operand)\n\n {\n\n auto p = any_cast<typename std::add_const<typename std::remove_reference<ValueType>::type>::type>(&operand);\n\n if(p == nullptr) throw bad_any_cast(operand.type(),typeid(ValueType));\n\n return *p;\n\n }\n\n \n\n /// Performs *any_cast<remove_reference_t<ValueType>>(&operand), or throws bad_any_cast on failure.\n\n template<typename ValueType>\n\n inline ValueType any_cast(any& operand)\n\n {\n\n auto p = any_cast<typename std::remove_reference<ValueType>::type>(&operand);\n", "file_path": "include/any.hpp", "rank": 8, "score": 63977.974402211235 }, { "content": "//\n\n// Implementation of N4562 std::experimental::any (merged into C++17) for C++11 compilers.\n\n//\n\n// See also:\n\n// + http://en.cppreference.com/w/cpp/any\n\n// + http://en.cppreference.com/w/cpp/experimental/any\n\n// + http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4562.html#any\n\n// + https://cplusplus.github.io/LWG/lwg-active.html#2509\n\n//\n\n//\n\n// Copyright (c) 2016 Denilson das Mercês Amorim\n\n//\n\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//\n\n#pragma once\n\n#include <typeinfo>\n\n#include <type_traits>\n\n#include <stdexcept>\n\n#include <cxxabi.h>\n", "file_path": "include/any.hpp", "rank": 9, "score": 63977.96271067128 }, { "content": " tmp.vtable->move(tmp.storage, this->storage);\n\n tmp.vtable = nullptr;\n\n }\n\n }\n\n else // same types\n\n {\n\n if(this->vtable != nullptr)\n\n this->vtable->swap(this->storage, rhs.storage);\n\n }\n\n }\n\n\n\nprivate: // Storage and Virtual Method Table\n\n union storage_union\n\n {\n\n using stack_storage_t = typename std::aligned_storage<2 * sizeof(void*), std::alignment_of<void*>::value>::type;\n\n\n\n void* dynamic;\n\n stack_storage_t stack; // 2 words for e.g. shared_ptr\n\n };\n\n\n", "file_path": "include/any.hpp", "rank": 10, "score": 63977.338314031615 }, { "content": " {\n\n using T = typename std::decay<ValueType>::type;\n\n \n\n this->vtable = vtable_for_type<T>();\n\n \n\n do_construct<ValueType,T>(std::forward<ValueType>(value));\n\n }\n\n };\n\n \n\n \n\n \n\n namespace detail\n\n {\n\n template<typename ValueType>\n\n inline ValueType any_cast_move_if_true(typename std::remove_reference<ValueType>::type* p, std::true_type)\n\n {\n\n return std::move(*p);\n\n }\n\n \n\n template<typename ValueType>\n", "file_path": "include/any.hpp", "rank": 11, "score": 63977.196861983124 }, { "content": " {\n\n rhs.vtable->move(rhs.storage, this->storage);\n\n rhs.vtable = nullptr;\n\n }\n\n }\n\n\n\n /// Same effect as this->clear().\n\n ~any()\n\n {\n\n this->clear();\n\n }\n\n\n\n /// Constructs an object of type any that contains an object of type T direct-initialized with\n\n /// std::forward<ValueType>(value).\n\n ///\n\n /// T shall satisfy the CopyConstructible requirements, otherwise the program is ill-formed.\n\n /// This is because an `any` may be copy constructed into another `any` at any time, so a copy should always be\n\n /// allowed.\n\n template <typename ValueType,\n\n typename = typename std::enable_if<!std::is_same<typename std::decay<ValueType>::type, any>::value>::type>\n", "file_path": "include/any.hpp", "rank": 12, "score": 63975.40664577657 }, { "content": " {\n\n dest.dynamic = new T(*reinterpret_cast<const T*>(src.dynamic));\n\n }\n\n\n\n static void move(storage_union& src, storage_union& dest) noexcept\n\n {\n\n dest.dynamic = src.dynamic;\n\n src.dynamic = nullptr;\n\n }\n\n\n\n static void swap(storage_union& lhs, storage_union& rhs) noexcept\n\n {\n\n // just exchage the storage pointers.\n\n std::swap(lhs.dynamic, rhs.dynamic);\n\n }\n\n };\n\n\n\n /// VTable for stack allocated storage.\n\n template <typename T> struct vtable_stack\n\n {\n", "file_path": "include/any.hpp", "rank": 13, "score": 63975.37536601211 }, { "content": " /// Base VTable specification.\n\n struct vtable_type\n\n {\n\n // Note: The caller is responssible for doing .vtable = nullptr after destructful operations\n\n // such as destroy() and/or move().\n\n\n\n /// The type of the object this vtable is for.\n\n const std::type_info& (*type)();\n\n\n\n /// Destroys the object in the union.\n\n /// The state of the union after this call is unspecified, caller must ensure not to use src anymore.\n\n void (*destroy)(storage_union&);\n\n\n\n /// Copies the **inner** content of the src union into the yet unitialized dest union.\n\n /// As such, both inner objects will have the same state, but on separate memory locations.\n\n void (*copy)(const storage_union& src, storage_union& dest);\n\n\n\n /// Moves the storage from src to the yet unitialized dest union.\n\n /// The state of src after this call is unspecified, caller must ensure not to use src anymore.\n\n void (*move)(storage_union& src, storage_union& dest);\n", "file_path": "include/any.hpp", "rank": 14, "score": 63974.68087761822 }, { "content": " if(p == nullptr) throw bad_any_cast(operand.type(),typeid(ValueType));\n\n return *p;\n\n }\n\n \n\n ///\n\n /// If ANY_IMPL_ANYCAST_MOVEABLE is not defined, does as N4562 specifies:\n\n /// Performs *any_cast<remove_reference_t<ValueType>>(&operand), or throws bad_any_cast on failure.\n\n ///\n\n /// If ANY_IMPL_ANYCAST_MOVEABLE is defined, does as LWG Defect 2509 specifies:\n\n /// If ValueType is MoveConstructible and isn't a lvalue reference, performs\n\n /// std::move(*any_cast<remove_reference_t<ValueType>>(&operand)), otherwise\n\n /// *any_cast<remove_reference_t<ValueType>>(&operand). Throws bad_any_cast on failure.\n\n ///\n\n template<typename ValueType>\n\n inline ValueType any_cast(any&& operand)\n\n {\n\n#ifdef ANY_IMPL_ANY_CAST_MOVEABLE\n\n // https://cplusplus.github.io/LWG/lwg-active.html#2509\n\n using can_move = std::integral_constant<bool,\n\n std::is_move_constructible<ValueType>::value\n", "file_path": "include/any.hpp", "rank": 15, "score": 63974.48045036043 }, { "content": " vtable_type* vtable;\n\n\n\n template<typename ValueType, typename T>\n\n typename std::enable_if<requires_allocation<T>::value>::type\n\n do_construct(ValueType&& value)\n\n {\n\n storage.dynamic = new T(std::forward<ValueType>(value));\n\n }\n\n\n\n template<typename ValueType, typename T>\n\n typename std::enable_if<!requires_allocation<T>::value>::type\n\n do_construct(ValueType&& value)\n\n {\n\n new (&storage.stack) T(std::forward<ValueType>(value));\n\n }\n\n \n\n /// Chooses between stack and dynamic allocation for the type decay_t<ValueType>,\n\n /// assigns the correct vtable, and constructs the object on our storage.\n\n template<typename ValueType>\n\n void construct(ValueType&& value)\n", "file_path": "include/any.hpp", "rank": 16, "score": 63971.322088202236 }, { "content": " any(ValueType&& value)\n\n {\n\n static_assert(std::is_copy_constructible<typename std::decay<ValueType>::type>::value,\n\n \"T shall satisfy the CopyConstructible requirements.\");\n\n this->construct(std::forward<ValueType>(value));\n\n }\n\n\n\n /// Has the same effect as any(rhs).swap(*this). No effects if an exception is thrown.\n\n any& operator=(const any& rhs)\n\n {\n\n any(rhs).swap(*this);\n\n return *this;\n\n }\n\n\n\n /// Has the same effect as any(std::move(rhs)).swap(*this).\n\n ///\n\n /// The state of *this is equivalent to the original state of rhs and rhs is left in a valid\n\n /// but otherwise unspecified state.\n\n any& operator=(any&& rhs) noexcept\n\n {\n", "file_path": "include/any.hpp", "rank": 17, "score": 63971.322088202236 }, { "content": "\n\n const char* what() const noexcept override\n\n {\n\n return GetMessage().c_str();\n\n }\n\n\n\nprivate:\n\n static std::string& GetMessage(void)\n\n {\n\n static std::string message;\n\n\n\n return message;\n\n }\n\n};\n\n\n", "file_path": "include/any.hpp", "rank": 18, "score": 63971.322088202236 }, { "content": " static const std::type_info& type() noexcept\n\n {\n\n return typeid(T);\n\n }\n\n\n\n static void destroy(storage_union& storage) noexcept\n\n {\n\n reinterpret_cast<T*>(&storage.stack)->~T();\n\n }\n\n\n\n static void copy(const storage_union& src, storage_union& dest)\n\n {\n\n new(&dest.stack) T(reinterpret_cast<const T&>(src.stack));\n\n }\n\n\n\n static void move(storage_union& src, storage_union& dest) noexcept\n\n {\n\n // one of the conditions for using vtable_stack is a nothrow move constructor,\n\n // so this move constructor will never throw a exception.\n\n new(&dest.stack) T(std::move(reinterpret_cast<T&>(src.stack)));\n", "file_path": "include/any.hpp", "rank": 19, "score": 63971.322088202236 }, { "content": " /// Returns the pointer to the vtable of the type T.\n\n template <typename T> static vtable_type* vtable_for_type()\n\n {\n\n using VTableType =\n\n typename std::conditional<requires_allocation<T>::value, vtable_dynamic<T>, vtable_stack<T>>::type;\n\n static vtable_type table = {\n\n VTableType::type, VTableType::destroy, VTableType::copy, VTableType::move, VTableType::swap,\n\n };\n\n return &table;\n\n }\n\n\n\nprotected:\n\n template <typename T> friend const T* any_cast(const any* operand) noexcept;\n\n template <typename T> friend T* any_cast(any* operand) noexcept;\n\n\n\n /// Same effect as is_same(this->type(), t);\n\n bool is_typed(const std::type_info& t) const\n\n {\n\n return is_same(this->type(), t);\n\n }\n", "file_path": "include/any.hpp", "rank": 20, "score": 63971.322088202236 }, { "content": " any(std::move(rhs)).swap(*this);\n\n return *this;\n\n }\n\n\n\n /// Has the same effect as any(std::forward<ValueType>(value)).swap(*this). No effect if a exception is thrown.\n\n ///\n\n /// T shall satisfy the CopyConstructible requirements, otherwise the program is ill-formed.\n\n /// This is because an `any` may be copy constructed into another `any` at any time, so a copy should always be\n\n /// allowed.\n\n template <typename ValueType,\n\n typename = typename std::enable_if<!std::is_same<typename std::decay<ValueType>::type, any>::value>::type>\n\n any& operator=(ValueType&& value)\n\n {\n\n static_assert(std::is_copy_constructible<typename std::decay<ValueType>::type>::value,\n\n \"T shall satisfy the CopyConstructible requirements.\");\n\n any(std::forward<ValueType>(value)).swap(*this);\n\n return *this;\n\n }\n\n\n\n /// If not empty, destroys the contained object.\n", "file_path": "include/any.hpp", "rank": 21, "score": 63971.322088202236 }, { "content": "\n\n /// Checks if two type infos are the same.\n\n ///\n\n /// If ANY_IMPL_FAST_TYPE_INFO_COMPARE is defined, checks only the address of the\n\n /// type infos, otherwise does an actual comparision. Checking addresses is\n\n /// only a valid approach when there's no interaction with outside sources\n\n /// (other shared libraries and such).\n\n static bool is_same(const std::type_info& a, const std::type_info& b)\n\n {\n\n#ifdef ANY_IMPL_FAST_TYPE_INFO_COMPARE\n\n return &a == &b;\n\n#else\n\n#ifdef __ANDROID__\n\n return a == b || strcmp(a.name(),b.name()) == 0;\n\n#else\n\n return a == b;\n\n#endif\n\n#endif\n\n }\n\n\n", "file_path": "include/any.hpp", "rank": 22, "score": 63971.322088202236 }, { "content": " /// Casts (with no type_info checks) the storage pointer as const T*.\n\n template<typename T>\n\n const T* cast() const noexcept\n\n {\n\n return requires_allocation<typename std::decay<T>::type>::value?\n\n reinterpret_cast<const T*>(storage.dynamic) :\n\n reinterpret_cast<const T*>(&storage.stack);\n\n }\n\n\n\n /// Casts (with no type_info checks) the storage pointer as T*.\n\n template<typename T>\n\n T* cast() noexcept\n\n {\n\n return requires_allocation<typename std::decay<T>::type>::value?\n\n reinterpret_cast<T*>(storage.dynamic) :\n\n reinterpret_cast<T*>(&storage.stack);\n\n }\n\n\n\nprivate:\n\n storage_union storage; // on offset(0) so no padding for align\n", "file_path": "include/any.hpp", "rank": 23, "score": 63971.322088202236 }, { "content": "\n\n /// Exchanges the storage between lhs and rhs.\n\n void (*swap)(storage_union& lhs, storage_union& rhs);\n\n };\n\n\n\n /// VTable for dynamically allocated storage.\n\n template <typename T> struct vtable_dynamic\n\n {\n\n static const std::type_info& type() noexcept\n\n {\n\n return typeid(T);\n\n }\n\n\n\n static void destroy(storage_union& storage) noexcept\n\n {\n\n // assert(reinterpret_cast<T*>(storage.dynamic));\n\n delete reinterpret_cast<T*>(storage.dynamic);\n\n }\n\n\n\n static void copy(const storage_union& src, storage_union& dest)\n", "file_path": "include/any.hpp", "rank": 24, "score": 63971.322088202236 }, { "content": " destroy(src);\n\n }\n\n\n\n static void swap(storage_union& lhs, storage_union& rhs) noexcept\n\n {\n\n std::swap(reinterpret_cast<T&>(lhs.stack), reinterpret_cast<T&>(rhs.stack));\n\n }\n\n };\n\n\n\n /// Whether the type T must be dynamically allocated or can be stored on the stack.\n\n template <typename T>\n\n struct requires_allocation\n\n : std::integral_constant<bool,\n\n !(std::is_nothrow_move_constructible<T>::value // N4562 §6.3/3 [any.class]\n\n && sizeof(T) <= sizeof(storage_union::stack) &&\n\n std::alignment_of<T>::value <=\n\n std::alignment_of<storage_union::stack_storage_t>::value)>\n\n {\n\n };\n\n\n", "file_path": "include/any.hpp", "rank": 25, "score": 63971.322088202236 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __ATTRIBUTE_HPP__\n\n#define __ATTRIBUTE_HPP__\n\n\n\n#include <unordered_map>\n\n#include <vector>\n\n\n\n#include \"any.hpp\"\n\n\n\nnamespace TEngine {\n", "file_path": "include/attribute.hpp", "rank": 26, "score": 62015.24685324209 }, { "content": " * Parts of the following code in this file refs to\n\n * https://github.com/Tencent/ncnn/blob/master/src/net.h\n\n * Tencent is pleased to support the open source community by making ncnn available.\n\n *\n\n * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.\n\n *\n\n * Licensed under the BSD 3-Clause License (the \"License\"); you may not use this\n\n * file except in compliance with the License. You may obtain a copy of the License at\n\n *\n\n * https://opensource.org/licenses/BSD-3-Clause\n\n */\n\n\n\n/*\n\n * Copyright (c) 2020, OPEN AI LAB\n\n * Author: [email protected]\n\n */\n\n\n\n#ifndef __NET_H__\n\n#define __NET_H__\n\n\n\n#include <vector>\n\n#include <string>\n\n#include <mutex>\n\n#include \"tengine_c_api.h\"\n\n\n\n/* layout type, not real layout */\n\n#define TENGINE_LAYOUT_NCHW 0\n\n#define TENGINE_LAYOUT_NHWC 1\n\n\n", "file_path": "core/include/net.h", "rank": 27, "score": 62014.1484040818 }, { "content": "#ifndef __COMPILER_HPP__\n\n#define __COMPILER_HPP__\n\n\n\n#include <string>\n\n\n\n#define DLLEXPORT __attribute__((visibility(\"default\")))\n\n\n\n#ifdef __ANDROID__\n\n\n\nnamespace std {\n\n\n\ntemplate <typename T> std::string to_string(T);\n\n}\n\n\n\n#endif\n\n\n\n#endif\n", "file_path": "include/compiler.hpp", "rank": 28, "score": 62013.173211708185 }, { "content": "\n\n return dict_map_.at(name);\n\n }\n\n\n\n virtual bool ExistAttr(const std::string& name) const\n\n {\n\n if(dict_map_.count(name))\n\n return true;\n\n else\n\n return false;\n\n }\n\n\n\n template <typename T> void GetAttr(const std::string& name, T* v, T default_v)\n\n {\n\n if(ExistAttr(name))\n\n {\n\n *v = any_cast<T>(GetAttr(name));\n\n }\n\n else\n\n {\n", "file_path": "include/attribute.hpp", "rank": 29, "score": 62012.55980372498 }, { "content": "\n\ninline Mat::Mat(int _w, int _h, size_t _elemsize, uint8_t _layout)\n\n : dim_num(0), layout(0), elemsize(0), elem_num(0), data(0), n(0), c(0), h(0), w(0)\n\n{\n\n create(_w, _h, _elemsize, _layout);\n\n}\n\n\n\ninline Mat::Mat(int _w, int _h, int _c, size_t _elemsize, uint8_t _layout)\n\n : dim_num(0), layout(0), elemsize(0), elem_num(0), data(0), n(0), c(0), h(0), w(0)\n\n{\n\n create(_w, _h, _c, _elemsize, _layout);\n\n}\n\n\n\ninline Mat::Mat(int _w, void* _data, size_t _elemsize, uint8_t _layout)\n\n : data(_data), elemsize(_elemsize), dims(1), w(_w), h(1), c(1)\n\n{\n\n cstep = w;\n\n}\n\n\n\ninline Mat::Mat(int _w, int _h, void* _data, size_t _elemsize, uint8_t _layout)\n", "file_path": "core/include/net.h", "rank": 30, "score": 62007.80628793925 }, { "content": "}\n\n\n\ninline float* Mat::row(int y)\n\n{\n\n return (float*)((unsigned char*)data + w * y * elemsize);\n\n}\n\n\n\ninline const float* Mat::row(int y) const\n\n{\n\n return (const float*)((unsigned char*)data + w * y * elemsize);\n\n}\n\n\n\ntemplate <typename T>\n\ninline T* Mat::row(int y)\n\n{\n\n return (T*)((unsigned char*)data + w * y * elemsize);\n\n}\n\n\n\ntemplate <typename T>\n\ninline const T* Mat::row(int y) const\n", "file_path": "core/include/net.h", "rank": 31, "score": 62007.80628793925 }, { "content": "{\n\n return Mat(w, rows, (unsigned char*)data + w * y * elemsize, elemsize);\n\n}\n\n\n\ninline Mat Mat::range(int x, int n)\n\n{\n\n return Mat(n, (unsigned char*)data + x * elemsize, elemsize);\n\n}\n\n\n\ninline const Mat Mat::range(int x, int n) const\n\n{\n\n return Mat(n, (unsigned char*)data + x * elemsize, elemsize);\n\n}\n\n\n\ntemplate <typename T>\n\ninline Mat::operator T*()\n\n{\n\n return (T*)data;\n\n}\n\n\n", "file_path": "core/include/net.h", "rank": 32, "score": 62007.80628793925 }, { "content": " int c;\n\n int h;\n\n int w;\n\n\n\n size_t cstep; \n\n\n\n // quantziation params\n\n std::vector<float> scales;\n\n std::vector<float> zero_points;\n\n};\n\n\n\ninline Mat::Mat() : dim_num(0), layout(0), elemsize(0), elem_num(0), data(0), n(0), c(0), h(0), w(0) \n\n{\n\n}\n\n\n\ninline Mat::Mat(int _w, size_t _elemsize, uint8_t _layout)\n\n : dim_num(0), layout(0), elemsize(0), elem_num(0), data(0), n(0), c(0), h(0), w(0)\n\n{\n\n create(_w, _elemsize, _layout);\n\n}\n", "file_path": "core/include/net.h", "rank": 33, "score": 62007.80628793925 }, { "content": " Mat reshape(int w, int h, int c) const;\n\n // allocate vec\n\n void create(int w, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // allocate image\n\n void create(int w, int h, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // allocate dim\n\n void create(int w, int h, int c, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n\n\n bool empty() const;\n\n size_t total() const;\n\n\n\n // shape only\n\n Mat shape() const; \n\n\n\n // data reference\n\n Mat channel(int c);\n\n const Mat channel(int c) const;\n\n float* row(int y);\n\n const float* row(int y) const;\n\n template<typename T> T* row(int y);\n", "file_path": "core/include/net.h", "rank": 34, "score": 62007.80628793925 }, { "content": "{\n\n return (const T*)((unsigned char*)data + w * y * elemsize);\n\n}\n\n\n\ninline Mat Mat::channel_range(int _c, int channels)\n\n{\n\n return Mat(w, h, channels, (unsigned char*)data + cstep * _c * elemsize, elemsize);\n\n}\n\n\n\ninline const Mat Mat::channel_range(int _c, int channels) const\n\n{\n\n return Mat(w, h, channels, (unsigned char*)data + cstep * _c * elemsize, elemsize);\n\n}\n\n\n\ninline Mat Mat::row_range(int y, int rows)\n\n{\n\n return Mat(w, rows, (unsigned char*)data + w * y * elemsize, elemsize);\n\n}\n\n\n\ninline const Mat Mat::row_range(int y, int rows) const\n", "file_path": "core/include/net.h", "rank": 35, "score": 62007.80628793925 }, { "content": " uint8_t layout;\n\n\n\n // element size in bytes\n\n // 4 = float32/int32\n\n // 2 = float16\n\n // 1 = int8/uint8\n\n // 0 = empty\n\n size_t elemsize;\n\n\n\n // total num\n\n int elem_num;\n\n\n\n // point data\n\n void* data;\n\n\n\n // the dimension rank\n\n int dims;\n\n\n\n // shape\n\n int n;\n", "file_path": "core/include/net.h", "rank": 36, "score": 62007.80628793925 }, { "content": " PIXEL_GRAY2RGB = PIXEL_GRAY | (PIXEL_RGB << PIXEL_CONVERT_SHIFT),\n\n PIXEL_GRAY2BGR = PIXEL_GRAY | (PIXEL_BGR << PIXEL_CONVERT_SHIFT),\n\n PIXEL_GRAY2RGBA = PIXEL_GRAY | (PIXEL_RGBA << PIXEL_CONVERT_SHIFT),\n\n PIXEL_GRAY2BGRA = PIXEL_GRAY | (PIXEL_BGRA << PIXEL_CONVERT_SHIFT),\n\n\n\n PIXEL_RGBA2RGB = PIXEL_RGBA | (PIXEL_RGB << PIXEL_CONVERT_SHIFT),\n\n PIXEL_RGBA2BGR = PIXEL_RGBA | (PIXEL_BGR << PIXEL_CONVERT_SHIFT),\n\n PIXEL_RGBA2GRAY = PIXEL_RGBA | (PIXEL_GRAY << PIXEL_CONVERT_SHIFT),\n\n PIXEL_RGBA2BGRA = PIXEL_RGBA | (PIXEL_BGRA << PIXEL_CONVERT_SHIFT),\n\n\n\n PIXEL_BGRA2RGB = PIXEL_BGRA | (PIXEL_RGB << PIXEL_CONVERT_SHIFT),\n\n PIXEL_BGRA2BGR = PIXEL_BGRA | (PIXEL_BGR << PIXEL_CONVERT_SHIFT),\n\n PIXEL_BGRA2GRAY = PIXEL_BGRA | (PIXEL_GRAY << PIXEL_CONVERT_SHIFT),\n\n PIXEL_BGRA2RGBA = PIXEL_BGRA | (PIXEL_RGBA << PIXEL_CONVERT_SHIFT),\n\n };\n\n // convenient construct from pixel data\n\n static Mat from_pixels(const unsigned char* pixels, int type, int w, int h);\n\n // convenient construct from pixel data with stride(bytes-per-row) parameter\n\n static Mat from_pixels(const unsigned char* pixels, int type, int w, int h, int stride);\n\n // convenient construct from pixel data and resize to specific size\n", "file_path": "core/include/net.h", "rank": 37, "score": 62007.80628793925 }, { "content": " Mat(int w, void* data, size_t elemsize, int elempack, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // external packed image\n\n Mat(int w, int h, void* data, size_t elemsize, int elempack, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // external packed dim\n\n Mat(int w, int h, int c, void* data, size_t elemsize, int elempack, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n\n\n // release\n\n ~Mat();\n\n // assign\n\n // Mat& operator=(const Mat& m);\n\n // set all\n\n void fill(float v);\n\n template <typename T> void fill(T v);\n\n // deep copy\n\n Mat clone() const;\n\n // reshape vec\n\n Mat reshape(int w) const;\n\n // reshape image\n\n Mat reshape(int w, int h) const;\n\n // reshape dim\n", "file_path": "core/include/net.h", "rank": 38, "score": 62007.80628793925 }, { "content": "class any final\n\n{\n\npublic:\n\n /// Constructs an object of type any with an empty state.\n\n any() : vtable(nullptr) {}\n\n\n\n /// Constructs an object of type any with an equivalent state as other.\n\n any(const any& rhs) : vtable(rhs.vtable)\n\n {\n\n if(!rhs.empty())\n\n {\n\n rhs.vtable->copy(rhs.storage, this->storage);\n\n }\n\n }\n\n\n\n /// Constructs an object of type any with a state equivalent to the original state of other.\n\n /// rhs is left in a valid but otherwise unspecified state.\n\n any(any&& rhs) noexcept : vtable(rhs.vtable)\n\n {\n\n if(!rhs.empty())\n", "file_path": "include/any.hpp", "rank": 39, "score": 62007.80628793925 }, { "content": " }\n\n\n\n virtual const any& GetAttr(const std::string& name) const\n\n {\n\n static any dummy;\n\n\n\n if(dict_map_.count(name))\n\n return dict_map_.at(name);\n\n\n\n return dummy;\n\n }\n\n\n\n void SetAttr(const std::string& name, any&& val)\n\n {\n\n dict_map_[name] = val;\n\n }\n\n\n\n void SetAttr(const std::string& name, const any& val)\n\n {\n\n dict_map_[name] = val;\n", "file_path": "include/attribute.hpp", "rank": 40, "score": 62007.80628793925 }, { "content": " int extract_tensor(float*& buffer, int& buffer_size, const char* node_name);\n\n // input data by tensor\n\n int input(std::string name, Mat& t);\n\n // output data by node num and tensor index\n\n int input_tensor(int node_index, int tensor_index, Mat& t);\n\n // output data by tensor\n\n int extract(std::string name, Mat& t);\n\n // output data by node num and tensor index\n\n int extract_tensor(int node_index, int tensor_index, Mat& t);\n\n\n\npublic:\n\n // set kenel mode\n\n static int set_kernel_mode(EKernelMode kernel_mode);\n\n // turn on/off wino\n\n static int switch_wino(bool is_open);\n\n // bind cpu \n\n static int set_worker_cpu_list(const int* cpu_list,int num);\n\n\n\n // run\n\n int run(int block = 1);\n", "file_path": "core/include/net.h", "rank": 41, "score": 62007.80628793925 }, { "content": " : data(_data), elemsize(_elemsize), dims(2), w(_w), h(_h), c(1)\n\n{\n\n cstep = w * h;\n\n}\n\n\n\ninline Mat::Mat(int _w, int _h, int _c, void* _data, size_t _elemsize, uint8_t _layout)\n\n : data(_data), elemsize(_elemsize), dims(3), w(_w), h(_h), c(_c)\n\n{\n\n cstep = w * h;\n\n}\n\n\n\n\n\ninline Mat Mat::channel(int _c)\n\n{\n\n return Mat(w, h, (unsigned char*)data + cstep * _c * elemsize, elemsize);\n\n}\n\n\n\ninline const Mat Mat::channel(int _c) const\n\n{\n\n return Mat(w, h, (unsigned char*)data + cstep * _c * elemsize, elemsize);\n", "file_path": "core/include/net.h", "rank": 42, "score": 62007.80628793925 }, { "content": " *v = default_v;\n\n }\n\n }\n\n\n\n template <typename T> void GetAttr(const std::string& name, T* v)\n\n {\n\n if(ExistAttr(name))\n\n {\n\n *v = any_cast<T>(GetAttr(name));\n\n }\n\n }\n\n\n\n virtual any& GetAttr(const std::string& name)\n\n {\n\n static any dummy;\n\n\n\n if(dict_map_.count(name))\n\n return dict_map_.at(name);\n\n\n\n return dummy;\n", "file_path": "include/attribute.hpp", "rank": 43, "score": 62007.80628793925 }, { "content": " return result;\n\n }\n\n\n\n virtual ~Attribute() {}\n\n\n\nprotected:\n\n attribute_map_t dict_map_;\n\n};\n\n\n\n#define INSERT_NEW_ATTRIBUTE(obj, name, val) obj[name] = val\n\n\n\n} // namespace TEngine\n\n#endif\n", "file_path": "include/attribute.hpp", "rank": 44, "score": 62007.80628793925 }, { "content": " PIXEL_CONVERT_SHIFT = 16,\n\n PIXEL_FORMAT_MASK = 0x0000ffff,\n\n PIXEL_CONVERT_MASK = 0xffff0000,\n\n\n\n PIXEL_RGB = 1,\n\n PIXEL_BGR = 2,\n\n PIXEL_GRAY = 3,\n\n PIXEL_RGBA = 4,\n\n PIXEL_BGRA = 5,\n\n\n\n PIXEL_RGB2BGR = PIXEL_RGB | (PIXEL_BGR << PIXEL_CONVERT_SHIFT),\n\n PIXEL_RGB2GRAY = PIXEL_RGB | (PIXEL_GRAY << PIXEL_CONVERT_SHIFT),\n\n PIXEL_RGB2RGBA = PIXEL_RGB | (PIXEL_RGBA << PIXEL_CONVERT_SHIFT),\n\n PIXEL_RGB2BGRA = PIXEL_RGB | (PIXEL_BGRA << PIXEL_CONVERT_SHIFT),\n\n\n\n PIXEL_BGR2RGB = PIXEL_BGR | (PIXEL_RGB << PIXEL_CONVERT_SHIFT),\n\n PIXEL_BGR2GRAY = PIXEL_BGR | (PIXEL_GRAY << PIXEL_CONVERT_SHIFT),\n\n PIXEL_BGR2RGBA = PIXEL_BGR | (PIXEL_RGBA << PIXEL_CONVERT_SHIFT),\n\n PIXEL_BGR2BGRA = PIXEL_BGR | (PIXEL_BGRA << PIXEL_CONVERT_SHIFT),\n\n\n", "file_path": "core/include/net.h", "rank": 45, "score": 62007.80628793925 }, { "content": "template <typename T>\n\ninline Mat::operator const T*() const\n\n{\n\n return (const T*)data;\n\n}\n\n\n\ninline float& Mat::operator[](size_t i)\n\n{\n\n return ((float*)data)[i];\n\n}\n\n\n\ninline const float& Mat::operator[](size_t i) const\n\n{\n\n return ((const float*)data)[i];\n\n}\n\n\n\n} // namespace tengine\n\n\n\n#endif\n", "file_path": "core/include/net.h", "rank": 46, "score": 62007.80628793925 }, { "content": " template<typename T> const T* row(int y) const;\n\n\n\n // range reference\n\n Mat channel_range(int c, int channels);\n\n const Mat channel_range(int c, int channels) const;\n\n Mat row_range(int y, int rows);\n\n const Mat row_range(int y, int rows) const;\n\n Mat range(int x, int n);\n\n const Mat range(int x, int n) const;\n\n\n\n // access raw data\n\n template<typename T> operator T*();\n\n template<typename T> operator const T*() const;\n\n\n\n // convenient access float vec element\n\n float& operator[](size_t i);\n\n const float& operator[](size_t i) const; \n\n\n\n enum PixelType\n\n {\n", "file_path": "core/include/net.h", "rank": 47, "score": 62007.80628793925 }, { "content": " static Mat from_pixels_resize(const unsigned char* pixels, int type, int w, int h, int target_width, int target_height);\n\n // convenient construct from pixel data and resize to specific size with stride(bytes-per-row) parameter\n\n static Mat from_pixels_resize(const unsigned char* pixels, int type, int w, int h, int stride, int target_width, int target_height);\n\n\n\n // convenient export to pixel data\n\n void to_pixels(unsigned char* pixels, int type) const;\n\n // convenient export to pixel data with stride(bytes-per-row) parameter\n\n void to_pixels(unsigned char* pixels, int type, int stride) const;\n\n // convenient export to pixel data and resize to specific size\n\n void to_pixels_resize(unsigned char* pixels, int type, int target_width, int target_height) const;\n\n // convenient export to pixel data and resize to specific size with stride(bytes-per-row) parameter\n\n void to_pixels_resize(unsigned char* pixels, int type, int target_width, int target_height, int target_stride) const;\n\n\n\n // substract channel-wise mean values, then multiply by normalize values, pass 0 to skip\n\n void substract_mean_normalize(const float* mean_vals, const float* norm_vals);\n\n\n\npublic:\n\n uint8_t dim_num;\n\n\n\n // nchw or nhwc\n", "file_path": "core/include/net.h", "rank": 48, "score": 62007.80628793925 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one\n\n * or more contributor license agreements. See the NOTICE file\n\n * distributed with this work for additional information\n\n * regarding copyright ownership. The ASF licenses this file\n\n * to you under the Apache License, Version 2.0 (the\n\n * License); you may not use this file except in compliance\n\n * with the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing,\n\n * software distributed under the License is distributed on an\n\n * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\n * KIND, either express or implied. See the License for the\n\n * specific language governing permissions and limitations\n\n * under the License.\n\n */\n\n\n\n/*\n", "file_path": "include/attribute.hpp", "rank": 49, "score": 62007.80628793925 }, { "content": " }\n\n\n\n void RemoveAttr(const std::string& name)\n\n {\n\n if(dict_map_.count(name))\n\n dict_map_.erase(name);\n\n }\n\n\n\n virtual std::vector<std::string> ListAttr(void) const\n\n {\n\n std::vector<std::string> result;\n\n\n\n std::unordered_map<std::string, any>::const_iterator begin = dict_map_.cbegin();\n\n\n\n while(begin != dict_map_.cend())\n\n {\n\n result.push_back(begin->first);\n\n begin++;\n\n }\n\n\n", "file_path": "include/attribute.hpp", "rank": 50, "score": 62007.80628793925 }, { "content": " void dump();\n\n\n\npublic:\n\n graph_t graph;\n\n bool b_preruned;\n\n std::mutex net_lock_;\n\n\n\n // ncnn model params\n\n std::string ncnn_param;\n\n std::string ncnn_model;\n\n\n\nprivate:\n\n // prerun\n\n int prerun();\n\n};\n\n\n", "file_path": "core/include/net.h", "rank": 51, "score": 62007.80628793925 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one\n\n * or more contributor license agreements. See the NOTICE file\n\n * distributed with this work for additional information\n\n * regarding copyright ownership. The ASF licenses this file\n\n * to you under the Apache License, Version 2.0 (the\n\n * License); you may not use this file except in compliance\n\n * with the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing,\n\n * software distributed under the License is distributed on an\n\n * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\n * KIND, either express or implied. See the License for the\n\n * specific language governing permissions and limitations\n\n * under the License.\n\n */\n\n\n\n/*\n", "file_path": "core/include/net.h", "rank": 52, "score": 62007.80628793925 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __LOGGER_HPP__\n\n#define __LOGGER_HPP__\n\n\n\n#include <iostream>\n\n#include <string>\n\n#include <memory>\n\n\n\n/* this file defines the interface of each logger implementation */\n\nnamespace TEngine {\n\n\n\nusing log_stream_t = std::unique_ptr<std::ostream>;\n\n\n", "file_path": "core/include/logger.hpp", "rank": 53, "score": 60173.180233206156 }, { "content": "\n\n return true;\n\n }\n\n\n\n return false;\n\n }\n\n\n\n bool SetItemFromAny(const std::string& name, const any& n)\n\n {\n\n ItemInfo* entry = FindItem(name, n.type().name());\n\n\n\n if(entry == nullptr)\n\n return SetItemCompatibleAny(name, n);\n\n\n\n entry->cpy_any(( char* )this + entry->data, n);\n\n\n\n return true;\n\n }\n\n\n\n const std::unordered_map<std::string, ItemInfo>& GetItemMap(void)\n", "file_path": "core/include/parameter.hpp", "rank": 54, "score": 60172.12329118258 }, { "content": " // skip type checking if type_name is nullptr\n\n if(type_name && entry.type_name && strcmp(type_name, entry.type_name))\n\n {\n\n // printf(\"requested: %s recorded:%s\\n\",item_type->name(),entry.type_info->name());\n\n return nullptr;\n\n }\n\n\n\n return &entry;\n\n }\n\n\n\n bool GetItemVal(const std::string& name, const char* type_name, void* val)\n\n {\n\n ItemInfo* entry = FindItem(name, type_name);\n\n\n\n if(entry == nullptr)\n\n return false;\n\n\n\n entry->cpy_func(val, ( char* )this + entry->data);\n\n\n\n return true;\n", "file_path": "core/include/parameter.hpp", "rank": 55, "score": 60172.02898119712 }, { "content": " }\n\n\n\n bool SetItemVal(const std::string& name, const char* type_name, const void* val)\n\n {\n\n ItemInfo* entry = FindItem(name, type_name);\n\n\n\n if(entry == nullptr)\n\n return false;\n\n\n\n entry->cpy_func(( char* )this + entry->data, val);\n\n\n\n return true;\n\n }\n\n\n\n bool SetItemCompatibleAny(const std::string& name, const any& n)\n\n {\n\n if(item_map_.count(name) == 0)\n\n return false;\n\n\n\n ItemInfo& entry = item_map_.at(name);\n", "file_path": "core/include/parameter.hpp", "rank": 56, "score": 60169.91284297931 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __SERIALIZER_HPP__\n\n#define __SERIALIZER_HPP__\n\n\n\n#include <vector>\n\n#include <string>\n\n#include <unordered_map>\n\n#include <functional>\n\n#include <memory>\n\n\n\n#include \"static_graph_interface.hpp\"\n\n#include \"generic_factory.hpp\"\n\n#include \"safe_object_manager.hpp\"\n\n#include \"graph.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/serializer.hpp", "rank": 57, "score": 60169.4665853381 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __GRAPH_HPP__\n\n#define __GRAPH_HPP__\n\n\n\n#include <vector>\n\n#include <string>\n\n#include <functional>\n\n\n\n#include \"base_object.hpp\"\n\n#include \"operator.hpp\"\n\n#include \"tensor.hpp\"\n\n#include \"node.hpp\"\n\n\n\n#include \"static_graph.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/graph.hpp", "rank": 58, "score": 60169.43609257588 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __OPERATOR_HPP__\n\n#define __OPERATOR_HPP__\n\n\n\n#include <functional>\n\n\n\n#include \"attribute.hpp\"\n\n#include \"base_object.hpp\"\n\n#include \"operator_manager.hpp\"\n\n#include \"generic_factory.hpp\"\n\n#include \"tensor_shape.hpp\"\n\n#include \"static_graph.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/operator.hpp", "rank": 59, "score": 60169.27324335657 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __TENSOR_HPP__\n\n#define __TENSOR_HPP__\n\n\n\n#include <iostream>\n\n#include <string>\n\n#include <atomic>\n\n\n\n#include \"base_object.hpp\"\n\n#include \"tensor_shape.hpp\"\n\n#include \"logger.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/tensor.hpp", "rank": 60, "score": 60169.26391969426 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __NOTIFY_HPP__\n\n#define __NOTIFY_HPP__\n\n\n\n#include <string>\n\n#include <vector>\n\n#include <iostream>\n\n#include <functional>\n\n\n\n#include \"any.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/notify.hpp", "rank": 61, "score": 60169.22669348157 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __NODE_HPP__\n\n#define __NODE_HPP__\n\n\n\n#include <vector>\n\n#include <string>\n\n\n\n#include \"base_object.hpp\"\n\n#include \"operator.hpp\"\n\n#include \"tensor.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/node.hpp", "rank": 62, "score": 60169.131301071284 }, { "content": "#ifndef __ALPHABETA_HPP__\n\n#define __ALPHABETA_HPP__\n\n\n\n#include <map>\n\n#include <iostream>\n\n#include <string>\n", "file_path": "core/include/alphabeta.hpp", "rank": 63, "score": 60169.12014610349 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#pragma once\n\n#include <type_traits>\n\n#include <typeinfo>\n\n#ifndef _MSC_VER\n\n#include <cxxabi.h>\n\n#endif\n\n#include <memory>\n\n#include <string>\n\n#include <cstdlib>\n\n// For Debug\n\n//获取类型易读的名称\n\nnamespace TEngine {\n\ntemplate <class T> static std::string type_name()\n\n{\n\n typedef typename std::remove_reference<T>::type TR;\n\n std::unique_ptr<char, void (*)(void*)> own(\n\n#if !defined(__GNUC__) || defined(NO_CXA_DEMANGLE)\n", "file_path": "include/type_name.hpp", "rank": 64, "score": 60168.9144046799 }, { "content": " {\n\n return name_;\n\n }\n\n\n\n Tensor* GetInputTensor(int idx)\n\n {\n\n NodePort* ptr = GetNodePort(inputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n\n\n\n return ptr->tensor;\n\n }\n\n\n\n const Tensor* GetInputTensor(int idx) const\n\n {\n\n const NodePort* ptr = GetNodePort(inputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n", "file_path": "core/include/node.hpp", "rank": 65, "score": 60168.698847534564 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __PARAMETER_HPP__\n\n#define __PARAMETER_HPP__\n\n\n\n#include <functional>\n\n#include <unordered_map>\n\n\n\n#include \"any.hpp\"\n\n\n\nnamespace TEngine {\n\n\n", "file_path": "core/include/parameter.hpp", "rank": 66, "score": 60168.676644152125 }, { "content": "\n\n return ptr->tensor;\n\n }\n\n\n\n Tensor* GetOutputTensor(int idx)\n\n {\n\n NodePort* ptr = GetNodePort(outputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n\n\n\n return ptr->tensor;\n\n }\n\n\n\n const Tensor* GetOutputTensor(int idx) const\n\n {\n\n const NodePort* ptr = GetNodePort(outputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n", "file_path": "core/include/node.hpp", "rank": 67, "score": 60168.6726341029 }, { "content": " nullptr,\n\n#else\n\n abi::__cxa_demangle(typeid(TR).name(), nullptr, nullptr, nullptr),\n\n#endif\n\n std::free);\n\n std::string r = own != nullptr ? own.get() : typeid(TR).name();\n\n if(std::is_const<TR>::value)\n\n r += \" const\";\n\n if(std::is_volatile<TR>::value)\n\n r += \" volatile\";\n\n if(std::is_lvalue_reference<T>::value)\n\n r += \"&\";\n\n else if(std::is_rvalue_reference<T>::value)\n\n r += \"&&\";\n\n return r;\n\n}\n\n\n\ntemplate <typename T> static void OutputTypeName(T&& t)\n\n{\n\n std::cout << type_name<T>() << std::endl;\n", "file_path": "include/type_name.hpp", "rank": 68, "score": 60168.6685150005 }, { "content": "\n\n return ptr->tensor;\n\n }\n\n\n\n NodePort* GetInputPort(int idx)\n\n {\n\n NodePort* ptr = GetNodePort(inputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n\n\n\n return ptr;\n\n }\n\n const NodePort* GetInputPort(int idx) const\n\n {\n\n const NodePort* ptr = GetNodePort(inputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n\n\n", "file_path": "core/include/node.hpp", "rank": 69, "score": 60168.64660417921 }, { "content": " return outputs_[idx].get();\n\n }\n\n\n\n const NodePort* GetOutputPort(int idx) const\n\n {\n\n const NodePort* ptr = GetNodePort(outputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n\n\n\n return ptr;\n\n }\n\n\n\n NodePort* GetOutputPort(int idx)\n\n {\n\n NodePort* ptr = GetNodePort(outputs_, idx);\n\n\n\n if(ptr == nullptr)\n\n return nullptr;\n\n\n", "file_path": "core/include/node.hpp", "rank": 70, "score": 60168.62075584324 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __NAMED_DATA_HPP__\n\n#define __NAMED_DATA_HPP__\n\n\n\n#include <iostream>\n\n#include <unordered_map>\n\n#include <vector>\n\n#include <string>\n\n\n\nnamespace TEngine {\n\n\n\ntemplate <typename T> struct NamedData\n\n{\n\n using map_t = std::unordered_map<std::string, T*>;\n\n\n\n static map_t& GetMap(void)\n\n {\n\n static map_t internal_map;\n", "file_path": "include/named_data.hpp", "rank": 71, "score": 60168.369109013496 }, { "content": " * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#ifndef __VARARG_HPP__\n\n#define __VARARG_HPP__\n\n\n\n/*provide utilities to print var args*/\n\n\n\n#include <iostream>\n\n#include <typeinfo>\n\n\n\n#include \"type_name.hpp\"\n\n\n\nstatic inline void VarArgPrint() {}\n\n\n\ntemplate <typename T, typename... Args> void VarArgPrint(std::ostream& os, T first, Args... args)\n\n{\n\n os << first << std::endl;\n\n\n\n VarArgPrint(os, args...);\n", "file_path": "core/include/vararg.hpp", "rank": 72, "score": 60167.7325730245 }, { "content": "\n\n bool AddNode(Node* node, bool set_owner = true);\n\n bool AddTensor(Tensor* tensor, bool set_owner = true);\n\n bool RemoveTensor(Tensor* tensor);\n\n bool RemoveNode(Node* node);\n\n\n\n bool CreateNodeFromStatic(Node*, const StaticGraph*, const StaticNode*);\n\n bool SetupConnection(Tensor*, const StaticGraph*, const StaticTensor*);\n\n\n\n bool RealCreateFromStatic(const StaticGraphPtr&);\n\n static Graph* CreateFromStatic(const std::string& graph_name, const StaticGraphPtr& static_graph);\n\n\n\n StaticGraphPtr& GetOrigGraph(void);\n\n\n\n std::vector<Node*> input_nodes;\n\n std::vector<Node*> output_nodes;\n\n std::vector<Node*> seq_nodes;\n\n\n\n static void BFSVisit(Graph* graph, std::vector<Node*>& starts, graph_visit_t func, bool backward = true,\n\n bool input_ready = true);\n", "file_path": "core/include/graph.hpp", "rank": 73, "score": 60167.19765367319 }, { "content": " {\n\n return version_;\n\n }\n\n\n\n /* helper functions */\n\n bool RegisterOpLoadMethod(const std::string& op_name, const any& load_func)\n\n {\n\n if(op_load_map_.count(op_name))\n\n return false;\n\n\n\n op_load_map_[op_name] = load_func;\n\n return true;\n\n }\n\n\n\n bool FindOpLoadMethod(const std::string& op_name)\n\n {\n\n if(op_load_map_.count(op_name))\n\n return true;\n\n\n\n return false;\n", "file_path": "core/include/serializer.hpp", "rank": 74, "score": 60167.1438659115 }, { "content": "}\n\n\n\ntemplate <typename T> static void OutputTypeNameToCerr(T&& t)\n\n{\n\n std::cerr << type_name<T>() << std::endl;\n\n}\n\n\n\ntemplate <typename T> static std::string GetNameForType(T&& t)\n\n{\n\n return \"org:\" + type_name<T>() + \" -- decay:\" + type_name<typename std::decay<T>::type>();\n\n}\n\n\n\nstatic std::string GetTypeName(const char* name)\n\n{\n\n#if !defined(__GNUC__) || defined(NO_CXA_DEMANGLE)\n\n return name;\n\n#else\n\n std::unique_ptr<char, void (*)(void*)> own(abi::__cxa_demangle(name, nullptr, nullptr, nullptr), std::free);\n\n std::string r = own.get();\n\n return r;\n\n#endif\n\n}\n\n\n\nstatic inline void OutputTypeName(const char* name)\n\n{\n\n std::cout << \"=== \" << GetTypeName(name) << std::endl;\n\n}\n\n} // namespace TEngine\n", "file_path": "include/type_name.hpp", "rank": 75, "score": 60167.04551902158 }, { "content": " }\n\n\n\n any& GetOpLoadMethod(const std::string& op_name)\n\n {\n\n return op_load_map_[op_name];\n\n }\n\n\n\n bool RegisterOpSaveMethod(const std::string& op_name, const any& save_func)\n\n {\n\n if(op_save_map_.count(op_name))\n\n return false;\n\n\n\n op_save_map_[op_name] = save_func;\n\n return true;\n\n }\n\n\n\n bool FindOpSaveMethod(const std::string& op_name)\n\n {\n\n if(op_save_map_.count(op_name))\n\n return true;\n", "file_path": "core/include/serializer.hpp", "rank": 76, "score": 60166.859460650805 }, { "content": "\n\n void AddConsumer(NodePort* in_port)\n\n {\n\n consumer.push_back(in_port);\n\n }\n\n\n\n bool RemoveConsumer(NodePort* in_port)\n\n {\n\n auto ir = consumer.begin();\n\n\n\n while(ir != consumer.end())\n\n {\n\n if((*ir) == in_port)\n\n {\n\n consumer.erase(ir);\n\n return true;\n\n }\n\n ir++;\n\n }\n\n\n", "file_path": "core/include/tensor.hpp", "rank": 77, "score": 60166.310835596625 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one\n\n * or more contributor license agreements. See the NOTICE file\n\n * distributed with this work for additional information\n\n * regarding copyright ownership. The ASF licenses this file\n\n * to you under the Apache License, Version 2.0 (the\n\n * License); you may not use this file except in compliance\n\n * with the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing,\n\n * software distributed under the License is distributed on an\n\n * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\n * KIND, either express or implied. See the License for the\n\n * specific language governing permissions and limitations\n\n * under the License.\n\n */\n\n\n\n/*\n\n * Copyright (c) 2017, Open AI Lab\n\n * Author: [email protected]\n\n */\n\n#pragma once\n\n#include <string>\n\n#include <stdexcept>\n\n\n\nnamespace TEngine {\n\nusing error_code_t = std::string;\n", "file_path": "include/te_error.hpp", "rank": 78, "score": 60166.02517001889 }, { "content": " auto ir = port_list.begin();\n\n\n\n while(ir != port_list.end())\n\n {\n\n if((*ir)->port_index == idx)\n\n return (*ir).get();\n\n ir++;\n\n }\n\n\n\n return nullptr;\n\n }\n\n\n\n void AddInputTensor(Tensor* tensor)\n\n {\n\n int idx = inputs_.size();\n\n\n\n SetInputPort(idx, tensor);\n\n }\n\n\n\n void AddOutputTensor(Tensor* tensor)\n", "file_path": "core/include/node.hpp", "rank": 79, "score": 60165.97954544696 }, { "content": " return internal_map;\n\n }\n\n\n\n static T* GetDefaultData(void)\n\n {\n\n return GetData(\"default\");\n\n }\n\n\n\n static void SetDefaultData(T* data)\n\n {\n\n SetData(\"default\", data);\n\n }\n\n\n\n static T* GetData(const std::string& name)\n\n {\n\n map_t& map = GetMap();\n\n\n\n if(map.count(name) == 0)\n\n return nullptr;\n\n\n", "file_path": "include/named_data.hpp", "rank": 80, "score": 60165.97954544696 }, { "content": "\n\n ir++;\n\n }\n\n }\n\n\n\n using Operator::ParseParam;\n\n virtual void ParseParam(P& param, Operator* op)\n\n {\n\n ParsePredefinedParam(param, op);\n\n }\n\n\n\n bool ParamFromStaticOp(StaticOp* s_op) override\n\n {\n\n param_ = any_cast<P>(s_op->param);\n\n\n\n return true;\n\n }\n\n\n\n any GetDefParam(void) override\n\n {\n", "file_path": "core/include/operator.hpp", "rank": 81, "score": 60165.946993333426 }, { "content": " dynamic_shape_ = val;\n\n return true;\n\n }\n\n\n\n bool InputReshaped(void)\n\n {\n\n Tensor* input = GetInputTensor(0);\n\n return input->Reshaped();\n\n }\n\n\n\n /*\n\n please note here the idx just for node,\n\n does not represent the tensor idx in in/out\n\n */\n\n\n\n int GetParentNum(void);\n\n Node* GetParentNode(int idx);\n\n\n\nprotected:\n\n OperatorPtr op_;\n", "file_path": "core/include/node.hpp", "rank": 82, "score": 60165.90514884025 }, { "content": " return ptr;\n\n }\n\n\n\n NodePort* GetNodePort(std::vector<NodePortPtr>& port_list, int idx)\n\n {\n\n auto ir = port_list.begin();\n\n\n\n while(ir != port_list.end())\n\n {\n\n if((*ir)->port_index == idx)\n\n return (*ir).get();\n\n\n\n ir++;\n\n }\n\n\n\n return nullptr;\n\n }\n\n\n\n const NodePort* GetNodePort(const std::vector<NodePortPtr>& port_list, int idx) const\n\n {\n", "file_path": "core/include/node.hpp", "rank": 83, "score": 60165.66220754082 }, { "content": " return RemoveNodePort(outputs_, idx);\n\n }\n\n\n\n bool RemoveInputPort(int idx)\n\n {\n\n return RemoveNodePort(inputs_, idx);\n\n }\n\n\n\n bool RemoveNodePort(std::vector<NodePortPtr>& port_list, int idx)\n\n {\n\n auto ir = port_list.begin();\n\n\n\n while(ir != port_list.end())\n\n {\n\n if((*ir)->port_index == idx)\n\n {\n\n port_list.erase(ir);\n\n return true;\n\n }\n\n ir++;\n", "file_path": "core/include/node.hpp", "rank": 84, "score": 60165.559523553056 }, { "content": "\n\n virtual bool GetParamItem(const char* param_name, const char* type_name, void* val)\n\n {\n\n return false;\n\n }\n\n virtual bool SetParamItem(const char* param_name, const char* type_name, const void* val)\n\n {\n\n return false;\n\n }\n\n\n\n virtual any GetDefParam(void)\n\n {\n\n return any();\n\n }\n\n\n\n virtual bool InferShape(const std::vector<TShape>& ishape, std::vector<TShape>& oshape, int layout)\n\n {\n\n oshape = ishape;\n\n return true;\n\n }\n", "file_path": "core/include/operator.hpp", "rank": 85, "score": 60165.4554122893 }, { "content": " return false;\n\n }\n\n\n\n NodePort* producer;\n\n std::vector<NodePort*> consumer;\n\n\n\n Node* GetConsumerNode(int idx);\n\n\n\n /* note: as tensor.hpp is defined in representation level,\n\n so that the memory allocated is only valid for const tensor\n\n to hold the trained parameters\n\n please use get_tensor_mem()/set_tensor_mem() to get/set tensor memory\n\n in operator run functioins\n\n\n\n */\n\n\n\n void* GetMemAddr(void) const\n\n {\n\n if(!ExistAttr(\"mem_addr\"))\n\n return nullptr;\n", "file_path": "core/include/tensor.hpp", "rank": 86, "score": 60165.384667001534 }, { "content": " const char* item_type = entry.type_name;\n\n const char* any_type = n.type().name();\n\n\n\n /* several special cases */\n\n if(!strcmp(item_type, typeid(const char*).name()) && !strcmp(any_type, typeid(std::string).name()))\n\n {\n\n const char** ptr = ( const char** )(( char* )this + entry.data);\n\n const std::string& str = any_cast<std::string>(n);\n\n\n\n ptr[0] = str.c_str(); // unsafe, since any may be destroyed soon\n\n\n\n return true;\n\n }\n\n\n\n if(!strcmp(item_type, typeid(std::string).name()) && !strcmp(any_type, typeid(const char*).name()))\n\n {\n\n std::string* p_str = ( std::string* )(( char* )this + entry.data);\n\n const char* ptr = any_cast<const char*>(n);\n\n\n\n *p_str = ptr;\n", "file_path": "core/include/parameter.hpp", "rank": 87, "score": 60164.87175056724 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one\n\n * or more contributor license agreements. See the NOTICE file\n\n * distributed with this work for additional information\n\n * regarding copyright ownership. The ASF licenses this file\n\n * to you under the Apache License, Version 2.0 (the\n\n * License); you may not use this file except in compliance\n\n * with the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing,\n\n * software distributed under the License is distributed on an\n\n * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\n * KIND, either express or implied. See the License for the\n\n * specific language governing permissions and limitations\n\n * under the License.\n\n */\n\n\n\n/*\n", "file_path": "core/include/node.hpp", "rank": 88, "score": 60161.23607884929 }, { "content": "class Mat\n\n{\n\npublic:\n\n // empty\n\n Mat();\n\n // vec\n\n Mat(int w, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // image\n\n Mat(int w, int h, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // dim\n\n Mat(int w, int h, int c, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // copy\n\n Mat(const Mat& m);\n\n // external vec\n\n Mat(int w, void* data, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // external image\n\n Mat(int w, int h, void* data, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // external dim\n\n Mat(int w, int h, int c, void* data, size_t elemsize = 4u, uint8_t layout = TENGINE_LAYOUT_NCHW);\n\n // external packed vec\n", "file_path": "core/include/net.h", "rank": 89, "score": 60161.23607884929 }, { "content": " port->owner = this;\n\n port->port_index = idx;\n\n port->tensor = tensor;\n\n auto ir = port_list.begin();\n\n\n\n while(ir != port_list.end())\n\n {\n\n if((*ir)->port_index == idx)\n\n {\n\n (*ir).reset(port);\n\n return;\n\n }\n\n ir++;\n\n }\n\n\n\n port_list.push_back(NodePortPtr(port));\n\n }\n\n\n\n bool RemoveOutputPort(int idx)\n\n {\n", "file_path": "core/include/node.hpp", "rank": 90, "score": 60161.23607884929 }, { "content": " }\n\n Operator* GetOp(void) const\n\n {\n\n return op_.get();\n\n }\n\n\n\n unsigned int GetInputNum(void) const\n\n {\n\n return inputs_.size();\n\n }\n\n unsigned int GetOutputNum(void) const\n\n {\n\n return outputs_.size();\n\n }\n\n\n\n int GetNodeIndex(void) const\n\n {\n\n return index_;\n\n }\n\n const std::string& GetName(void) const\n", "file_path": "core/include/node.hpp", "rank": 91, "score": 60161.23607884929 }, { "content": " virtual int CreateEvent(const std::string& name) = 0;\n\n virtual bool RemoveEvent(int event) = 0;\n\n virtual bool RemoveEvent(const std::string& name) = 0;\n\n\n\n virtual std::string EventName(int event) = 0;\n\n virtual int EventNum(const std::string& name) = 0;\n\n\n\n virtual std::string BusName() = 0;\n\n\n\n // Drop target pending events for this type of event, return dropped number\n\n virtual int DropPendingEvent(int event)\n\n {\n\n return 0;\n\n }\n\n\n\n // Drop all pending events, return dropped number\n\n virtual int DropPendingEvent()\n\n {\n\n return 0;\n\n }\n", "file_path": "core/include/notify.hpp", "rank": 92, "score": 60161.23607884929 }, { "content": " int event;\n\n int book_count;\n\n std::string name;\n\n uint32_t pending_count;\n\n uint64_t send_count;\n\n uint64_t sync_send_count;\n\n uint64_t drop_count;\n\n uint64_t process_count;\n\n uint64_t send_fail_count;\n\n\n\n void Dump(std::ostream& os)\n\n {\n\n os << \"event: \" << event << \" name: \" << name << \" booked handler: \" << book_count << std::endl;\n\n os << \"\\tsend \" << send_count << \" sync_send \" << sync_send_count << \" send fail \" << send_fail_count\n\n << \"\\n\";\n\n os << \"\\tpending \" << pending_count << \" process \" << process_count << \" drop \" << drop_count << \"\\n\";\n\n }\n\n };\n\n\n\n // Create/Register a new event on the bus, and return the event id\n", "file_path": "core/include/notify.hpp", "rank": 93, "score": 60161.23607884929 }, { "content": "\n\n virtual bool Send(const std::string& event_name, EventData* data, int priority = 10) = 0;\n\n virtual bool SyncSend(const std::string& event_name, EventData* data) = 0;\n\n virtual bool Book(const std::string& event_name, const EventHandle& handle) = 0;\n\n\n\n virtual bool Send(int event, EventData* data, int priority = 10) = 0;\n\n virtual bool SyncSend(int event, EventData* data) = 0;\n\n virtual bool Book(int event, const EventHandle& handle) = 0;\n\n\n\n virtual int ProcessAllEvents(void) = 0;\n\n virtual void SetBatchNum(int budget) = 0;\n\n virtual int GetBatchNum(void) = 0;\n\n\n\n virtual bool GetStats(int event, EventStats& stats) = 0;\n\n\n\n virtual ~EventBusInterface(){};\n\n};\n\n\n\nusing EventData = EventBusInterface::EventData;\n\nusing EventStats = EventBusInterface::EventStats;\n\nusing EventHandle = EventBusInterface::EventHandle;\n\n} // namespace TEngine\n\n\n\n#endif\n", "file_path": "core/include/notify.hpp", "rank": 94, "score": 60161.23607884929 }, { "content": "class Net\n\n{\n\npublic:\n\n // Net initial\n\n Net();\n\n // Net clear\n\n ~Net();\n\n\n\n int load_param(const char* protopath);\n\n int load_model(const char* modelpath);\n\n \n\n // load model\n\n int load_model(context_t context, const char* model_format, const char* model_file, ...);\n\n // set device\n\n int set_device(std::string device);\n\n // set input shape\n\n int input_shape(int n, int c, int h, int w, const char* node_name);\n\n // input data by buffer\n\n int input_tensor(const float* buffer, const int buffer_size, const char* node_name);\n\n // output data by buffer\n", "file_path": "core/include/net.h", "rank": 95, "score": 60161.23607884929 }, { "content": " {\n\n int idx = outputs_.size();\n\n\n\n SetOutputPort(idx, tensor);\n\n }\n\n\n\n void SetInputPort(unsigned int idx, Tensor* tensor)\n\n {\n\n SetNodePort(inputs_, idx, tensor);\n\n }\n\n\n\n void SetOutputPort(int idx, Tensor* tensor)\n\n {\n\n SetNodePort(outputs_, idx, tensor);\n\n }\n\n\n\n void SetNodePort(std::vector<NodePortPtr>& port_list, int idx, Tensor* tensor)\n\n {\n\n NodePort* port = new NodePort();\n\n\n", "file_path": "core/include/node.hpp", "rank": 96, "score": 60161.23607884929 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one\n\n * or more contributor license agreements. See the NOTICE file\n\n * distributed with this work for additional information\n\n * regarding copyright ownership. The ASF licenses this file\n\n * to you under the Apache License, Version 2.0 (the\n\n * License); you may not use this file except in compliance\n\n * with the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing,\n\n * software distributed under the License is distributed on an\n\n * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\n * KIND, either express or implied. See the License for the\n\n * specific language governing permissions and limitations\n\n * under the License.\n\n */\n\n\n\n/*\n", "file_path": "core/include/notify.hpp", "rank": 97, "score": 60161.23607884929 }, { "content": "class Mat;\n", "file_path": "core/include/net.h", "rank": 98, "score": 60161.23607884929 }, { "content": " return ptr;\n\n }\n\n\n\n Tensor* GetInputTensorSeq(int idx)\n\n {\n\n return GetInputPortSeq(idx)->tensor;\n\n }\n\n\n\n NodePort* GetInputPortSeq(int idx)\n\n {\n\n return inputs_[idx].get();\n\n }\n\n\n\n Tensor* GetOutputTensorSeq(int idx)\n\n {\n\n return GetOutputPortSeq(idx)->tensor;\n\n }\n\n\n\n NodePort* GetOutputPortSeq(int idx)\n\n {\n", "file_path": "core/include/node.hpp", "rank": 99, "score": 60161.23607884929 } ]
C++
src/scanner/src/scanner.cpp
zainmehdi/graphslam
7abb9fd99e03f422e98571b89c6fb03208a7a64f
#include "utils.hpp" #include "scanner.hpp" #include <iostream> int gicp_maximum_iterations; double gicp_maximum_correspondence_distance, gicp_transformation_epsilon, gicp_euclidean_fitness_epsilon; int loop_closure_skip; double fitness_keyframe_threshold, fitness_loop_threshold, distance_threshold, rotation_threshold; double k_disp_disp, k_rot_disp, k_rot_rot; double sigma_xy, sigma_th; ros::Publisher registration_pub; ros::Publisher pointcloud_debug_pub; ros::Publisher delta_pub; ros::ServiceClient keyframe_last_client; ros::ServiceClient keyframe_closest_client; pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> gicp; Eigen::Matrix4f carry_transform; unsigned int loop_closure_skip_count; using namespace scanner; Alignement gicp_register(const sensor_msgs::PointCloud2 input_1, const sensor_msgs::PointCloud2 input_2, Eigen::Matrix4f& transform){ pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_1 = format_pointcloud(input_1); pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_2 = format_pointcloud(input_2); gicp.setInputSource(pointcloud_1); gicp.setInputTarget(pointcloud_2); pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_transform(new pcl::PointCloud<pcl::PointXYZ>); gicp.align(*pointcloud_transform, transform); Alignement output; output.convergence_state = gicp.getConvergeCriteria()->getConvergenceState(); output.converged = gicp.hasConverged(); output.fitness = gicp.getFitnessScore(); if (gicp.hasConverged()) { transform = gicp.getFinalTransformation(); output.transform = transform; geometry_msgs::Pose2D transform_Delta = make_Delta(transform); Eigen::MatrixXd covariance_Delta = compute_covariance(sigma_xy, sigma_th); output.Delta = create_Pose2DWithCovariance_msg(transform_Delta, covariance_Delta); } return output; } Alignement gicp_register(const sensor_msgs::PointCloud2 input_1, const sensor_msgs::PointCloud2 input_2){ Eigen::Matrix4f guess_null(Eigen::Matrix4f::Identity()); return gicp_register(input_1, input_2, guess_null); } bool vote_for_keyframe(const common::Pose2DWithCovariance Delta, const double fitness) { if (fitness > fitness_keyframe_threshold) return true; if (fabs(Delta.pose.theta) > rotation_threshold) return true; if ((Delta.pose.x*Delta.pose.x+Delta.pose.y*Delta.pose.y) > distance_threshold*distance_threshold) return true; return false; } void scanner_callback(const sensor_msgs::LaserScan& input) { common::Registration output; output.first_frame_flag = false; output.keyframe_flag = false; output.loop_closure_flag = false; common::LastKeyframe keyframe_last_request; bool keyframe_last_request_returned = keyframe_last_client.call(keyframe_last_request); if (!keyframe_last_request_returned) { ROS_INFO("### NO LAST KEYFRAME FOUND : ASSUME FIRST KEYFRAME ###"); output.first_frame_flag = true; output.keyframe_new.scan = input; output.keyframe_new.pointcloud = scan_to_pointcloud(input); } if (keyframe_last_request_returned) { sensor_msgs::PointCloud2 input_pointcloud = scan_to_pointcloud(input); sensor_msgs::PointCloud2 keyframe_last_pointcloud = keyframe_last_request.response.keyframe_last.pointcloud; double start = ros::Time::now().toSec(); gicp.setMaxCorrespondenceDistance(0.5); Alignement alignement_last = gicp_register(input_pointcloud, keyframe_last_pointcloud, carry_transform); double end = ros::Time::now().toSec(); output.keyframe_flag = vote_for_keyframe(alignement_last.Delta, alignement_last.fitness); output.keyframe_new.ts = input.header.stamp; output.keyframe_new.pointcloud = input_pointcloud; output.keyframe_new.scan = input; output.keyframe_last = keyframe_last_request.response.keyframe_last; output.factor_new.id_1 = keyframe_last_request.response.keyframe_last.id; output.factor_new.id_2 = output.keyframe_new.id; output.factor_new.delta = alignement_last.Delta; if (output.keyframe_flag) { ROS_INFO("RG: align time: %f; fitness: %f", end - start, alignement_last.fitness); ROS_INFO_STREAM("RG: convergence state: " << convergence_text(alignement_last.convergence_state)); ROS_INFO("RG: Delta: %f %f %f", alignement_last.Delta.pose.x, alignement_last.Delta.pose.y, alignement_last.Delta.pose.theta); carry_transform.setIdentity(); loop_closure_skip_count++; if (loop_closure_skip_count >= loop_closure_skip) { common::ClosestKeyframe keyframe_closest_request; keyframe_closest_request.request.keyframe_last = keyframe_last_request.response.keyframe_last; bool keyframe_closest_request_returned = keyframe_closest_client.call(keyframe_closest_request); if (keyframe_closest_request_returned) { Eigen::Matrix4f T_last = make_transform(keyframe_last_request.response.keyframe_last.pose_opti.pose); Eigen::Matrix4f T_loop = make_transform(keyframe_closest_request.response.keyframe_closest.pose_opti.pose); Eigen::Matrix4f loop_transform = T_last.inverse()*T_loop; sensor_msgs::PointCloud2 keyframe_closest_pointcloud = keyframe_closest_request.response.keyframe_closest.pointcloud; start = ros::Time::now().toSec(); gicp.setMaxCorrespondenceDistance(1.0); Alignement alignement_loop = gicp_register(keyframe_closest_pointcloud, keyframe_last_pointcloud, loop_transform); end = ros::Time::now().toSec(); ROS_INFO("LC: align time: %f; fitness: %f", end - start, alignement_loop.fitness); ROS_INFO_STREAM("LC: convergence state: " << convergence_text(alignement_loop.convergence_state)); ROS_INFO("LC: Delta: %f %f %f", alignement_loop.Delta.pose.x, alignement_loop.Delta.pose.y, alignement_loop.Delta.pose.theta); output.loop_closure_flag = (alignement_loop.converged && alignement_loop.fitness < fitness_loop_threshold); output.keyframe_last = keyframe_last_request.response.keyframe_last; output.keyframe_loop = keyframe_closest_request.response.keyframe_closest; output.factor_loop.id_1 = keyframe_last_request.response.keyframe_last.id; output.factor_loop.id_2 = keyframe_closest_request.response.keyframe_closest.id; output.factor_loop.delta = alignement_loop.Delta; if (output.loop_closure_flag) loop_closure_skip_count = 0; } } } } registration_pub.publish(output); } int main(int argc, char** argv) { ros::init(argc, argv, "scanner"); ros::NodeHandle n; ros::Subscriber scanner_sub = n.subscribe("/base_scan", 1, scanner_callback); delta_pub = n.advertise<geometry_msgs::Pose2D>("/scanner/delta", 1); registration_pub = n.advertise<common::Registration>("/scanner/registration", 1); pointcloud_debug_pub = n.advertise<sensor_msgs::PointCloud2>("/scanner/debug_pointcloud", 1); keyframe_last_client = n.serviceClient<common::LastKeyframe>("/graph/last_keyframe"); keyframe_closest_client = n.serviceClient<common::ClosestKeyframe>("/graph/closest_keyframe"); gicp.setUseReciprocalCorrespondences(true); if(ros::param::get("/scanner/gicp_maximum_iterations", gicp_maximum_iterations)) { gicp.setMaximumIterations(gicp_maximum_iterations); ROS_INFO("ROSPARAM: [LOADED] /scanner/gicp_maximum_iterations = %d", gicp_maximum_iterations); } else { gicp_maximum_iterations = 50; gicp.setMaximumIterations(gicp_maximum_iterations); ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/gicp_maximum_iterations = %d", gicp_maximum_iterations); } if(ros::param::get("/scanner/gicp_maximum_correspondence_distance", gicp_maximum_correspondence_distance)) { gicp.setMaxCorrespondenceDistance(gicp_maximum_correspondence_distance); ROS_INFO("ROSPARAM: [LOADED] /scanner/gicp_maximum_correspondence_distance = %f", gicp_maximum_correspondence_distance); } else { gicp_maximum_correspondence_distance = 0.05; gicp.setMaxCorrespondenceDistance(gicp_maximum_correspondence_distance); ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/gicp_maximum_correspondence_distance = %f", gicp_maximum_correspondence_distance); } gicp_transformation_epsilon = 1e-8; gicp.setTransformationEpsilon(gicp_transformation_epsilon); if(ros::param::get("/scanner/gicp_euclidean_fitness_epsilon", gicp_euclidean_fitness_epsilon)) { gicp.setEuclideanFitnessEpsilon(gicp_euclidean_fitness_epsilon); ROS_INFO("ROSPARAM: [LOADED] /scanner/gicp_euclidean_fitness_epsilon = %f", gicp_euclidean_fitness_epsilon); } else { gicp_euclidean_fitness_epsilon = 1.0; gicp.setEuclideanFitnessEpsilon(gicp_euclidean_fitness_epsilon); ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/gicp_euclidean_fitness_epsilon = %f", gicp_euclidean_fitness_epsilon); } if(ros::param::get("/scanner/fitness_keyframe_threshold", fitness_keyframe_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/fitness_keyframe_threshold = %f", fitness_keyframe_threshold); } else { fitness_keyframe_threshold = 1.5; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/fitness_keyframe_threshold = %f", fitness_keyframe_threshold); } if(ros::param::get("/scanner/fitness_loop_threshold", fitness_loop_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/fitness_loop_threshold = %f", fitness_loop_threshold); } else { fitness_loop_threshold = 4.5; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/fitness_loop_threshold = %f", fitness_loop_threshold); } if(ros::param::get("/scanner/distance_threshold", distance_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/distance_threshold = %f", distance_threshold); } else { distance_threshold = 1.0; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/distance_threshold = %f", distance_threshold); } if(ros::param::get("/scanner/rotation_threshold", rotation_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/rotation_threshold = %f", rotation_threshold); } else { rotation_threshold = 1.0; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/rotation_threshold = %f", rotation_threshold); } if(ros::param::get("/scanner/loop_closure_skip", loop_closure_skip)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/loop_closure_skip = %d", loop_closure_skip); } else { loop_closure_skip = 4; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/loop_closure_skip = %d", loop_closure_skip); } if(ros::param::get("/scanner/k_disp_disp", k_disp_disp)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/k_disp_disp = %f", k_disp_disp); } else { k_disp_disp = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/k_disp_disp = %f", k_disp_disp); } if(ros::param::get("/scanner/k_rot_disp", k_rot_disp)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/k_rot_disp = %f", k_rot_disp); } else { k_rot_disp = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/k_rot_disp = %f", k_rot_disp); } if(ros::param::get("/scanner/k_rot_rot", k_rot_rot)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/k_rot_rot = %f", k_rot_rot); } else { k_rot_rot = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/k_rot_rot = %f", k_rot_rot); } if(ros::param::get("/scanner/sigma_xy", sigma_xy)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/sigma_xy = %f", sigma_xy); } else { sigma_xy = 0.002; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/sigma_xy = %f", sigma_xy); } if(ros::param::get("/scanner/sigma_th", sigma_th)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/sigma_th = %f", sigma_th); } else { sigma_th = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/sigma_th = %f", sigma_th); } ROS_INFO("ICP: max iter sim transf: %d", gicp.getConvergeCriteria()->getMaximumIterationsSimilarTransforms()); ROS_INFO("ICP: fail after max iter: %d ", gicp.getConvergeCriteria()->getFailureAfterMaximumIterations()); ROS_INFO("ICP: abs MSE : %f [x1e8]", 1e8*gicp.getConvergeCriteria()->getAbsoluteMSE()); ROS_INFO("ICP: rel MSE : %f ", gicp.getConvergeCriteria()->getRelativeMSE()); ROS_INFO("ICP: rot th : %f [rad]", acos(gicp.getConvergeCriteria()->getRotationThreshold())); ROS_INFO("ICP: trans th: %f [m]", sqrt(gicp.getConvergeCriteria()->getTranslationThreshold())); ROS_INFO("ICP: max iter: %d ", gicp.getConvergeCriteria()->getMaximumIterations()); ROS_INFO("ICP: RANSAC iter: %d ", int(gicp.getRANSACIterations())); gicp.getConvergeCriteria()->setMaximumIterationsSimilarTransforms(10); ROS_INFO("ICP: max iter sim transf: %d", gicp.getConvergeCriteria()->getMaximumIterationsSimilarTransforms()); carry_transform.setIdentity(); loop_closure_skip_count = 0; ros::spin(); return 0; }
#include "utils.hpp" #include "scanner.hpp" #include <iostream> int gicp_maximum_iterations; double gicp_maximum_correspondence_distance, gicp_transformation_epsilon, gicp_euclidean_fitness_epsilon; int loop_closure_skip; double fitness_keyframe_threshold, fitness_loop_threshold, distance_threshold, rotation_threshold; double k_disp_disp, k_rot_disp, k_rot_rot; double sigma_xy, sigma_th; ros::Publisher registration_pub; ros::Publisher pointcloud_debug_pub; ros::Publisher delta_pub; ros::ServiceClient keyframe_last_client; ros::ServiceClient keyframe_closest_client; pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> gicp; Eigen::Matrix4f carry_transform; unsigned int loop_closure_skip_count; using namespace scanner; Alignement gicp_register(const sensor_msgs::PointCloud2 input_1, const sensor_msgs::PointCloud2 input_2, Eigen::Matrix4f& transform){ pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_1 = format_pointcloud(input_1); pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_2 = format_pointcloud(input_2); gicp.setInputSource(pointcloud_1); gicp.setInputTarget(pointcloud_2); pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_transform(new pcl::PointCloud<pcl::PointXYZ>); gicp.align(*pointcloud_transform, transform); Alignement output; output.convergence_state = gicp.getConvergeCriteria()->getConvergenceState(); output.converged = gicp.hasConverged(); output.fitness = gicp.getFitnessScore(); if (gicp.hasConverged()) { transform = gicp.getFinalTransformation(); output.transform = transform; geometry_msgs::Pose2D transform_Delta = make_Delta(transform); Eigen::MatrixXd covariance_Delta = compute_covariance(sigma_xy, sigma_th); output.Delta = create_Pose2DWithCovariance_msg(transform_Delta, covariance_Delta); } return output; } Alignement gicp_register(const sensor_msgs::PointCloud2 input_1, const sensor_msgs::PointCloud2 input_2){ Eigen::Matrix4f guess_null(Eigen::Matrix4f::Identity()); return gicp_register(input_1, input_2, guess_null); } bool vote_for_keyframe(const common::Pose2DWithCovariance Delta, const double fitness) {
void scanner_callback(const sensor_msgs::LaserScan& input) { common::Registration output; output.first_frame_flag = false; output.keyframe_flag = false; output.loop_closure_flag = false; common::LastKeyframe keyframe_last_request; bool keyframe_last_request_returned = keyframe_last_client.call(keyframe_last_request); if (!keyframe_last_request_returned) { ROS_INFO("### NO LAST KEYFRAME FOUND : ASSUME FIRST KEYFRAME ###"); output.first_frame_flag = true; output.keyframe_new.scan = input; output.keyframe_new.pointcloud = scan_to_pointcloud(input); } if (keyframe_last_request_returned) { sensor_msgs::PointCloud2 input_pointcloud = scan_to_pointcloud(input); sensor_msgs::PointCloud2 keyframe_last_pointcloud = keyframe_last_request.response.keyframe_last.pointcloud; double start = ros::Time::now().toSec(); gicp.setMaxCorrespondenceDistance(0.5); Alignement alignement_last = gicp_register(input_pointcloud, keyframe_last_pointcloud, carry_transform); double end = ros::Time::now().toSec(); output.keyframe_flag = vote_for_keyframe(alignement_last.Delta, alignement_last.fitness); output.keyframe_new.ts = input.header.stamp; output.keyframe_new.pointcloud = input_pointcloud; output.keyframe_new.scan = input; output.keyframe_last = keyframe_last_request.response.keyframe_last; output.factor_new.id_1 = keyframe_last_request.response.keyframe_last.id; output.factor_new.id_2 = output.keyframe_new.id; output.factor_new.delta = alignement_last.Delta; if (output.keyframe_flag) { ROS_INFO("RG: align time: %f; fitness: %f", end - start, alignement_last.fitness); ROS_INFO_STREAM("RG: convergence state: " << convergence_text(alignement_last.convergence_state)); ROS_INFO("RG: Delta: %f %f %f", alignement_last.Delta.pose.x, alignement_last.Delta.pose.y, alignement_last.Delta.pose.theta); carry_transform.setIdentity(); loop_closure_skip_count++; if (loop_closure_skip_count >= loop_closure_skip) { common::ClosestKeyframe keyframe_closest_request; keyframe_closest_request.request.keyframe_last = keyframe_last_request.response.keyframe_last; bool keyframe_closest_request_returned = keyframe_closest_client.call(keyframe_closest_request); if (keyframe_closest_request_returned) { Eigen::Matrix4f T_last = make_transform(keyframe_last_request.response.keyframe_last.pose_opti.pose); Eigen::Matrix4f T_loop = make_transform(keyframe_closest_request.response.keyframe_closest.pose_opti.pose); Eigen::Matrix4f loop_transform = T_last.inverse()*T_loop; sensor_msgs::PointCloud2 keyframe_closest_pointcloud = keyframe_closest_request.response.keyframe_closest.pointcloud; start = ros::Time::now().toSec(); gicp.setMaxCorrespondenceDistance(1.0); Alignement alignement_loop = gicp_register(keyframe_closest_pointcloud, keyframe_last_pointcloud, loop_transform); end = ros::Time::now().toSec(); ROS_INFO("LC: align time: %f; fitness: %f", end - start, alignement_loop.fitness); ROS_INFO_STREAM("LC: convergence state: " << convergence_text(alignement_loop.convergence_state)); ROS_INFO("LC: Delta: %f %f %f", alignement_loop.Delta.pose.x, alignement_loop.Delta.pose.y, alignement_loop.Delta.pose.theta); output.loop_closure_flag = (alignement_loop.converged && alignement_loop.fitness < fitness_loop_threshold); output.keyframe_last = keyframe_last_request.response.keyframe_last; output.keyframe_loop = keyframe_closest_request.response.keyframe_closest; output.factor_loop.id_1 = keyframe_last_request.response.keyframe_last.id; output.factor_loop.id_2 = keyframe_closest_request.response.keyframe_closest.id; output.factor_loop.delta = alignement_loop.Delta; if (output.loop_closure_flag) loop_closure_skip_count = 0; } } } } registration_pub.publish(output); } int main(int argc, char** argv) { ros::init(argc, argv, "scanner"); ros::NodeHandle n; ros::Subscriber scanner_sub = n.subscribe("/base_scan", 1, scanner_callback); delta_pub = n.advertise<geometry_msgs::Pose2D>("/scanner/delta", 1); registration_pub = n.advertise<common::Registration>("/scanner/registration", 1); pointcloud_debug_pub = n.advertise<sensor_msgs::PointCloud2>("/scanner/debug_pointcloud", 1); keyframe_last_client = n.serviceClient<common::LastKeyframe>("/graph/last_keyframe"); keyframe_closest_client = n.serviceClient<common::ClosestKeyframe>("/graph/closest_keyframe"); gicp.setUseReciprocalCorrespondences(true); if(ros::param::get("/scanner/gicp_maximum_iterations", gicp_maximum_iterations)) { gicp.setMaximumIterations(gicp_maximum_iterations); ROS_INFO("ROSPARAM: [LOADED] /scanner/gicp_maximum_iterations = %d", gicp_maximum_iterations); } else { gicp_maximum_iterations = 50; gicp.setMaximumIterations(gicp_maximum_iterations); ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/gicp_maximum_iterations = %d", gicp_maximum_iterations); } if(ros::param::get("/scanner/gicp_maximum_correspondence_distance", gicp_maximum_correspondence_distance)) { gicp.setMaxCorrespondenceDistance(gicp_maximum_correspondence_distance); ROS_INFO("ROSPARAM: [LOADED] /scanner/gicp_maximum_correspondence_distance = %f", gicp_maximum_correspondence_distance); } else { gicp_maximum_correspondence_distance = 0.05; gicp.setMaxCorrespondenceDistance(gicp_maximum_correspondence_distance); ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/gicp_maximum_correspondence_distance = %f", gicp_maximum_correspondence_distance); } gicp_transformation_epsilon = 1e-8; gicp.setTransformationEpsilon(gicp_transformation_epsilon); if(ros::param::get("/scanner/gicp_euclidean_fitness_epsilon", gicp_euclidean_fitness_epsilon)) { gicp.setEuclideanFitnessEpsilon(gicp_euclidean_fitness_epsilon); ROS_INFO("ROSPARAM: [LOADED] /scanner/gicp_euclidean_fitness_epsilon = %f", gicp_euclidean_fitness_epsilon); } else { gicp_euclidean_fitness_epsilon = 1.0; gicp.setEuclideanFitnessEpsilon(gicp_euclidean_fitness_epsilon); ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/gicp_euclidean_fitness_epsilon = %f", gicp_euclidean_fitness_epsilon); } if(ros::param::get("/scanner/fitness_keyframe_threshold", fitness_keyframe_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/fitness_keyframe_threshold = %f", fitness_keyframe_threshold); } else { fitness_keyframe_threshold = 1.5; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/fitness_keyframe_threshold = %f", fitness_keyframe_threshold); } if(ros::param::get("/scanner/fitness_loop_threshold", fitness_loop_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/fitness_loop_threshold = %f", fitness_loop_threshold); } else { fitness_loop_threshold = 4.5; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/fitness_loop_threshold = %f", fitness_loop_threshold); } if(ros::param::get("/scanner/distance_threshold", distance_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/distance_threshold = %f", distance_threshold); } else { distance_threshold = 1.0; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/distance_threshold = %f", distance_threshold); } if(ros::param::get("/scanner/rotation_threshold", rotation_threshold)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/rotation_threshold = %f", rotation_threshold); } else { rotation_threshold = 1.0; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/rotation_threshold = %f", rotation_threshold); } if(ros::param::get("/scanner/loop_closure_skip", loop_closure_skip)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/loop_closure_skip = %d", loop_closure_skip); } else { loop_closure_skip = 4; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/loop_closure_skip = %d", loop_closure_skip); } if(ros::param::get("/scanner/k_disp_disp", k_disp_disp)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/k_disp_disp = %f", k_disp_disp); } else { k_disp_disp = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/k_disp_disp = %f", k_disp_disp); } if(ros::param::get("/scanner/k_rot_disp", k_rot_disp)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/k_rot_disp = %f", k_rot_disp); } else { k_rot_disp = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/k_rot_disp = %f", k_rot_disp); } if(ros::param::get("/scanner/k_rot_rot", k_rot_rot)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/k_rot_rot = %f", k_rot_rot); } else { k_rot_rot = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/k_rot_rot = %f", k_rot_rot); } if(ros::param::get("/scanner/sigma_xy", sigma_xy)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/sigma_xy = %f", sigma_xy); } else { sigma_xy = 0.002; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/sigma_xy = %f", sigma_xy); } if(ros::param::get("/scanner/sigma_th", sigma_th)) { ROS_INFO("ROSPARAM: [LOADED] /scanner/sigma_th = %f", sigma_th); } else { sigma_th = 0.001; ROS_WARN("ROSPARAM: [NOT LOADED][DEFAULT SET] /scanner/sigma_th = %f", sigma_th); } ROS_INFO("ICP: max iter sim transf: %d", gicp.getConvergeCriteria()->getMaximumIterationsSimilarTransforms()); ROS_INFO("ICP: fail after max iter: %d ", gicp.getConvergeCriteria()->getFailureAfterMaximumIterations()); ROS_INFO("ICP: abs MSE : %f [x1e8]", 1e8*gicp.getConvergeCriteria()->getAbsoluteMSE()); ROS_INFO("ICP: rel MSE : %f ", gicp.getConvergeCriteria()->getRelativeMSE()); ROS_INFO("ICP: rot th : %f [rad]", acos(gicp.getConvergeCriteria()->getRotationThreshold())); ROS_INFO("ICP: trans th: %f [m]", sqrt(gicp.getConvergeCriteria()->getTranslationThreshold())); ROS_INFO("ICP: max iter: %d ", gicp.getConvergeCriteria()->getMaximumIterations()); ROS_INFO("ICP: RANSAC iter: %d ", int(gicp.getRANSACIterations())); gicp.getConvergeCriteria()->setMaximumIterationsSimilarTransforms(10); ROS_INFO("ICP: max iter sim transf: %d", gicp.getConvergeCriteria()->getMaximumIterationsSimilarTransforms()); carry_transform.setIdentity(); loop_closure_skip_count = 0; ros::spin(); return 0; }
if (fitness > fitness_keyframe_threshold) return true; if (fabs(Delta.pose.theta) > rotation_threshold) return true; if ((Delta.pose.x*Delta.pose.x+Delta.pose.y*Delta.pose.y) > distance_threshold*distance_threshold) return true; return false; }
function_block-function_prefix_line
[ { "content": "struct Alignement{\n\n bool converged;\n\n float fitness;\n\n pcl::registration::DefaultConvergenceCriteria<float>::ConvergenceState convergence_state;\n\n Eigen::Matrix4f transform;\n\n common::Pose2DWithCovariance Delta;\n\n};\n\n\n\n\n\n/**\n\n * \\brief Create a human-readable text for the convergence criteria\n\n */\n\nstd::string convergence_text(pcl::registration::DefaultConvergenceCriteria<float>::ConvergenceState state)\n\n{\n\n std::string text;\n\n switch (state){ // defined in default_convergence_criteria.h, line 73\n\n case 0:\n\n return \"Not converged\";\n\n case 1:\n\n return \"Ierations\";\n", "file_path": "src/scanner/include/scanner.hpp", "rank": 0, "score": 76762.40281063394 }, { "content": "#include <common/ClosestKeyframe.h>\n\n\n\n#include <pcl/io/pcd_io.h>\n\n#include <pcl/conversions.h>\n\n#include <pcl/point_cloud.h>\n\n#include <pcl/point_types.h>\n\n#include <pcl/PCLPointCloud2.h>\n\n#include <pcl_ros/transforms.h>\n\n#include <pcl/registration/gicp.h>\n\n#include <pcl_conversions/pcl_conversions.h>\n\n\n\nnamespace scanner {\n\n\n\n/**\n\n * \\brief convert ROS LaserScan message to ROS pointcloud\n\n */\n\nsensor_msgs::PointCloud2 scan_to_pointcloud(sensor_msgs::LaserScan input) {\n\n\n\n laser_geometry::LaserProjection projector;\n\n sensor_msgs::PointCloud2 output;\n", "file_path": "src/scanner/include/scanner.hpp", "rank": 1, "score": 55168.284034836644 }, { "content": "#include <ros/ros.h>\n\n#include <ros/console.h>\n\n\n\n#include <sstream>\n\n#include <string>\n\n\n\n#include <tf/transform_listener.h>\n\n\n\n#include <geometry_msgs/Pose2D.h>\n\n\n\n#include <sensor_msgs/PointCloud2.h>\n\n#include <sensor_msgs/LaserScan.h>\n\n\n\n#include <laser_geometry/laser_geometry.h>\n\n\n\n#include <common/Factor.h>\n\n#include <common/Keyframe.h>\n\n#include <common/Registration.h>\n\n#include <common/Pose2DWithCovariance.h>\n\n#include <common/LastKeyframe.h>\n", "file_path": "src/scanner/include/scanner.hpp", "rank": 2, "score": 55160.66438011968 }, { "content": " projector.projectLaser(input, output);\n\n\n\n return output;\n\n}\n\n\n\n/**\n\n * \\brief convert ROS pointcloud to PCL pointcloud\n\n */\n\npcl::PointCloud<pcl::PointXYZ>::Ptr format_pointcloud(sensor_msgs::PointCloud2 input) {\n\n\n\n pcl::PCLPointCloud2 pcl2_pointcloud;\n\n pcl_conversions::toPCL(input, pcl2_pointcloud);\n\n\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr output(new pcl::PointCloud<pcl::PointXYZ>);\n\n pcl::fromPCLPointCloud2(pcl2_pointcloud, *output);\n\n\n\n return output;\n\n}\n\n\n\n/**\n\n * \\brief Alignement output\n\n */\n", "file_path": "src/scanner/include/scanner.hpp", "rank": 3, "score": 55159.95382963879 }, { "content": " case 2:\n\n return \"Transform\";\n\n case 3:\n\n return \"Abs MSE\";\n\n case 4:\n\n return \"Rel MSE\";\n\n case 5:\n\n return \"No correspondences \";\n\n default:\n\n break;\n\n }\n\n return text;\n\n}\n\n\n\n}\n\n\n", "file_path": "src/scanner/include/scanner.hpp", "rank": 4, "score": 55156.932660462124 }, { "content": "int main(int argc, char** argv) {\n\n ros::init(argc, argv, \"gicp\");\n\n ros::NodeHandle n;\n\n ros::Rate r(1);\n\n\n\n ros::Subscriber robot_0_scan_sub = n.subscribe(\"/robot_0/base_scan\", 1, robot_0_scanner_callback);\n\n ros::Subscriber robot_1_scan_sub = n.subscribe(\"/robot_1/base_scan\", 1, robot_1_scanner_callback);\n\n ros::Subscriber ground_truth_0_sub = n.subscribe(\"/robot_0/base_pose_ground_truth\", 1, robot_0_gt_callback);\n\n ros::Subscriber ground_truth_1_sub = n.subscribe(\"/robot_1/base_pose_ground_truth\", 1, robot_1_gt_callback);\n\n delta_pub = n.advertise<common::Pose2DWithCovariance>(\"/scanner/delta\", 1);\n\n\n\n // Setup GICP algorithm\n\n gicp.setUseReciprocalCorrespondences(true);\n\n gicp.setMaximumIterations(50); // ICP example 50\n\n gicp.setMaxCorrespondenceDistance(1); // ICP example 0.05\n\n gicp.setTransformationEpsilon(1e-8); // ICP example 1e-8\n\n gicp.setEuclideanFitnessEpsilon(0.01); // ICP example 1\n\n gicp.getConvergeCriteria()->setMaximumIterationsSimilarTransforms(10);\n\n // gicp.setRotationEpsilon();\n\n // gicp.setCorrespondenceRandomness();\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 5, "score": 50439.637806680796 }, { "content": "void gicp_register(sensor_msgs::PointCloud2 input_1,\n\n\t\t\t\t sensor_msgs::PointCloud2 input_2,\n\n\t\t\t\t Eigen::Matrix4f& transform) {\n\n double start = ros::Time::now().toSec();\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_1 = scanner::format_pointcloud(input_1);\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_2 = scanner::format_pointcloud(input_2);\n\n\n\n try {\n\n\tgicp.setInputTarget(pointcloud_1);\n\n gicp.setInputSource(pointcloud_2);\n\n\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_transform(new pcl::PointCloud<pcl::PointXYZ>);\n\n gicp.align(*pointcloud_transform, transform);\n\n }\n\n catch (int e) {\n\n std::cout << \"An exception occurred. Exception Nr. \" << e << '\\n';\n\n }\n\n\n\n ROS_INFO(\"#############################\");\n\n\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 6, "score": 50436.63303052532 }, { "content": " // gicp.setMaximumOptimizerIterations(50);\n\n\n\n carry_transform.setIdentity();\n\n int end = ros::Time::now().toSec() + 3;\n\n\n\n while(ros::ok()) {\n\n sensor_msgs::PointCloud2 robot_0_pointcloud = scanner::scan_to_pointcloud(robot_0_laserscan);\n\n sensor_msgs::PointCloud2 robot_1_pointcloud = scanner::scan_to_pointcloud(robot_1_laserscan);\n\n\n\n if(ros::Time::now().toSec() > end) {\n\n gicp_register(robot_0_pointcloud, robot_1_pointcloud, carry_transform);\n\n carry_transform = gicp.getFinalTransformation();\n\n }\n\n \n\n r.sleep();\n\n ros::spinOnce();\n\n }\n\n return 0;\n\n}\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 7, "score": 50435.8302223314 }, { "content": "#include <nav_msgs/Odometry.h>\n\n#include \"scanner.hpp\"\n\n#include \"utils.hpp\"\n\n#include \"../../../devel/include/common/Pose2DWithCovariance.h\"\n\n//#include \"Pose2DWithCovariance.h\"\n\n\n\nros::Publisher delta_pub;\n\n\n\nconst double fitness_keyframe_threshold = 0.5;\n\ndouble k_disp_disp = 0.1, k_rot_disp = 0.1, k_rot_rot = 0.1;\n\n\n\n//pcl::GeneralizedIterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> gicp;\n\npcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> gicp;\n\nEigen::Matrix4f carry_transform;\n\n\n\nsensor_msgs::LaserScan robot_0_laserscan;\n\nsensor_msgs::LaserScan robot_1_laserscan;\n\nnav_msgs::Odometry robot_1_gt;\n\nnav_msgs::Odometry robot_0_gt;\n\n\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 8, "score": 50435.50973156849 }, { "content": " ROS_INFO(\"Converged?: %d, Fitness Score: %f\", gicp.hasConverged(), gicp.getFitnessScore());\n\n ROS_INFO_STREAM(\"RG: convergence state: \" << scanner::convergence_text(gicp.getConvergeCriteria()->getConvergenceState()));\n\n // ROS_INFO(\"GT: x0 = %f; y1 = %f; th1 = %f\", robot_0_gt.pose.pose.position.x, robot_0_gt.pose.pose.position.y, tf::getYaw(robot_0_gt.pose.pose.orientation));\n\n // ROS_INFO(\"GT: x1 = %f; y1 = %f; th1 = %f\", robot_1_gt.pose.pose.position.x, robot_1_gt.pose.pose.position.y, tf::getYaw(robot_1_gt.pose.pose.orientation));\n\n ROS_INFO(\"GT: dx = %f; dy = %f; dth = %f\", Delta_01.pose.x, Delta_01.pose.y, Delta_01.pose.theta);\n\n ROS_INFO(\"RG: dx = %f; dy = %f; dth = %f\", Delta.pose.x, Delta.pose.y, Delta.pose.theta);\n\n // ROS_INFO(\"RG: sx = %f; sy = %f; sth = %f\", sqrt(Delta.covariance[0]), sqrt(Delta.covariance[4]), sqrt(Delta.covariance[8]));\n\n ROS_INFO(\"RG: ex = %f; ey = %f; eth = %f\", Delta_err.pose.x, Delta_err.pose.y, Delta_err.pose.theta);\n\n double end = ros::Time::now().toSec();\n\n ROS_INFO(\"Time to Completion: %f seconds\", end - start);\n\n ROS_INFO(\"#############################\");\n\n\n\n delta_pub.publish(Delta);\n\n}\n\n\n\nvoid gicp_register(sensor_msgs::PointCloud2 input_1, sensor_msgs::PointCloud2 input_2) {\n\n Eigen::Matrix4f guess_null(Eigen::Matrix4f::Identity());\n\n gicp_register(input_1, input_2, guess_null);\n\n}\n\n\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 9, "score": 50433.61672896298 }, { "content": " // Ground Truth (GT):\n\n common::Pose2DWithCovariance pose_0, pose_1;\n\n pose_0.pose.x = robot_0_gt.pose.pose.position.x;\n\n pose_0.pose.y = robot_0_gt.pose.pose.position.y;\n\n pose_0.pose.theta = tf::getYaw(robot_0_gt.pose.pose.orientation);\n\n pose_1.pose.x = robot_1_gt.pose.pose.position.x;\n\n pose_1.pose.y = robot_1_gt.pose.pose.position.y;\n\n pose_1.pose.theta = tf::getYaw(robot_1_gt.pose.pose.orientation);\n\n common::Pose2DWithCovariance Delta_01 = between(pose_0, pose_1);\n\n\n\n // Register (RG):\n\n transform = gicp.getFinalTransformation();\n\n geometry_msgs::Pose2D transform_Delta = make_Delta(transform);\n\n Eigen::MatrixXd covariance_Delta = compute_covariance(k_disp_disp, k_rot_disp, k_rot_rot, transform_Delta);\n\n common::Pose2DWithCovariance Delta = create_Pose2DWithCovariance_msg(transform_Delta, covariance_Delta);\n\n\n\n // Error\n\n common::Pose2DWithCovariance Delta_err = between(Delta_01, Delta);\n\n\n\n // Print\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 10, "score": 50432.62620875282 }, { "content": "void robot_0_scanner_callback(const sensor_msgs::LaserScan& input) {\n\n robot_0_laserscan = input;\n\n// ROS_INFO(\"robot_0_laserscan received.\");\n\n}\n\n\n\nvoid robot_1_scanner_callback(const sensor_msgs::LaserScan& input) {\n\n robot_1_laserscan = input;\n\n// ROS_INFO(\"robot_1_laserscan received.\");\n\n}\n\n\n\nvoid robot_0_gt_callback(const nav_msgs::Odometry& input) {\n\n robot_0_gt = input;\n\n// ROS_INFO(\"robot_0_gt received.\");\n\n}\n\n\n\nvoid robot_1_gt_callback(const nav_msgs::Odometry& input) {\n\n robot_1_gt = input;\n\n// ROS_INFO(\"robot_1_gt received.\");\n\n}\n\n\n", "file_path": "src/scanner/src/gicp.cpp", "rank": 11, "score": 50426.32514255785 }, { "content": " struct Parameters {\n\n bool use_penalty = false; /// if use_penalty then penalty method else ADMM or ALM (see max_inner)\n\n double p = 1.0; /// p norm\n\n double mu = 10.0; /// penalty weight\n\n double alpha = 1.2; /// penalty increase factor\n\n double max_mu = 1e5; /// max penalty\n\n int max_icp = 100; /// max ICP iteration\n\n int max_outer = 100; /// max outer iteration\n\n int max_inner = 1; /// max inner iteration. If max_inner=1 then ADMM else ALM\n\n double stop = 1e-5; /// stopping criteria\n\n bool print_icpn = false; /// (debug) print ICP iteration \n\n };\n\n /// Shrinkage operator (Automatic loop unrolling using template)\n\n template<unsigned int I>\n\n inline double shrinkage(double mu, double n, double p, double s) {\n\n return shrinkage<I-1>(mu, n, p, 1.0 - (p/mu)*std::pow(n, p-2.0)*std::pow(s, p-1.0));\n\n }\n\n template<>\n\n inline double shrinkage<0>(double, double, double, double s) {return s;}\n\n /// 3D Shrinkage for point-to-point\n", "file_path": "src/common/include/ICP.h", "rank": 32, "score": 23066.77250637627 }, { "content": " X.colwise() += X_mean;\n\n Y.colwise() += X_mean;\n\n /// Return transformation\n\n return transformation;\n\n }\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Target normals (one 3D normal per column)\n\n /// @param Confidence weights\n\n template <typename Derived1, typename Derived2, typename Derived3, typename Derived4>\n\n inline Eigen::Affine3d point_to_plane(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Yp,\n\n Eigen::MatrixBase<Derived3>& Yn,\n\n const Eigen::MatrixBase<Derived4>& w) {\n\n return point_to_plane(X, Yp, Yn, w, Eigen::VectorXd::Zero(X.cols()));\n\n }\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\n/// ICP implementation using ADMM/ALM/Penalty method\n\nnamespace SICP {\n", "file_path": "src/common/include/ICP.h", "rank": 33, "score": 23064.42660963145 }, { "content": " }\n\n return s;\n\n }\n\n /// Returns the dim'th component of the idx'th point in the class:\n\n inline num_t kdtree_get_pt(const size_t idx, int dim) const {\n\n return m_data_matrix.coeff(dim,idx);\n\n }\n\n /// Optional bounding-box computation: return false to default to a standard bbox computation loop.\n\n template <class BBOX> bool kdtree_get_bbox(BBOX&) const {return false;}\n\n };\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\n/// Compute the rigid motion for point-to-point and point-to-plane distances\n\nnamespace RigidMotionEstimator {\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Confidence weights\n\n template <typename Derived1, typename Derived2, typename Derived3>\n\n Eigen::Affine3d point_to_point(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Y,\n", "file_path": "src/common/include/ICP.h", "rank": 34, "score": 23063.508629972377 }, { "content": " }\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\n/// ICP implementation using iterative reweighting\n\nnamespace ICP {\n\n enum Function {\n\n PNORM,\n\n TUKEY,\n\n FAIR,\n\n LOGISTIC,\n\n TRIMMED,\n\n NONE\n\n };\n", "file_path": "src/common/include/ICP.h", "rank": 35, "score": 23063.07241532191 }, { "content": "///////////////////////////////////////////////////////////////////////////////\n\n/// \"Sparse Iterative Closest Point\"\n\n/// by Sofien Bouaziz, Andrea Tagliasacchi, Mark Pauly\n\n/// Copyright (C) 2013 LGG, EPFL\n\n///////////////////////////////////////////////////////////////////////////////\n\n/// 1) This file contains different implementations of the ICP algorithm.\n\n/// 2) This code requires EIGEN and NANOFLANN.\n\n/// 3) If OPENMP is activated some part of the code will be parallelized.\n\n/// 4) This code is for now designed for 3D registration\n\n/// 5) Two main input types are Eigen::Matrix3Xd or Eigen::Map<Eigen::Matrix3Xd>\n\n///////////////////////////////////////////////////////////////////////////////\n\n/// namespace nanoflann: NANOFLANN KD-tree adaptor for EIGEN\n\n/// namespace RigidMotionEstimator: functions to compute the rigid motion\n\n/// namespace SICP: sparse ICP implementation\n\n/// namespace ICP: reweighted ICP implementation\n\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef ICP_H\n\n#define ICP_H\n\n#include <nanoflann.hpp>\n\n#include <Eigen/Dense>\n", "file_path": "src/common/include/ICP.h", "rank": 36, "score": 23062.769735555277 }, { "content": " template<unsigned int I>\n\n inline void shrink(Eigen::Matrix3Xd& Q, double mu, double p) {\n\n double Ba = std::pow((2.0/mu)*(1.0-p), 1.0/(2.0-p));\n\n double ha = Ba + (p/mu)*std::pow(Ba, p-1.0);\n\n #pragma omp parallel for\n\n for(int i=0; i<Q.cols(); ++i) {\n\n double n = Q.col(i).norm();\n\n double w = 0.0;\n\n if(n > ha) w = shrinkage<I>(mu, n, p, (Ba/n + 1.0)/2.0);\n\n Q.col(i) *= w;\n\n }\n\n }\n\n /// 1D Shrinkage for point-to-plane\n\n template<unsigned int I>\n\n inline void shrink(Eigen::VectorXd& y, double mu, double p) {\n\n double Ba = std::pow((2.0/mu)*(1.0-p), 1.0/(2.0-p));\n\n double ha = Ba + (p/mu)*std::pow(Ba, p-1.0);\n\n #pragma omp parallel for\n\n for(int i=0; i<y.rows(); ++i) {\n\n double n = std::abs(y(i));\n", "file_path": "src/common/include/ICP.h", "rank": 37, "score": 23062.622228793727 }, { "content": " }\n\n }\n\n /// @param Residuals\n\n /// @param Parameter\n\n void logistic_weight(Eigen::VectorXd& r, double p) {\n\n for(int i=0; i<r.rows(); ++i) {\n\n r(i) = (p/r(i))*std::tanh(r(i)/p);\n\n }\n\n }\n\n struct sort_pred {\n\n bool operator()(const std::pair<int,double> &left,\n\n const std::pair<int,double> &right) {\n\n return left.second < right.second;\n\n }\n\n };\n\n /// @param Residuals\n\n /// @param Parameter\n\n void trimmed_weight(Eigen::VectorXd& r, double p) {\n\n std::vector<std::pair<int, double> > sortedDist(r.rows());\n\n for(int i=0; i<r.rows(); ++i) {\n", "file_path": "src/common/include/ICP.h", "rank": 38, "score": 23062.49779311258 }, { "content": " #pragma omp section\n\n for(int i=0; i<C.cols(); i++) {\n\n double dist_to_plane = -((X.col(i) - Y.col(i)).dot(N.col(i)) - u(i))*w(i);\n\n RHS.head<3>() += C.col(i)*dist_to_plane;\n\n RHS.tail<3>() += N.col(i)*dist_to_plane;\n\n }\n\n }\n\n }\n\n LHS = LHS.selfadjointView<Eigen::Upper>();\n\n /// Compute transformation\n\n Eigen::Affine3d transformation;\n\n Eigen::LDLT<Matrix66> ldlt(LHS);\n\n RHS = ldlt.solve(RHS);\n\n transformation = Eigen::AngleAxisd(RHS(0), Eigen::Vector3d::UnitX()) *\n\n Eigen::AngleAxisd(RHS(1), Eigen::Vector3d::UnitY()) *\n\n Eigen::AngleAxisd(RHS(2), Eigen::Vector3d::UnitZ());\n\n transformation.translation() = RHS.tail<3>();\n\n /// Apply transformation\n\n X = transformation*X;\n\n /// Re-apply mean\n", "file_path": "src/common/include/ICP.h", "rank": 39, "score": 23062.01527369365 }, { "content": " }\n\n transformation.translation().noalias() = Y_mean - transformation.linear()*X_mean;\n\n /// Apply transformation\n\n X = transformation*X;\n\n /// Re-apply mean\n\n X.colwise() += X_mean;\n\n Y.colwise() += Y_mean;\n\n /// Return transformation\n\n return transformation;\n\n }\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n template <typename Derived1, typename Derived2>\n\n inline Eigen::Affine3d point_to_point(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Y) {\n\n return point_to_point(X, Y, Eigen::VectorXd::Ones(X.cols()));\n\n }\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Target normals (one 3D normal per column)\n", "file_path": "src/common/include/ICP.h", "rank": 40, "score": 23061.958471708796 }, { "content": " const Eigen::MatrixBase<Derived3>& w) {\n\n /// Normalize weight vector\n\n Eigen::VectorXd w_normalized = w/w.sum();\n\n /// De-mean\n\n Eigen::Vector3d X_mean, Y_mean;\n\n for(int i=0; i<3; ++i) {\n\n X_mean(i) = (X.row(i).array()*w_normalized.transpose().array()).sum();\n\n Y_mean(i) = (Y.row(i).array()*w_normalized.transpose().array()).sum();\n\n }\n\n X.colwise() -= X_mean;\n\n Y.colwise() -= Y_mean;\n\n /// Compute transformation\n\n Eigen::Affine3d transformation;\n\n Eigen::Matrix3d sigma = X * w_normalized.asDiagonal() * Y.transpose();\n\n Eigen::JacobiSVD<Eigen::Matrix3d> svd(sigma, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n if(svd.matrixU().determinant()*svd.matrixV().determinant() < 0.0) {\n\n Eigen::Vector3d S = Eigen::Vector3d::Ones(); S(2) = -1.0;\n\n transformation.linear().noalias() = svd.matrixV()*S.asDiagonal()*svd.matrixU().transpose();\n\n } else {\n\n transformation.linear().noalias() = svd.matrixV()*svd.matrixU().transpose();\n", "file_path": "src/common/include/ICP.h", "rank": 41, "score": 23061.082279632057 }, { "content": "///////////////////////////////////////////////////////////////////////////////\n\nnamespace nanoflann {\n\n /// KD-tree adaptor for working with data directly stored in an Eigen Matrix, without duplicating the data storage.\n\n /// This code is adapted from the KDTreeEigenMatrixAdaptor class of nanoflann.hpp\n\n template <class MatrixType, int DIM = -1, class Distance = nanoflann::metric_L2, typename IndexType = int>\n\n struct KDTreeAdaptor {\n\n typedef KDTreeAdaptor<MatrixType,DIM,Distance> self_t;\n\n typedef typename MatrixType::Scalar num_t;\n\n typedef typename Distance::template traits<num_t,self_t>::distance_t metric_t;\n\n typedef KDTreeSingleIndexAdaptor< metric_t,self_t,DIM,IndexType> index_t;\n\n index_t* index;\n\n KDTreeAdaptor(const MatrixType &mat, const int leaf_max_size = 10) : m_data_matrix(mat) {\n\n const size_t dims = mat.rows();\n\n index = new index_t( dims, *this, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size, dims ) );\n\n index->buildIndex();\n\n }\n\n ~KDTreeAdaptor() {delete index;}\n\n const MatrixType &m_data_matrix;\n\n /// Query for the num_closest closest points to a given point (entered as query_point[0:dim-1]).\n\n inline void query(const num_t *query_point, const size_t num_closest, IndexType *out_indices, num_t *out_distances_sq) const {\n", "file_path": "src/common/include/ICP.h", "rank": 42, "score": 23060.207613351267 }, { "content": " /// @param Residuals\n\n /// @param Parameter\n\n void pnorm_weight(Eigen::VectorXd& r, double p, double reg=1e-8) {\n\n for(int i=0; i<r.rows(); ++i) {\n\n r(i) = p/(std::pow(r(i),2-p) + reg);\n\n }\n\n }\n\n /// @param Residuals\n\n /// @param Parameter\n\n void tukey_weight(Eigen::VectorXd& r, double p) {\n\n for(int i=0; i<r.rows(); ++i) {\n\n if(r(i) > p) r(i) = 0.0;\n\n else r(i) = std::pow((1.0 - std::pow(r(i)/p,2.0)), 2.0);\n\n }\n\n }\n\n /// @param Residuals\n\n /// @param Parameter\n\n void fair_weight(Eigen::VectorXd& r, double p) {\n\n for(int i=0; i<r.rows(); ++i) {\n\n r(i) = 1.0/(1.0 + r(i)/p);\n", "file_path": "src/common/include/ICP.h", "rank": 43, "score": 23059.85834898821 }, { "content": " for(int icp=0; icp<par.max_icp; ++icp) {\n\n if(par.print_icpn) std::cout << \"Iteration #\" << icp << \"/\" << par.max_icp << std::endl;\n\n \n\n /// Find closest point\n\n #pragma omp parallel for\n\n for(int i=0; i<X.cols(); ++i) {\n\n int id = kdtree.closest(X.col(i).data());\n\n Qp.col(i) = Y.col(id);\n\n Qn.col(i) = N.col(id);\n\n }\n\n /// Computer rotation and translation\n\n double mu = par.mu;\n\n for(int outer=0; outer<par.max_outer; ++outer) {\n\n double dual = 0.0;\n\n for(int inner=0; inner<par.max_inner; ++inner) {\n\n /// Z update (shrinkage)\n\n Z = (Qn.array()*(X-Qp).array()).colwise().sum().transpose()+C.array()/mu;\n\n shrink<3>(Z, mu, par.p);\n\n /// Rotation and translation update\n\n Eigen::VectorXd U = Z-C/mu;\n", "file_path": "src/common/include/ICP.h", "rank": 44, "score": 23059.818361668596 }, { "content": " /// ICP\n\n for(int icp=0; icp<par.max_icp; ++icp) {\n\n /// Find closest point\n\n #pragma omp parallel for\n\n for(int i=0; i<X.cols(); ++i) {\n\n int id = kdtree.closest(X.col(i).data());\n\n Qp.col(i) = Y.col(id);\n\n Qn.col(i) = N.col(id);\n\n }\n\n /// Computer rotation and translation\n\n for(int outer=0; outer<par.max_outer; ++outer) {\n\n /// Compute weights\n\n W = (Qn.array()*(X-Qp).array()).colwise().sum().abs().transpose();\n\n robust_weight(par.f, W, par.p);\n\n /// Rotation and translation update\n\n RigidMotionEstimator::point_to_plane(X, Qp, Qn, W);\n\n /// Stopping criteria\n\n double stop1 = (X-Xo1).colwise().norm().maxCoeff();\n\n Xo1 = X;\n\n if(stop1 < par.stop) break;\n", "file_path": "src/common/include/ICP.h", "rank": 45, "score": 23059.65815033402 }, { "content": " Eigen::Matrix3Xd Xo2 = X;\n\n /// ICP\n\n for(int icp=0; icp<par.max_icp; ++icp) {\n\n if(par.print_icpn) std::cout << \"Iteration #\" << icp << \"/\" << par.max_icp << std::endl;\n\n /// Find closest point\n\n #pragma omp parallel for\n\n for(int i=0; i<X.cols(); ++i) {\n\n Q.col(i) = Y.col(kdtree.closest(X.col(i).data()));\n\n }\n\n /// Computer rotation and translation\n\n double mu = par.mu;\n\n for(int outer=0; outer<par.max_outer; ++outer) {\n\n double dual = 0.0;\n\n for(int inner=0; inner<par.max_inner; ++inner) {\n\n /// Z update (shrinkage)\n\n Z = X-Q+C/mu;\n\n shrink<3>(Z, mu, par.p);\n\n /// Rotation and translation update\n\n Eigen::Matrix3Xd U = Q+Z-C/mu;\n\n RigidMotionEstimator::point_to_point(X, U);\n", "file_path": "src/common/include/ICP.h", "rank": 46, "score": 23059.6005283802 }, { "content": " Matrix66 LHS = Matrix66::Zero();\n\n Vector6 RHS = Vector6::Zero();\n\n Block33 TL = LHS.topLeftCorner<3,3>();\n\n Block33 TR = LHS.topRightCorner<3,3>();\n\n Block33 BR = LHS.bottomRightCorner<3,3>();\n\n Eigen::MatrixXd C = Eigen::MatrixXd::Zero(3,X.cols());\n\n #pragma omp parallel\n\n {\n\n #pragma omp for\n\n for(int i=0; i<X.cols(); i++) {\n\n C.col(i) = X.col(i).cross(N.col(i));\n\n }\n\n #pragma omp sections nowait\n\n {\n\n #pragma omp section\n\n for(int i=0; i<X.cols(); i++) TL.selfadjointView<Eigen::Upper>().rankUpdate(C.col(i), w(i));\n\n #pragma omp section\n\n for(int i=0; i<X.cols(); i++) TR += (C.col(i)*N.col(i).transpose())*w(i);\n\n #pragma omp section\n\n for(int i=0; i<X.cols(); i++) BR.selfadjointView<Eigen::Upper>().rankUpdate(N.col(i), w(i));\n", "file_path": "src/common/include/ICP.h", "rank": 47, "score": 23059.581770015913 }, { "content": " sortedDist[i] = std::pair<int, double>(i,r(i));\n\n }\n\n std::sort(sortedDist.begin(), sortedDist.end(), sort_pred());\n\n r.setZero();\n\n int nbV = r.rows()*p;\n\n for(int i=0; i<nbV; ++i) {\n\n r(sortedDist[i].first) = 1.0;\n\n }\n\n }\n\n /// @param Function type\n\n /// @param Residuals\n\n /// @param Parameter\n\n void robust_weight(Function f, Eigen::VectorXd& r, double p) {\n\n switch(f) {\n\n case PNORM: pnorm_weight(r,p); break;\n\n case TUKEY: tukey_weight(r,p); break;\n\n case FAIR: fair_weight(r,p); break;\n\n case LOGISTIC: logistic_weight(r,p); break;\n\n case TRIMMED: trimmed_weight(r,p); break;\n\n case NONE: uniform_weight(r); break;\n", "file_path": "src/common/include/ICP.h", "rank": 48, "score": 23059.53850550873 }, { "content": " #pragma omp parallel for\n\n for(int i=0; i<X.cols(); ++i) {\n\n Q.col(i) = Y.col(kdtree.closest(X.col(i).data()));\n\n }\n\n /// Computer rotation and translation\n\n for(int outer=0; outer<par.max_outer; ++outer) {\n\n /// Compute weights\n\n W = (X-Q).colwise().norm();\n\n robust_weight(par.f, W, par.p);\n\n /// Rotation and translation update\n\n RigidMotionEstimator::point_to_point(X, Q, W);\n\n /// Stopping criteria\n\n double stop1 = (X-Xo1).colwise().norm().maxCoeff();\n\n Xo1 = X;\n\n if(stop1 < par.stop) break;\n\n }\n\n /// Stopping criteria\n\n double stop2 = (X-Xo2).colwise().norm().maxCoeff();\n\n Xo2 = X;\n\n if(stop2 < par.stop) break;\n", "file_path": "src/common/include/ICP.h", "rank": 49, "score": 23058.976465055377 }, { "content": " /// Stopping criteria\n\n dual = (X-Xo1).colwise().norm().maxCoeff();\n\n Xo1 = X;\n\n if(dual < par.stop) break;\n\n }\n\n /// C update (lagrange multipliers)\n\n Eigen::Matrix3Xd P = X-Q-Z;\n\n if(!par.use_penalty) C.noalias() += mu*P;\n\n /// mu update (penalty)\n\n if(mu < par.max_mu) mu *= par.alpha;\n\n /// Stopping criteria\n\n double primal = P.colwise().norm().maxCoeff();\n\n if(primal < par.stop && dual < par.stop) break;\n\n }\n\n /// Stopping criteria\n\n double stop = (X-Xo2).colwise().norm().maxCoeff();\n\n Xo2 = X;\n\n if(stop < par.stop) break;\n\n }\n\n }\n", "file_path": "src/common/include/ICP.h", "rank": 50, "score": 23058.34306600326 }, { "content": " RigidMotionEstimator::point_to_plane(X, Qp, Qn, Eigen::VectorXd::Ones(X.cols()), U);\n\n /// Stopping criteria\n\n dual = (X-Xo1).colwise().norm().maxCoeff();\n\n Xo1 = X;\n\n if(dual < par.stop) break;\n\n }\n\n /// C update (lagrange multipliers)\n\n Eigen::VectorXf P = (Qn.array()*(X-Qp).array()).colwise().sum().transpose()-Z.array();\n\n if(!par.use_penalty) C.noalias() += mu*P;\n\n /// mu update (penalty)\n\n if(mu < par.max_mu) mu *= par.alpha;\n\n /// Stopping criteria\n\n double primal = P.array().abs().maxCoeff();\n\n if(primal < par.stop && dual < par.stop) break;\n\n }\n\n /// Stopping criteria\n\n double stop = (X-Xo2).colwise().norm().maxCoeff();\n\n Xo2 = X;\n\n if(stop < par.stop) break;\n\n }\n", "file_path": "src/common/include/ICP.h", "rank": 51, "score": 23058.092065389428 }, { "content": " nanoflann::KNNResultSet<typename MatrixType::Scalar,IndexType> resultSet(num_closest);\n\n resultSet.init(out_indices, out_distances_sq);\n\n index->findNeighbors(resultSet, query_point, nanoflann::SearchParams());\n\n }\n\n /// Query for the closest points to a given point (entered as query_point[0:dim-1]).\n\n inline IndexType closest(const num_t *query_point) const {\n\n IndexType out_indices;\n\n num_t out_distances_sq;\n\n query(query_point, 1, &out_indices, &out_distances_sq);\n\n return out_indices;\n\n }\n\n const self_t & derived() const {return *this;}\n\n self_t & derived() {return *this;}\n\n inline size_t kdtree_get_point_count() const {return m_data_matrix.cols();}\n\n /// Returns the distance between the vector \"p1[0:size-1]\" and the data point with index \"idx_p2\" stored in the class:\n\n inline num_t kdtree_distance(const num_t *p1, const size_t idx_p2,size_t size) const {\n\n num_t s=0;\n\n for (size_t i=0; i<size; i++) {\n\n const num_t d= p1[i]-m_data_matrix.coeff(i,idx_p2);\n\n s+=d*d;\n", "file_path": "src/common/include/ICP.h", "rank": 52, "score": 23058.066516997507 }, { "content": " /// @param Confidence weights\n\n /// @param Right hand side\n\n template <typename Derived1, typename Derived2, typename Derived3, typename Derived4, typename Derived5>\n\n Eigen::Affine3d point_to_plane(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Y,\n\n Eigen::MatrixBase<Derived3>& N,\n\n const Eigen::MatrixBase<Derived4>& w,\n\n const Eigen::MatrixBase<Derived5>& u) {\n\n typedef Eigen::Matrix<double, 6, 6> Matrix66;\n\n typedef Eigen::Matrix<double, 6, 1> Vector6;\n\n typedef Eigen::Block<Matrix66, 3, 3> Block33;\n\n /// Normalize weight vector\n\n Eigen::VectorXd w_normalized = w/w.sum();\n\n /// De-mean\n\n Eigen::Vector3d X_mean;\n\n for(int i=0; i<3; ++i)\n\n X_mean(i) = (X.row(i).array()*w_normalized.transpose().array()).sum();\n\n X.colwise() -= X_mean;\n\n Y.colwise() -= X_mean;\n\n /// Prepare LHS and RHS\n", "file_path": "src/common/include/ICP.h", "rank": 53, "score": 23058.004785744608 }, { "content": " default: uniform_weight(r); break;\n\n }\n\n }\n\n /// Reweighted ICP with point to point\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Parameters\n\n void point_to_point(Eigen::Matrix3Xd& X,\n\n Eigen::Matrix3Xd& Y,\n\n Parameters par = Parameters()) {\n\n /// Build kd-tree\n\n nanoflann::KDTreeAdaptor<Eigen::Matrix3Xd, 3, nanoflann::metric_L2_Simple> kdtree(Y);\n\n /// Buffers\n\n Eigen::Matrix3Xd Q = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::VectorXd W = Eigen::VectorXd::Zero(X.cols());\n\n Eigen::Matrix3Xd Xo1 = X;\n\n Eigen::Matrix3Xd Xo2 = X;\n\n /// ICP\n\n for(int icp=0; icp<par.max_icp; ++icp) {\n\n /// Find closest point\n", "file_path": "src/common/include/ICP.h", "rank": 54, "score": 23057.99529772305 }, { "content": " }\n\n }\n\n /// Reweighted ICP with point to plane\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Target normals (one 3D normal per column)\n\n /// @param Parameters\n\n template <typename Derived1, typename Derived2, typename Derived3>\n\n void point_to_plane(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Y,\n\n Eigen::MatrixBase<Derived3>& N,\n\n Parameters par = Parameters()) {\n\n /// Build kd-tree\n\n nanoflann::KDTreeAdaptor<Eigen::MatrixBase<Derived2>, 3, nanoflann::metric_L2_Simple> kdtree(Y);\n\n /// Buffers\n\n Eigen::Matrix3Xd Qp = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::Matrix3Xd Qn = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::VectorXd W = Eigen::VectorXd::Zero(X.cols());\n\n Eigen::Matrix3Xd Xo1 = X;\n\n Eigen::Matrix3Xd Xo2 = X;\n", "file_path": "src/common/include/ICP.h", "rank": 55, "score": 23056.39041644682 }, { "content": " double s = 0.0;\n\n if(n > ha) s = shrinkage<I>(mu, n, p, (Ba/n + 1.0)/2.0);\n\n y(i) *= s;\n\n }\n\n }\n\n /// Sparse ICP with point to point\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Parameters\n\n template <typename Derived1, typename Derived2>\n\n void point_to_point(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Y,\n\n Parameters par = Parameters()) {\n\n /// Build kd-tree\n\n nanoflann::KDTreeAdaptor<Eigen::MatrixBase<Derived2>, 3, nanoflann::metric_L2_Simple> kdtree(Y);\n\n /// Buffers\n\n Eigen::Matrix3Xd Q = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::Matrix3Xd Z = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::Matrix3Xd C = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::Matrix3Xd Xo1 = X;\n", "file_path": "src/common/include/ICP.h", "rank": 56, "score": 23056.39041644682 }, { "content": " }\n\n /// Stopping criteria\n\n double stop2 = (X-Xo2).colwise().norm().maxCoeff() ;\n\n Xo2 = X;\n\n if(stop2 < par.stop) break;\n\n }\n\n }\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\n#endif\n", "file_path": "src/common/include/ICP.h", "rank": 57, "score": 23056.39041644682 }, { "content": " /// Sparse ICP with point to plane\n\n /// @param Source (one 3D point per column)\n\n /// @param Target (one 3D point per column)\n\n /// @param Target normals (one 3D normal per column)\n\n /// @param Parameters\n\n template <typename Derived1, typename Derived2, typename Derived3>\n\n void point_to_plane(Eigen::MatrixBase<Derived1>& X,\n\n Eigen::MatrixBase<Derived2>& Y,\n\n Eigen::MatrixBase<Derived3>& N,\n\n Parameters par = Parameters()) {\n\n /// Build kd-tree\n\n nanoflann::KDTreeAdaptor<Eigen::MatrixBase<Derived2>, 3, nanoflann::metric_L2_Simple> kdtree(Y);\n\n /// Buffers\n\n Eigen::Matrix3Xd Qp = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::Matrix3Xd Qn = Eigen::Matrix3Xd::Zero(3, X.cols());\n\n Eigen::VectorXd Z = Eigen::VectorXd::Zero(X.cols());\n\n Eigen::VectorXd C = Eigen::VectorXd::Zero(X.cols());\n\n Eigen::Matrix3Xd Xo1 = X;\n\n Eigen::Matrix3Xd Xo2 = X;\n\n /// ICP\n", "file_path": "src/common/include/ICP.h", "rank": 58, "score": 23056.39041644682 }, { "content": "#include <common/ClosestKeyframe.h>\n\n\n\n/**\n\n * \\brief Create a Pose2DWithCovariance message from numeric input\n\n */\n\ncommon::Pose2DWithCovariance create_Pose2DWithCovariance_msg(double x, double y, double th, const Eigen::MatrixXd& Q) {\n\n common::Pose2DWithCovariance output;\n\n output.pose.x = x;\n\n output.pose.y = y;\n\n output.pose.theta = th;\n\n\n\n if(Q.rows() == 3 && Q.cols() == 3) {\n\n for(int i = 0; i < Q.rows(); i++) {\n\n for(int j = 0; j < Q.cols(); j++) {\n\n output.covariance[( i * Q.rows() ) + j] = Q(i, j);\n\n }\n\n }\n\n }\n\n\n\n return output;\n", "file_path": "src/common/include/utils.hpp", "rank": 59, "score": 21642.905960124925 }, { "content": " * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n *************************************************************************/\n\n\n\n#ifndef NANOFLANN_HPP_\n\n#define NANOFLANN_HPP_\n\n\n\n#include <vector>\n\n#include <cassert>\n\n#include <algorithm>\n\n#include <stdexcept>\n\n#include <cstdio> // for fwrite()\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 60, "score": 21642.667168790435 }, { "content": "}\n\n\n\n/**\n\n * \\brief Create a Pose2DWithCovariance message from numeric input\n\n */\n\ncommon::Pose2DWithCovariance create_Pose2DWithCovariance_msg(const geometry_msgs::Pose2D& pose, const Eigen::MatrixXd& Q) {\n\n common::Pose2DWithCovariance output = create_Pose2DWithCovariance_msg(pose.x, pose.y, pose.theta, Q);\n\n \n\n return output;\n\n}\n\n\n\n/**\n\n * \\brief Convert a 3D matrix transform to a 2D Delta\n\n */\n\ngeometry_msgs::Pose2D make_Delta(const Eigen::MatrixXf& T) {\n\n geometry_msgs::Pose2D Delta;\n\n Delta.x = T(0, 3);\n\n Delta.y = T(1, 3);\n\n Delta.theta = atan2( T(1, 0) , T(0, 0) );\n\n return Delta;\n", "file_path": "src/common/include/utils.hpp", "rank": 61, "score": 21642.512360676184 }, { "content": "}\n\n\n\n/**\n\n * \\brief Convert a 2D Delta to a 3D matrix transform\n\n */\n\nEigen::Matrix4f make_transform(const geometry_msgs::Pose2D& Delta) {\n\n Eigen::Matrix4f transform;\n\n transform.setIdentity();\n\n float cos_th = cos(Delta.theta);\n\n float sin_th = sin(Delta.theta);\n\n transform(0,0) = cos_th;\n\n transform(0,1) = -sin_th;\n\n transform(1,0) = sin_th;\n\n transform(1,1) = cos_th;\n\n transform(0,3) = Delta.x;\n\n transform(1,3) = Delta.y;\n\n return transform;\n\n}\n\n\n\n/**\n", "file_path": "src/common/include/utils.hpp", "rank": 62, "score": 21642.333142680243 }, { "content": " double sin_th = sin( pose.theta );\n\n\n\n // Help: composition is:\n\n // pose_xy = pose_xy + R(pose.th) * delta_xy; with R(th) = [cos(th) -sin(th); sin(th) cos(th)]\n\n // pose_th = pose_th + delta.th;\n\n output.x = pose.x + ( cos_th * delta.x + -sin_th * delta.y );\n\n output.y = pose.y + ( sin_th * delta.x + cos_th * delta.y );\n\n output.theta = pose.theta + delta.theta;\n\n output.theta = std::fmod(output.theta + M_PI, 2 * M_PI) - M_PI;\n\n\n\n return output;\n\n}\n\n\n\n/**\n\n * \\brief Compose two 2D poses additively.\n\n *\n\n * This corresponds to Pose_end = Pose_init (+) Delta\n\n */\n\ncommon::Pose2DWithCovariance compose(const common::Pose2DWithCovariance& pose, const common::Pose2DWithCovariance& delta) {\n\n\n", "file_path": "src/common/include/utils.hpp", "rank": 63, "score": 21641.584461251936 }, { "content": "\tstruct SearchParams\n\n\t{\n\n\t\t/** Note: The first argument (checks_IGNORED_) is ignored, but kept for compatibility with the FLANN interface */\n\n\t\tSearchParams(int checks_IGNORED_ = 32, float eps_ = 0, bool sorted_ = true ) :\n\n eps(eps_), sorted(sorted_) {\n\n checks_IGNORED_ = checks_IGNORED_;\n\n }\n\n\n\n\t\tint checks; //!< Ignored parameter (Kept for compatibility with the FLANN interface).\n\n\t\tfloat eps; //!< search for eps-approximate neighbours (default: 0)\n\n\t\tbool sorted; //!< only for radius search, require neighbours sorted by distance (default: true)\n\n\t};\n\n\t/** @} */\n\n\n\n\n\n\t/** @addtogroup memalloc_grp Memory allocation\n\n\t * @{ */\n\n\n\n\t/**\n\n\t * Allocates (using C's malloc) a generic type T.\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 64, "score": 21641.485975805597 }, { "content": " common::Pose2DWithCovariance output;\n\n output.pose = compose(pose.pose, delta.pose);\n\n\n\n return output;\n\n}\n\n\n\n/**\n\n * \\brief Compute pose increment or Delta.\n\n *\n\n * This corresponds to Delta = Pose_end (-) Pose_init\n\n */\n\ngeometry_msgs::Pose2D between(const geometry_msgs::Pose2D& pose_1, const geometry_msgs::Pose2D& pose_2) {\n\n geometry_msgs::Pose2D output;\n\n double cos_th = cos( pose_1.theta );\n\n double sin_th = sin( pose_1.theta );\n\n\n\n // Help: composition is:\n\n // delta_xy = R(pose1.th).transposed * (pose2_xy - pose1_xy); with R(th) = [cos(th) -sin(th); sin(th) cos(th)]\n\n // delta_th = pose2_th - pose1.th;\n\n double dx = pose_2.x - pose_1.x;\n", "file_path": "src/common/include/utils.hpp", "rank": 65, "score": 21640.79580617493 }, { "content": " double dy = pose_2.y - pose_1.y;\n\n output.x = ( cos_th * dx + sin_th * dy );\n\n output.y = ( -sin_th * dx + cos_th * dy );\n\n output.theta = pose_2.theta - pose_1.theta;\n\n output.theta = std::fmod(output.theta + M_PI, 2 * M_PI) - M_PI;\n\n\n\n return output;\n\n}\n\n\n\n/**\n\n * \\brief Compute pose increment or Delta.\n\n *\n\n * This corresponds to Delta = Pose_end (-) Pose_init\n\n */\n\ncommon::Pose2DWithCovariance between(const common::Pose2DWithCovariance& pose_1, const common::Pose2DWithCovariance& pose_2) {\n\n\n\n common::Pose2DWithCovariance output;\n\n output.pose = between(pose_1.pose, pose_2.pose);\n\n\n\n return output;\n", "file_path": "src/common/include/utils.hpp", "rank": 66, "score": 21640.744935158604 }, { "content": "#include <vector>\n\n#include <math.h>\n\n#include <iostream>\n\n#include <string>\n\n#include <sstream>\n\n\n\n#include <ros/ros.h>\n\n#include <ros/console.h>\n\n\n\n#include <common/Factor.h>\n\n#include <common/Keyframe.h>\n\n#include <common/ClosestKeyframe.h>\n\n#include <common/LastKeyframe.h>\n\n#include <common/Registration.h>\n\n#include <common/Pose2DWithCovariance.h>\n\n#include <common/OdometryBuffer.h>\n\n\n\n#include <gtsam/inference/Key.h>\n\n#include <gtsam/geometry/Pose2.h>\n\n#include <gtsam/slam/PriorFactor.h>\n", "file_path": "src/graph/include/graph.hpp", "rank": 67, "score": 21640.682053562075 }, { "content": "#include <ros/ros.h>\n\n#include <ros/console.h>\n\n\n\n#include <sstream>\n\n#include <string>\n\n\n\n#include <tf/transform_listener.h>\n\n\n\n#include <geometry_msgs/Pose2D.h>\n\n\n\n#include <sensor_msgs/PointCloud2.h>\n\n#include <sensor_msgs/LaserScan.h>\n\n\n\n#include <laser_geometry/laser_geometry.h>\n\n\n\n#include <common/Factor.h>\n\n#include <common/Keyframe.h>\n\n#include <common/Registration.h>\n\n#include <common/Pose2DWithCovariance.h>\n\n#include <common/LastKeyframe.h>\n", "file_path": "src/common/include/utils.hpp", "rank": 68, "score": 21640.591384834177 }, { "content": "\t\t\t\t\t * Dimension used for subdivision.\n\n\t\t\t\t\t */\n\n\t\t\t\t\tint divfeat;\n\n\t\t\t\t\t/**\n\n\t\t\t\t\t * The values used for subdivision.\n\n\t\t\t\t\t */\n\n\t\t\t\t\tDistanceType divlow, divhigh;\n\n\t\t\t\t} sub;\n\n\t\t\t};\n\n\t\t\t/**\n\n\t\t\t * The child nodes.\n\n\t\t\t */\n\n\t\t\tNode* child1, * child2;\n\n\t\t};\n\n\t\ttypedef Node* NodePtr;\n\n\n\n\n\n\t\tstruct Interval\n\n\t\t{\n\n\t\t\tElementType low, high;\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 69, "score": 21639.936431975173 }, { "content": "\t\t\t\tremaining = blocksize - sizeof(void*) - shift;\n\n\t\t\t\tloc = ((char*)m + sizeof(void*) + shift);\n\n\t\t\t}\n\n\t\t\tvoid* rloc = loc;\n\n\t\t\tloc = (char*)loc + size;\n\n\t\t\tremaining -= size;\n\n\n\n\t\t\tusedMemory += size;\n\n\n\n\t\t\treturn rloc;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Allocates (using this pool) a generic type T.\n\n\t\t *\n\n\t\t * Params:\n\n\t\t * count = number of instances to allocate.\n\n\t\t * Returns: pointer (of type T*) to memory buffer\n\n\t\t */\n\n\t\ttemplate <typename T>\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 70, "score": 21639.501380336347 }, { "content": "\n\n\t\t/**\n\n\t\t * Computes the inde memory usage\n\n\t\t * Returns: memory used by the index\n\n\t\t */\n\n\t\tsize_t usedMemory() const\n\n\t\t{\n\n\t\t\treturn pool.usedMemory+pool.wastedMemory+dataset.kdtree_get_point_count()*sizeof(IndexType); // pool memory and vind array memory\n\n\t\t}\n\n\n\n\t\t/** \\name Query methods\n\n\t\t * @{ */\n\n\n\n\t\t/**\n\n\t\t * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored inside\n\n\t\t * the result object.\n\n\t\t *\n\n\t\t * Params:\n\n\t\t * result = the result object in which the indices of the nearest-neighbors are stored\n\n\t\t * vec = the vector for which to search the nearest neighbors\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 71, "score": 21639.432830683436 }, { "content": "\t * \\code\n\n\t * // Must return the number of data points\n\n\t * inline size_t kdtree_get_point_count() const { ... }\n\n\t *\n\n\t * // Must return the Euclidean (L2) distance between the vector \"p1[0:size-1]\" and the data point with index \"idx_p2\" stored in the class:\n\n\t * inline DistanceType kdtree_distance(const T *p1, const size_t idx_p2,size_t size) const { ... }\n\n\t *\n\n\t * // Must return the dim'th component of the idx'th point in the class:\n\n\t * inline T kdtree_get_pt(const size_t idx, int dim) const { ... }\n\n\t *\n\n\t * // Optional bounding-box computation: return false to default to a standard bbox computation loop.\n\n\t * // Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\n\n\t * // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n\n\t * template <class BBOX>\n\n\t * bool kdtree_get_bbox(BBOX &bb) const\n\n\t * {\n\n\t * bb[0].low = ...; bb[0].high = ...; // 0th dimension limits\n\n\t * bb[1].low = ...; bb[1].high = ...; // 1st dimension limits\n\n\t * ...\n\n\t * return true;\n\n\t * }\n\n\t *\n\n\t * \\endcode\n\n\t *\n\n\t * \\tparam IndexType Will be typically size_t or int\n\n\t */\n\n\ttemplate <typename Distance, class DatasetAdaptor,int DIM = -1, typename IndexType = size_t>\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 72, "score": 21639.20565571257 }, { "content": "}\n\n\n\nEigen::MatrixXd covariance_to_eigen(const common::Factor::_delta_type::_covariance_type& cov) {\n\n\n\n Eigen::Matrix3d Q = Eigen::Matrix3d(&(cov[0]));\n\n\n\n return Q;\n\n}\n\n\n\ncommon::Pose2DWithCovariance eigen_to_covariance(common::Pose2DWithCovariance& pose, const Eigen::MatrixXd& Q) {\n\n for(int i = 0; i < Q.rows(); i++) {\n\n for(int j = 0; j < Q.cols(); j++) {\n\n pose.covariance[( i * Q.rows() ) + j] = Q(i, j);\n\n }\n\n }\n\n\n\n return pose;\n\n}\n\n\n\n\n", "file_path": "src/common/include/utils.hpp", "rank": 73, "score": 21639.031113114917 }, { "content": "\t\t// Must return the number of data points\n\n\t\tinline size_t kdtree_get_point_count() const {\n\n\t\t\treturn m_data_matrix.rows();\n\n\t\t}\n\n\n\n\t\t// Returns the distance between the vector \"p1[0:size-1]\" and the data point with index \"idx_p2\" stored in the class:\n\n\t\tinline num_t kdtree_distance(const num_t *p1, const size_t idx_p2,size_t size) const\n\n\t\t{\n\n\t\t\tnum_t s=0;\n\n\t\t\tfor (size_t i=0; i<size; i++) {\n\n\t\t\t\tconst num_t d= p1[i]-m_data_matrix.coeff(idx_p2,i);\n\n\t\t\t\ts+=d*d;\n\n\t\t\t}\n\n\t\t\treturn s;\n\n\t\t}\n\n\n\n\t\t// Returns the dim'th component of the idx'th point in the class:\n\n\t\tinline num_t kdtree_get_pt(const size_t idx, int dim) const {\n\n\t\t\treturn m_data_matrix.coeff(idx,dim);\n\n\t\t}\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 74, "score": 21638.49754780493 }, { "content": "#include <cmath> // for fabs(),...\n\n#include <limits>\n\n\n\n// Avoid conflicting declaration of min/max macros in windows headers\n\n#if !defined(NOMINMAX) && (defined(_WIN32) || defined(_WIN32_) || defined(WIN32) || defined(_WIN64))\n\n# define NOMINMAX\n\n# ifdef max\n\n# undef max\n\n# undef min\n\n# endif\n\n#endif\n\n\n\nnamespace nanoflann\n\n{\n\n/** @addtogroup nanoflann_grp nanoflann C++ library for ANN\n\n * @{ */\n\n\n\n \t/** Library version: 0xMmP (M=Major,m=minor,P=path) */\n\n\t#define NANOFLANN_VERSION 0x113\n\n\n\n\t/** @addtogroup result_sets_grp Result set classes\n\n\t * @{ */\n\n\ttemplate <typename DistanceType, typename IndexType = size_t, typename CountType = size_t>\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 75, "score": 21638.49177408065 }, { "content": "\n\n\t\t// Optional bounding-box computation: return false to default to a standard bbox computation loop.\n\n\t\t// Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\n\n\t\t// Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n\n\t\ttemplate <class BBOX>\n\n\t\tbool kdtree_get_bbox(BBOX &bb) const {\n\n\t\t\treturn false;\n\n\t\t}\n\n\n\n\t\t/** @} */\n\n\n\n\t}; // end of KDTreeEigenMatrixAdaptor\n\n\t/** @} */\n\n\n\n/** @} */ // end of grouping\n\n} // end of NS\n\n\n\n\n\n#endif /* NANOFLANN_HPP_ */\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 76, "score": 21638.469193797173 }, { "content": " double sigma_xy_squared = k_disp_disp * Dl;\n\n double sigma_th_squared = ( k_rot_disp * Dl ) + ( k_rot_rot * fabs(input.theta) );\n\n \n\n Eigen::MatrixXd Q(3, 3);\n\n Q.setZero();\n\n Q(0, 0) = sigma_xy_squared;\n\n Q(1, 1) = sigma_xy_squared;\n\n Q(2, 2) = sigma_th_squared;\n\n\n\n return Q;\n\n}\n\n\n\n/**\n\n * \\brief Compose two 2D poses additively.\n\n *\n\n * This corresponds to Pose_end = Pose_init (+) Delta\n\n */\n\ngeometry_msgs::Pose2D compose(const geometry_msgs::Pose2D& pose, const geometry_msgs::Pose2D& delta) {\n\n geometry_msgs::Pose2D output;\n\n double cos_th = cos( pose.theta );\n", "file_path": "src/common/include/utils.hpp", "rank": 77, "score": 21638.267161744592 }, { "content": "#include <gtsam/slam/BetweenFactor.h>\n\n#include <gtsam/nonlinear/Values.h>\n\n#include <gtsam/nonlinear/Marginals.h>\n\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\n\n\n#include <boost/algorithm/string/split.hpp>\n\n#include <boost/algorithm/string/classification.hpp>\n\n\n", "file_path": "src/graph/include/graph.hpp", "rank": 78, "score": 21638.113105201333 }, { "content": "\t *\n\n\t * Params:\n\n\t * count = number of instances to allocate.\n\n\t * Returns: pointer (of type T*) to memory buffer\n\n\t */\n\n\ttemplate <typename T>\n\n\tinline T* allocate(size_t count = 1)\n\n\t{\n\n\t\tT* mem = (T*) ::malloc(sizeof(T)*count);\n\n\t\treturn mem;\n\n\t}\n\n\n\n\n\n\t/**\n\n\t * Pooled storage allocator\n\n\t *\n\n\t * The following routines allow for the efficient allocation of storage in\n\n\t * small chunks from a specified pool. Rather than allowing each structure\n\n\t * to be freed individually, an entire pool of storage is freed at once.\n\n\t * This method has two advantages over just using malloc() and free(). First,\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 79, "score": 21638.060780228334 }, { "content": "\t\t\t\twastedMemory += remaining;\n\n\n\n\t\t\t\t/* Allocate new storage. */\n\n\t\t\t\tconst size_t blocksize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ?\n\n\t\t\t\t\t\t\tsize + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE;\n\n\n\n\t\t\t\t// use the standard C malloc to allocate memory\n\n\t\t\t\tvoid* m = ::malloc(blocksize);\n\n\t\t\t\tif (!m) {\n\n\t\t\t\t\tfprintf(stderr,\"Failed to allocate memory.\\n\");\n\n\t\t\t\t\treturn NULL;\n\n\t\t\t\t}\n\n\n\n\t\t\t\t/* Fill first word of new block with pointer to previous block. */\n\n\t\t\t\t((void**) m)[0] = base;\n\n\t\t\t\tbase = m;\n\n\n\n\t\t\t\tsize_t shift = 0;\n\n\t\t\t\t//int size_t = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1);\n\n\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 80, "score": 21637.95807103652 }, { "content": "\t *\n\n\t * \ttypedef KDTreeEigenMatrixAdaptor< Eigen::Matrix<num_t,Dynamic,Dynamic> > my_kd_tree_t;\n\n\t * \tconst int max_leaf = 10;\n\n\t * \tmy_kd_tree_t mat_index(dimdim, mat, max_leaf );\n\n\t * \tmat_index.index->buildIndex();\n\n\t * \tmat_index.index->...\n\n\t * \\endcode\n\n\t *\n\n\t * \\tparam DIM If set to >0, it specifies a compile-time fixed dimensionality for the points in the data set, allowing more compiler optimizations.\n\n\t * \\tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc.\n\n\t * \\tparam IndexType The type for indices in the KD-tree index (typically, size_t of int)\n\n\t */\n\n\ttemplate <class MatrixType, int DIM = -1, class Distance = nanoflann::metric_L2, typename IndexType = size_t>\n\n\tstruct KDTreeEigenMatrixAdaptor\n\n\t{\n\n\t\ttypedef KDTreeEigenMatrixAdaptor<MatrixType,DIM,Distance> self_t;\n\n\t\ttypedef typename MatrixType::Scalar num_t;\n\n\t\ttypedef typename Distance::template traits<num_t,self_t>::distance_t metric_t;\n\n\t\ttypedef KDTreeSingleIndexAdaptor< metric_t,self_t,DIM,IndexType> index_t;\n\n\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 81, "score": 21637.616734418545 }, { "content": "\t\t\tinit_vind();\n\n\t\t\tcomputeBoundingBox(root_bbox);\n\n\t\t\troot_node = divideTree(0, m_size, root_bbox ); // construct the tree\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Returns size of index.\n\n\t\t */\n\n\t\tsize_t size() const\n\n\t\t{\n\n\t\t\treturn m_size;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Returns the length of an index feature.\n\n\t\t */\n\n\t\tsize_t veclen() const\n\n\t\t{\n\n\t\t\treturn static_cast<size_t>(DIM>0 ? DIM : dim);\n\n\t\t}\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 82, "score": 21637.12924013171 }, { "content": "\t\t * to the 'cutfeat' dimension at 'cutval' position.\n\n\t\t *\n\n\t\t * On return:\n\n\t\t * dataset[ind[0..lim1-1]][cutfeat]<cutval\n\n\t\t * dataset[ind[lim1..lim2-1]][cutfeat]==cutval\n\n\t\t * dataset[ind[lim2..count]][cutfeat]>cutval\n\n\t\t */\n\n\t\tvoid planeSplit(IndexType* ind, const IndexType count, int cutfeat, DistanceType cutval, IndexType& lim1, IndexType& lim2)\n\n\t\t{\n\n\t\t\t/* Move vector indices for left subtree to front of list. */\n\n\t\t\tIndexType left = 0;\n\n\t\t\tIndexType right = count-1;\n\n\t\t\tfor (;; ) {\n\n\t\t\t\twhile (left<=right && dataset_get(ind[left],cutfeat)<cutval) ++left;\n\n\t\t\t\twhile (right && left<=right && dataset_get(ind[right],cutfeat)>=cutval) --right;\n\n\t\t\t\tif (left>right || !right) break; // \"!right\" was added to support unsigned Index types\n\n\t\t\t\tstd::swap(ind[left], ind[right]);\n\n\t\t\t\t++left;\n\n\t\t\t\t--right;\n\n\t\t\t}\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 83, "score": 21637.014835881368 }, { "content": "\t\t\t\treturn mindist<rhs.mindist;\n\n\t\t\t}\n\n\t\t};\n\n\n\n\t\t/**\n\n\t\t * Array of k-d trees used to find neighbours.\n\n\t\t */\n\n\t\tNodePtr root_node;\n\n\t\ttypedef BranchStruct<NodePtr, DistanceType> BranchSt;\n\n\t\ttypedef BranchSt* Branch;\n\n\n\n\t\tBoundingBox root_bbox;\n\n\n\n\t\t/**\n\n\t\t * Pooled memory allocator.\n\n\t\t *\n\n\t\t * Using a pooled memory allocator is more efficient\n\n\t\t * than allocating memory directly when there is a large\n\n\t\t * number small of memory allocations.\n\n\t\t */\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 84, "score": 21636.860560589957 }, { "content": "\t\tvoid searchLevel(RESULTSET& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq,\n\n\t\t\t\t\t\t std::vector<DistanceType>& dists, const float epsError) const\n\n\t\t{\n\n\t\t\t/* If this is a leaf node, then do check and return. */\n\n\t\t\tif ((node->child1 == NULL)&&(node->child2 == NULL)) {\n\n\t\t\t\t//count_leaf += (node->lr.right-node->lr.left); // Removed since was neither used nor returned to the user.\n\n\t\t\t\tDistanceType worst_dist = result_set.worstDist();\n\n\t\t\t\tfor (IndexType i=node->lr.left; i<node->lr.right; ++i) {\n\n\t\t\t\t\tconst IndexType index = vind[i];// reorder... : i;\n\n\t\t\t\t\tDistanceType dist = distance(vec, index, (DIM>0 ? DIM : dim));\n\n\t\t\t\t\tif (dist<worst_dist) {\n\n\t\t\t\t\t\tresult_set.addPoint(dist,vind[i]);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\n\n\t\t\t/* Which child branch should be taken first? */\n\n\t\t\tint idx = node->sub.divfeat;\n\n\t\t\tElementType val = vec[idx];\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 85, "score": 21636.813629419175 }, { "content": "\t\t\t\t// compute bounding-box of leaf points\n\n\t\t\t\tfor (int i=0; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\t\tbbox[i].low = dataset_get(vind[left],i);\n\n\t\t\t\t\tbbox[i].high = dataset_get(vind[left],i);\n\n\t\t\t\t}\n\n\t\t\t\tfor (IndexType k=left+1; k<right; ++k) {\n\n\t\t\t\t\tfor (int i=0; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\t\t\tif (bbox[i].low>dataset_get(vind[k],i)) bbox[i].low=dataset_get(vind[k],i);\n\n\t\t\t\t\t\tif (bbox[i].high<dataset_get(vind[k],i)) bbox[i].high=dataset_get(vind[k],i);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tIndexType idx;\n\n\t\t\t\tint cutfeat;\n\n\t\t\t\tDistanceType cutval;\n\n\t\t\t\tmiddleSplit_(&vind[0]+left, right-left, idx, cutfeat, cutval, bbox);\n\n\n\n\t\t\t\tnode->sub.divfeat = cutfeat;\n\n\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 86, "score": 21636.71479453576 }, { "content": "\t\t\tif (dataset.kdtree_get_bbox(bbox))\n\n\t\t\t{\n\n\t\t\t\t// Done! It was implemented in derived class\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tfor (int i=0; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\t\tbbox[i].low =\n\n\t\t\t\t\t\tbbox[i].high = dataset_get(0,i);\n\n\t\t\t\t}\n\n\t\t\t\tconst size_t N = dataset.kdtree_get_point_count();\n\n\t\t\t\tfor (size_t k=1; k<N; ++k) {\n\n\t\t\t\t\tfor (int i=0; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\t\t\tif (dataset_get(k,i)<bbox[i].low) bbox[i].low = dataset_get(k,i);\n\n\t\t\t\t\t\tif (dataset_get(k,i)>bbox[i].high) bbox[i].high = dataset_get(k,i);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 87, "score": 21636.619547425642 }, { "content": "\t\t}\n\n\t}\n\n\t/** @} */\n\n\n\n\n\n\t/** @addtogroup metric_grp Metric (distance) classes\n\n\t * @{ */\n\n\n\n\ttemplate<typename T> inline T abs(T x) { return (x<0) ? -x : x; }\n\n\ttemplate<> inline int abs<int>(int x) { return ::abs(x); }\n\n\ttemplate<> inline float abs<float>(float x) { return fabsf(x); }\n\n\ttemplate<> inline double abs<double>(double x) { return fabs(x); }\n\n\ttemplate<> inline long double abs<long double>(long double x) { return fabsl(x); }\n\n\n\n\t/** Manhattan distance functor (generic version, optimized for high-dimensionality data sets).\n\n\t * Corresponding distance traits: nanoflann::metric_L1\n\n\t * \\tparam T Type of the elements (e.g. double, float, uint8_t)\n\n\t * \\tparam DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t)\n\n\t */\n\n\ttemplate<class T, class DataSource, typename _DistanceType = T>\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 88, "score": 21636.54192925516 }, { "content": "\t/** @} */\n\n\n\n\n\n\n\n\t/** @addtogroup param_grp Parameter structs\n\n\t * @{ */\n\n\n\n\t/** Parameters (see http://code.google.com/p/nanoflann/ for help choosing the parameters)\n\n\t */\n\n\tstruct KDTreeSingleIndexAdaptorParams\n\n\t{\n\n\t\tKDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10, int dim_ = -1) :\n\n\t\t\tleaf_max_size(_leaf_max_size), dim(dim_)\n\n\t\t{}\n\n\n\n\t\tsize_t leaf_max_size;\n\n\t\tint dim;\n\n\t};\n\n\n\n\t/** Search options for KDTreeSingleIndexAdaptor::findNeighbors() */\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 89, "score": 21636.48785117654 }, { "content": "\t\tindex_t* index; //! The kd-tree index for the user to call its methods as usual with any other FLANN index.\n\n\n\n\t\t/// Constructor: takes a const ref to the matrix object with the data points\n\n\t\tKDTreeEigenMatrixAdaptor(const int dimensionality, const MatrixType &mat, const int leaf_max_size = 10) : m_data_matrix(mat)\n\n\t\t{\n\n\t\t\tconst size_t dims = mat.cols();\n\n\t\t\tif (DIM>0 && static_cast<int>(dims)!=DIM)\n\n\t\t\t\tthrow std::runtime_error(\"Data set dimensionality does not match the 'DIM' template argument\");\n\n\t\t\tindex = new index_t( dims, *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size, dims ) );\n\n\t\t\tindex->buildIndex();\n\n\t\t}\n\n\n\n\t\t~KDTreeEigenMatrixAdaptor() {\n\n\t\t\tdelete index;\n\n\t\t}\n\n\n\n\t\tconst MatrixType &m_data_matrix;\n\n\n\n\t\t/** Query for the \\a num_closest closest points to a given point (entered as query_point[0:dim-1]).\n\n\t\t * Note that this is a short-cut method for index->findNeighbors().\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 90, "score": 21636.367542636977 }, { "content": "\t\tvoid computeMinMax(IndexType* ind, IndexType count, int element, ElementType& min_elem, ElementType& max_elem)\n\n\t\t{\n\n\t\t\tmin_elem = dataset_get(ind[0],element);\n\n\t\t\tmax_elem = dataset_get(ind[0],element);\n\n\t\t\tfor (IndexType i=1; i<count; ++i) {\n\n\t\t\t\tElementType val = dataset_get(ind[i],element);\n\n\t\t\t\tif (val<min_elem) min_elem = val;\n\n\t\t\t\tif (val>max_elem) max_elem = val;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tvoid middleSplit(IndexType* ind, IndexType count, IndexType& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox)\n\n\t\t{\n\n\t\t\t// find the largest span from the approximate bounding box\n\n\t\t\tElementType max_span = bbox[0].high-bbox[0].low;\n\n\t\t\tcutfeat = 0;\n\n\t\t\tcutval = (bbox[0].high+bbox[0].low)/2;\n\n\t\t\tfor (int i=1; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\tElementType span = bbox[i].low-bbox[i].low;\n\n\t\t\t\tif (span>max_span) {\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 91, "score": 21636.320061703474 }, { "content": "\t\t\tfor (int i=1; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\tElementType span = bbox[i].high-bbox[i].low;\n\n\t\t\t\tif (span>max_span) {\n\n\t\t\t\t\tmax_span = span;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tElementType max_spread = -1;\n\n\t\t\tcutfeat = 0;\n\n\t\t\tfor (int i=0; i<(DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\tElementType span = bbox[i].high-bbox[i].low;\n\n\t\t\t\tif (span>(1-EPS)*max_span) {\n\n\t\t\t\t\tElementType min_elem, max_elem;\n\n\t\t\t\t\tcomputeMinMax(ind, count, cutfeat, min_elem, max_elem);\n\n\t\t\t\t\tElementType spread = max_elem-min_elem;;\n\n\t\t\t\t\tif (spread>max_spread) {\n\n\t\t\t\t\t\tcutfeat = i;\n\n\t\t\t\t\t\tmax_spread = spread;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 92, "score": 21636.31024213493 }, { "content": "\t\t */\n\n\t\tPooledAllocator(const size_t blocksize = BLOCKSIZE)\n\n\t\t{\n\n\t\t\tthis->blocksize = blocksize;\n\n\t\t\tremaining = 0;\n\n\t\t\tbase = NULL;\n\n\n\n\t\t\tusedMemory = 0;\n\n\t\t\twastedMemory = 0;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Destructor. Frees all the memory allocated in this pool.\n\n\t\t */\n\n\t\t~PooledAllocator()\n\n\t\t{\n\n\t\t\twhile (base != NULL) {\n\n\t\t\t\tvoid *prev = *((void**) base); /* Get pointer to prev block. */\n\n\t\t\t\t::free(base);\n\n\t\t\t\tbase = prev;\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 93, "score": 21636.222806703114 }, { "content": "\t\tconst KDTreeSingleIndexAdaptorParams index_params;\n\n\n\n\t\tsize_t m_size;\n\n\t\tint dim; //!< Dimensionality of each data point\n\n\n\n\n\n\t\t/*--------------------- Internal Data Structures --------------------------*/\n\n\t\tstruct Node\n\n\t\t{\n\n\t\t\tunion {\n\n\t\t\t\tstruct\n\n\t\t\t\t{\n\n\t\t\t\t\t/**\n\n\t\t\t\t\t * Indices of points in leaf node\n\n\t\t\t\t\t */\n\n\t\t\t\t\tIndexType left, right;\n\n\t\t\t\t} lr;\n\n\t\t\t\tstruct\n\n\t\t\t\t{\n\n\t\t\t\t\t/**\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 94, "score": 21636.201894891747 }, { "content": "\t\t\t\t\tif (i<capacity) {\n\n\t\t\t\t\t\tdists[i] = dists[i-1];\n\n\t\t\t\t\t\tindices[i] = indices[i-1];\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\telse break;\n\n\t\t\t}\n\n\t\t\tif (i<capacity) {\n\n\t\t\t\tdists[i] = dist;\n\n\t\t\t\tindices[i] = index;\n\n\t\t\t}\n\n\t\t\tif (count<capacity) count++;\n\n\t\t}\n\n\n\n\t\tinline DistanceType worstDist() const\n\n\t\t{\n\n\t\t\treturn dists[capacity-1];\n\n\t\t}\n\n\t};\n\n\n\n\n\n\t/**\n\n\t * A result-set class used when performing a radius based search.\n\n\t */\n\n\ttemplate <typename DistanceType, typename IndexType = size_t>\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 95, "score": 21636.198582550114 }, { "content": "\t\t */\n\n inline void knnSearch(const ElementType *query_point, const size_t num_closest, IndexType *out_indices, DistanceType *out_distances_sq) const\n\n\t\t{\n\n\t\t\tnanoflann::KNNResultSet<DistanceType,IndexType> resultSet(num_closest);\n\n\t\t\tresultSet.init(out_indices, out_distances_sq);\n\n\t\t\tthis->findNeighbors(resultSet, query_point, nanoflann::SearchParams());\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Find all the neighbors to \\a query_point[0:dim-1] within a maximum radius.\n\n\t\t * The output is given as a vector of pairs, of which the first element is a point index and the second the corresponding distance.\n\n\t\t * Previous contents of \\a IndicesDists are cleared.\n\n\t\t *\n\n\t\t * If searchParams.sorted==true, the output list is sorted by ascending distances.\n\n\t\t *\n\n\t\t * For a better performance, it is advisable to do a .reserve() on the vector if you have any wild guess about the number of expected matches.\n\n\t\t *\n\n\t\t * \\sa knnSearch, findNeighbors\n\n\t\t * \\return The number of points within the given radius (i.e. indices.size() or dists.size() )\n\n\t\t */\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 96, "score": 21636.081247329304 }, { "content": "\t\tinline CountType size() const\n\n\t\t{\n\n\t\t\treturn count;\n\n\t\t}\n\n\n\n\t\tinline bool full() const\n\n\t\t{\n\n\t\t\treturn count == capacity;\n\n\t\t}\n\n\n\n\n\n\t\tinline void addPoint(DistanceType dist, IndexType index)\n\n\t\t{\n\n\t\t\tCountType i;\n\n\t\t\tfor (i=count; i>0; --i) {\n\n#ifdef NANOFLANN_FIRST_MATCH // If defined and two poins have the same distance, the one with the lowest-index will be returned first.\n\n\t\t\t\tif ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) {\n\n#else\n\n\t\t\t\tif (dists[i-1]>dist) {\n\n#endif\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 97, "score": 21636.03250149487 }, { "content": "\t\t\t}\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Returns a pointer to a piece of new memory of the given size in bytes\n\n\t\t * allocated from the pool.\n\n\t\t */\n\n\t\tvoid* malloc(const size_t req_size)\n\n\t\t{\n\n\t\t\t/* Round size up to a multiple of wordsize. The following expression\n\n\t\t\t only works for WORDSIZE that is a power of 2, by masking last bits of\n\n\t\t\t incremented size to zero.\n\n\t\t\t */\n\n\t\t\tconst size_t size = (req_size + (WORDSIZE - 1)) & ~(WORDSIZE - 1);\n\n\n\n\t\t\t/* Check whether a new block must be allocated. Note that the first word\n\n\t\t\t of a block is reserved for a pointer to the previous block.\n\n\t\t\t */\n\n\t\t\tif (size > remaining) {\n\n\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 98, "score": 21635.89499981172 }, { "content": "\n\n\t\t\tfor (int i = 0; i < (DIM>0 ? DIM : dim); ++i) {\n\n\t\t\t\tif (vec[i] < root_bbox[i].low) {\n\n\t\t\t\t\tdists[i] = distance.accum_dist(vec[i], root_bbox[i].low, i);\n\n\t\t\t\t\tdistsq += dists[i];\n\n\t\t\t\t}\n\n\t\t\t\tif (vec[i] > root_bbox[i].high) {\n\n\t\t\t\t\tdists[i] = distance.accum_dist(vec[i], root_bbox[i].high, i);\n\n\t\t\t\t\tdistsq += dists[i];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\treturn distsq;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Performs an exact search in the tree starting from a node.\n\n\t\t * \\tparam RESULTSET Should be any ResultSet<DistanceType>\n\n\t\t */\n\n\t\ttemplate <class RESULTSET>\n", "file_path": "src/common/include/nanoflann.hpp", "rank": 99, "score": 21635.808558230765 } ]
C++
Stream.cpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
#include "Common.hpp" #include "Stream.hpp" #include <Core/AnsiWide.hpp> CStream::CStream() : m_nMode(GENERIC_NONE) , m_nFormat(0) , m_nVersion(0) { } CStream::~CStream() { } template<typename CharT> size_t CStream::ReadLine(std::vector<CharT>& vBuffer) { if (!IsEOF()) { CharT cChar; do { Read(&cChar, sizeof(CharT)); if ( (cChar != '\r') && (cChar != '\n') ) vBuffer.push_back(cChar); } while ( (!IsEOF()) && (cChar != '\r') && (cChar != '\n') ); if ( (!IsEOF()) && (cChar == '\r') ) Read(&cChar, sizeof(CharT)); } return vBuffer.size(); } CString CStream::ReadLine(TextFormat eFormat) { CString strLine; if (eFormat == ANSI_TEXT) { std::vector<char> vBuffer; if (ReadLine(vBuffer) == 0) return TXT(""); size_t nChars = vBuffer.size(); const char* pszBegin = &vBuffer.front(); const char* pszEnd = pszBegin + nChars; strLine.BufferSize(nChars+1); #ifdef ANSI_BUILD std::copy(pszBegin, pszEnd, strLine.Buffer()); #else Core::ansiToWide(pszBegin, pszEnd, strLine.Buffer()); #endif strLine[nChars] = TXT('\0'); } else { std::vector<wchar_t> vBuffer; if (ReadLine(vBuffer) == 0) return TXT(""); size_t nChars = vBuffer.size(); const wchar_t* pszBegin = &vBuffer.front(); const wchar_t* pszEnd = pszBegin + nChars; strLine.BufferSize(nChars+1); #ifdef ANSI_BUILD Core::wideToAnsi(pszBegin, pszEnd, strLine.Buffer()); #else std::copy(pszBegin, pszEnd, strLine.Buffer()); #endif strLine[nChars] = TXT('\0'); } return strLine; } void CStream::WriteLine(const CString& str, TextFormat eFormat) { size_t nChars = str.Length(); if (eFormat == ANSI_TEXT) { #ifdef ANSI_BUILD Write(str.Buffer(), Core::numBytes<char>(nChars)); #else Write(T2A(str), Core::numBytes<char>(nChars)); #endif Write("\r\n", Core::numBytes<char>(2)); } else { #ifdef ANSI_BUILD Write(T2W(str), Core::numBytes<wchar_t>(nChars)); #else Write(str.Buffer(), Core::numBytes<wchar_t>(nChars)); #endif Write(L"\r\n", Core::numBytes<wchar_t>(2)); } } uint32 CStream::Format() const { return m_nFormat; } void CStream::SetFormat(uint32 nFormat) { m_nFormat = nFormat; } uint32 CStream::Version() const { return m_nVersion; } void CStream::SetVersion(uint32 nVersion) { m_nVersion = nVersion; }
#include "Common.hpp" #include "Stream.hpp" #include <Core/AnsiWide.hpp> CStream::CStream() : m_nMode(GENERIC_NONE) , m_nFormat(0) , m_nVersion(0) { } CStream::~CStream() { } template<typename CharT> size_t CStream::ReadLine(std::vector<CharT>& vBuffer) { if (!IsEOF()) { CharT cChar; do { Read(&cChar, sizeof(CharT)); if ( (cChar != '\r') && (cChar != '\n') ) vBuffer.push_back(cChar); } while ( (!IsEOF()) && (cChar != '\r') && (cChar != '\n') ); if ( (!IsEOF()) && (cChar == '\r') ) Read(&cChar, sizeof(CharT)); } return vBuffer.size(); } CString CStream::ReadLine(TextFormat eFormat) { CString strLine; if (eFormat == ANSI_TEXT) { std::vector<char> vBuffer; if (ReadLine(vBuffer) == 0) return TXT(""); size_t nChars = vBuffer.size(); const char* pszBegin = &vBuffer.front(); const char* pszEnd = pszBegin + nChars; strLine.BufferSize(nChars+1); #ifdef ANSI_BUILD std::copy(pszBegin, pszEnd, strLine.Buffer()); #else Core::ansiToWide(pszBegin, pszEnd, strLine.Buffer()); #endif strLine[nChars] = TXT('\0'); } else { std::vector<wchar_t> vBuffer; if (ReadLine(vBuffer) == 0) return TXT(""); size_t nChars = vBuffer.size(); const wchar_t* pszBegin = &vBuffer.front(); const wchar_t* pszEnd = pszBegin + nChars; strLine.BufferSize(nChars+1); #ifdef ANSI_BUILD Core::wideToAnsi(pszBegin, pszEnd, strLine.Buffer()); #else std::copy(pszBegin, pszEnd, strLine.Buffer()); #endif strLine[nChars] = TXT('\0'); } return strLine; }
uint32 CStream::Format() const { return m_nFormat; } void CStream::SetFormat(uint32 nFormat) { m_nFormat = nFormat; } uint32 CStream::Version() const { return m_nVersion; } void CStream::SetVersion(uint32 nVersion) { m_nVersion = nVersion; }
void CStream::WriteLine(const CString& str, TextFormat eFormat) { size_t nChars = str.Length(); if (eFormat == ANSI_TEXT) { #ifdef ANSI_BUILD Write(str.Buffer(), Core::numBytes<char>(nChars)); #else Write(T2A(str), Core::numBytes<char>(nChars)); #endif Write("\r\n", Core::numBytes<char>(2)); } else { #ifdef ANSI_BUILD Write(T2W(str), Core::numBytes<wchar_t>(nChars)); #else Write(str.Buffer(), Core::numBytes<wchar_t>(nChars)); #endif Write(L"\r\n", Core::numBytes<wchar_t>(2)); } }
function_block-full_function
[ { "content": "class CString\n\n{\n\npublic:\n\n\t//\n\n\t// Constructors/Destructor.\n\n\t//\n\n\tCString();\n\n\tCString(uint iRscID);\n\n\tCString(const tchar* pszBuffer);\n\n\tCString(const tchar* pszBuffer, size_t iChars);\n\n\tCString(const CString& strSrc);\n\n\t~CString();\n\n\n\n\tvoid BufferSize(size_t nChars);\n\n\tvoid LoadRsc(uint iRscID);\n\n\n\n\t//\n\n\t// Attributes.\n\n\t//\n\n\tbool Empty() const;\n", "file_path": "String.hpp", "rank": 0, "score": 36815.105217885335 }, { "content": "class CPath : public CString\n\n{\n\npublic:\n\n\t//\n\n\t// Constructors/Destructor.\n\n\t//\n\n\tCPath();\n\n CPath(const tchar* pszPath);\n\n\tCPath(const CString& strSrc);\n\n\tCPath(const tstring& source);\n\n CPath(const tchar* pszDir, const tchar* pszFile);\n\n\n\n\t//\n\n\t// File/Dir attributes.\n\n\t//\n\n bool Exists() const;\n\n bool ReadOnly() const;\n\n\tbool IsFolder() const;\n\n\tDWORD Attributes() const; // throw(Win32Exception)\n\n\tvoid SetAttributes(DWORD attributes); // throw(Win32Exception)\n", "file_path": "Path.hpp", "rank": 1, "score": 31875.40500268184 }, { "content": "** Method:\t\tIsPathSeparator()\n\n**\n\n** Description:\tHelper functions to check if a character is a path separator.\n\n**\n\n** Parameters:\tcChar\tThe character to test..\n\n**\n\n** Returns:\t\ttrue or false.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\ninline bool IsPathSeparator(tchar cChar)\n\n{\n\n\treturn ((cChar == TXT('\\\\')) || (cChar == TXT('/')));\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tNormalise()\n\n**\n\n** Description:\tNormalises the path by removing the trailing path separator if\n", "file_path": "Path.cpp", "rank": 2, "score": 16.33397449002421 }, { "content": "\n\nCString& CString::RepCtrlChars()\n\n{\n\n\tReplace(TXT('\\t'), TXT(\"\\\\t\"));\n\n\tReplace(TXT('\\r'), TXT(\"\\\\r\"));\n\n\tReplace(TXT('\\n'), TXT(\"\\\\n\"));\n\n\n\n\treturn *this;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tTrim()\n\n**\n\n** Description:\tTrims the leading and/or trailing whitespace from the string.\n\n**\n\n** Parameters:\tbLeft\tTrim leading whitespace.\n\n**\t\t\t\tbRight\tTrim trailing whitespace.\n\n**\n\n** Returns:\t\tThis.\n\n**\n", "file_path": "String.cpp", "rank": 3, "score": 15.637067026533138 }, { "content": "/******************************************************************************\n\n** Method:\t\tReplace()\n\n**\n\n** Description:\tReplaces a character with another character.\n\n**\n\n** Parameters:\tcOldChar\tThe character to replace.\n\n**\t\t\t\tcNewChar\tThe character to replace it with.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::Replace(tchar cOldChar, tchar cNewChar)\n\n{\n\n\ttchar* psz = m_pszData;\n\n\n\n\twhile (*psz != TXT('\\0'))\n\n\t{\n\n\t\tif (*psz == cOldChar)\n", "file_path": "String.cpp", "rank": 4, "score": 15.32455088597132 }, { "content": "**\n\n** Description:\tAllocates space for and copies the string.\n\n**\n\n** Parameters:\tlpszBuffer\tThe source string.\n\n**\t\t\t\tiChars\t\tThe number of chars to copy.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::Copy(const tchar* lpszBuffer, size_t nChars)\n\n{\n\n\tASSERT(lpszBuffer);\n\n\n\n\t// Empty string?\n\n\tif (*lpszBuffer == TXT('\\0'))\n\n\t{\n\n\t\tFree();\n\n\t\treturn;\n", "file_path": "String.cpp", "rank": 5, "score": 15.04389714038659 }, { "content": "\t}\n\n\n\n\t// Copy.\n\n\tBufferSize(nChars+1);\n\n\ttstrncpy(m_pszData, lpszBuffer, nChars);\n\n\n\n\t// Ensure string is terminated.\n\n\tm_pszData[nChars] = TXT('\\0');\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFree()\n\n**\n\n** Description:\tFree up the memory used by the string. This is used internally\n\n**\t\t\t\tto ensure there is no memory used by the library when the\n\n**\t\t\t\tmemory checking functions are called.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n", "file_path": "String.cpp", "rank": 6, "score": 14.746278582029593 }, { "content": "** Method:\t\tFormatDate/DateTime()\n\n**\n\n** Description:\tConvert a time_t value to a string.\n\n**\n\n** Parameters:\ttValue\t\tThe value.\n\n**\n\n** Returns:\t\tThe value as a string.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCString CStrCvt::FormatDate(time_t tValue)\n\n{\n\n\tconst size_t MAX_CHARS = 10;\n\n\ttchar szValue[MAX_CHARS+1];\n\n\n\n\tif (_tcsftime(szValue, MAX_CHARS+1, TXT(\"%Y-%m-%d\"), localtime(&tValue)) == 0)\n\n\t\tthrow Core::BadLogicException(TXT(\"Insufficient buffer size used in CStrCvt::FormatDate()\"));\n\n\n\n\treturn szValue;\n", "file_path": "StrCvt.cpp", "rank": 7, "score": 14.666217065349196 }, { "content": "/******************************************************************************\n\n** Method:\t\tFieldSeparator()\n\n**\n\n** Description:\tGets the separator used between date fields.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tThe separator characters.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCString CDate::FieldSeparator()\n\n{\n\n\t// Get the size of the buffer and allocate one.\n\n\tint nChars = ::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SDATE, nullptr, 0);\n\n\n\n\ttchar* pszBuffer = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\tpszBuffer[0] = TXT('\\0');\n", "file_path": "Date.cpp", "rank": 8, "score": 13.27380319684289 }, { "content": "size_t CListView::StringWidth(size_t nChars) const\n\n{\n\n\t// Create a string of 'X's.\n\n\ttstring str(nChars, TXT('X'));\n\n\n\n\treturn StringWidth(str.c_str());\n\n}\n\n\n\n/******************************************************************************\n\n** Methods:\t\tFindItem()\n\n**\n\n** Description:\tFinds an item either by text value or by lParam member.\n\n**\n\n** Parameters:\tpszText\t\tText item to find.\n\n**\t\t\t\tlData\t\tLPARAM data to find.\n\n**\t\t\t\tpData\t\tLPARAM data to find.\n\n**\t\t\t\tbPartial\tExtact or partial find?\n\n**\t\t\t\tnStart\t\tThe item to start from.\n\n**\n\n** Returns:\t\tNothing.\n", "file_path": "ListView.cpp", "rank": 9, "score": 13.075881154039923 }, { "content": "\t\t// Caret not at start OR already have sign?\n\n\t\tif ( (nSelStart > 0) || (tstrchr(szText, TXT('+')) != nullptr) || (tstrchr(szText, TXT('-')) != nullptr) )\n\n\t\t\treturn true;\n\n\t}\n\n\n\n\t// Is a decimal point AND already have one?\n\n\tif ( (cChar == TXT('.')) && (tstrchr(szText, TXT('.')) != nullptr) )\n\n\t\treturn true;\n\n\n\n\t// Is a fraction separator AND already have one?\n\n\tif ( (cChar == TXT('/')) && (tstrchr(szText, TXT('/')) != nullptr) )\n\n\t\treturn true;\n\n\n\n\t// Is a fraction separator AND already have one?\n\n\tif ( (cChar == TXT(' ')) && (tstrchr(szText, TXT(' ')) != nullptr) )\n\n\t\treturn true;\n\n\n\n\t// Allowing decimal places AND is a digit?\n\n\tif ( (m_nDecDigits > 0) && (isdigit(cChar)) )\n\n\t{\n", "file_path": "DecimalBox.cpp", "rank": 10, "score": 12.79241860624709 }, { "content": "\t\ttchar* pszValue = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars)));\n\n\n\n\t\t// Format the string.\n\n\t\t::GetDateFormat(LOCALE_USER_DEFAULT, nDateFmt, &st, nullptr, pszValue, static_cast<int>(nChars));\n\n\n\n\t\treturn pszValue;\n\n\t}\n\n\n\n\tthrow Core::InvalidArgException(TXT(\"Invalid string format requested\"));\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFromString()\n\n**\n\n** Description:\tConverts a formatted string to a date. It expects a string\n\n**\t\t\t\tformatted as DD/MM/YYYY.\n\n**\n\n** Parameters:\tpszDate\t\tThe date.\n\n**\n\n** Returns:\t\ttrue or false.\n", "file_path": "Date.cpp", "rank": 11, "score": 12.637050254083157 }, { "content": "\tif (nFields >= FMT_SHORT)\n\n\t{\n\n\t\tstrFont += CString::Fmt(TXT(\",%u,%u,%u,%u\"), lfWeight, lfItalic, lfUnderline, lfStrikeOut);\n\n\t}\n\n\n\n\t// Includes all fields?\n\n\tif (nFields >= FMT_FULL)\n\n\t{\n\n\t\tstrFont += CString::Fmt(TXT(\",%d,%d,%d,%u,%u,%u,%u,%u\"), lfWidth, lfEscapement, lfOrientation,\n\n\t\t\t\t\t\t\t\tlfCharSet, lfOutPrecision, lfClipPrecision, lfQuality, lfPitchAndFamily);\n\n\t}\n\n\n\n\treturn strFont;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tParse()\n\n**\n\n** Description:\tFills in a LOGFONT from the definition in the string.\n\n**\t\t\t\tThe string definition can contain a variable number of fields\n", "file_path": "LogFont.cpp", "rank": 12, "score": 12.608194617168074 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file FolderIteratorTests.cpp\n\n//! \\brief The unit tests for the FolderIterator class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/FolderIterator.hpp>\n\n#include <WCL/Path.hpp>\n\n#include <WCL/File.hpp>\n\n#include <Core/Algorithm.hpp>\n\n#include <Core/Functor.hpp>\n\n\n\nstatic const tchar* TEST_ROOT_NAME = TXT(\"FolderIteratorTests\");\n\n\n\nstatic const tchar* TEST_ROOT_FOLDER_1_NAME = TXT(\"Test-Root-Folder-1\");\n\nstatic const tchar* TEST_ROOT_FOLDER_2_NAME = TXT(\"Test-Root-Folder-2\");\n\nstatic const tchar* TEST_ROOT_FILE_1_NAME = TXT(\"Test-Root-File-1.txt\");\n\nstatic const tchar* TEST_ROOT_FILE_2_NAME = TXT(\"Test-Root-File-2.doc\");\n\n\n", "file_path": "Test/FolderIteratorTests.cpp", "rank": 13, "score": 12.47486227456228 }, { "content": "** Parameters:\teFormat\t\tThe list of fields to serialise.\n\n**\n\n** Returns:\t\tThe font definition.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCString CLogFont::Format(FontFormat eFormat) const\n\n{\n\n\tCString strFont;\n\n\n\n\tint nFields = eFormat;\n\n\n\n\t// Always contains FaceName & Height.\n\n\tif (nFields >= FMT_MINIMAL)\n\n\t{\n\n\t\tstrFont += CString::Fmt(TXT(\"%s,%d\"), lfFaceName, lfHeight);\n\n\t}\n\n\n\n\t// Includes Weight, Italic, Underline & Strikeout?\n", "file_path": "LogFont.cpp", "rank": 14, "score": 12.21817956318461 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file StringTests.cpp\n\n//! \\brief The unit tests for the CString class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <Core/tiosfwd.hpp>\n\n#include <sstream>\n\n#include <WCL/StringIO.hpp>\n\n#include <WCL/MemStream.hpp>\n\n#include <WCL/Buffer.hpp>\n\n\n\nTEST_SET(String)\n\n{\n\n\tCString str = CString::Fmt(TXT(\"%s\"), TXT(\"Hello World\"));\n\n\n\nTEST_CASE(\"[in]equality operator performs a case-sensitive comparison\")\n\n{\n\n\tTEST_TRUE(str == TXT(\"Hello World\"));\n", "file_path": "Test/StringTests.cpp", "rank": 15, "score": 12.111214135454539 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file AppConfigTests.cpp\n\n//! \\brief The unit tests for the AppConfig class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/AppConfig.hpp>\n\n#include <WCL/RegKey.hpp>\n\n#include <Core/StringUtils.hpp>\n\n#include <WCL/IniFile.hpp>\n\n#include <WCL/File.hpp>\n\n\n\nstatic HKEY s_rootKey = HKEY_CURRENT_USER;\n\nstatic tstring s_publisher = TXT(\"Chris Oldwood\");\n\nstatic tstring s_pubPath = Core::fmt(TXT(\"Software\\\\%s\"), s_publisher.c_str());\n\nstatic tstring s_application = TXT(\"Unit Tests\");\n\nstatic tstring s_appPath = Core::fmt(TXT(\"Software\\\\%s\\\\%s\"), s_publisher.c_str(), s_application.c_str());\n\n\n\nnamespace\n\n{\n\n\n", "file_path": "Test/AppConfigTests.cpp", "rank": 16, "score": 12.071656618057443 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file RegistryCfgProviderTests.cpp\n\n//! \\brief The unit tests for the RegistryCfgProvider class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/RegistryCfgProvider.hpp>\n\n#include <WCL/Path.hpp>\n\n#include <Core/StringUtils.hpp>\n\n#include <WCL/RegKey.hpp>\n\n\n\nstatic const HKEY rootKey = HKEY_CURRENT_USER;\n\nstatic const tstring publisher = TXT(\"Chris Oldwood\");\n\nstatic const tstring pubPath = Core::fmt(TXT(\"Software\\\\%s\"), publisher.c_str());\n\nstatic const tstring application = TXT(\"Unit Tests\");\n\nstatic const tstring appPath = Core::fmt(TXT(\"Software\\\\%s\\\\%s\"), publisher.c_str(), application.c_str());\n\n\n\nTEST_SET(RegistryCfgProvider)\n\n{\n", "file_path": "Test/RegistryCfgProviderTests.cpp", "rank": 17, "score": 11.87287778310731 }, { "content": "\n\nvoid CEditBox::GetCreateParams(WNDCREATE& rParams)\n\n{\n\n\t// Get base class settings.\n\n\tCCtrlWnd::GetCreateParams(rParams);\n\n\n\n\t// Override any settings.\n\n\trParams.pszClassName = TXT(\"EDIT\");\n\n\trParams.dwStyle |= ES_MULTILINE | ES_AUTOVSCROLL | ES_LEFT | WS_VSCROLL;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tWndProc()\n\n**\n\n** Description:\tCatch WM_CHAR messages and filter the characters, if required.\n\n**\t\t\t\t\n\n** Parameters:\tStandard window procedure parameters.\n\n**\n\n** Returns:\t\tLRESULT based on the message.\n\n**\n", "file_path": "EditBox.cpp", "rank": 18, "score": 11.573252831242733 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file StringUtilsTests.cpp\n\n//! \\brief The unit tests for the string utility functions.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/StringUtils.hpp>\n\n#include <WCL/Rect.hpp>\n\n\n\nTEST_SET(StringUtils)\n\n{\n\n\n\nTEST_CASE(\"a rectangle is serialised to a string as a comma separated list of the members\")\n\n{\n\n\tTEST_TRUE(Core::format<>(CRect(1,2,3,4)) == TXT(\"1,2,3,4\"));\n\n\tTEST_TRUE(Core::parse<CRect>(TXT(\"1,2,3,4\")) == CRect(1,2,3,4));\n\n\n\n\tTEST_THROWS(Core::parse<CRect>(TXT(\"1,2,3\")));\n\n\tTEST_THROWS(Core::parse<CRect>(TXT(\"A,B,C,D\")));\n\n}\n\nTEST_CASE_END\n\n\n\n}\n\nTEST_SET_END\n", "file_path": "Test/StringUtilsTests.cpp", "rank": 19, "score": 11.518584449760748 }, { "content": "bool CDecimalBox::FilterKey(tchar cChar)\n\n{\n\n\t// Check base class first.\n\n\tif (CEditBox::FilterKey(cChar))\n\n\t\treturn true;\n\n\n\n\ttchar szText[MAX_DBL_STR_LEN+1] = { 0 };\n\n\tint\t nSelStart, nSelEnd;\n\n\n\n\t// Get the current text.\n\n\tEdit_GetText(m_hWnd, szText, MAX_DBL_STR_LEN);\n\n\n\n\t// Get the current selection.\n\n\tSelected(nSelStart, nSelEnd);\n\n\n\n\tint nSelChars = nSelEnd - nSelStart;\n\n\n\n\t// Is the sign char?\n\n\tif ( (cChar == TXT('+')) || (cChar == TXT('-')) )\n\n\t{\n", "file_path": "DecimalBox.cpp", "rank": 20, "score": 11.499806265061864 }, { "content": "\n\n\tLONG lResult = ::RegSetValue(m_hKey, NULL, REG_SZ, pszValue, static_cast<DWORD>(tstrlen(pszValue)));\n\n\n\n\tif (lResult != ERROR_SUCCESS)\n\n\t\tthrow RegistryException(lResult, TXT(\"Failed to write the default key value\"));\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n//! Write a named string value under the key.\n\n\n\nvoid RegKey::WriteStringValue(const tchar* pszName, const tchar* pszValue)\n\n{\n\n\tASSERT(m_hKey != NULL);\n\n\tASSERT(pszValue != nullptr);\n\n\n\n\tsize_t nChars = tstrlen(pszValue);\n\n\tsize_t nBytes = Core::numBytes<tchar>(nChars) + sizeof(tchar);\n\n\n\n\tLONG lResult = ::RegSetValueEx(m_hKey, pszName, 0, REG_SZ, reinterpret_cast<CONST BYTE*>(pszValue), static_cast<DWORD>(nBytes));\n\n\n", "file_path": "RegKey.cpp", "rank": 21, "score": 11.354947611004684 }, { "content": "TEST_CASE_END\n\n\n\nTEST_CASE(\"path can be implictly converted to various string types\")\n\n{\n\n\tCPath path(TXT(\"C:\\\\Temp\"));\n\n\n\n\tconst tchar* path_cstr = path;\n\n\tTEST_TRUE(tstrcmp(path_cstr, TXT(\"C:\\\\Temp\")) == 0);\n\n\n\n\tCString path_cstring = path;\n\n\tTEST_TRUE(path_cstring == TXT(\"C:\\\\Temp\"));\n\n\n\n\ttstring path_tstring(path);\n\n\tTEST_TRUE(path_tstring == TXT(\"C:\\\\Temp\"));\n\n}\n\nTEST_CASE_END\n\n\n\nTEST_CASE(\"the parent of a path is the containing folder\")\n\n{\n\n\tCPath filePath(TXT(\"C:\\\\Parent\\\\File.Ext\"));\n", "file_path": "Test/PathTests.cpp", "rank": 23, "score": 11.168177885832382 }, { "content": "** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCStatusBarLabel::CStatusBarLabel(size_t nChars)\n\n\t: m_nChars(nChars)\n\n\t, m_strLabel()\n\n{\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDestructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tNone.\n\n**\n", "file_path": "StatusBarLabel.cpp", "rank": 24, "score": 11.108869012982389 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file IniFileCfgProviderTests.cpp\n\n//! \\brief The unit tests for the IniFileCfgProvider class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/IniFileCfgProvider.hpp>\n\n#include <WCL/File.hpp>\n\n\n\nTEST_SET(IniFileCfgProvider)\n\n{\n\n\tconst tstring publisher = TXT(\"Chris Oldwood\");\n\n\tconst tstring application = TXT(\"Unit Tests\");\n\n\n\nTEST_CASE_SETUP()\n\n{\n\n\tCIniFile iniFile;\n\n\n\n\tASSERT(!iniFile.m_strPath.Exists());\n", "file_path": "Test/IniFileCfgProviderTests.cpp", "rank": 25, "score": 10.936737766485761 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file ConsoleCmdTests.cpp\n\n//! \\brief The unit tests for the ConsoleCmd class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/ConsoleCmd.hpp>\n\n#include <Core/CmdLineException.hpp>\n\n#include <sstream>\n\n\n\n#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) // GCC 4.2+\n\n// deprecated conversion from string constant to 'tchar*'\n\n#pragma GCC diagnostic ignored \"-Wwrite-strings\"\n\n#endif\n\n\n\nstatic Core::CmdLineSwitch s_switches[] =\n\n{\n\n\t{ 1, TXT(\"?\"), nullptr, Core::CmdLineSwitch::ONCE, Core::CmdLineSwitch::NONE, nullptr, TXT(\"Test\") },\n\n};\n\nstatic size_t s_switchCount = ARRAY_SIZE(s_switches);\n\n\n", "file_path": "Test/ConsoleCmdTests.cpp", "rank": 26, "score": 10.878769692544521 }, { "content": "\tconst tchar* expectedDescription = TXT(\"description\");\n\n\tconst tchar* expectedUsage = TXT(\"usage\");\n\n\tconst tchar* expectedException = TXT(\"error reason\");\n\n\tconst int expectedReturnCode = EXIT_FAILURE;\n\n\n\n\ttchar* argv[] = { TXT(\"Test.exe\"), TXT(\"command\") };\n\n\tconst int argc = ARRAY_SIZE(argv);\n\n\n\n\tTestCmd command(argc, argv);\n\n\ttostringstream out, err;\n\n\n\n\tcommand.m_description = expectedDescription;\n\n\tcommand.m_usage = expectedUsage;\n\n\tcommand.m_exception = expectedException;\n\n\n\n\tint result = command.execute(out, err);\n\n\n\n\tTEST_TRUE(result == expectedReturnCode);\n\n\n\n\tTEST_TRUE(tstrstr(out.str().c_str(), expectedDescription) != nullptr);\n", "file_path": "Test/ConsoleCmdTests.cpp", "rank": 27, "score": 10.876663566550501 }, { "content": "*/\n\n\n\nvoid CDecimalBox::OnCreate(const CRect&)\n\n{\n\n\tTextLimit(m_nMaxChars);\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFilterKey()\n\n**\n\n** Description:\tCalled on WM_CHAR to determine if the the keystroke should be\n\n**\t\t\t\tallowed or not.\n\n**\n\n** Parameters:\tcChar\tThe character to test.\n\n**\n\n** Returns:\t\ttrue or false.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n", "file_path": "DecimalBox.cpp", "rank": 28, "score": 10.85251459766272 }, { "content": "**\n\n** Parameters:\trStream\t\tThe stream to read from.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid operator >>(WCL::IInputStream& rStream, CString& rString)\n\n{\n\n\tuint32 numChars = 0;\n\n\n\n\trStream >> numChars;\n\n\n\n\tif (numChars != 0)\n\n\t{\n\n\t\trString.BufferSize(numChars);\n\n\t\trStream.Read(rString.m_pszData, Core::numBytes<tchar>(numChars));\n\n\t}\n\n}\n", "file_path": "String.cpp", "rank": 29, "score": 10.849713948222416 }, { "content": "**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::LoadRsc(uint iRscID)\n\n{\n\n\t// Initial buffer size.\n\n\tsize_t nChars = 32;\n\n\n\n\tBufferSize(nChars+1);\n\n\n\n\t// Load until buffer is big enough.\n\n\twhile(static_cast<size_t>(::LoadString(CModule::This().Handle(), iRscID, m_pszData, static_cast<int>(nChars+1))) == nChars)\n\n\t{\n\n\t\tnChars *= 2;\n\n\t\tBufferSize(nChars+1);\n\n\t}\n\n}\n", "file_path": "String.cpp", "rank": 30, "score": 10.844865639474087 }, { "content": "\t\tstrFilter += TXT('.');\n\n\t\t++m_nMaxChars;\n\n\t}\n\n/*\n\n\t// Allow fractions?\n\n\tif (m_nFlags & ALLOW_FRACTIONS)\n\n\t{\n\n\t\tstrFilter += \"/ \";\n\n\t\t++m_nMaxChars;\n\n\t}\n\n*/\n\n\tFilter(strFilter);\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDestructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tNone.\n", "file_path": "DecimalBox.cpp", "rank": 31, "score": 10.83580209802571 }, { "content": "bool CIniFile::ReadBool(const tchar* pszSection, const tchar* pszEntry, bool bDefault) const\n\n{\n\n\tASSERT(pszSection);\n\n\tASSERT(pszEntry);\n\n\n\n\ttchar szValue[MAX_CHARS+1] = { 0 };\n\n\n\n\t// Read as a string.\n\n\t::GetPrivateProfileString(pszSection, pszEntry, TXT(\"\"), szValue, MAX_CHARS, m_strPath);\n\n\n\n\t// Read anything?\n\n\tif (szValue[0] == TXT('\\0'))\n\n\t\treturn bDefault;\n\n\n\n\t// Check first character.\n\n\treturn ( (szValue[0] == TXT('T')) || (szValue[0] == TXT('t')) );\n\n}\n\n\n\nbool CIniFile::ReadBool(const tstring& strSection, const tstring& strEntry, bool bDefault) const\n\n{\n", "file_path": "IniFile.cpp", "rank": 33, "score": 10.808060040601951 }, { "content": "\t\t\t*psz = cNewChar;\n\n\n\n\t\t++psz;\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tReplace()\n\n**\n\n** Description:\tReplaces a character with a string.\n\n**\n\n** Parameters:\tcChar\t\tThe character to replace.\n\n**\t\t\t\tpszString\tThe string to replace it with.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::Replace(tchar cChar, const tchar* pszString)\n", "file_path": "String.cpp", "rank": 34, "score": 10.802884396507114 }, { "content": "}\n\n\n\nCString CStrCvt::FormatDateTime(time_t tValue)\n\n{\n\n\tconst size_t MAX_CHARS = 19;\n\n\ttchar szValue[MAX_CHARS+1];\n\n\n\n\tif (_tcsftime(szValue, MAX_CHARS+1, TXT(\"%Y-%m-%d %H:%M:%S\"), localtime(&tValue)) == 0)\n\n\t\tthrow Core::BadLogicException(TXT(\"Insufficient buffer size used in CStrCvt::FormatDateTime()\"));\n\n\n\n\treturn szValue;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFormatError()\n\n**\n\n** Description:\tConverts a system error code to a string.\n\n**\n\n** Parameters:\tdwError\t\tThe error code.\n\n**\n", "file_path": "StrCvt.cpp", "rank": 35, "score": 10.790386693756274 }, { "content": "\t\t// Always allow Backspace.\n\n\t\tm_pFilter[8] = true;\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFilterKey()\n\n**\n\n** Description:\tCalled on WM_CHAR to determine if the the keystroke should be\n\n**\t\t\t\tallowed or not.\n\n**\n\n** Parameters:\tcChar\tThe character to test.\n\n**\n\n** Returns:\t\ttrue or false.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nbool CEditBox::FilterKey(tchar cChar)\n\n{\n", "file_path": "EditBox.cpp", "rank": 36, "score": 10.753778468601514 }, { "content": "\t\t// Extract details.\n\n\t\tm_strName = tstrtok(szPrinter, TXT(\",\"));\n\n\t\tm_strDriver = tstrtok(nullptr, TXT(\",\"));\n\n\t\tm_strPort = tstrtok(nullptr, TXT(\",\"));\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDestructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCPrinter::~CPrinter()\n", "file_path": "Printer.cpp", "rank": 37, "score": 10.720136946299299 }, { "content": "\t\tm_pszData[iStrLen] = cChar;\n\n\t\tm_pszData[iStrLen+1] = TXT('\\0');\n\n\n\n\t\t// Free old string, if not empty string.\n\n\t\tif (pOldData != &strNULL)\n\n\t\t\tfree(pOldData);\n\n\t}\n\n\telse\n\n\t{\n\n\t\t// Just append.\n\n\t\tm_pszData[iStrLen] = cChar;\n\n\t\tm_pszData[iStrLen+1] = TXT('\\0');\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\toperator>>()\n\n**\n\n** Description:\tLoad the string in from a stream. This reads the buffer size,\n\n**\t\t\t\tallocates the space and reads the whole string.\n", "file_path": "String.cpp", "rank": 38, "score": 10.677978651498535 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file AppConfig.cpp\n\n//! \\brief The AppConfig class definition.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include \"AppConfig.hpp\"\n\n#include \"IniFileCfgProvider.hpp\"\n\n#include \"RegistryCfgProvider.hpp\"\n\n#include <Core/Tokeniser.hpp>\n\n\n\nnamespace WCL\n\n{\n\n\n\n//! The name for the default section.\n\nconst tstring AppConfig::DEFAULT_SECTION = TXT(\"\");\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n//! Constructor.\n\n\n", "file_path": "AppConfig.cpp", "rank": 39, "score": 10.658289567918988 }, { "content": "*******************************************************************************\n\n*/\n\n\n\nCString& CString::Trim(bool bLeft, bool bRight)\n\n{\n\n\t// Trim leading?\n\n\tif (bLeft)\n\n\t{\n\n\t\tsize_t nChars = 0;\n\n\n\n\t\tfor (tchar* psz = m_pszData; (*psz != TXT('\\0')) && (tisspace(static_cast<utchar>(*psz))); ++psz)\n\n\t\t\t++nChars;\n\n\n\n\t\tDelete(0, nChars);\n\n\t}\n\n\n\n\tsize_t nLength = Length();\n\n\n\n\t// Trim trailing?\n\n\tif (bRight)\n", "file_path": "String.cpp", "rank": 40, "score": 10.634261615941778 }, { "content": "**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCPrinter::CPrinter()\n\n\t: m_strName()\n\n\t, m_strDriver()\n\n\t, m_strPort()\n\n{\n\n\tconst size_t MAX_LEN = 1024;\n\n\ttchar szPrinter[MAX_LEN+1] = { 0 };\n\n\n\n\t// Get the defualt printer.\n\n\tGetProfileString(TXT(\"Windows\"), TXT(\"Device\"), TXT(\"\"), szPrinter, MAX_LEN);\n\n\n\n\t// Is a default?\n\n\tif ( (szPrinter[0] != TXT('\\0')) && (tstrcmp(szPrinter, TXT(\",,,\")) != 0) )\n\n\t{\n", "file_path": "Printer.cpp", "rank": 41, "score": 10.60910548286826 }, { "content": "\t// Ensure string is terminated.\n\n\t*(strContents.Buffer()+nChars) = TXT('\\0');\n\n\n\n\treturn nChars;\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n//! Read the entire contents of a text file.\n\n\n\ntstring CFile::ReadTextFile(const tchar* pszPath)\n\n{\n\n\tCString str;\n\n\tTextFormat eFormat;\n\n\n\n\tsize_t nChars = ReadTextFile(pszPath, str, eFormat);\n\n\n\n\treturn tstring(str.Buffer(), str.Buffer()+nChars);\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n", "file_path": "File.cpp", "rank": 42, "score": 10.555821316020168 }, { "content": "** Parameters:\tpszPath\t\tThe path to append.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CPath::operator/=(const tchar* pszPath)\n\n{\n\n\tASSERT(pszPath != NULL);\n\n\n\n\t// Check RHS path for leading separator.\n\n\tif ((*pszPath != TXT('\\\\')) && (*pszPath != TXT('/')))\n\n\t{\n\n\t\tsize_t nLength = Length();\n\n\n\n\t\t// Check LHS path for trailing separator.\n\n\t\tif ( (nLength > 0) && (m_pszData[nLength-1] != TXT('\\\\')) )\n\n\t\t\toperator +=(TXT('\\\\'));\n\n\t}\n", "file_path": "Path.cpp", "rank": 43, "score": 10.360413634004795 }, { "content": "CDecimalBox::CDecimalBox(bool bSigned, uint nIntDigits, uint nDecDigits, uint nFlags)\n\n\t: m_bSigned(bSigned)\n\n\t, m_nIntDigits(nIntDigits)\n\n\t, m_nDecDigits(nDecDigits)\n\n\t, m_nMaxChars(nIntDigits + nDecDigits)\n\n\t, m_nFlags(nFlags)\n\n{\n\n\t// Setup character filter.\n\n\tCString strFilter(TXT(\"0123456789\"));\n\n\n\n\t// Allow signed values?\n\n\tif (m_bSigned)\n\n\t{\n\n\t\tstrFilter += TXT(\"+-\");\n\n\t\t++m_nMaxChars;\n\n\t}\n\n\n\n\t// Allow decimal point?\n\n\tif (nDecDigits)\n\n\t{\n", "file_path": "DecimalBox.cpp", "rank": 44, "score": 10.358157957908237 }, { "content": "\tHRESULT hr = ::CoCreateInstance(rCLSID, nullptr, CLSCTX_ALL, oIID, reinterpret_cast<LPVOID*>(&this->m_ptr));\n\n\n\n\tif (FAILED(hr))\n\n\t{\n\n\t\twchar_t szBuffer[MAX_GUID_CHARS+1];\n\n\n\n\t\t// Convert the CLSID to a string.\n\n\t\tif (::StringFromGUID2(rCLSID, szBuffer, MAX_GUID_CHARS+1) == 0)\n\n\t\t\tthrow Core::BadLogicException(TXT(\"Invalid buffer size passed to StringFromGUID2()\"));\n\n\n\n\t\tCString strCLSID = W2T(szBuffer);\n\n\n\n\t\t// Convert the IID to a string.\n\n\t\tif (::StringFromGUID2(oIID, szBuffer, MAX_GUID_CHARS+1) == 0)\n\n\t\t\tthrow Core::BadLogicException(TXT(\"Invalid buffer size passed to StringFromGUID2()\"));\n\n\n\n\t\tCString strIID = W2T(szBuffer);\n\n\n\n\t\tthrow ComException(hr, CString::Fmt(TXT(\"Failed to create a COM object of class %s or obtain the interface %s\"), strCLSID.c_str(), strIID.c_str()));\n\n\t}\n", "file_path": "ComPtr.hpp", "rank": 45, "score": 10.352146241876838 }, { "content": "\ttchar szPath[MAX_PATH+1] = { 0 };\n\n\n\n\t// Get the Applications full path and name.\n\n\tDWORD dwChars = ::GetModuleFileName(NULL, szPath, MAX_PATH);\n\n\n\n\tif (dwChars == 0)\n\n\t\tthrow WCL::Win32Exception(::GetLastError(), TXT(\"Failed to retrieve the full path of the module\"));\n\n\n\n\t// Assume no path by default.\n\n\ttchar* pszFileName = szPath;\n\n\n\n\t// Find the start of the filename.\n\n\ttchar* pszFinalSep = tstrrchr(szPath, TXT('\\\\'));\n\n\n\n\tif (pszFinalSep != nullptr)\n\n\t\tpszFileName = pszFinalSep+1;\n\n\n\n\t// Append or replace the extension.\n\n\ttchar* pszExt = tstrrchr(pszFileName, TXT('.'));\n\n\n", "file_path": "IniFile.cpp", "rank": 46, "score": 10.290560950074386 }, { "content": "\t\t\tconst wchar_t* pBuffer = static_cast<const wchar_t*>(m_pBuffer);\n\n\n\n#ifdef ANSI_BUILD\n\n\t\t\treturn CString(Core::wideToAnsi(pBuffer, pBuffer+nChars).c_str());\n\n#else\n\n\t\t\treturn CString(pBuffer, nChars);\n\n#endif\n\n\t\t}\n\n\t}\n\n\n\n\treturn TXT(\"\");\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n//! Fill the buffer with the contents of a string.\n\n\n\nvoid CBuffer::FromString(const CString& str, TextFormat eFormat, bool bIncNull)\n\n{\n\n\tsize_t nChars = str.Length();\n\n\n", "file_path": "Buffer.cpp", "rank": 47, "score": 10.22850813954479 }, { "content": "\n\n\t// Get the size of the buffer and allocate one.\n\n\tint nChars = ::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDATE, nullptr, 0);\n\n\n\n\ttchar* pszBuffer = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\tpszBuffer[0] = TXT('\\0');\n\n\n\n\t// Get the locale string.\n\n\tif (::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDATE, pszBuffer, nChars+1) != 0)\n\n\t{\n\n\t\teOrder = static_cast<DateOrder>(_ttoi(pszBuffer));\n\n\n\n\t\tif ((eOrder != MONTH_DAY_YEAR) && (eOrder != DAY_MONTH_YEAR) && (eOrder != YEAR_MONTH_DAY))\n\n\t\t\tthrow Core::BadLogicException(Core::fmt(TXT(\"Unsupported locale date order '%s'\"), pszBuffer));\n\n\t}\n\n\n\n\treturn eOrder;\n\n}\n\n\n", "file_path": "Date.cpp", "rank": 48, "score": 10.206468080903282 }, { "content": "** Parameters:\tNone.\n\n**\n\n** Returns:\t\tThe string.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCString CComboBox::Text() const\n\n{\n\n\tCString\tstrText;\n\n\n\n\t// Get string length.\n\n\tsize_t nChars = TextLength();\n\n\n\n\t// Allocate space.\n\n\tstrText.BufferSize(nChars+1);\n\n\n\n\t// Fetch string.\n\n\tComboBox_GetText(m_hWnd, strText.Buffer(), static_cast<int>(nChars+1));\n\n\n", "file_path": "ComboBox.cpp", "rank": 49, "score": 10.202263436842678 }, { "content": "*******************************************************************************\n\n*/\n\n\n\nsize_t CIniFile::ReadSectionNames(CStrArray& astrNames)\n\n{\n\n\t// Allocate initial buffer.\n\n\tsize_t nChars = 1024;\n\n\ttchar* pszNames = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\t// Read all names, reallocating if necessary...\n\n\twhile (::GetPrivateProfileSectionNames(pszNames, static_cast<DWORD>(nChars), m_strPath) >= (nChars-2))\n\n\t{\n\n\t\t// Double the buffer size.\n\n\t\tnChars *= 2;\n\n\t\tpszNames = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\t}\n\n\n\n\t// For all strings.\n\n\twhile (*pszNames != TXT('\\0'))\n\n\t{\n", "file_path": "IniFile.cpp", "rank": 50, "score": 10.192050325836828 }, { "content": "**\n\n** Returns:\t\tThe string.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCString CWnd::Title() const\n\n{\n\n\tCString\tstrText;\n\n\n\n\t// Get string length.\n\n\tsize_t nChars = SendMessage(WM_GETTEXTLENGTH, 0, 0L);\n\n\n\n\t// Allocate space.\n\n\tstrText.BufferSize(nChars+1);\n\n\n\n\t// Fetch string.\n\n\tSendMessage(WM_GETTEXT, nChars+1, reinterpret_cast<LPARAM>(strText.Buffer()));\n\n\n\n\treturn strText;\n\n}\n", "file_path": "Wnd.cpp", "rank": 51, "score": 10.159211439340261 }, { "content": "\t// Increase buffer size?\n\n\tif (pData->m_nAllocSize < nChars)\n\n\t{\n\n\t\tFree();\n\n\n\n\t\tsize_t nBytes = Core::numBytes<tchar>(nChars);\n\n\n\n\t\t// Allocate new buffer.\n\n\t\tpData = static_cast<StringData*>(malloc(nBytes + sizeof(StringData)));\n\n\t\tASSERT(pData != nullptr);\n\n\n\n\t\tpData->m_nAllocSize = nChars;\n\n\t\tpData->m_acData[0] = TXT('\\0');\n\n\n\n\t\tm_pszData = pData->m_acData;\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tCopy()\n", "file_path": "String.cpp", "rank": 52, "score": 10.143092520455195 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file IniFileTests.cpp\n\n//! \\brief The unit tests for the IniFile class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/IniFile.hpp>\n\n\n\nTEST_SET(IniFile)\n\n{\n\n\n\nTEST_CASE(\"default construction refers to a file with the name of the process and an .ini extension\")\n\n{\n\n\tconst tchar* processName = TXT(\"test\");\n\n\tconst CPath folder = CPath::ApplicationDir();\n\n\n\n\ttstring expected = Core::fmt(TXT(\"%s\\\\%s.ini\"), folder.c_str(), processName);\n\n\n\n\tCIniFile oIniFile;\n\n\n\n\tTEST_TRUE(tstricmp(expected.c_str(), oIniFile.m_strPath) == 0);\n\n}\n\nTEST_CASE_END\n\n\n\n}\n\nTEST_SET_END\n", "file_path": "Test/IniFileTests.cpp", "rank": 53, "score": 10.054354793409443 }, { "content": "\treturn str;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFind()\n\n**\n\n** Description:\tFinds the first occurence of the character in the string\n\n**\t\t\t\tstarting from the position specified.\n\n**\n\n** Parameters:\tcChar\tThe character to find.\n\n**\n\n** Returns:\t\tThe zero based index of the character OR\n\n**\t\t\t\t-1 if the character was not found.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nsize_t CString::Find(tchar cChar, size_t nStart) const\n\n{\n\n\tASSERT(nStart <= Length());\n", "file_path": "String.cpp", "rank": 54, "score": 10.04354426585408 }, { "content": "\tif (numChars != 0)\n\n\t{\n\n\t\trStream.Write(rString.m_pszData, Core::numBytes<tchar>(numChars));\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFormat()\n\n**\n\n** Description:\tFormat the string using sprintf() style variable args..\n\n**\n\n** Parameters:\tSee sprintf().\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::Format(const tchar* pszFormat, ...)\n\n{\n", "file_path": "String.cpp", "rank": 55, "score": 9.992190760664535 }, { "content": "\n\n/******************************************************************************\n\n** Method:\t\tBufferSize()\n\n**\n\n** Description:\tEnsure enough space is allocated for the string and the null\n\n**\t\t\t\tterminator.\n\n**\n\n** Parameters:\tiSize\tThe buffer length in characters, inc a null terminator.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::BufferSize(size_t nChars)\n\n{\n\n\tASSERT(nChars > 0);\n\n\n\n\tStringData* pData = GetData();\n\n\n", "file_path": "String.cpp", "rank": 56, "score": 9.992190760664535 }, { "content": "** Description:\t.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCDoc::CDoc()\n\n\t: m_Path(TXT(\"Untitled\"))\n\n{\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDestructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tNone.\n", "file_path": "Doc.cpp", "rank": 57, "score": 9.946620796106163 }, { "content": "\tif (pszExt != nullptr)\n\n\t\ttstrcpy(pszExt, TXT(\".ini\"));\n\n\telse\n\n\t\ttstrcat(pszFileName, TXT(\".ini\"));\n\n\n\n\t// Save final path.\n\n\tm_strPath = szPath;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tConstructor.\n\n**\n\n** Description:\tInitialises with the given path.\n\n**\n\n** Parameters:\tpszPath\t\t.INI file path.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n", "file_path": "IniFile.cpp", "rank": 58, "score": 9.91779706315493 }, { "content": "\n\n/******************************************************************************\n\n** Method:\t\toperator<<()\n\n**\n\n** Description:\tSave the string out to a stream. This stores the size of the\n\n**\t\t\t\tbuffer followed by the buffer.\n\n**\n\n** Parameters:\trStream\t\tThe stream to write to.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid operator <<(WCL::IOutputStream& rStream, const CString& rString)\n\n{\n\n\tuint32 numChars = rString.GetData()->m_nAllocSize;\n\n\n\n\trStream << numChars;\n\n\n", "file_path": "String.cpp", "rank": 59, "score": 9.89112707537851 }, { "content": "size_t CIniFile::ReadSection(const tchar* pszSection, CStrArray& astrEntries)\n\n{\n\n\tASSERT(pszSection);\n\n\n\n\t// Allocate initial buffer.\n\n\tsize_t nChars = 1024;\n\n\ttchar* pszEntries = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\t// Read all entries, reallocating if necessary...\n\n\twhile (::GetPrivateProfileSection(pszSection, pszEntries, static_cast<DWORD>(nChars), m_strPath) >= (nChars-2))\n\n\t{\n\n\t\t// Double the buffer size.\n\n\t\tnChars *= 2;\n\n\t\tpszEntries = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\t}\n\n\n\n\t// For all strings.\n\n\twhile (*pszEntries != TXT('\\0'))\n\n\t{\n\n\t\tastrEntries.Add(pszEntries);\n", "file_path": "IniFile.cpp", "rank": 60, "score": 9.875444140248884 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file PathTests.cpp\n\n//! \\brief The unit tests for the CPath class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/Path.hpp>\n\n\n\nTEST_SET(Path)\n\n{\n\n\n\nTEST_CASE(\"Initial state is an empty string\")\n\n{\n\n\tTEST_TRUE(CPath().Empty());\n\n\tTEST_TRUE(CPath().Length() == 0);\n\n\tTEST_TRUE(CPath() == TXT(\"\"));\n\n}\n\nTEST_CASE_END\n\n\n", "file_path": "Test/PathTests.cpp", "rank": 61, "score": 9.870151057705456 }, { "content": "\t\t\tstr += *psz;\n\n\t\t\tpsz += 1;\n\n\t\t}\n\n\t}\n\n\n\n\tCopy(str);\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tRepCtrlChars()\n\n**\n\n** Description:\tReplaces any control characters with its \"C\" equivalent.\n\n**\t\t\t\te.g. 0x0A -> \"\\n\"\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tThis.\n\n**\n\n*******************************************************************************\n\n*/\n", "file_path": "String.cpp", "rank": 62, "score": 9.86897931152642 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file ResourceStringTests.cpp\n\n//! \\brief The unit tests for the resource string utility functions.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/ResourceString.hpp>\n\n#include \"Resource.h\"\n\n\n\nTEST_SET(ResourceString)\n\n{\n\n\tHMODULE module = ::GetModuleHandle(NULL);\n\n\n\nTEST_CASE(\"Loading a string for an invalid ID returns an empty string\")\n\n{\n\n\tconst uint INVALID_STRING_ID = 999;\n\n\tconst tstring expected = TXT(\"\");\n\n\n\n\tconst tstring actual = WCL::loadString(module, INVALID_STRING_ID);\n", "file_path": "Test/ResourceStringTests.cpp", "rank": 63, "score": 9.819381078031117 }, { "content": "*/\n\n\n\nCComCtl32::CComCtl32()\n\n\t: m_oDLL(TXT(\"COMCTL32.DLL\"))\n\n{\n\n\tm_oDLL.Load();\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDestructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n", "file_path": "ComCtl32.cpp", "rank": 64, "score": 9.802797144734487 }, { "content": "*******************************************************************************\n\n*/\n\n\n\nCString CTime::FieldSeparator()\n\n{\n\n\t// Get the size of the buffer and allocate one.\n\n\tint nChars = ::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STIME, nullptr, 0);\n\n\n\n\ttchar* pszBuffer = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\tpszBuffer[0] = TXT('\\0');\n\n\n\n\t// Get the locale string.\n\n\t::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STIME, pszBuffer, nChars+1);\n\n\n\n\treturn pszBuffer;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tToString()\n", "file_path": "Time.cpp", "rank": 65, "score": 9.777949655326477 }, { "content": "** Method:\t\tFormatLong()\n\n**\n\n** Description:\tConvert a long value to a string.\n\n**\n\n** Parameters:\tnValue\t\tThe value.\n\n**\n\n** Returns:\t\tThe value as a string.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCString CStrCvt::FormatLong(long lValue)\n\n{\n\n\tconst size_t MAX_CHARS = std::numeric_limits<long>::digits10+1;\n\n\n\n\ttchar szValue[MAX_CHARS+1] = { 0 };\n\n\n\n\treturn _ltot(lValue, szValue, 10);\n\n}\n\n\n", "file_path": "StrCvt.cpp", "rank": 66, "score": 9.74350435138492 }, { "content": "\n\n\toperator +=(pszPath);\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tExpandVars()\n\n**\n\n** Description:\tExpands any path variables such as %ProgramFiles%, %SystemRoot%\n\n**\t\t\t\tand %Temp% into the actual path.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CPath::ExpandVars()\n\n{\n\n\t// Do a crude search and replace on all possible matches.\n\n\tif (Find(TXT('%')) != Core::npos)\n\n\t{\n\n\t\tReplace(TXT(\"%ProgramFiles%\"), CPath::SpecialDir(CSIDL_PROGRAM_FILES));\n\n\t\tReplace(TXT(\"%SystemRoot%\"), CPath::WindowsDir());\n\n\t\tReplace(TXT(\"%Temp%\"), CPath::TempDir());\n\n\t}\n\n}\n", "file_path": "Path.cpp", "rank": 67, "score": 9.740583804270566 }, { "content": "{\n\n\tASSERT(pszString != nullptr);\n\n\n\n\tCString str;\n\n\tconst tchar* psz = m_pszData;\n\n\n\n\twhile (*psz != TXT('\\0'))\n\n\t{\n\n\t\tif (*psz == cChar)\n\n\t\t\tstr += pszString;\n\n\t\telse\n\n\t\t\tstr += *psz;\n\n\n\n\t\t++psz;\n\n\t}\n\n\n\n\tCopy(str);\n\n}\n\n\n\n/******************************************************************************\n", "file_path": "String.cpp", "rank": 68, "score": 9.720050770576714 }, { "content": "\t\tthrow Core::BadLogicException(Core::fmt(TXT(\"Insufficient buffer size calculated in CString::FormatEx(). Result: %d\"), nResult));\n\n\n\n\tm_pszData[nResult] = TXT('\\0');\n\n\n\n#endif\n\n}\n\n\n\n/******************************************************************************\n\n** Methods:\t\tFmt()\n\n**\t\t\t\tFmtEx()\n\n**\n\n** Description:\tFormat the string using sprintf() style variable args..\n\n**\n\n** Parameters:\tSee sprintf().\n\n**\n\n** Returns:\t\tThe formatted string.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n", "file_path": "String.cpp", "rank": 69, "score": 9.718990047886132 }, { "content": "**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCStrCvtException::CStrCvtException(int eErrCode)\n\n{\n\n\t// Convert error to string.\n\n\tswitch(eErrCode)\n\n\t{\n\n\t\tcase E_INVALID_FORMAT:\n\n\t\t\tm_details = TXT(\"Invalid format\");\n\n\t\t\tbreak;\n\n\n\n\t\tcase E_INVALID_RANGE:\n\n\t\t\tm_details = TXT(\"Number out of range\");\n\n\t\t\tbreak;\n\n\n\n\t\t// Shouldn't happen!\n", "file_path": "StrCvtException.cpp", "rank": 70, "score": 9.718990047886132 }, { "content": "\t\tif (::StringFromGUID2(oIID, szBuffer, MAX_GUID_CHARS+1) == 0)\n\n\t\t\tthrow Core::BadLogicException(TXT(\"Invalid buffer size passed to StringFromGUID2()\"));\n\n\n\n\t\tCString strIID = W2T(szBuffer);\n\n\n\n\t\tthrow ComException(hr, CString::Fmt(TXT(\"Failed to obtain the interface %s\"), strIID.c_str()));\n\n\t}\n\n}\n\n\n\n//namespace WCL\n\n}\n\n\n\n#endif // WCL_COMPTR_HPP\n", "file_path": "ComPtr.hpp", "rank": 72, "score": 9.649948819800786 }, { "content": "** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCMemStreamException::CMemStreamException(int eErrCode)\n\n{\n\n\t// Convert error to string.\n\n\tswitch(eErrCode)\n\n\t{\n\n\t\tcase E_OPEN_FAILED:\n\n\t\t\tm_details = TXT(\"An error occured opening a memory stream\");\n\n\t\t\tbreak;\n\n\n\n\t\tcase E_CREATE_FAILED:\n\n\t\t\tm_details = TXT(\"An error occured creating a memory stream\");\n\n\t\t\tbreak;\n\n\n\n\t\tcase E_READ_FAILED:\n\n\t\t\tm_details = TXT(\"An error occured reading from a memory stream\");\n", "file_path": "MemStreamException.cpp", "rank": 73, "score": 9.634618114452234 }, { "content": "**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CSDIFrame::UpdateTitle()\n\n{\n\n\t// Get application object.\n\n\tCSDIApp& oApp = CSDIApp::This();\n\n\n\n\t// Get the application name.\n\n\tCString strTitle = oApp.m_strTitle;\n\n\n\n\t// Append doc title, if available.\n\n\tif (oApp.m_pDoc != nullptr)\n\n\t{\n\n\t\tstrTitle += TXT(\" - [\");\n\n\t\tstrTitle += oApp.m_pDoc->Path();\n\n\t\tstrTitle += TXT(\"]\");\n", "file_path": "SDIFrame.cpp", "rank": 74, "score": 9.622698376354998 }, { "content": "\t\tpszEnd = m_pszString;\n\n\n\n\t\t// Stopped on a separator?\n\n\t\tif (*m_pszString != TXT('\\0'))\n\n\t\t{\n\n\t\t\t// Switch state, if returning separators.\n\n\t\t\tif (m_nFlags & RETURN_SEPS)\n\n\t\t\t{\n\n\t\t\t\tm_eNextToken = SEPARATOR_TOKEN;\n\n\t\t\t}\n\n\t\t\t// Skip separators.\n\n\t\t\telse \n\n\t\t\t{\n\n\t\t\t\t++m_pszString;\n\n\n\n\t\t\t\t// Merge consecutive separators?\n\n\t\t\t\tif (m_nFlags & MERGE_SEPS)\n\n\t\t\t\t{\n\n\t\t\t\t\twhile ( (*m_pszString != TXT('\\0')) && (tstrchr(m_strSeps, *m_pszString) != nullptr) )\n\n\t\t\t\t\t\t++m_pszString;\n", "file_path": "StrTok.cpp", "rank": 75, "score": 9.622698376354998 }, { "content": "\t{ CF_DIBV5,\t\t\tTXT(\"CF_DIBV5\") },\n\n\t{ CF_NONE,\t\t\tNULL }\n\n};\n\n\n\n/******************************************************************************\n\n** Method:\t\tConstructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCClipboard::CClipboard()\n\n\t: m_pBuffer()\n\n\t, m_pStream()\n\n\t, m_iFormat(0)\n", "file_path": "Clipboard.cpp", "rank": 76, "score": 9.594694706513339 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! The CRT hook function to write all TRACE and ASSERTs to a file.\n\n\n\nint TraceLogger::ReportHook(int /*nType*/, char* pszMessage, int* piRetVal)\n\n{\n\n\t// Create default logfile path.\n\n\tif (g_szTraceLog[0] == TXT('\\0'))\n\n\t\ttstrcpy(g_szTraceLog, CPath(CPath::ApplicationDir(), TXT(\"TraceLog.txt\")));\n\n\n\n\tFILE* fLogFile = _tfopen(g_szTraceLog, TXT(\"a\"));\n\n\n\n\t// Opened log file okay?\n\n\tif (fLogFile != nullptr)\n\n\t{\n\n\t\t// Start of new message?\n\n\t\tif (g_bNewLine)\n\n\t\t{\n\n\t\t\tSYSTEMTIME st = {0};\n\n\n\n\t\t\t::GetSystemTime(&st);\n", "file_path": "TraceLogger.cpp", "rank": 77, "score": 9.59234956844422 }, { "content": "\tTEST_TRUE(tstrstr(out.str().c_str(), expectedUsage) != nullptr);\n\n\tTEST_TRUE(tstrstr(err.str().c_str(), expectedException) != nullptr);\n\n}\n\nTEST_CASE_END\n\n\n\nTEST_CASE(\"execute should display command specific usage when an invalid command switch is found\")\n\n{\n\n\tconst tchar* expectedDescription = TXT(\"description\");\n\n\tconst tchar* expectedUsage = TXT(\"usage\");\n\n\tconst tchar* expectedException = TXT(\"--invalid-switch\");\n\n\tconst int expectedReturnCode = EXIT_FAILURE;\n\n\n\n\ttchar* argv[] = { TXT(\"Test.exe\"), TXT(\"command\"), TXT(\"--invalid-switch\") };\n\n\tconst int argc = ARRAY_SIZE(argv);\n\n\n\n\tTestCmd command(argc, argv);\n\n\ttostringstream out, err;\n\n\n\n\tcommand.m_description = expectedDescription;\n\n\tcommand.m_usage = expectedUsage;\n", "file_path": "Test/ConsoleCmdTests.cpp", "rank": 78, "score": 9.54037575575009 }, { "content": "\t\t\t\t\t\t\t\t\t\tTXT(\"Message: H=0x%p M=0x%08X W=0x%08X L=0x%08X\\n\\n%hs\"),\n\n\t\t\t\t\t\t\t\t\t\thWnd, iMsg, wParam, lParam, e.what());\n\n\t}\n\n\tcatch (...)\n\n\t{\n\n\t\tWCL::ReportUnhandledException(\tTXT(\"Unexpected unknown exception caught in DlgProc()\\n\\n\")\n\n\t\t\t\t\t\t\t\t\t\tTXT(\"Message: H=0x%p M=0x%08X W=0x%08X L=0x%08X\"),\n\n\t\t\t\t\t\t\t\t\t\thWnd, iMsg, wParam, lParam);\n\n\t}\n\n\n\n\t// Set the return value.\n\n\t::SetWindowLongPtr(hWnd, DWLP_MSGRESULT, lMsgResult);\n\n\n\n\t// Return if msg was handled.\n\n\treturn bMsgHandled;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDialogProc()\n\n**\n", "file_path": "Dialog.cpp", "rank": 79, "score": 9.520813119969358 }, { "content": "**\n\n*******************************************************************************\n\n*/\n\n\n\nint CStrCvt::ParseInt(const tchar* pszString, int nFlags)\n\n{\n\n\tASSERT(pszString != nullptr);\n\n\tASSERT((nFlags == PARSE_ANY_FORMAT) || (nFlags == PARSE_OCTAL_ONLY) || (nFlags == PARSE_DECIMAL_ONLY) || (nFlags == PARSE_HEX_ONLY));\n\n\n\n\terrno = 0;\n\n\n\n\ttchar* pcEndChar = nullptr;\n\n\n\n\tint nValue = tstrtol(pszString, &pcEndChar, nFlags);\n\n\t\n\n\tif (*pcEndChar != TXT('\\0'))\n\n\t\tthrow CStrCvtException(CStrCvtException::E_INVALID_FORMAT);\n\n\n\n\tASSERT((errno == 0) || (errno == ERANGE));\n\n\n", "file_path": "StrCvt.cpp", "rank": 80, "score": 9.513812214549088 }, { "content": "*******************************************************************************\n\n*/\n\n\n\ndouble CStrCvt::ParseDouble(const tchar* pszString, int /*nFlags*/)\n\n{\n\n\tASSERT(pszString != nullptr);\n\n\n\n\terrno = 0;\n\n\n\n\ttchar* pcEndChar = nullptr;\n\n\n\n\tdouble dValue = tstrtod(pszString, &pcEndChar);\n\n\t\n\n\tif (*pcEndChar != TXT('\\0'))\n\n\t\tthrow CStrCvtException(CStrCvtException::E_INVALID_FORMAT);\n\n\n\n\tASSERT((errno == 0) || (errno == ERANGE));\n\n\n\n\tif (errno == ERANGE)\n\n\t\tthrow CStrCvtException(CStrCvtException::E_INVALID_RANGE);\n\n\n\n\treturn dValue;\n\n}\n", "file_path": "StrCvt.cpp", "rank": 81, "score": 9.513812214549088 }, { "content": "**\t\t\t\tnStart\tThe start character.\n\n**\t\t\t\tnEnd\tThe end character + 1.\n\n**\n\n** Returns:\t\tThe number of occurrences.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nsize_t CString::Count(tchar cChar, size_t nStart, size_t nEnd) const\n\n{\n\n\tASSERT(nEnd <= Length());\n\n\tASSERT(nStart <= nEnd);\n\n\n\n\tsize_t nMatches = 0;\n\n\tconst tchar* pszStart = m_pszData+nStart;\n\n\tconst tchar* pszEnd = m_pszData+nEnd;\n\n\n\n\twhile (pszStart < pszEnd)\n\n\t{\n\n\t\tif (*pszStart == cChar)\n", "file_path": "String.cpp", "rank": 82, "score": 9.507495122023276 }, { "content": "\n\n/******************************************************************************\n\n**\n\n** Constants.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\n// Window class name.\n\nconst tchar* CFrameWnd::CLASS_NAME = TXT(\"FrameWnd\");\n\n\n\n/******************************************************************************\n\n** Method:\t\tDefault constructor.\n\n**\n\n** Description:\t.\n\n**\n\n** Parameters:\tiIconID\t\tThe frame window icon.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n", "file_path": "FrameWnd.cpp", "rank": 83, "score": 9.460799894217068 }, { "content": "\t\t\t\t\t\t\t\t\t\toTranslation.m_wLanguage, oTranslation.m_wCodePage, pszName);\n\n\n\n\tvoid* pValue = nullptr;\n\n\tuint nChars = 0;\n\n\n\n\t// Read the value.\n\n\tBOOL bResult = ::VerQueryValue(m_pBuffer.get(), const_cast<tchar*>(strEntry.c_str()), &pValue, &nChars);\n\n\n\n\ttstring strResult;\n\n\n\n\tif (bResult != 0)\n\n\t{\n\n\t\t// Create the return value from the buffer.\n\n\t\t// NB: We have to strip the nul terminator, if present.\n\n\t\tconst tchar* pszBegin = static_cast<const tchar*>(pValue);\n\n\t\tconst tchar* pszEnd = std::find(pszBegin, pszBegin + nChars, TXT('\\0'));\n\n\n\n\t\tstrResult = tstring(pszBegin, pszEnd);\n\n\t}\n\n\n", "file_path": "VerInfoReader.cpp", "rank": 84, "score": 9.405453093036186 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file DateTimeTests.cpp\n\n//! \\brief The unit tests for the CDateTime class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/DateTime.hpp>\n\n\n\nTEST_SET(DateTime)\n\n{\n\n\tCDateTime testDateTime(CDate(1, 2, 2003), CTime(1, 2, 3));\n\n\n\nTEST_CASE(\"using ISO format outputs an ISO date and time separated by a 'T'\")\n\n{\n\n\tTEST_TRUE(testDateTime.ToString(CDate::FMT_ISO, CTime::FMT_ISO) == TXT(\"2003-02-01T01:02:03\"));\n\n}\n\nTEST_CASE_END\n\n\n\nTEST_CASE(\"using Windows short format outputs a short date and time separated by a space\")\n\n{\n\n\tTEST_TRUE(testDateTime.ToString(CDate::FMT_WIN_SHORT, CTime::FMT_WIN_SHORT) == TXT(\"01/02/2003 01:02\"));\n\n}\n\nTEST_CASE_END\n\n\n\n}\n\nTEST_SET_END\n", "file_path": "Test/DateTimeTests.cpp", "rank": 85, "score": 9.384543586108826 }, { "content": "void CIniFile::WriteInt(const tchar* pszSection, const tchar* pszEntry, int iValue)\n\n{\n\n\tASSERT(pszSection);\n\n\tASSERT(pszEntry);\n\n\n\n\t::WritePrivateProfileString(pszSection, pszEntry, CStrCvt::FormatInt(iValue), m_strPath);\n\n}\n\n\n\nuint CIniFile::ReadUInt(const tchar* pszSection, const tchar* pszEntry, uint nDefault) const\n\n{\n\n\tASSERT(pszSection);\n\n\tASSERT(pszEntry);\n\n\n\n\ttchar szValue[MAX_CHARS+1] = { 0 };\n\n\n\n\t// Read as a string.\n\n\t::GetPrivateProfileString(pszSection, pszEntry, TXT(\"\"), szValue, MAX_CHARS, m_strPath);\n\n\n\n\t// Read anything?\n\n\tif (szValue[0] == TXT('\\0'))\n", "file_path": "IniFile.cpp", "rank": 86, "score": 9.375341023771897 }, { "content": "\t// Get the size of the buffer and allocate one.\n\n\tint nChars = ::GetLocaleInfo(LOCALE_USER_DEFAULT, nLCType, nullptr, 0);\n\n\n\n\ttchar* pszBuffer = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\tpszBuffer[0] = TXT('\\0');\n\n\n\n\t// Get the locale string.\n\n\t::GetLocaleInfo(LOCALE_USER_DEFAULT, nLCType, pszBuffer, nChars+1);\n\n\n\n\treturn pszBuffer;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tDayOfWeekStr()\n\n**\n\n** Description:\tConverts the day of the week to a string.\n\n**\n\n** Parameters:\tbFullName\tGet the full name (true) or short name (false).\n\n**\n", "file_path": "Date.cpp", "rank": 87, "score": 9.369945881745652 }, { "content": "\toNetRsc.lpComment = const_cast<tchar*>(TXT(\"\"));\n\n\toNetRsc.lpProvider = const_cast<tchar*>(TXT(\"\"));\n\n\n\n\tFindComputers(&oNetRsc, astrComputers);\n\n\n\n\treturn astrComputers.Size();\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tFindComputers()\n\n**\n\n** Description:\tInternal method to do the work of finding all computers.\n\n**\n\n** Parameters:\tpNetRsc\t\t\tThe network container to enumerate.\n\n**\t\t\t\tastrComputers\tThe return buffer for the computer names.\n\n**\n\n** Returns:\t\tThe result of the last call.\n\n**\n\n*******************************************************************************\n\n*/\n", "file_path": "NetFinder.cpp", "rank": 88, "score": 9.345481682832723 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file TimeTests.cpp\n\n//! \\brief The unit tests for the CTime class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/Time.hpp>\n\n\n\nTEST_SET(Time)\n\n{\n\n\tCTime testTime(1, 2, 3);\n\n\n\nTEST_CASE(\"using ISO format outputs hours, minutes and seconds separated by a colon\")\n\n{\n\n\tTEST_TRUE(testTime.ToString(CTime::FMT_ISO) == TXT(\"01:02:03\"));\n\n}\n\nTEST_CASE_END\n\n\n\nTEST_CASE(\"using Windows short format outputs hours and minutes only separated by a colon\")\n", "file_path": "Test/TimeTests.cpp", "rank": 89, "score": 9.306304388799946 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file DateTests.cpp\n\n//! \\brief The unit tests for the CDate class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/Date.hpp>\n\n\n\nTEST_SET(Date)\n\n{\n\n\tCDate testDate(1, 2, 2003);\n\n\n\nTEST_CASE(\"using ISO format outputs year, month and day separated by a dash\")\n\n{\n\n\tTEST_TRUE(testDate.ToString(CDate::FMT_ISO) == TXT(\"2003-02-01\"));\n\n}\n\nTEST_CASE_END\n\n\n\nTEST_CASE(\"using Windows short format outputs day, month and year separated by a slash\")\n", "file_path": "Test/DateTests.cpp", "rank": 90, "score": 9.271268389776893 }, { "content": "\t\tFatalMsg(TXT(\"Failed to initialise COMCTL32.DLL\"));\n\n\t\treturn false;\n\n\t}\n\n\n\n\t// Call application method.\n\n\tif (!OnOpen())\n\n\t\treturn false;\n\n\n\n\treturn true;\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tRun()\n\n**\n\n** Description:\tCalled by WinMain to start the main processing.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\ttrue or false.\n\n**\n", "file_path": "App.cpp", "rank": 91, "score": 9.203916945969745 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//! \\file VerInfoReaderTests.cpp\n\n//! \\brief The unit tests for the VerInfoReader class.\n\n//! \\author Chris Oldwood\n\n\n\n#include \"Common.hpp\"\n\n#include <Core/UnitTest.hpp>\n\n#include <WCL/VerInfoReader.hpp>\n\n#include <WCL/Path.hpp>\n\n\n\nTEST_SET(VerInfoReader)\n\n{\n\n\tconst tstring filename(CPath::Application());\n\n\n\nTEST_CASE(\"querying a file that doesn't have version information returns false\")\n\n{\n\n\ttstring nonExeFile(CPath::SystemDir() / TXT(\"compmgmt.msc\"));\n\n\n\n\tTEST_TRUE(CPath(nonExeFile).Exists());\n\n\tTEST_TRUE(WCL::VerInfoReader::HasVersionInfo(nonExeFile) == false);\n", "file_path": "Test/VerInfoReaderTests.cpp", "rank": 92, "score": 9.189910653504523 }, { "content": "\n\n//! The size of the string buffer in characters.\n\nconst size_t MAX_CHARS = 256;\n\n\n\n/******************************************************************************\n\n** Method:\t\tConstructor.\n\n**\n\n** Description:\tSetup the Path as the application path and name, replacing\n\n**\t\t\t\t.EXE with .INI.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nCIniFile::CIniFile()\n\n\t: m_strPath()\n\n{\n", "file_path": "IniFile.cpp", "rank": 93, "score": 9.141943239330601 }, { "content": "**\n\n** Description:\tCalled by DllMain just before unloading the dll.\n\n**\n\n** Parameters:\tNone.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CDll::Unload()\n\n{\n\n\ttry\n\n\t{\n\n\t\tOnUnload();\n\n\t}\n\n\tcatch (const std::exception& e)\n\n\t{\n\n\t\tCore::debugWrite(TXT(\"Unhandled exception caught in CDll::OnUnload() - %hs\\n\"), e.what());\n\n\t}\n", "file_path": "Dll.cpp", "rank": 94, "score": 9.141861192706068 }, { "content": "\tif (errno == ERANGE)\n\n\t\tthrow CStrCvtException(CStrCvtException::E_INVALID_RANGE);\n\n\n\n\treturn nValue;\n\n}\n\n\n\nuint CStrCvt::ParseUInt(const tchar* pszString, int nFlags)\n\n{\n\n\tASSERT(pszString != nullptr);\n\n\tASSERT((nFlags == PARSE_ANY_FORMAT) || (nFlags == PARSE_OCTAL_ONLY) || (nFlags == PARSE_DECIMAL_ONLY) || (nFlags == PARSE_HEX_ONLY));\n\n\n\n\terrno = 0;\n\n\n\n\ttchar* pcEndChar = nullptr;\n\n\n\n\tuint nValue = tstrtoul(pszString, &pcEndChar, nFlags);\n\n\t\n\n\tif (*pcEndChar != TXT('\\0'))\n\n\t\tthrow CStrCvtException(CStrCvtException::E_INVALID_FORMAT);\n\n\n", "file_path": "StrCvt.cpp", "rank": 95, "score": 9.129545865362083 }, { "content": "\t{\n\n\t\t// Just append.\n\n\t\ttstrcat(m_pszData, pszString);\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tOperator +=()\n\n**\n\n** Description:\tConcatenate the supplied character onto the existing string.\n\n**\t\t\t\tIt grows the buffer if necessary.\n\n**\n\n** Parameters:\trFile\tA reference to the file.\n\n**\n\n** Returns:\t\tNothing.\n\n**\n\n*******************************************************************************\n\n*/\n\n\n\nvoid CString::operator +=(tchar cChar)\n", "file_path": "String.cpp", "rank": 96, "score": 9.081125438773984 }, { "content": "\t\t// \"C:\\\" is a valid root.\n\n\t\tif (IsPathSeparator(*pszEnd) && (*(pszEnd-1) != TXT(':')))\n\n\t\t\t*pszEnd = TXT('\\0');\n\n\t}\n\n}\n\n\n\n/******************************************************************************\n\n** Method:\t\tSelectFiles()\n\n**\n\n** Description:\tSelect multiple files using the common dialog.\n\n**\n\n** Parameters:\trParent\t\tThe dialogs parent.\n\n**\t\t\t\tpszExts\t\tFile extensions.\n\n**\t\t\t\tpszDefExt\tDefault file extension.\n\n**\t\t\t\tpszDir\t\tInitial directory.\n\n**\t\t\t\tastrFiles\tThe return buffer for the filenames.\n\n**\n\n** Returns:\t\ttrue\t\tIf user pressed OK.\n\n**\t\t\t\tfalse\t\tIf user pressed Cancel.\n\n**\n", "file_path": "Path.cpp", "rank": 97, "score": 9.042481823448222 }, { "content": "TEST_CASE(\"execute should return result code from doExecute\")\n\n{\n\n\tconst int expected = 42;\n\n\n\n\ttchar* argv[] = { TXT(\"Test.exe\"), TXT(\"command\") };\n\n\tconst int argc = ARRAY_SIZE(argv);\n\n\n\n\tTestCmd command(argc, argv);\n\n\ttostringstream out, err;\n\n\n\n\tcommand.m_returnCode = expected;\n\n\n\n\tint result = command.execute(out, err);\n\n\n\n\tTEST_TRUE(result == expected);\n\n}\n\nTEST_CASE_END\n\n\n\nTEST_CASE(\"execute should display command specific usage when a CmdLineException occurs\")\n\n{\n", "file_path": "Test/ConsoleCmdTests.cpp", "rank": 98, "score": 9.042481823448222 }, { "content": "CString CDate::DayOfWeekName(int nDay, bool bFullName)\n\n{\n\n\tASSERT((nDay >= 0) && (nDay <= 6));\n\n\n\n\t// Map day to locale type ID.\n\n\tint nLCType = (bFullName) ? (LOCALE_SDAYNAME1 + nDay) : (LOCALE_SABBREVDAYNAME1 + nDay);\n\n\n\n\t// Get the size of the buffer and allocate one.\n\n\tint nChars = ::GetLocaleInfo(LOCALE_USER_DEFAULT, nLCType, nullptr, 0);\n\n\n\n\ttchar* pszBuffer = static_cast<tchar*>(alloca(Core::numBytes<tchar>(nChars+1)));\n\n\n\n\tpszBuffer[0] = TXT('\\0');\n\n\n\n\t// Get the locale string.\n\n\t::GetLocaleInfo(LOCALE_USER_DEFAULT, nLCType, pszBuffer, nChars+1);\n\n\n\n\treturn pszBuffer;\n\n}\n\n\n", "file_path": "Date.cpp", "rank": 99, "score": 8.998240134853997 } ]
C++
libraries/AD520X/AD520X.cpp
AndreTeixeira1998/Arduino
16918bada3cf9dfee0f6baa72ee1de87602b84ca
#include "AD520X.h" AD520X::AD520X(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) { _pmCount = 6; _select = select; _dataOut = dataOut; _clock = clock; _reset = reset; _shutdown = shutdown; _hwSPI = (dataOut == 255) && (clock == 255); } void AD520X::begin(uint8_t value) { pinMode(_select, OUTPUT); digitalWrite(_select, HIGH); pinMode(_reset, OUTPUT); digitalWrite(_reset, LOW); pinMode(_shutdown, OUTPUT); digitalWrite(_shutdown, LOW); _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1); if(_hwSPI) { #if defined(ESP32) if (_useHSPI) { mySPI = new SPIClass(HSPI); mySPI->end(); mySPI->begin(14, 12, 13, _select); } else { mySPI = new SPIClass(VSPI); mySPI->end(); mySPI->begin(18, 19, 23, _select); } #else mySPI = &SPI; mySPI->end(); mySPI->begin(); #endif delay(1); } else { pinMode(_dataOut, OUTPUT); pinMode(_clock, OUTPUT); digitalWrite(_dataOut, LOW); digitalWrite(_clock, LOW); } setAll(value); } #if defined(ESP32) void AD520X::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select) { _clock = clk; _dataOut = mosi; _select = select; pinMode(_select, OUTPUT); digitalWrite(_select, HIGH); mySPI->end(); mySPI->begin(clk, miso, mosi, select); } #endif bool AD520X::setValue(uint8_t pm, uint8_t value) { if (pm >= _pmCount) return false; _value[pm] = value; updateDevice(pm); return true; } void AD520X::setAll(uint8_t value) { for (uint8_t pm = 0; pm < _pmCount; pm++) { setValue(pm, value); } } uint8_t AD520X::getValue(uint8_t pm) { if (pm >= _pmCount) return 0; return _value[pm]; } bool AD520X::setPercentage(uint8_t pm, float percentage) { if ((percentage < 0) || (percentage > 100.0)) return false; return setValue(pm, round(percentage * (255.0 / 100.0))); } float AD520X::getPercentage(uint8_t pm) { if (pm >= _pmCount) return 0; uint8_t v = _value[pm]; if (v == 0) return 0.0; return (100.0 / 255.0) * v; } void AD520X::reset(uint8_t value) { digitalWrite(_reset, HIGH); digitalWrite(_reset, LOW); setAll(value); } void AD520X::setSPIspeed(uint32_t speed) { _SPIspeed = speed; _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1); }; void AD520X::updateDevice(uint8_t pm) { digitalWrite(_select, LOW); if (_hwSPI) { mySPI->beginTransaction(_spi_settings); mySPI->transfer(pm); mySPI->transfer(_value[pm]); mySPI->endTransaction(); } else { swSPI_transfer(pm); swSPI_transfer(_value[pm]); } digitalWrite(_select, HIGH); } void AD520X::swSPI_transfer(uint8_t val) { uint8_t clk = _clock; uint8_t dao = _dataOut; for (uint8_t mask = 0x80; mask; mask >>= 1) { digitalWrite(dao,(val & mask)); digitalWrite(clk, HIGH); digitalWrite(clk, LOW); } } AD5206::AD5206(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 6; } AD5204::AD5204(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 4; } AD8403::AD8403(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 4; } AD8402::AD8402(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 2; } AD8400::AD8400(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 1; }
#include "AD520X.h" AD520X::AD520X(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) { _pmCount = 6; _select = select; _dataOut = dataOut; _clock = clock; _reset = reset; _shutdown = shutdown; _hwSPI = (dataOut == 255) && (clock == 255); } void AD520X::begin(uint8_t value) { pinMode(_select, OUTPUT); digitalWrite(_select, HIGH); pinMode(_reset, OUTPUT); digitalWrite(_reset, LOW); pinMode(_shutdown, OUTPUT); digitalWrite(_shutdown, LOW); _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1); if(_hwSPI) { #if defined(ESP32) if (_useHSPI) { mySPI = new SPIClass(HSPI); mySPI->end(); mySPI->begin(14, 12, 13, _select); } else { mySPI = new SPIClass(VSPI); mySPI->end(); mySPI->begin(18, 19, 23, _select); } #else mySPI = &SPI; mySPI->end(); mySPI->begin(); #endif delay(1); } else { pinMode(_dataOut, OUTPUT); pinMode(_clock, OUTPUT); digitalWrite(_dataOut, LOW); digitalWrite(_clock, LOW); } setAll(value); } #if defined(ESP32)
#endif bool AD520X::setValue(uint8_t pm, uint8_t value) { if (pm >= _pmCount) return false; _value[pm] = value; updateDevice(pm); return true; } void AD520X::setAll(uint8_t value) { for (uint8_t pm = 0; pm < _pmCount; pm++) { setValue(pm, value); } } uint8_t AD520X::getValue(uint8_t pm) { if (pm >= _pmCount) return 0; return _value[pm]; } bool AD520X::setPercentage(uint8_t pm, float percentage) { if ((percentage < 0) || (percentage > 100.0)) return false; return setValue(pm, round(percentage * (255.0 / 100.0))); } float AD520X::getPercentage(uint8_t pm) { if (pm >= _pmCount) return 0; uint8_t v = _value[pm]; if (v == 0) return 0.0; return (100.0 / 255.0) * v; } void AD520X::reset(uint8_t value) { digitalWrite(_reset, HIGH); digitalWrite(_reset, LOW); setAll(value); } void AD520X::setSPIspeed(uint32_t speed) { _SPIspeed = speed; _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1); }; void AD520X::updateDevice(uint8_t pm) { digitalWrite(_select, LOW); if (_hwSPI) { mySPI->beginTransaction(_spi_settings); mySPI->transfer(pm); mySPI->transfer(_value[pm]); mySPI->endTransaction(); } else { swSPI_transfer(pm); swSPI_transfer(_value[pm]); } digitalWrite(_select, HIGH); } void AD520X::swSPI_transfer(uint8_t val) { uint8_t clk = _clock; uint8_t dao = _dataOut; for (uint8_t mask = 0x80; mask; mask >>= 1) { digitalWrite(dao,(val & mask)); digitalWrite(clk, HIGH); digitalWrite(clk, LOW); } } AD5206::AD5206(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 6; } AD5204::AD5204(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 4; } AD8403::AD8403(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 4; } AD8402::AD8402(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 2; } AD8400::AD8400(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut, uint8_t clock) : AD520X(select, reset, shutdown, dataOut, clock) { _pmCount = 1; }
void AD520X::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select) { _clock = clk; _dataOut = mosi; _select = select; pinMode(_select, OUTPUT); digitalWrite(_select, HIGH); mySPI->end(); mySPI->begin(clk, miso, mosi, select); }
function_block-function_prefix_line
[ { "content": "class MS5611_SPI\n\n{\n\npublic:\n\n explicit MS5611_SPI(uint8_t select, uint8_t dataOut = 255, uint8_t dataIn = 255, uint8_t clock = 255);\n\n\n\n bool begin();\n\n\n\n // reset command + get constants\n\n // returns false if ROM constants == 0;\n\n bool reset();\n\n\n\n // the actual reading of the sensor;\n\n // returns MS5611_READ_OK upon success\n\n int read(uint8_t bits);\n\n // wrapper, uses the preset oversampling rate.\n\n inline int read() { return read( (uint8_t) _samplingRate); };\n\n\n\n // sets oversampling to a value between 8 and 12\n\n void setOversampling(osr_t samplingRate);\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 0, "score": 69837.37261446693 }, { "content": " uint8_t _samplingRate;\n\n int32_t _temperature;\n\n int32_t _pressure;\n\n float _pressureOffset;\n\n float _temperatureOffset;\n\n int _result;\n\n float C[7];\n\n uint32_t _lastRead;\n\n uint32_t _deviceID;\n\n bool _compensation;\n\n\n\n uint8_t _select;\n\n uint8_t _dataIn;\n\n uint8_t _dataOut;\n\n uint8_t _clock;\n\n bool _hwSPI;\n\n uint32_t _SPIspeed = 1000000;\n\n uint8_t swSPI_transfer(uint8_t value);\n\n SPIClass * mySPI;\n\n SPISettings _spi_settings;\n\n #if defined(ESP32)\n\n bool _useHSPI = true;\n\n #endif\n\n};\n\n\n\n\n\n// -- END OF FILE --\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 1, "score": 66410.84541808694 }, { "content": "#pragma once\n\n//\n\n// FILE: MS5611_SPI.h\n\n// AUTHOR: Rob Tillaart\n\n// VERSION: 0.1.0\n\n// PURPOSE: MS5611 (SPI) Temperature & Humidity library for Arduino\n\n// URL: https://github.com/RobTillaart/MS5611_SPI\n\n\n\n\n\n#include \"Arduino.h\"\n\n#include \"SPI.h\"\n\n\n\n// BREAKOUT MS5611 aka GY63 - see datasheet\n\n//\n\n// SPI I2C\n\n// +--------+\n\n// VCC VCC | o |\n\n// GND GND | o |\n\n// SCL | o |\n\n// SDI SDA | o |\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 2, "score": 66403.82430226979 }, { "content": "\n\n // ESP32 specific\n\n #if defined(ESP32)\n\n void selectHSPI() { _useHSPI = true; };\n\n void selectVSPI() { _useHSPI = false; };\n\n bool usesHSPI() { return _useHSPI; };\n\n bool usesVSPI() { return !_useHSPI; };\n\n\n\n // to overrule ESP32 default hardware pins\n\n void setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select);\n\n #endif\n\n\n\n\n\nprivate:\n\n void convert(const uint8_t addr, uint8_t bits);\n\n uint32_t readADC();\n\n uint16_t readProm(uint8_t reg);\n\n int command(const uint8_t command);\n\n\n\n uint8_t _address;\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 3, "score": 66403.52538688219 }, { "content": "// CSO | o |\n\n// SDO | o L | L = led\n\n// PS | o O | O = opening PS = protocol select\n\n// +--------+\n\n//\n\n// PS to VCC ==> I2C (GY-63 board has internal pull up, so not needed)\n\n// PS to GND ==> SPI\n\n// CS to VCC ==> 0x76\n\n// CS to GND ==> 0x77\n\n\n\n\n\n#define MS5611_SPI_LIB_VERSION (F(\"0.1.0 EXPERIMENTAL\"))\n\n\n\n\n\n#define MS5611_READ_OK 0\n\n#define MS5611_ERROR_2 2 // TODO ??\n\n#define MS5611_NOT_READ -999\n\n\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 4, "score": 66401.28898432372 }, { "content": "\n\n uint32_t getDeviceID() const { return _deviceID; };\n\n\n\n void setCompensation(bool flag = true) { _compensation = flag; };\n\n bool getCompensation() { return _compensation; };\n\n\n\n // develop functions.\n\n /*\n\n void setAddress(uint8_t address) { _address = address; }; // RANGE CHECK\n\n uint8_t getAddress() const { return _address; };\n\n uint8_t detectAddress() { todo }; // works with only one on the bus?\n\n */\n\n\n\n\n\n // speed in Hz\n\n void setSPIspeed(uint32_t speed);\n\n uint32_t getSPIspeed() { return _SPIspeed; };\n\n\n\n // debugging\n\n bool usesHWSPI() { return _hwSPI; };\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 5, "score": 66401.27980056402 }, { "content": " // oversampling rate is in osr_t\n\n osr_t getOversampling() const { return (osr_t) _samplingRate; };\n\n\n\n // temperature is in ²C\n\n float getTemperature() const;\n\n\n\n // pressure is in mBar\n\n float getPressure() const;\n\n\n\n // OFFSET - 0.3.6\n\n void setPressureOffset(float offset = 0) { _pressureOffset = offset; };\n\n float getPressureOffset() { return _pressureOffset; };\n\n void setTemperatureOffset(float offset = 0) { _temperatureOffset = offset; };\n\n float getTemperatureOffset() { return _temperatureOffset; };\n\n\n\n // to check for failure\n\n int getLastResult() const { return _result; };\n\n\n\n // last time in millis() when the sensor has been read.\n\n uint32_t lastRead() const { return _lastRead; };\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 6, "score": 66396.13798624165 }, { "content": "void MS5611_SPI::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataIn = miso;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_clock, OUTPUT);\n\n pinMode(_dataIn, INPUT);\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_clock, HIGH);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI and restart\n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 7, "score": 65484.13631019353 }, { "content": " }\n\n else\n\n {\n\n Serial.println(\"SW_SPI\");\n\n pinMode(_dataIn, INPUT);\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n\n\n return reset();\n\n}\n\n\n\n\n\nbool MS5611_SPI::reset()\n\n{\n\n command(MS5611_CMD_RESET);\n\n uint32_t start = micros();\n\n // while loop prevents blocking RTOS\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 8, "score": 65474.255254644595 }, { "content": " _select = select;\n\n _dataIn = dataIn;\n\n _dataOut = dataOut;\n\n _clock = clock;\n\n _hwSPI = (dataIn == 255) && (dataOut == 255) && (clock == 255);\n\n}\n\n\n\n\n\nbool MS5611_SPI::begin()\n\n{\n\n // print experimental message.\n\n Serial.println(MS5611_SPI_LIB_VERSION);\n\n\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n setSPIspeed(_SPIspeed);\n\n\n\n if(_hwSPI)\n\n {\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 9, "score": 65473.49867003151 }, { "content": " value += swSPI_transfer(0x00);\n\n value <<= 8;\n\n value += swSPI_transfer(0x00);\n\n }\n\n digitalWrite(_select, HIGH);\n\n // Serial.println(value, HEX);\n\n return value;\n\n}\n\n\n\n\n\nint MS5611_SPI::command(const uint8_t command)\n\n{\n\n yield();\n\n digitalWrite(_select, LOW);\n\n if (_hwSPI)\n\n {\n\n mySPI->beginTransaction(_spi_settings);\n\n mySPI->transfer(command);\n\n mySPI->endTransaction();\n\n }\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 10, "score": 65473.27187567519 }, { "content": " else // Software SPI\n\n {\n\n swSPI_transfer(command);\n\n }\n\n digitalWrite(_select, HIGH);\n\n return 0;\n\n}\n\n\n\n\n\n// simple one mode version\n\nuint8_t MS5611_SPI::swSPI_transfer(uint8_t val)\n\n{\n\n uint8_t clk = _clock;\n\n uint8_t dao = _dataOut;\n\n uint8_t dai = _dataIn;\n\n uint8_t value = 0;\n\n for (uint8_t mask = 0x80; mask; mask >>= 1)\n\n {\n\n digitalWrite(dao,(val & mask));\n\n digitalWrite(clk, HIGH);\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 11, "score": 65469.97776496765 }, { "content": "\n\n uint32_t value = 0;\n\n\n\n digitalWrite(_select, LOW);\n\n if (_hwSPI)\n\n {\n\n mySPI->beginTransaction(_spi_settings);\n\n mySPI->transfer(0x00);\n\n value += mySPI->transfer(0x00);\n\n value <<= 8;\n\n value += mySPI->transfer(0x00);\n\n value <<= 8;\n\n value += mySPI->transfer(0x00);\n\n mySPI->endTransaction();\n\n }\n\n else // Software SPI\n\n {\n\n swSPI_transfer(0x00);\n\n value += swSPI_transfer(0x00);\n\n value <<= 8;\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 12, "score": 65467.67572980606 }, { "content": " value += mySPI->transfer(0x00);\n\n value <<= 8;\n\n value += mySPI->transfer(0x00);\n\n mySPI->endTransaction();\n\n }\n\n else // Software SPI\n\n {\n\n swSPI_transfer(MS5611_CMD_READ_PROM + reg * 2);\n\n value += swSPI_transfer(0x00);\n\n value <<= 8;\n\n value += swSPI_transfer(0x00);\n\n }\n\n digitalWrite(_select, HIGH);\n\n return value;\n\n}\n\n\n\n\n\nuint32_t MS5611_SPI::readADC()\n\n{\n\n // command(MS5611_CMD_READ_ADC);\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 13, "score": 65467.21704536897 }, { "content": "\n\n\n\n/////////////////////////////////////////////////////\n\n//\n\n// PUBLIC\n\n//\n\nMS5611_SPI::MS5611_SPI(uint8_t select, uint8_t dataOut, uint8_t dataIn, uint8_t clock)\n\n{\n\n // _address = deviceAddress; // TODO\n\n _samplingRate = OSR_ULTRA_LOW;\n\n _temperature = MS5611_NOT_READ;\n\n _pressure = MS5611_NOT_READ;\n\n _result = MS5611_NOT_READ;\n\n _lastRead = 0;\n\n _deviceID = 0;\n\n _pressureOffset = 0;\n\n _temperatureOffset = 0;\n\n _compensation = true;\n\n\n\n // SPI\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 14, "score": 65464.29268628136 }, { "content": " while (micros() - start < waitTime)\n\n {\n\n yield();\n\n delayMicroseconds(10);\n\n }\n\n}\n\n\n\n\n\nuint16_t MS5611_SPI::readProm(uint8_t reg)\n\n{\n\n // last EEPROM register is CRC - Page 13 datasheet.\n\n uint8_t promCRCRegister = 7;\n\n if (reg > promCRCRegister) return 0;\n\n\n\n uint16_t value = 0;\n\n digitalWrite(_select, LOW);\n\n if (_hwSPI)\n\n {\n\n mySPI->beginTransaction(_spi_settings);\n\n mySPI->transfer(MS5611_CMD_READ_PROM + reg * 2);\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 15, "score": 65464.15905986805 }, { "content": " #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n\n {\n\n mySPI = new SPIClass(HSPI);\n\n mySPI->end();\n\n mySPI->begin(14, 12, 13, _select); // CLK=14 MISO=12 MOSI=13\n\n }\n\n else // VSPI\n\n {\n\n mySPI = new SPIClass(VSPI);\n\n mySPI->end();\n\n mySPI->begin(18, 19, 23, _select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n\n Serial.println(\"HW_SPI\");\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n delay(1);\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 16, "score": 65463.08723166896 }, { "content": " if (_temperatureOffset == 0) return _temperature * 0.01;\n\n return _temperature * 0.01 + _temperatureOffset;\n\n};\n\n\n\n\n\nfloat MS5611_SPI::getPressure() const\n\n{\n\n if (_pressureOffset == 0) return _pressure * 0.01;\n\n return _pressure * 0.01 + _pressureOffset;\n\n};\n\n\n\n\n\nvoid MS5611_SPI::setSPIspeed(uint32_t speed)\n\n{\n\n _SPIspeed = speed;\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);\n\n};\n\n\n\n\n\n#if defined(ESP32)\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 17, "score": 65460.15125915301 }, { "content": "//\n\n// FILE: MS5611_SPI.cpp\n\n// AUTHOR: Rob Tillaart\n\n// VERSION: 0.1.0\n\n// PURPOSE: MS5611 (SPI) Temperature & Humidity library for Arduino\n\n// URL: https://github.com/RobTillaart/MS5611\n\n//\n\n// HISTORY:\n\n// 0.1.0 2022-01-18 initial version by Rob Tillaart (15-okt-2014)\n\n\n\n\n\n#include \"MS5611_SPI.h\"\n\n\n\n\n\n// datasheet page 10\n\n#define MS5611_CMD_READ_ADC 0x00\n\n#define MS5611_CMD_READ_PROM 0xA0\n\n#define MS5611_CMD_RESET 0x1E\n\n#define MS5611_CMD_CONVERT_D1 0x40\n\n#define MS5611_CMD_CONVERT_D2 0x50\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 18, "score": 65458.08169039945 }, { "content": "\n\n/////////////////////////////////////////////////////\n\n//\n\n// PRIVATE\n\n//\n\nvoid MS5611_SPI::convert(const uint8_t addr, uint8_t bits)\n\n{\n\n // values from page 3 datasheet - MAX column (rounded up)\n\n uint16_t del[5] = {600, 1200, 2300, 4600, 9100};\n\n\n\n uint8_t index = bits;\n\n if (index < 8) index = 8;\n\n else if (index > 12) index = 12;\n\n index -= 8;\n\n uint8_t offset = index * 2;\n\n command(addr + offset);\n\n\n\n uint16_t waitTime = del[index];\n\n uint32_t start = micros();\n\n // while loop prevents blocking RTOS\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 19, "score": 65457.34645444875 }, { "content": " value <<= 1;\n\n if (digitalRead(dai) != 0) value += 1;\n\n digitalWrite(clk, LOW);\n\n }\n\n digitalWrite(dao, LOW);\n\n // Serial.print(\" # \");\n\n // Serial.println(value, HEX);\n\n return value;\n\n}\n\n\n\n\n\n// -- END OF FILE --\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 20, "score": 65456.71986096268 }, { "content": " sens -= sens2;\n\n }\n\n // END SECOND ORDER COMPENSATION\n\n }\n\n\n\n _pressure = (_D1 * sens * 4.76837158205E-7 - offset) * 3.051757813E-5;\n\n\n\n _lastRead = millis();\n\n return MS5611_READ_OK;\n\n}\n\n\n\n\n\nvoid MS5611_SPI::setOversampling(osr_t samplingRate)\n\n{\n\n _samplingRate = (uint8_t) samplingRate;\n\n}\n\n\n\n\n\nfloat MS5611_SPI::getTemperature() const\n\n{\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 21, "score": 65454.282153487045 }, { "content": " // C[7] == CRC - skipped.\n\n uint16_t tmp = readProm(reg);\n\n C[reg] *= tmp;\n\n // _deviceID is a simple SHIFT XOR merge of PROM data\n\n _deviceID <<= 4;\n\n _deviceID ^= tmp;\n\n // Serial.println(readProm(reg));\n\n if (reg > 0)\n\n {\n\n ROM_OK = ROM_OK && (tmp != 0);\n\n }\n\n }\n\n return ROM_OK;\n\n}\n\n\n\n\n\nint MS5611_SPI::read(uint8_t bits)\n\n{\n\n // VARIABLES NAMES BASED ON DATASHEET\n\n // ALL MAGIC NUMBERS ARE FROM DATASHEET\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 22, "score": 65447.812952995366 }, { "content": " while (micros() - start < 3000) // increased as first ROM values were missed.\n\n {\n\n yield();\n\n delayMicroseconds(10);\n\n }\n\n // constants that were multiplied in read()\n\n // do this once and you save CPU cycles\n\n C[0] = 1;\n\n C[1] = 32768L; // SENSt1 = C[1] * 2^15\n\n C[2] = 65536L; // OFFt1 = C[2] * 2^16\n\n C[3] = 3.90625E-3; // TCS = C[3] / 2^6\n\n C[4] = 7.8125E-3; // TCO = C[4] / 2^7\n\n C[5] = 256; // Tref = C[5] * 2^8\n\n C[6] = 1.1920928955E-7; // TEMPSENS = C[6] / 2^23\n\n // read factory calibrations from EEPROM.\n\n bool ROM_OK = true;\n\n for (uint8_t reg = 0; reg < 7; reg++)\n\n {\n\n // used indices match datasheet.\n\n // C[0] == manufacturer - read but not used;\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 23, "score": 65447.420604203864 }, { "content": " convert(MS5611_CMD_CONVERT_D1, bits);\n\n // NOTE: D1 and D2 seem reserved in MBED (NANO BLE)\n\n uint32_t _D1 = readADC();\n\n convert(MS5611_CMD_CONVERT_D2, bits);\n\n uint32_t _D2 = readADC();\n\n\n\n // Serial.println(_D1);\n\n // Serial.println(_D2);\n\n\n\n // TEST VALUES - comment lines above\n\n // uint32_t _D1 = 9085466;\n\n // uint32_t _D2 = 8569150;\n\n\n\n // TEMP & PRESS MATH - PAGE 7/20\n\n float dT = _D2 - C[5];\n\n _temperature = 2000 + dT * C[6];\n\n\n\n float offset = C[2] + dT * C[4];\n\n float sens = C[1] + dT * C[3];\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 24, "score": 65447.37868824083 }, { "content": "enum osr_t\n\n{\n\n OSR_ULTRA_HIGH = 12, // 10 millis\n\n OSR_HIGH = 11, // 5 millis\n\n OSR_STANDARD = 10, // 3 millis\n\n OSR_LOW = 9, // 2 millis\n\n OSR_ULTRA_LOW = 8 // 1 millis Default = backwards compatible\n\n};\n\n\n\n\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.h", "rank": 25, "score": 65443.188305196665 }, { "content": " if (_compensation)\n\n {\n\n // SECOND ORDER COMPENSATION - PAGE 8/20\n\n // COMMENT OUT < 2000 CORRECTION IF NOT NEEDED\n\n // NOTE TEMPERATURE IS IN 0.01 C\n\n if (_compensation && _temperature < 2000)\n\n {\n\n float T2 = dT * dT * 4.6566128731E-10;\n\n float t = (_temperature - 2000) * (_temperature - 2000);\n\n float offset2 = 2.5 * t;\n\n float sens2 = 1.25 * t;\n\n // COMMENT OUT < -1500 CORRECTION IF NOT NEEDED\n\n if (_temperature < -1500)\n\n {\n\n t = (_temperature + 1500) * (_temperature + 1500);\n\n offset2 += 7 * t;\n\n sens2 += 5.5 * t;\n\n }\n\n _temperature -= T2;\n\n offset -= offset2;\n", "file_path": "libraries/MS5611_SPI/MS5611_SPI.cpp", "rank": 26, "score": 65443.188305196665 }, { "content": "enum hmcOutputMode\n\n{\n\n HEADING = 0, RAWMAGX = 1, RAWMAGY= 2, MAGX = 3, MAGY = 4\n\n};\n\n\n\n\n", "file_path": "libraries/hmc6352/hmc6352.h", "rank": 27, "score": 53816.64366267485 }, { "content": "{\n\n MS5611 sensor(0x77);\n\n\n\n assertTrue(sensor.begin());\n\n\n\n // default\n\n assureEqual(OSR_ULTRA_LOW, sensor.getOversampling());\n\n\n\n sensor.setOversampling(OSR_ULTRA_LOW);\n\n assureEqual(OSR_ULTRA_LOW, sensor.getOversampling());\n\n sensor.setOversampling(OSR_LOW);\n\n assureEqual(OSR_LOW, sensor.getOversampling());\n\n sensor.setOversampling(OSR_STANDARD);\n\n assureEqual(OSR_STANDARD, sensor.getOversampling());\n\n sensor.setOversampling(OSR_HIGH);\n\n assureEqual(OSR_HIGH, sensor.getOversampling());\n\n sensor.setOversampling(OSR_ULTRA_HIGH);\n\n assureEqual(OSR_ULTRA_HIGH, sensor.getOversampling());\n\n}\n\n*/\n\n\n\n\n\nunittest_main()\n\n\n\n// --------\n", "file_path": "libraries/MS5611_SPI/test/unit_test_001.cpp", "rank": 28, "score": 52542.275128849724 }, { "content": " fprintf(stderr, \"MS5611_SPI_LIB_VERSION: %s\\n\", (char *) MS5611_SPI_LIB_VERSION );\n\n}\n\n\n\n\n\nunittest_teardown()\n\n{\n\n}\n\n\n\n/*\n\nunittest(test_new_operator)\n\n{\n\n assertEqualINF(exp(800));\n\n assertEqualINF(0.0/0.0);\n\n assertEqualINF(42);\n\n\n\n assertEqualNAN(INFINITY - INFINITY);\n\n assertEqualNAN(0.0/0.0);\n\n assertEqualNAN(42);\n\n}\n\n*/\n", "file_path": "libraries/MS5611_SPI/test/unit_test_001.cpp", "rank": 29, "score": 52540.23273656511 }, { "content": "// assertFalse(actual);\n\n// assertNull(actual);\n\n\n\n// // special cases for floats\n\n// assertEqualFloat(expected, actual, epsilon); // fabs(a - b) <= epsilon\n\n// assertNotEqualFloat(unwanted, actual, epsilon); // fabs(a - b) >= epsilon\n\n// assertInfinity(actual); // isinf(a)\n\n// assertNotInfinity(actual); // !isinf(a)\n\n// assertNAN(arg); // isnan(a)\n\n// assertNotNAN(arg); // !isnan(a)\n\n\n\n\n\n#include <ArduinoUnitTests.h>\n\n\n\n#include \"Arduino.h\"\n\n#include \"MS5611_SPI.h\"\n\n\n\n\n\nunittest_setup()\n\n{\n", "file_path": "libraries/MS5611_SPI/test/unit_test_001.cpp", "rank": 30, "score": 52540.11741467876 }, { "content": "//\n\n// FILE: unit_test_001.cpp\n\n// AUTHOR: Rob Tillaart\n\n// DATE: 2021-01-01\n\n// PURPOSE: unit tests for the MS5611 temperature and pressure library\n\n// https://github.com/RobTillaart/MS5611\n\n// https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md\n\n//\n\n\n\n// supported assertions\n\n// ----------------------------\n\n// assertEqual(expected, actual); // a == b\n\n// assertNotEqual(unwanted, actual); // a != b\n\n// assertComparativeEquivalent(expected, actual); // abs(a - b) == 0 or (!(a > b) && !(a < b))\n\n// assertComparativeNotEquivalent(unwanted, actual); // abs(a - b) > 0 or ((a > b) || (a < b))\n\n// assertLess(upperBound, actual); // a < b\n\n// assertMore(lowerBound, actual); // a > b\n\n// assertLessOrEqual(upperBound, actual); // a <= b\n\n// assertMoreOrEqual(lowerBound, actual); // a >= b\n\n// assertTrue(actual);\n", "file_path": "libraries/MS5611_SPI/test/unit_test_001.cpp", "rank": 31, "score": 52529.128665537326 }, { "content": "\n\n\n\nunittest(test_constants)\n\n{\n\n assertEqual(MS5611_READ_OK , 0);\n\n assertEqual(MS5611_ERROR_2 , 2); \n\n assertEqual(MS5611_NOT_READ, -999);\n\n}\n\n\n\n\n\n/*\n\nunittest(test_constructor)\n\n{\n\n MS5611 sensor(0x77);\n\n assertTrue(sensor.begin());\n\n\n\n assertEqualFloat(-9.99, sensor.getTemperature(), 0.01);\n\n assertEqualFloat(-9.99, sensor.getPressure(), 0.01);\n\n assertEqual(0, sensor.getLastResult());\n\n assertEqual(0, sensor.lastRead());\n", "file_path": "libraries/MS5611_SPI/test/unit_test_001.cpp", "rank": 32, "score": 52529.128665537326 }, { "content": "}\n\n\n\n\n\nunittest(test_read_sensor)\n\n{\n\n MS5611 sensor(0x77);\n\n\n\n assertTrue(sensor.begin());\n\n\n\n assureEqual(MS5611_READ_OK, sensor.read());\n\n\n\n // as Wire not implemented in tests\n\n // assertEqual(MS5611_NOT_READ, sensor.getTemperature());\n\n // assertEqual(MS5611_NOT_READ, sensor.getPressure());\n\n // assertEqual(MS5611_NOT_READ, sensor.getLastResult());\n\n // assertEqual(0, sensor.lastRead());\n\n}\n\n\n\n\n\nunittest(test_overSampling)\n", "file_path": "libraries/MS5611_SPI/test/unit_test_001.cpp", "rank": 33, "score": 52529.128665537326 }, { "content": "#define GY521_SIGNAL_PATH_RESET 0x68\n", "file_path": "libraries/GY521/GY521_registers.h", "rank": 34, "score": 47179.281253753405 }, { "content": "#### Base\n\n\n\n- **MS5611_SPI(uint8_t select, uint8_t dataOut = 255, uint8_t dataIn = 255, uint8_t clock = 255)** constructor.\n\n- **bool begin()** initializes internals, \n\n- **reset()** resets the chip and loads constants from its ROM.\n\n- **int read(uint8_t bits)** the actual reading of the sensor. \n\nNumber of bits determines the oversampling factor. Returns MS5611_READ_OK upon success.\n\n- **int read()** wraps the **read()** above, uses the preset oversampling (see below). \n\nReturns MS5611_READ_OK upon success.\n\n- **float getTemperature()** returns temperature in °C. \n\nSubsequent calls will return the same value until a new **read()** is called.\n\n- **float getPressure()** pressure is in mBar. \n\nSubsequent calls will return the same value until a new **read()** is called.\n\n\n\n\n\n#### Oversampling\n\n\n\n- **void setOversampling(osr_t samplingRate)** sets the amount of oversampling. \n\nSee table below and test example how to use.\n\n- **osr_t getOversampling()** returns amount of oversampling.\n\n\n\n\n\nSome numbers from datasheet, page 3 MAX column rounded up. (see #23)\n\n(actual read time differs - see performance sketch)\n\n\n\n| definition | value | oversampling ratio | resolution (mbar) | time (us) | notes |\n\n|:--------------:|:-----:|:------------------:|:-----------------:|:---------:|:------:|\n\n| OSR_ULTRA_HIGH | 12 | 4096 | 0.012 | 9100 |\n\n| OSR_HIGH | 11 | 2048 | 0.018 | 4600 |\n\n| OSR_STANDARD | 10 | 1024 | 0.027 | 2300 |\n\n| OSR_LOW | 9 | 512 | 0.042 | 1200 |\n\n| OSR_ULTRA_LOW | 8 | 256 | 0.065 | 600 | Default = backwards compatible\n\n\n\n\n\n\n", "file_path": "libraries/MS5611_SPI/README.md", "rank": 35, "score": 42773.52101739656 }, { "content": "#### SPI - ESP32 specific\n\n\n\n// to be tested.\n\n\n\n- **void selectHSPI()**\n\n- **void selectVSPI()**\n\n- **bool usesHSPI()**\n\n- **bool usesVSPI()**\n\n- **void setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)**\n\n\n\n\n\n## Operation\n\n\n\nSee examples\n\n\n\n\n\n## Future\n\n\n\n- follow I2C library.\n\n- investigate internal heating with SPI.\n", "file_path": "libraries/MS5611_SPI/README.md", "rank": 36, "score": 42757.16741780358 }, { "content": "\n\n[![Arduino CI](https://github.com/RobTillaart/MS5611_SPI/workflows/Arduino%20CI/badge.svg)](https://github.com/marketplace/actions/arduino_ci)\n\n[![Arduino-lint](https://github.com/RobTillaart/MS5611_SPI/actions/workflows/arduino-lint.yml/badge.svg)](https://github.com/RobTillaart/MS5611_SPI/actions/workflows/arduino-lint.yml)\n\n[![JSON check](https://github.com/RobTillaart/MS5611_SPI/actions/workflows/jsoncheck.yml/badge.svg)](https://github.com/RobTillaart/MS5611_SPI/actions/workflows/jsoncheck.yml)\n\n[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/RobTillaart/MS5611_SPI/blob/master/LICENSE)\n\n[![GitHub release](https://img.shields.io/github/release/RobTillaart/MS5611_SPI.svg?maxAge=3600)](https://github.com/RobTillaart/MS5611_SPI/releases)\n\n\n\n\n\n# MS5611_SPI\n\n\n\nArduino library (SPI) for MS5611 temperature and pressure sensor.\n\n\n\n\n\n# WARNING EXPERIMENTAL\n\n\n\n**Note: This library is under development and NOT stable**\n\n\n\nSPI communication sec seems to work as \"reasonable\" values are read.\n\n\n\nAll SPI tests so far gave too high temperatures, some were rising slowly, others faster.\n\nValues are read correctly but somehow the selection of SPI as protocol seems to cause internal heating.\n\n\n\nAs I only have 1 sensor I cannot verify if there is something broken.\n\nSelecting I2C still does give stable results from the sensor.\n\n\n\n\n\n| Platform | tested | time (us)| Notes |\n\n|:----------------|-------:|:--------:|--------:|\n\n| UNO SW SPI | fail | | temperature is rising very fast (stopped)\n\n| UNO HW SPI | fail | | no data, \n\n| ESP32 SW SPI V | Y | 1299 | VSPI pins; temperature is rising slowly\n\n| ESP32 SW SPI H | Y | 1298 | HSPI pins; temperature too high (+3) but looks stable\n\n| ESP32 HSPI | Y | 1396 | temperature is rising slowly\n\n| ESP32 VSPI | Y | 1395 | temperature is rising slowly\n\n| NANO 33 SW SPI | - | - | not tested yet\n\n| NANO 33 HW SPI | - | - | not tested yet\n\n\n\n\n", "file_path": "libraries/MS5611_SPI/README.md", "rank": 37, "score": 42755.78906238472 }, { "content": "#### Note UNO\n\n\n\nfor VCC 3V3 was used as the other pins CLK and SDI have a voltage converter in the GY-63.\n\nUnclear why HW SPI blocks for UNO. (to investigate)\n\n\n\n\n\n#### Note ESP32 \n\n\n\nHSPI pins: not reliable at start, incorrect PROM reads, both HW and SW. \n\nadjusting the timing improves this a bit.\n\n+ these pins also interfere with uploading.\n\n\n\n\n\n#### Conclusion for now\n\n\n\nIn short a lot of open ends to investigate. \n\n\n\nIf you have experiences with this library please share them in the issues.\n\n\n\n----\n\n\n\n## Description\n\n\n\nThe MS5611 is a high resolution temperature and pressure sensor a.k.a GY-63.\n\nThe high resolution is made possible by oversampling many times.\n\n\n\nThis library only implements the SPI interface.\n\n\n\nBased upon the 0.3.6 version of the I2C library, \n\nsee - https://github.com/RobTillaart/MS5611\n\n\n\n\n\n#### Breakout GY-63\n\n\n\n```cpp\n\n//\n\n// BREAKOUT MS5611 aka GY63 - see datasheet\n\n//\n\n// SPI I2C\n\n// +--------+\n\n// VCC VCC | o |\n\n// GND GND | o |\n\n// SCL | o |\n\n// SDI SDA | o |\n\n// CSO | o |\n\n// SDO | o L | L = led\n\n// PS | o O | O = opening PS = protocol select\n\n// +--------+\n\n//\n\n// PS to VCC ==> I2C (GY-63 board has internal pull up, so not needed)\n\n// PS to GND ==> SPI\n\n// CS to VCC ==> 0x76\n\n// CS to GND ==> 0x77\n\n//\n\n```\n\n\n\n#### Related libraries\n\n\n\nFor pressure conversions see - https://github.com/RobTillaart/pressure\n\n\n\nFor temperature conversions see - https://github.com/RobTillaart/Temperature\n\n\n\n\n\n## Release Notes\n\n\n\n### 0.1.0 initial release\n\n\n\nBased upon 0.3.8 of the I2C MS5611 library.\n\n\n\n\n\n## Interface\n\n\n", "file_path": "libraries/MS5611_SPI/README.md", "rank": 38, "score": 42750.693572559874 }, { "content": "#### Offset \n\n\n\nThe offset functions are added (0.3.6) to calibrate the sensor against e.g. a local weather station. \n\nThis calibration can only be done runtime.\n\n\n\n- **void setPressureOffset(float offset = 0)** Set an offset to calibrate the pressure. \n\nCan be used to get the pressure relative to e.g. 1 Atm. \n\nSet the offset to -1013 HPa/mBar and you get a sort of relative pressure.\n\nDefault the offset is set to 0.\n\n- **float getPressureOffset()** returns the current pressure offset.\n\n- **void setTemperatureOffset(float offset = 0)** Set an offset to calibrate the temperature. \n\nCan be used to get the temperature in degrees Kelvin, just set the offset to +273.15.\n\nDefault the offset is set to 0.\n\n- **float getTemperatureOffset()** returns the current temperature offset.\n\n\n\n\n\n#### Misc\n\n\n\n- **int getLastResult()** checks last I2C communication. Replace with more informative error handling?\n\n- **uint32_t lastRead()** last time when **read()** was called in milliseconds since startup.\n\n\n\n\n\n#### DeviceID\n\n\n\n- **uint32_t getDeviceID()** returns the hashed values of the calibration PROM. \n\nAs these calibration are set in the factory and differ (enough) per sensor these can serve as an unique deviceID.\n\n\n\nHaving a device-ID can be used in many ways:\n\n- use known offsets for each sensor automatically, \n\n- work as an identification of that specific copy of the project (customer specific tracking).\n\n- ID in a mesh network\n\n- etc.\n\n\n\nNote: this is not an official ID from the device / datasheet, it is made up from calibration data.\n\n\n\n\n\n#### 2nd order pressure compensation\n\n\n\n- **setCompensation(bool flag = true)** to enable/desiable the 2nd order compensation. \n\nThe default = true. \n\nDisabling the compensation will be slightly faster but you loose precision.\n\n- **getCompensation()** returns flag set above.\n\n\n\n\n\n#### SPI functions\n\n\n\n// to be tested.\n\n\n\n- **void setSPIspeed(uint32_t speed)**\n\n- **uint32_t getSPIspeed()**\n\n- **bool usesHWSPI()**\n\n\n\n\n", "file_path": "libraries/MS5611_SPI/README.md", "rank": 39, "score": 42747.53393236563 }, { "content": "### Constructors\n\n\n\n- **AD520X(uint8_t select, uint8_t reset, uint8_t shutdown, uint8_t dataOut = 255, uint8_t clock = 255)** constructor \n\nBase class, not to be used directly.\n\nIf dataOut and clock are set to 255 (default) it uses hardware SPI. \n\nIf dataOut and clock are set to another (valid) value) it uses software SPI.\n\nreset and shutdown may be set to 255 too, which effectively disables them. \n\n- **AD5204(select, reset, shutdown, dataOut = 255, clock = 255)** has 4 channels.\n\n- **AD5206(select, reset, shutdown, dataOut = 255, clock = 255)** has 6 channels.\n\n- **AD8400(select, reset, shutdown, dataOut = 255, clock = 255)** has 1 channel.\n\n- **AD8402(select, reset, shutdown, dataOut = 255, clock = 255)** has 2 channels.\n\n- **AD8403(select, reset, shutdown, dataOut = 255, clock = 255)** has 4 channels.\n\n\n\nNote: hardware SPI is 10+ times faster on an UNO than software SPI. \n\n\n\n\n\n### Base\n\n\n\nSince 0.2.0 the functions have more default parameters. Potentiometer is default pot 0 \n\nand value is default the **AD520X_MIDDLE_VALUE** of 128.\n\n\n\n- **void begin(uint8_t value = 128)** value is the initial value of all potentiometer.\n\n- **bool setValue(uint8_t pm = 0, uint8_t value = 128)** set a potentiometer to a value. \n\nDefault value is middle value. \n\nReturns true if successful, false if not.\n\n- **void setAll(uint8_t value = 128)** set all potentiometers to the same value e.g. 0 or max or mid value.\n\n- **uint8_t getValue(uint8_t pm = 0)** returns the last set value of a specific potentiometer.\n\n- **void reset(uint8_t value = 128)** resets all potentiometers to value, default 128.\n\n- **bool setPercentage(uint8_t pm = 0, float percentage = 50)** similar to setValue, percentage from 0..100% \n\nReturns true when successful, false if not.\n\n- **float getPercentage(uint8_t pm = 0)** return the value of potentiometer pm as percentage.\n\n\n\n\n\nThe library has defined **#define AD520X_MIDDLE_VALUE 128**\n\n\n\n\n", "file_path": "libraries/AD520X/README.md", "rank": 42, "score": 43.2310756899485 }, { "content": " _clock = clk;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI \n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n\n// value = 0..65535\n\nvoid DAC8550::setValue(uint16_t value)\n\n{\n\n _value = value;\n\n updateDevice();\n\n}\n\n\n\n\n", "file_path": "libraries/DAC8550/DAC8550.cpp", "rank": 43, "score": 41.186585441142945 }, { "content": " pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n}\n\n\n\n\n\n#if defined(ESP32)\n\nvoid MCP_DAC::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI\n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n", "file_path": "libraries/MCP_DAC/MCP_DAC.cpp", "rank": 44, "score": 41.17386790825895 }, { "content": " mySPI = new SPIClass(VSPI);\n\n mySPI->end();\n\n mySPI->begin(18, 19, 23, select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n }\n\n else // software SPI\n\n {\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n\n\n reset();\n\n}\n", "file_path": "libraries/AD985X/AD985X.cpp", "rank": 45, "score": 40.75868712925418 }, { "content": "}\n\n\n\n\n\n#if defined(ESP32)\n\nvoid DAC8551::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI \n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n\n// value = 0..65535\n\nvoid DAC8551::setValue(uint16_t value)\n", "file_path": "libraries/DAC8551/DAC8551.cpp", "rank": 47, "score": 40.3905195077286 }, { "content": "{\n\n _gain = 1;\n\n _value[0] = 0;\n\n _value[1] = 0;\n\n _buffered = false;\n\n _active = true;\n\n}\n\n\n\n\n\nvoid MCP_DAC::begin(uint8_t select)\n\n{\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);\n\n\n\n if (_hwSPI)\n\n {\n\n #if defined(ESP32)\n", "file_path": "libraries/MCP_DAC/MCP_DAC.cpp", "rank": 48, "score": 40.20206694765528 }, { "content": "void MAX31855::setSPIspeed(uint32_t speed)\n\n{\n\n _SPIspeed = speed;\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);\n\n};\n\n\n\n\n\n#if defined(ESP32)\n\nvoid MAX31855::setGPIOpins(uint8_t clock, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clock;\n\n _miso = miso;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n // disable SPI and enable again\n\n mySPI->end();\n\n mySPI->begin(clock, miso, mosi, select);\n\n}\n", "file_path": "libraries/MAX31855_RT/MAX31855.cpp", "rank": 49, "score": 40.035677629324915 }, { "content": " _dataOut = spiData;\n\n _clock = spiClock;\n\n _select = slaveSelect;\n\n _address = (address & 0x03) << 6;\n\n}\n\n\n\n\n\n// initializes the SPI\n\n// and sets internal state\n\nvoid DAC8554::begin()\n\n{\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1);\n\n\n\n if(_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n", "file_path": "libraries/DAC8554/DAC8554.cpp", "rank": 50, "score": 39.40190860768778 }, { "content": " mySPI->begin();\n\n #endif\n\n delay(1);\n\n }\n\n else // software SPI\n\n {\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n\n\n _register = 0;\n\n _value = 0;\n\n}\n\n\n\n\n\n#if defined(ESP32)\n\nvoid DAC8550::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n", "file_path": "libraries/DAC8550/DAC8550.cpp", "rank": 51, "score": 39.159439717323465 }, { "content": "\n\n\n\n#if defined(ESP32)\n\nvoid AD9850::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, LOW);\n\n\n\n mySPI->end(); // disable SPI \n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n\nvoid AD9850::reset()\n\n{\n\n // be sure to select the correct device \n", "file_path": "libraries/AD985X/AD985X.cpp", "rank": 52, "score": 38.84544263462396 }, { "content": "\n\n _value[0] = 0;\n\n _value[1] = 0;\n\n _register[0] = 0x00;\n\n _register[1] = 0x40;\n\n}\n\n\n\n\n\n#if defined(ESP32)\n\nvoid DAC8552::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI \n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n", "file_path": "libraries/DAC8552/DAC8552.cpp", "rank": 54, "score": 38.74368123062517 }, { "content": "// and sets internal state\n\nvoid DAC8551::begin()\n\n{\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1);\n\n\n\n if(_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n\n {\n\n mySPI = new SPIClass(HSPI);\n\n mySPI->end();\n\n mySPI->begin(14, 12, 13, _select); // CLK=14 MISO=12 MOSI=13\n\n }\n\n else // VSPI\n\n {\n\n mySPI = new SPIClass(VSPI);\n", "file_path": "libraries/DAC8551/DAC8551.cpp", "rank": 55, "score": 38.720877481885246 }, { "content": "\n\n\n\nvoid MCP_ADC::begin(uint8_t select)\n\n{\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);\n\n\n\n if (_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n\n {\n\n mySPI = new SPIClass(HSPI);\n\n mySPI->end();\n\n mySPI->begin(14, 12, 13, select); // CLK=14 MISO=12 MOSI=13\n\n }\n\n else // VSPI\n", "file_path": "libraries/MCP_ADC/MCP_ADC.cpp", "rank": 56, "score": 38.47552275203046 }, { "content": " // device select = HIGH See - https://github.com/RobTillaart/AD985X/issues/13\n\n digitalWrite(_select, LOW); \n\n digitalWrite(_reset, LOW);\n\n digitalWrite(_fqud, LOW);\n\n\n\n _hwSPI = ((dataOut == 0) || (clock == 0));\n\n\n\n _spi_settings = SPISettings(2000000, LSBFIRST, SPI_MODE0);\n\n\n\n if (_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n\n {\n\n mySPI = new SPIClass(HSPI);\n\n mySPI->end();\n\n mySPI->begin(14, 12, 13, select); // CLK=14 MISO=12 MOSI=13\n\n }\n\n else // VSPI\n\n {\n", "file_path": "libraries/AD985X/AD985X.cpp", "rank": 57, "score": 38.449741446458205 }, { "content": "protected:\n\n uint8_t _dataOut;\n\n uint8_t _clock;\n\n uint8_t _select;\n\n uint8_t _reset;\n\n uint8_t _shutdown;\n\n bool _hwSPI = 3;\n\n uint32_t _SPIspeed = 16000000;\n\n\n\n uint8_t _value[6];\n\n uint8_t _pmCount = 6;\n\n\n\n void updateDevice(uint8_t pm);\n\n void swSPI_transfer(uint8_t value);\n\n\n\n SPIClass * mySPI;\n\n SPISettings _spi_settings;\n\n\n\n #if defined(ESP32)\n\n bool _useHSPI = true;\n\n #endif\n\n};\n\n\n\n\n", "file_path": "libraries/AD520X/AD520X.h", "rank": 59, "score": 38.003464416751314 }, { "content": "\n\n\n\n// initializes the SPI\n\n// and sets internal state\n\nvoid DAC8552::begin()\n\n{\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE1);\n\n\n\n if(_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n\n {\n\n mySPI = new SPIClass(HSPI);\n\n mySPI->end();\n\n mySPI->begin(14, 12, 13, _select); // CLK=14 MISO=12 MOSI=13\n\n }\n", "file_path": "libraries/DAC8552/DAC8552.cpp", "rank": 60, "score": 37.99101395561347 }, { "content": "// extended unit tests\n\n// 0.1.6 2021-12-21 update library.json, license, minor edits\n\n\n\n\n\n#include \"MCP_DAC.h\"\n\n\n\n\n\nMCP_DAC::MCP_DAC(uint8_t dataOut, uint8_t clock)\n\n{\n\n _dataOut = dataOut;\n\n _clock = clock;\n\n _select = 0;\n\n _hwSPI = (dataOut == 255) || (clock == 255);\n\n _channels = 1;\n\n _maxValue = 255;\n\n reset();\n\n}\n\n\n\n\n\nvoid MCP_DAC::reset()\n", "file_path": "libraries/MCP_DAC/MCP_DAC.cpp", "rank": 61, "score": 37.696354243842926 }, { "content": " swSPI_transfer(configRegister);\n\n swSPI_transfer(value >> 8);\n\n swSPI_transfer(value & 0xFF);\n\n }\n\n digitalWrite(_select, HIGH);\n\n}\n\n\n\n\n\n// simple one mode version\n\nvoid DAC8554::swSPI_transfer(uint8_t value)\n\n{\n\n uint8_t clk = _clock;\n\n uint8_t dao = _dataOut;\n\n for (uint8_t mask = 0x80; mask; mask >>= 1)\n\n {\n\n digitalWrite(dao,(value & mask));\n\n digitalWrite(clk, HIGH);\n\n digitalWrite(clk, LOW);\n\n }\n\n}\n\n\n\n\n\n// -- END OF FILE --\n\n\n", "file_path": "libraries/DAC8554/DAC8554.cpp", "rank": 62, "score": 37.067099358179185 }, { "content": " else // Software SPI\n\n {\n\n swSPI_transfer(configRegister);\n\n swSPI_transfer(_value[channel] >> 8);\n\n swSPI_transfer(_value[channel] & 0xFF);\n\n }\n\n digitalWrite(_select, HIGH);\n\n}\n\n\n\n\n\n// simple one mode version\n\nvoid DAC8552::swSPI_transfer(uint8_t value)\n\n{\n\n uint8_t clk = _clock;\n\n uint8_t dao = _dataOut;\n\n for (uint8_t mask = 0x80; mask; mask >>= 1)\n\n {\n\n digitalWrite(dao,(value & mask));\n\n digitalWrite(clk, HIGH);\n\n digitalWrite(clk, LOW);\n\n }\n\n}\n\n\n\n\n\n// -- END OF FILE --\n\n\n", "file_path": "libraries/DAC8552/DAC8552.cpp", "rank": 63, "score": 36.77145358028496 }, { "content": " mySPI->end();\n\n mySPI->begin(18, 19, 23, _select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n delay(1);\n\n }\n\n else // software SPI\n\n {\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n\n\n _register = 0;\n\n _value = 0;\n", "file_path": "libraries/DAC8551/DAC8551.cpp", "rank": 64, "score": 35.9793510124697 }, { "content": " _select = slaveSelect;\n\n}\n\n\n\n\n\nDAC8550::DAC8550(uint8_t spiData, uint8_t spiClock, uint8_t slaveSelect)\n\n{\n\n _hwSPI = false;\n\n _dataOut = spiData;\n\n _clock = spiClock;\n\n _select = slaveSelect;\n\n}\n\n\n\n\n\n// initializes the SPI\n\n// and sets internal state\n\nvoid DAC8550::begin()\n\n{\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n", "file_path": "libraries/DAC8550/DAC8550.cpp", "rank": 65, "score": 35.774320660251455 }, { "content": " else // VSPI\n\n {\n\n mySPI = new SPIClass(VSPI);\n\n mySPI->end();\n\n mySPI->begin(18, 19, 23, _select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n delay(1);\n\n }\n\n else // software SPI\n\n {\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n", "file_path": "libraries/DAC8552/DAC8552.cpp", "rank": 66, "score": 35.74845834981706 }, { "content": "// simple one mode version\n\nvoid DAC8551::swSPI_transfer(uint8_t value)\n\n{\n\n uint8_t clk = _clock;\n\n uint8_t dao = _dataOut;\n\n for (uint8_t mask = 0x80; mask; mask >>= 1)\n\n {\n\n digitalWrite(dao,(value & mask));\n\n digitalWrite(clk, HIGH);\n\n digitalWrite(clk, LOW);\n\n }\n\n}\n\n\n\n\n\n/////////////////////////////////////////////////////////\n\n//\n\n// derive 8501, 8531 and 8550 from 8551\n\n// \n\n\n\nDAC8501::DAC8501(uint8_t slaveSelect) : DAC8551(slaveSelect)\n", "file_path": "libraries/DAC8551/DAC8551.cpp", "rank": 67, "score": 35.613869166963006 }, { "content": " {\n\n mySPI = new SPIClass(VSPI);\n\n mySPI->end();\n\n mySPI->begin(18, 19, 23, select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n }\n\n else // software SPI\n\n {\n\n pinMode(_dataIn, INPUT);\n\n pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n}\n", "file_path": "libraries/MCP_ADC/MCP_ADC.cpp", "rank": 68, "score": 35.49974210718656 }, { "content": "\n\n\n\n#if defined(ESP32)\n\nvoid MAX6675::setGPIOpins(uint8_t clock, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clock;\n\n _miso = miso;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n // disable SPI and enable again\n\n mySPI->end();\n\n mySPI->begin(clock, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n\nuint8_t MAX6675::read()\n\n{\n", "file_path": "libraries/MAX6675/MAX6675.cpp", "rank": 69, "score": 35.302864322110956 }, { "content": " pinMode(_dataOut, OUTPUT);\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_dataOut, LOW);\n\n digitalWrite(_clock, LOW);\n\n }\n\n\n\n for (uint8_t i = 0; i < 4; i++)\n\n {\n\n _register[i] = 0;\n\n _value[i] = 0;\n\n }\n\n}\n\n\n\n\n\n#if defined(ESP32)\n\nvoid DAC8554::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataOut = mosi;\n\n _select = select;\n", "file_path": "libraries/DAC8554/DAC8554.cpp", "rank": 70, "score": 35.0630057960936 }, { "content": " pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI \n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////\n\n//\n\n// SETVALUE\n\n//\n\n// channel = 0, 1, 2, 3\n\n// value = 0..65535\n\nvoid DAC8554::bufferValue(uint8_t channel, uint16_t value)\n\n{\n\n uint8_t configRegister = _address;\n\n configRegister |= DAC8554_BUFFER_WRITE;\n", "file_path": "libraries/DAC8554/DAC8554.cpp", "rank": 71, "score": 34.75378704048195 }, { "content": " mySPI = new SPIClass(VSPI);\n\n mySPI->end();\n\n mySPI->begin(18, 19, 23, _select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n delay(1);\n\n }\n\n else\n\n {\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_clock, LOW);\n\n pinMode(_miso, INPUT);\n\n }\n\n}\n\n\n\n\n", "file_path": "libraries/MAX31855_RT/MAX31855.cpp", "rank": 72, "score": 34.236346764427616 }, { "content": " mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n #endif\n\n delay(1);\n\n }\n\n else\n\n {\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_clock, LOW);\n\n pinMode(_miso, INPUT);\n\n }\n\n}\n\n\n\n\n\nvoid MAX6675::setSPIspeed(uint32_t speed)\n\n{\n\n _SPIspeed = speed;\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);\n\n};\n", "file_path": "libraries/MAX6675/MAX6675.cpp", "rank": 75, "score": 33.42774439250353 }, { "content": " digitalWrite(_select, HIGH);\n\n pulsePin(_reset);\n\n if (_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) pulsePin(14); // HSPI magic number clock\n\n else pulsePin(18); // VSPI magic number clock\n\n #else \n\n // UNO hardware SPI\n\n pulsePin(SPI_CLOCK);\n\n #endif\n\n }\n\n else pulsePin(_clock);\n\n digitalWrite(_select, LOW);\n\n\n\n _config = 0; // 0 phase no power down\n\n _freq = 0;\n\n _factor = 0;\n\n _offset = 0;\n\n _autoUpdate = true;\n", "file_path": "libraries/AD985X/AD985X.cpp", "rank": 76, "score": 33.20560260682114 }, { "content": "\n\n\n\n#if defined(ESP32)\n\nvoid MCP_ADC::setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)\n\n{\n\n _clock = clk;\n\n _dataIn = miso;\n\n _dataOut = mosi;\n\n _select = select;\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n mySPI->end(); // disable SPI\n\n mySPI->begin(clk, miso, mosi, select);\n\n}\n\n#endif\n\n\n\n\n\nuint32_t MCP_ADC::count()\n\n{\n", "file_path": "libraries/MCP_ADC/MCP_ADC.cpp", "rank": 77, "score": 32.774100621662974 }, { "content": "### Shutdown\n\n\n\n- **void shutDown()** shuts down the device, optional one might need to **triggerLatch()**\n\n- **bool isActive()** returns false if device is in shutdown mode.\n\nNote: **write()** will set active to true again.\n\n\n\n\n\n### Hardware SPI\n\n\n\nTo be used only if one needs a specific speed.\n\n\n\n- **void setSPIspeed(uint32_t speed)** set SPI transfer rate\n\n- **uint32_t getSPIspeed()** returns SPI transfer rate\n\n\n\n\n\n### LDAC\n\n\n\n- **void setLatchPin(uint8_t latchPin)** defines the latchPin, this is optional. The latchPin is used for simultaneous setting a value in multiple devices. Note the latchPin must be the same for all instances that need to be triggered together.\n\n- **triggerLatch()** toggles the defined latchPin, and all devices that are connected to it.\n\n\n\n\n\n### Buffered \n\n\n\nMCP49xxx series only, see page 20 ==> not functional for MCP48xx series.\n\n\n\n- **void setBufferedMode(bool mode = false)** set buffered mode on/off. The default = false, unbuffered.\n\n- **bool getBufferedMode()** returns set value\n\n\n\n\n\n### Debug\n\n\n\n- **void reset()** resets internal variables to initial value. (use with care!)\n\n- **bool usesHWSPI()** returns true if HW SPI is used.\n\n\n\n\n\n### ESP32 specific\n\n\n\nThis functionality is new in 0.1.2 and it is expected that the interface will change\n\nin the future. \n\n\n\n- **void selectHSPI()** in case hardware SPI, the ESP32 has two options HSPI and VSPI.\n\n- **void selectVSPI()** see above.\n\n- **bool usesHSPI()** returns true if HSPI is used.\n\n- **bool usesVSPI()** returns true if VSPI is used.\n\n\n\nThe **selectVSPI()** or the **selectHSPI()** needs to be called \n\nBEFORE the **begin()** function.\n\n\n\n\n\n#### experimental\n\n\n\n- **void setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)** overrule GPIO pins of ESP32 for hardware SPI. needs to be called \n\nAFTER the **begin()** function.\n\n\n\n```cpp\n\nvoid setup()\n\n{\n\n MCP.selectVSPI();\n\n MCP.begin(15);\n\n MCP.setGPIOpins(CLK, MISO, MOSI, SELECT); // SELECT should match the param of begin()\n\n}\n\n```\n\n\n\nThis interface can change in the future as the **select** pin is known\n\nin the code.\n\n\n\n\n", "file_path": "libraries/MCP_DAC/README.md", "rank": 78, "score": 32.60380820737428 }, { "content": " mySPI->transfer(_value >> 8);\n\n mySPI->transfer(_value & 0xFF);\n\n mySPI->endTransaction();\n\n }\n\n else // Software SPI \n\n {\n\n swSPI_transfer(configRegister);\n\n swSPI_transfer(_value >> 8);\n\n swSPI_transfer(_value & 0xFF);\n\n }\n\n digitalWrite(_select, HIGH);\n\n}\n\n\n\n\n\n// simple one mode version\n\nvoid DAC8550::swSPI_transfer(uint8_t value)\n\n{\n\n uint8_t clk = _clock;\n\n uint8_t dao = _dataOut;\n\n for (uint8_t mask = 0x80; mask; mask >>= 1)\n", "file_path": "libraries/DAC8550/DAC8550.cpp", "rank": 79, "score": 32.588453151132654 }, { "content": " else // Software SPI\n\n {\n\n for (uint8_t b = 0; b < bytes; b++)\n\n {\n\n data[b] = swSPI_transfer(data[b]);\n\n }\n\n }\n\n digitalWrite(_select, HIGH);\n\n\n\n if (bytes == 2) return ((256 * data[0] + data[1]) & _maxValue);\n\n // data[0]?\n\n return ((256 * data[1] + data[2]) & _maxValue);\n\n}\n\n\n\n\n\n// MSBFIRST\n\nuint8_t MCP_ADC::swSPI_transfer(uint8_t val)\n\n{\n\n uint8_t clk = _clock;\n\n uint8_t dao = _dataOut;\n", "file_path": "libraries/MCP_ADC/MCP_ADC.cpp", "rank": 80, "score": 32.427271669640874 }, { "content": "//\n\n// AD9850\n\n//\n\n\n\nAD9850::AD9850()\n\n{\n\n}\n\n\n\n\n\nvoid AD9850::begin(uint8_t select, uint8_t resetPin, uint8_t FQUDPin, uint8_t dataOut , uint8_t clock)\n\n{\n\n _select = select;\n\n _reset = resetPin;\n\n _fqud = FQUDPin;\n\n _dataOut = dataOut;\n\n _clock = clock;\n\n // following 3 are always set.\n\n pinMode(_select, OUTPUT);\n\n pinMode(_reset, OUTPUT);\n\n pinMode(_fqud, OUTPUT);\n", "file_path": "libraries/AD985X/AD985X.cpp", "rank": 81, "score": 31.645829703559166 }, { "content": " _rawData = mySPI->transfer(0);\n\n _rawData <<= 8;\n\n _rawData += mySPI->transfer(0);\n\n digitalWrite(_select, HIGH);\n\n mySPI->endTransaction();\n\n }\n\n else // Software SPI\n\n {\n\n // split _swSPIdelay in equal dLow and dHigh\n\n // dLow should be longer one when _swSPIdelay = odd.\n\n uint16_t dHigh = _swSPIdelay/2;\n\n uint16_t dLow = _swSPIdelay - dHigh;\n\n digitalWrite(_select, LOW);\n\n for (int8_t i = 15; i >= 0; i--)\n\n {\n\n _rawData <<= 1;\n\n digitalWrite(_clock, LOW);\n\n if (dLow > 0) delayMicroseconds(dLow); // DUE might need 1 us\n\n if ( digitalRead(_miso) ) _rawData++;\n\n digitalWrite(_clock, HIGH);\n", "file_path": "libraries/MAX6675/MAX6675.cpp", "rank": 82, "score": 31.60229215286294 }, { "content": "", "file_path": "libraries/AD985X/README.md", "rank": 83, "score": 31.314862454114284 }, { "content": "### Core\n\n\n\n- **DAC8501(uint8_t slaveSelect)** Constructor for DAC8501 with hardware SPI,\n\n- **DAC8531(uint8_t slaveSelect)** Constructor for DAC8531 with hardware SPI,\n\n- **DAC8550(uint8_t slaveSelect)** Constructor for DAC8550 with hardware SPI,\n\n- **DAC8551(uint8_t slaveSelect)** Constructor for DAC8551 with hardware SPI,\n\nsince 0.2.0 the slaveSelect pin needs to be defined.\n\n- **DAC8501(uint8_t spiData, uint8_t spiClock, uint8_t slaveSelect)** Constructor for the software SPI\n\n- **DAC8531(uint8_t spiData, uint8_t spiClock, uint8_t slaveSelect)** Constructor for the software SPI\n\n- **DAC8550(uint8_t spiData, uint8_t spiClock, uint8_t slaveSelect)** Constructor for the software SPI\n\n- **DAC8551(uint8_t spiData, uint8_t spiClock, uint8_t slaveSelect)** Constructor for the software SPI\n\n- **void begin()** initializes all pins to default state\n\n- **void setValue(uint16_t value)** set the value of the channel to 0 - 65535\n\n- **uint16_t getValue()** returns the last value written.\n\n\n\n\n\n### Hardware SPI\n\n\n\nTo be used only if one needs a specific speed.\n\n\n\n- **void setSPIspeed(uint32_t speed)** set SPI transfer rate.\n\n- **uint32_t getSPIspeed()** returns SPI transfer rate.\n\n- **bool usesHWSPI()** returns true if HW SPI is used.\n\n\n\n\n\n### ESP32 specific\n\n\n\n- **void selectHSPI()** in case hardware SPI, the ESP32 has two options HSPI and VSPI.\n\n- **void selectVSPI()** see above.\n\n- **bool usesHSPI()** returns true if HSPI is used.\n\n- **bool usesVSPI()** returns true if VSPI is used.\n\n\n\nThe **selectVSPI()** or the **selectHSPI()** needs to be called \n\nBEFORE the **begin()** function.\n\n\n\n\n\n#### experimental\n\n\n\n- **void setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)** \n\noverrule GPIO pins of ESP32 for hardware SPI. \n\nNeeds to be called AFTER the **begin()** function.\n\n\n\n\n", "file_path": "libraries/DAC8551/README.md", "rank": 84, "score": 31.01002230046676 }, { "content": "\n\n pinMode(_select, OUTPUT);\n\n digitalWrite(_select, HIGH);\n\n\n\n if (_hwSPI)\n\n {\n\n #if defined(ESP32)\n\n if (_useHSPI) // HSPI\n\n {\n\n mySPI = new SPIClass(HSPI);\n\n mySPI->end();\n\n mySPI->begin(14, 12, 13, _select); // CLK=14 MISO=12 MOSI=13\n\n }\n\n else // VSPI\n\n {\n\n mySPI = new SPIClass(VSPI);\n\n mySPI->end();\n\n mySPI->begin(18, 19, 23, _select); // CLK=18 MISO=19 MOSI=23\n\n }\n\n #else // generic hardware SPI\n", "file_path": "libraries/MAX6675/MAX6675.cpp", "rank": 85, "score": 30.248693599195477 }, { "content": " }\n\n else // Software SPI\n\n {\n\n // split _swSPIdelay in equal dLow and dHigh\n\n // dLow should be longer one when _swSPIdelay = odd.\n\n uint16_t dHigh = _swSPIdelay/2;\n\n uint16_t dLow = _swSPIdelay - dHigh;\n\n digitalWrite(_select, LOW);\n\n for (int8_t i = 31; i >= 0; i--)\n\n {\n\n _rawData <<= 1;\n\n digitalWrite(_clock, LOW);\n\n if (dLow > 0) delayMicroseconds(dLow); // DUE might need 1 us\n\n if ( digitalRead(_miso) ) _rawData++;\n\n digitalWrite(_clock, HIGH);\n\n if (dHigh > 0) delayMicroseconds(dHigh); // DUE\n\n }\n\n digitalWrite(_select, HIGH);\n\n }\n\n\n", "file_path": "libraries/MAX31855_RT/MAX31855.cpp", "rank": 86, "score": 30.019075104198638 }, { "content": "\n\n digitalWrite(_select, LOW);\n\n if (_hwSPI)\n\n {\n\n mySPI->beginTransaction(_spi_settings);\n\n mySPI->transfer(configRegister);\n\n mySPI->transfer(_value >> 8);\n\n mySPI->transfer(_value & 0xFF);\n\n mySPI->endTransaction();\n\n }\n\n else // Software SPI \n\n {\n\n swSPI_transfer(configRegister);\n\n swSPI_transfer(_value >> 8);\n\n swSPI_transfer(_value & 0xFF);\n\n }\n\n digitalWrite(_select, HIGH);\n\n}\n\n\n\n\n", "file_path": "libraries/DAC8551/DAC8551.cpp", "rank": 87, "score": 29.95261633132443 }, { "content": "\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);// 8 MHz - datasheet page 8\n\n\n\n if (_hwSPI)\n\n {\n\n // TODO - ESP32 specific support - see MCP_ADC.\n\n mySPI = &SPI;\n\n mySPI->end();\n\n mySPI->begin();\n\n }\n\n else\n\n {\n\n ::pinMode(_dataIn, INPUT);\n\n ::pinMode(_dataOut, OUTPUT);\n\n ::pinMode(_clock, OUTPUT);\n\n ::digitalWrite(_dataOut, LOW);\n\n ::digitalWrite(_clock, LOW);\n\n }\n\n\n\n // check connected\n", "file_path": "libraries/MCP23S17/MCP23S17.cpp", "rank": 88, "score": 29.895639282599742 }, { "content": " _bitDelay = 10;\n\n}\n\n\n\n\n\nvoid TM1637::init(uint8_t clockPin, uint8_t dataPin, uint8_t digits)\n\n{\n\n _clock = clockPin;\n\n _data = dataPin;\n\n _digits = digits;\n\n\n\n pinMode(_clock, OUTPUT);\n\n digitalWrite(_clock, HIGH);\n\n pinMode(_data, OUTPUT);\n\n digitalWrite(_data, HIGH);\n\n}\n\n\n\n\n\nvoid TM1637::displayInt(long value)\n\n{\n\n uint8_t data[8] = { 16, 16, 16, 16, 16, 16, 16, 16};\n", "file_path": "libraries/TM1637_RT/TM1637.cpp", "rank": 89, "score": 29.619413325621586 }, { "content": " _dataOut = dataOut;\n\n _clock = clock;\n\n _error = MCP23S17_OK;\n\n _hwSPI = false;\n\n}\n\n\n\n\n\nMCP23S17::MCP23S17(uint8_t select, uint8_t address)\n\n{\n\n _address = address;\n\n _select = select;\n\n _error = MCP23S17_OK;\n\n _hwSPI = true;\n\n}\n\n\n\n\n\nbool MCP23S17::begin()\n\n{\n\n ::pinMode(_select, OUTPUT);\n\n ::digitalWrite(_select, HIGH);\n", "file_path": "libraries/MCP23S17/MCP23S17.cpp", "rank": 90, "score": 29.50717695275362 }, { "content": " writeSync(_clock, HIGH);\n\n\n\n // get ACKNOWLEDGE\n\n pinMode(_data, INPUT);\n\n delayMicroseconds(_bitDelay);\n\n uint8_t rv = digitalRead(_data);\n\n\n\n // FORCE OUTPUT LOW\n\n pinMode(_data, OUTPUT);\n\n digitalWrite(_data, LOW);\n\n delayMicroseconds(_bitDelay);\n\n return rv;\n\n}\n\n\n\n\n\nvoid TM1637::start()\n\n{\n\n writeSync(_clock, HIGH);\n\n writeSync(_data, HIGH);\n\n writeSync(_data, LOW);\n", "file_path": "libraries/TM1637_RT/TM1637.cpp", "rank": 91, "score": 29.311896408703827 }, { "content": "### ESP32 specific\n\n\n\n- **void selectHSPI()** in case hardware SPI, the ESP32 has two options HSPI and VSPI.\n\n- **void selectVSPI()** see above.\n\n- **bool usesHSPI()** returns true if HSPI is used.\n\n- **bool usesVSPI()** returns true if VSPI is used.\n\n\n\nThe **selectVSPI()** or the **selectHSPI()** needs to be called \n\nBEFORE the **begin()** function.\n\n\n\n\n\n#### experimental\n\n\n\n- **void setGPIOpins(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t select)** \n\noverrule GPIO pins of ESP32 for hardware SPI. \n\nNeeds to be called AFTER the **begin()** function.\n\n\n\n\n\n### Power down\n\n\n\nCheck datasheet for details.\n\n\n\n- **void setPowerDown(uint8_t powerDownMode)** sets power down mode. 0 - 3.\n\n- **uint8_t getPowerDownMode()** returns last written mode.\n\n- **void setSinglePowerDown(uint8_t channel, uint8_t powerDownMode)** does not affect other channels.\n\n\n\n| Power down mode | Value |\n\n|:----------------------------|:-----:|\n\n| DAC8554_POWERDOWN_NORMAL | 0x00 |\n\n| DAC8554_POWERDOWN_1K | 0x40 |\n\n| DAC8554_POWERDOWN_100K | 0x80 |\n\n| DAC8554_POWERDOWN_HIGH_IMP | 0xC0 |\n\n\n\n\n\n### Broadcast\n\n\n\n- **void bufferValue(uint8_t channel, uint16_t value)** prepare a new value for a channel. \n\n- **void broadcastBuffer()** write all buffers to all(up to 4) 8554's channel's.\n\n- **void broadcastValue(uint16_t value)** write value to all(up to 4) 8554's channel's.\n\n- **void broadcastPowerDown(uint8_t powerDownMode)** write powerDownMode to all 8554's channel's.\n\n\n\n\n\n## Operation\n\n\n\nSee examples\n\n\n\n**demo_hw_spi.ino**\n\n- write a sawtooth to channel A followed by a sinus \n\n- uses HW SPI\n\n\n\n**demo_sw_spi.ino**\n\n- write a sawtooth to channel A followed by a sinus \n\n- uses SW SPI\n\n\n\n**demo_same_time_write.ino**\n\n- writes two square waves that trigger at the same time\n\n\n\n**demo_sequential_write.ino**\n\n- writes two square waves sequentially (slight time difference)\n\n\n\n**demo_powerdown.ino**\n\n- idem\n\n\n\n\n\n## Future\n\n\n\n- testing\n\n\n", "file_path": "libraries/DAC8554/README.md", "rank": 92, "score": 29.148629155727924 }, { "content": "\n\n\n\n//////////////////////////////////////////////////////////////////\n\n//\n\n// PRIVATE\n\n//\n\n\n\nvoid DAC8554::writeDevice(uint8_t configRegister, uint16_t value)\n\n{\n\n digitalWrite(_select, LOW);\n\n if (_hwSPI)\n\n {\n\n mySPI->beginTransaction(_spi_settings);\n\n mySPI->transfer(configRegister);\n\n mySPI->transfer(value >> 8);\n\n mySPI->transfer(value & 0xFF);\n\n mySPI->endTransaction();;\n\n }\n\n else // Software SPI\n\n {\n", "file_path": "libraries/DAC8554/DAC8554.cpp", "rank": 93, "score": 28.970778676740004 }, { "content": "\n\nvoid HX711::begin(uint8_t dataPin, uint8_t clockPin)\n\n{\n\n _dataPin = dataPin;\n\n _clockPin = clockPin;\n\n\n\n pinMode(_dataPin, INPUT);\n\n pinMode(_clockPin, OUTPUT);\n\n digitalWrite(_clockPin, LOW);\n\n\n\n reset();\n\n}\n\n\n\n\n\nvoid HX711::reset()\n\n{\n\n _offset = 0;\n\n _scale = 1;\n\n _gain = 128;\n\n _lastRead = 0;\n", "file_path": "libraries/HX711/HX711.cpp", "rank": 94, "score": 28.904897823076 }, { "content": "\n\n\n\nvoid MCP_DAC::setSPIspeed(uint32_t speed)\n\n{\n\n _SPIspeed = speed;\n\n _spi_settings = SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0);\n\n};\n\n\n\n\n\n//////////////////////////////////////////////////////////////////\n\n//\n\n// PROTECTED\n\n//\n\nvoid MCP_DAC::transfer(uint16_t data)\n\n{\n\n // DATA TRANSFER\n\n digitalWrite(_select, LOW);\n\n if (_hwSPI)\n\n {\n\n // mySPI->beginTransaction(SPISettings(_SPIspeed, MSBFIRST, SPI_MODE0));\n", "file_path": "libraries/MCP_DAC/MCP_DAC.cpp", "rank": 95, "score": 28.825780271424556 }, { "content": " float units = get_value(times) * _scale;\n\n return units;\n\n};\n\n\n\n\n\nvoid HX711::power_down()\n\n{\n\n digitalWrite(_clockPin, LOW);\n\n digitalWrite(_clockPin, HIGH);\n\n}\n\n\n\n\n\nvoid HX711::power_up()\n\n{\n\n digitalWrite(_clockPin, LOW);\n\n}\n\n\n\n\n\n// MSB_FIRST optimized shiftIn\n\n// see datasheet page 5 for timing\n", "file_path": "libraries/HX711/HX711.cpp", "rank": 96, "score": 28.800054211144793 }, { "content": "## Interface\n\n\n\nThe interface exists of the following functions:\n\n- **ShiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder = LSBFIRST)** constructor, bit order is default set to LSBFIRST.\n\n- **int read(void)** reads a new value\n\n- **int lastRead()** returns last value read\n\n- **void setDelay(uint16_t microseconds)** set delay per bit from 0 .. 65535 microseconds. Note that the delay is split in two parts to keep ~ 50% duty cycle.\n\n- **uint16_t getDelay()** returns the set delay in microseconds.\n\n- **bool setBitOrder(uint8_t bitOrder)** set LSBFIRST or MSBFIRST. Returns false for other values.\n\n- **uint8_t getBitOrder(void)** returns LSBFIRST or MSBFIRST\n\n\n\n\n\n## Operation\n\n\n\nSee examples\n\n\n\n\n\n## Future\n\n\n\n- Add a select pin to be more SPI alike?\n\n- improve documentation\n\n- add examples\n\n- increase max delay uint32_t ? \n\n- set delay in terms of frequency - delay is 'wave length'\n\n- set delay in terms of max total time the read may cost.\n\n- set default delay = 0, is no delay ?\n\n- adaptive speed example?\n\n- get set dutyCycle(0 .. 99%)\n\n-\n", "file_path": "libraries/shiftInSlow/README.md", "rank": 98, "score": 28.584991397937188 }, { "content": "### Resolution\n\n\n\n- **void setResolution(uint8_t resolution = 3)** set the resolution, if resolution > 3, it is not set.\n\n- **uint8_t getResolution()** returns the resolution set.\n\n\n\n| Value | Resolution | Conv time (ms) | Samples/s | Notes |\n\n|:------:|:-----------|:--------------:|:---------:|:-------:|\n\n| 0 | 0.5°C | 30 | 33 | |\n\n| 1 | 0.25°C | 65 | 15 | |\n\n| 2 | 0.125°C | 130 | 7 | |\n\n| 3 | 0.0625°C | 250 | 4 | default |\n\n\n\n\n\nNote: for the same resolution it is about 3x faster than a DS18B20.\n\n\n\n\n\n### Configuration\n\n\n\n- **void setConfigRegister(uint16_t configuration)** see table below + read datasheet.\n\n- **uint16_t getConfigRegister()** return set value.\n\n\n\n| Bit | Mask | Name | Description | Value |\n\n|:-----:|:------:|:-----------|:----------------|:-------|\n\n| 0 | 0x0001 | ALT MOD | alert mode | **0 = comparator output**, 1 = interrupt output\n\n| 1 | 0x0002 | ALT POL | alert polarity | **0 = active low**, 1 = active high\n\n| 2 | 0x0004 | ALT SEL | alert select | **0 = upper+lower+crit**, 1 = crit only\n\n| 3 | 0x0008 | ALT CNT | alert control | **0 = OFF**, 1 = ON\n\n| 4 | 0x0010 | ALT STAT | alert status | **0 = OFF**, 1 = ON (read!)\n\n| 5 | 0x0020 | INT CLR | interrupt clear | **0 = none**, 1 = clear interrupt\n\n| 6 | 0x0040 | WIN LOC | lock Tup + Tlow | **0 = unlocked**, 1 = Lock\n\n| 7 | 0x0080 | CRT LOC | lock Tcritical | **0 = unlocked**, 1 = Lock\n\n| 8 | 0x0100 | SHDN | shutdown, | **0 = continuous mode**, 1 = low power\n\n| 9-10 | 0x0600 | Hysteresis | Thysteresis | **00 = 0°C**, 01 = 1.5°C, 10 = 3°C, 11 = 6°C\n\n| 11-15 | | always 0 | |\n\n\n\nCheck datasheet for the details...\n\n\n\n\n", "file_path": "libraries/MCP9808_RT/README.md", "rank": 99, "score": 28.52736415248911 } ]
C++
src/particle_subscriber.cpp
tstellanova/particle_subscriber
175440928aaa8d9d92299787ecac352758171d2c
#include <Particle.h> #include <Adafruit_SSD1306_RK.h> #include <Adafruit_GFX_RK.h> void evt_doorbell_handler(const char *event, const char *data); int render_string(String command); int tone_test(String name); void blank_screen(); void oneshot_timer_cb(); const uint8_t SCREEN_WIDTH = 128; const uint8_t SCREEN_HEIGHT = 64; const uint16_t SPKR_PIN = D3; const unsigned int TONE_A4 = 440; const unsigned int TONE_B4 = 494; const unsigned int TONE_C4 = 262; const unsigned int TONE_D4 = 294; const unsigned int TONE_E4 = 330; const unsigned int TONE_F4 = 349; const unsigned int TONE_G4 = 392; const int NOTE_DURATION_MS = 500; static bool g_clear_screen = false; static bool g_playing_tones = false; static Timer g_screen_cleanup_timer(30000, oneshot_timer_cb, true); Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire); SystemSleepConfiguration g_sleep_config; SerialLogHandler logHandler(LOG_LEVEL_WARN, { { "app", LOG_LEVEL_INFO } }); void sync_play_tone(unsigned int frequency, int milliseconds) { if (frequency != 0) { tone(SPKR_PIN, frequency, milliseconds); } else { noTone(SPKR_PIN); } Particle.process(); delay(milliseconds); } void play_bell_tone() { if (!g_playing_tones) { g_playing_tones = true; for (int count= 0; count < 2; count++) { sync_play_tone(2*TONE_D4, NOTE_DURATION_MS); sync_play_tone(2*TONE_E4, NOTE_DURATION_MS); sync_play_tone(2*TONE_C4, NOTE_DURATION_MS); sync_play_tone(TONE_C4, NOTE_DURATION_MS); sync_play_tone(TONE_G4, 2*NOTE_DURATION_MS); sync_play_tone(0, 2*NOTE_DURATION_MS); } noTone(SPKR_PIN); g_playing_tones = false; } } void play_wakeup_tones() { sync_play_tone(TONE_C4, NOTE_DURATION_MS); sync_play_tone((2*TONE_C4), NOTE_DURATION_MS); sync_play_tone(TONE_C4, NOTE_DURATION_MS); sync_play_tone((2*TONE_C4), NOTE_DURATION_MS); noTone(SPKR_PIN); } void evt_doorbell_handler(const char *event, const char *data) { Log.info(event); render_string("DOOR"); play_bell_tone(); g_screen_cleanup_timer.reset(); g_screen_cleanup_timer.start(); } void oneshot_timer_cb() { g_clear_screen = true; } void blank_screen() { display.clearDisplay(); display.display(); } int render_string(String command) { display.clearDisplay(); display.setTextColor(WHITE); display.setCursor(4, 4); display.setTextSize(4); display.println(command); display.display(); delay(5000); return 0; } int tone_test(String name) { if (name.equalsIgnoreCase("bell")) { play_bell_tone(); } else if (name.equalsIgnoreCase("wakeup")) { play_wakeup_tones(); } return 0; } void display_setup() { delay(250); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Log.error("SSD1306 allocation failed"); } display.clearDisplay(); display.display(); delay(2000); } void setup() { pinMode(SPKR_PIN, OUTPUT); Particle.syncTime(); Particle.function("render",render_string); Particle.function("tone_test",tone_test); Particle.subscribe("household/frontdoor/bell01", evt_doorbell_handler); Log.info("My device ID: %s", (const char*)System.deviceID()); Particle.publishVitals(120); display_setup(); play_wakeup_tones(); } void loop() { delay(5000); Particle.process(); if (g_clear_screen) { g_clear_screen = false; blank_screen(); } }
#include <Particle.h> #include <Adafruit_SSD1306_RK.h> #include <Adafruit_GFX_RK.h> void evt_doorbell_handler(const char *event, const char *data); int render_string(String command); int tone_test(String name); void blank_screen(); void oneshot_timer_cb(); const uint8_t SCREEN_WIDTH = 128; const uint8_t SCREEN_HEIGHT = 64; const uint16_t SPKR_PIN = D3; const unsigned int TONE_A4 = 440; const unsigned int TONE_B4 = 494; const unsigned int TONE_C4 = 262; const unsigned int TONE_D4 = 294; const unsigned int TONE_E4 = 330; const unsigned int TONE_F4 = 349; const unsigned int TONE_G4 = 392; const int NOTE_DURATION_MS = 500; static bool g_clear_screen = false; static bool g_playing_tones = false; static Timer g_screen_cleanup_timer(30000, oneshot_timer_cb, true); Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire); SystemSleepConfiguration g_sleep_config; SerialLogHandler logHandler(LOG_LEVEL_WARN, { { "app", LOG_LEVEL_INFO } }); void sync_play_tone(unsigned int frequency, int milliseconds) { if (frequency != 0) { tone(SPKR_PIN, frequency, milliseconds); } else { noTone(SPKR_PIN); } Particle.process(); delay(milliseconds); } void play_bell_tone() { if (!g_playing_tones) { g_playing_tones = true; for (int count= 0; count < 2; count++) { sync_play_tone(2*TONE_D4, NOTE_DURATION_MS); sync_play_tone(2*TONE_E4, NOTE_DURATION_MS); sync_play_tone(2*TONE_C4, NOTE_DURATION_MS); sync_play_tone(TONE_C4, NOTE_DURATION_MS); sync_play_tone(TONE_G4, 2*NOTE_DURATION_MS); sync_play_tone(0, 2*NOTE_DURATION_MS); } noTone(SPKR_PIN); g_playing_tones = false; } } void play_wakeup_tones() { sync_play_tone(TONE_C4, NOTE_DURATION_MS); sync_play_tone((2*TONE_C4), NOTE_DURATION_MS); sync_play_tone(TONE_C4, NOTE_DURATION_MS); sync_play_tone((2*TONE_C4), NOTE_DURATION_MS); noTone(SPKR_PIN); } void evt_doorbell_handler(const char *event, const char *data) { Log.info(event); render_string("DOOR"); play_bell_tone(); g_screen_cleanup_timer.reset(); g_screen_cleanup_timer.start(); } void oneshot_timer_cb() { g_clear_screen = true; } void blank_screen() { display.clearDisplay(); display.display(); } int render_string(String command) { display.clearDisplay(); display.setTextColor(WHITE); display.setCursor(4, 4); display.setTextSize(4); display.println(command); display.display(); delay(5000); return 0; } int tone_test(String name) { if (name.equalsIgnoreCase("bell")) { play_bell_tone(); } else if (name.equalsIgnoreCase("wakeup")) { play_wakeup_tones(); } return 0; } void display_setup() { delay(250); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Log.error("SSD1306 allocation failed"); } display.clearDisplay(); display.display(); delay(2000); } void setup() { pinMode(SPKR_PIN, OUTPU
void loop() { delay(5000); Particle.process(); if (g_clear_screen) { g_clear_screen = false; blank_screen(); } }
T); Particle.syncTime(); Particle.function("render",render_string); Particle.function("tone_test",tone_test); Particle.subscribe("household/frontdoor/bell01", evt_doorbell_handler); Log.info("My device ID: %s", (const char*)System.deviceID()); Particle.publishVitals(120); display_setup(); play_wakeup_tones(); }
function_block-function_prefixed
[]
C++
src/Cropper.cpp
stippi/WonderBrush-v3
7f88c3e4fbe0bca9ef2df7a92d44789877edfe1e
#include "Cropper.h" #include <Bitmap.h> #include <BitmapStream.h> #include <Directory.h> #include <File.h> #include <Rect.h> #include <TranslationUtils.h> #include <TranslatorRoster.h> #include "RenderBuffer.h" #include "RenderEngine.h" Cropper::Cropper() : BApplication("application/x-vnd.yellowbites.Cropper") , fPrintUsage(true) , fTargetWidth(-1) , fTargetHeight(-1) , fTargetFolder("/boot/home/Desktop") , fTargetFormat(B_JPEG_FORMAT) { } void Cropper::MessageReceived(BMessage* message) { switch (message->what) { default: BApplication::MessageReceived(message); break; } } void Cropper::ReadyToRun() { if (fPrintUsage) _PrintUsage("Cropper"); PostMessage(B_QUIT_REQUESTED); } void Cropper::ArgvReceived(int32 argc, char** argv) { fPrintUsage = false; int32 i = 1; for (; i < argc; i++) { if (strcmp(argv[i], "-o") == 0) { if (i == argc - 1) break; fTargetFolder = argv[++i]; } else if (strcmp(argv[i], "-w") == 0) { if (i == argc - 1) break; fTargetWidth = atoi(argv[++i]); } else if (strcmp(argv[i], "-h") == 0) { if (i == argc - 1) break; fTargetHeight = atoi(argv[++i]); } else if (strcmp(argv[i], "-f") == 0) { if (i == argc - 1) break; const char* name = argv[++i]; bool found = false; BTranslatorRoster* roster = BTranslatorRoster::Default(); translator_id* translatorIDs; int32 idCount; roster->GetAllTranslators(&translatorIDs, &idCount); for (int32 t = 0; t < idCount; t++) { const translation_format* formats; int32 formatCount; roster->GetOutputFormats(translatorIDs[t], &formats, &formatCount); for (int32 f = 0; f < formatCount; f++) { if (formats[f].group != B_TRANSLATOR_BITMAP) continue; if (formats[f].type == B_TRANSLATOR_BITMAP) continue; if (strcmp(formats[f].name, name) == 0) { fTargetFormat = formats[f].type; found = true; break; } } if (found) break; } if (!found) { printf("Did not find translator \"%s\". Use -l to " "list available transators.\n", name); return; } delete[] translatorIDs; } else if (strcmp(argv[i], "-l") == 0) { BTranslatorRoster* roster = BTranslatorRoster::Default(); translator_id* translatorIDs; int32 idCount; roster->GetAllTranslators(&translatorIDs, &idCount); printf("Available formats:\n"); for (int32 t = 0; t < idCount; t++) { const translation_format* formats; int32 formatCount; roster->GetOutputFormats(translatorIDs[t], &formats, &formatCount); for (int32 f = 0; f < formatCount; f++) { if (formats[f].group != B_TRANSLATOR_BITMAP) continue; if (formats[f].type == B_TRANSLATOR_BITMAP) continue; printf(" \"%s\"\n", formats[f].name); } } delete[] translatorIDs; return; } else break; } if (i == argc) { _PrintUsage(argv[0]); return; } create_directory(fTargetFolder.Path(), 0777); for (; i < argc; i++) { BPath path(argv[i]); BBitmap* original = BTranslationUtils::GetBitmap(path.Path()); if (original == NULL) { fprintf(stderr, "Failed to load '%s'\n", argv[i]); continue; } int width = original->Bounds().IntegerWidth() + 1; if (fTargetWidth > 0 && fTargetWidth < width) width = fTargetWidth; int height = original->Bounds().IntegerHeight() + 1; if (fTargetHeight > 0 && fTargetWidth < height) height = fTargetHeight; _CropImage(original, width, height, fTargetFolder, argv[i]); delete original; } } void Cropper::RefsReceived(BMessage* message) { printf("Cropper::RefsReceived()\n"); } void Cropper::_PrintUsage(const char* appPath) { printf("Usage: %s -o <target folder> -f <translator> -w <width> -h <height> [image files]\n", appPath); printf(" -o - The target folder to place the resized images in.\n"); printf(" -w - The width of the resulting images. No horizontal cropping if ommited.\n"); printf(" -h - The height of the resulting images. No vertical cropping if ommited.\n"); printf(" -f - Use the specified translator.\n"); printf("Usage: %s -l\n", appPath); printf(" -l - List all available translators.\n"); } status_t Cropper::_CropImage(const BBitmap* bitmap, int width, int height, BPath path, const char* originalPath) const { BRect croppedRect(0, 0, width - 1, height - 1); BBitmap* resultBitmap = new BBitmap(croppedRect, B_BITMAP_NO_SERVER_LINK, B_RGBA32); status_t ret = resultBitmap->InitCheck(); if (ret != B_OK) { fprintf(stderr, "Failed to create bitmap: %s\n", strerror(ret)); delete bitmap; return ret; } uint8* src = (uint8*)bitmap->Bits(); uint8* dst = (uint8*)resultBitmap->Bits(); uint32 srcBPR = bitmap->BytesPerRow(); uint32 dstBPR = resultBitmap->BytesPerRow(); uint32 bytes = width * 4; for (int y = 0; y < height; y++) { memcpy(dst, src, bytes); src += srcBPR; dst += dstBPR; } BBitmapStream bitmapStream(resultBitmap); BString name(originalPath); name.Remove(0, name.FindLast('/') + 1); path.Append(name); BFile file(path.Path(), B_CREATE_FILE | B_ERASE_FILE | B_READ_WRITE); if (file.InitCheck() != B_OK) { fprintf(stderr, "Failed to create file '%s': %s\n", path.Path(), strerror(file.InitCheck())); return file.InitCheck(); } BTranslatorRoster* roster = BTranslatorRoster::Default(); ret = roster->Translate(&bitmapStream, NULL, NULL, &file, fTargetFormat); if (ret != B_OK) { fprintf(stderr, "Failed to translate file '%s': %s\n", path.Path(), strerror(ret)); return ret; } return B_OK; } int main(int argc, const char* argv[]) { Cropper app; app.Run(); return 0; }
#include "Cropper.h" #include <Bitmap.h> #include <BitmapStream.h> #include <Directory.h> #include <File.h> #include <Rect.h> #include <TranslationUtils.h> #include <TranslatorRoster.h> #include "RenderBuffer.h" #include "RenderEngine.h" Cropper::Cropper() : BApplication("application/x-vnd.yellowbites.Cropper") , f
roppedRect, B_BITMAP_NO_SERVER_LINK, B_RGBA32); status_t ret = resultBitmap->InitCheck(); if (ret != B_OK) { fprintf(stderr, "Failed to create bitmap: %s\n", strerror(ret)); delete bitmap; return ret; } uint8* src = (uint8*)bitmap->Bits(); uint8* dst = (uint8*)resultBitmap->Bits(); uint32 srcBPR = bitmap->BytesPerRow(); uint32 dstBPR = resultBitmap->BytesPerRow(); uint32 bytes = width * 4; for (int y = 0; y < height; y++) { memcpy(dst, src, bytes); src += srcBPR; dst += dstBPR; } BBitmapStream bitmapStream(resultBitmap); BString name(originalPath); name.Remove(0, name.FindLast('/') + 1); path.Append(name); BFile file(path.Path(), B_CREATE_FILE | B_ERASE_FILE | B_READ_WRITE); if (file.InitCheck() != B_OK) { fprintf(stderr, "Failed to create file '%s': %s\n", path.Path(), strerror(file.InitCheck())); return file.InitCheck(); } BTranslatorRoster* roster = BTranslatorRoster::Default(); ret = roster->Translate(&bitmapStream, NULL, NULL, &file, fTargetFormat); if (ret != B_OK) { fprintf(stderr, "Failed to translate file '%s': %s\n", path.Path(), strerror(ret)); return ret; } return B_OK; } int main(int argc, const char* argv[]) { Cropper app; app.Run(); return 0; }
PrintUsage(true) , fTargetWidth(-1) , fTargetHeight(-1) , fTargetFolder("/boot/home/Desktop") , fTargetFormat(B_JPEG_FORMAT) { } void Cropper::MessageReceived(BMessage* message) { switch (message->what) { default: BApplication::MessageReceived(message); break; } } void Cropper::ReadyToRun() { if (fPrintUsage) _PrintUsage("Cropper"); PostMessage(B_QUIT_REQUESTED); } void Cropper::ArgvReceived(int32 argc, char** argv) { fPrintUsage = false; int32 i = 1; for (; i < argc; i++) { if (strcmp(argv[i], "-o") == 0) { if (i == argc - 1) break; fTargetFolder = argv[++i]; } else if (strcmp(argv[i], "-w") == 0) { if (i == argc - 1) break; fTargetWidth = atoi(argv[++i]); } else if (strcmp(argv[i], "-h") == 0) { if (i == argc - 1) break; fTargetHeight = atoi(argv[++i]); } else if (strcmp(argv[i], "-f") == 0) { if (i == argc - 1) break; const char* name = argv[++i]; bool found = false; BTranslatorRoster* roster = BTranslatorRoster::Default(); translator_id* translatorIDs; int32 idCount; roster->GetAllTranslators(&translatorIDs, &idCount); for (int32 t = 0; t < idCount; t++) { const translation_format* formats; int32 formatCount; roster->GetOutputFormats(translatorIDs[t], &formats, &formatCount); for (int32 f = 0; f < formatCount; f++) { if (formats[f].group != B_TRANSLATOR_BITMAP) continue; if (formats[f].type == B_TRANSLATOR_BITMAP) continue; if (strcmp(formats[f].name, name) == 0) { fTargetFormat = formats[f].type; found = true; break; } } if (found) break; } if (!found) { printf("Did not find translator \"%s\". Use -l to " "list available transators.\n", name); return; } delete[] translatorIDs; } else if (strcmp(argv[i], "-l") == 0) { BTranslatorRoster* roster = BTranslatorRoster::Default(); translator_id* translatorIDs; int32 idCount; roster->GetAllTranslators(&translatorIDs, &idCount); printf("Available formats:\n"); for (int32 t = 0; t < idCount; t++) { const translation_format* formats; int32 formatCount; roster->GetOutputFormats(translatorIDs[t], &formats, &formatCount); for (int32 f = 0; f < formatCount; f++) { if (formats[f].group != B_TRANSLATOR_BITMAP) continue; if (formats[f].type == B_TRANSLATOR_BITMAP) continue; printf(" \"%s\"\n", formats[f].name); } } delete[] translatorIDs; return; } else break; } if (i == argc) { _PrintUsage(argv[0]); return; } create_directory(fTargetFolder.Path(), 0777); for (; i < argc; i++) { BPath path(argv[i]); BBitmap* original = BTranslationUtils::GetBitmap(path.Path()); if (original == NULL) { fprintf(stderr, "Failed to load '%s'\n", argv[i]); continue; } int width = original->Bounds().IntegerWidth() + 1; if (fTargetWidth > 0 && fTargetWidth < width) width = fTargetWidth; int height = original->Bounds().IntegerHeight() + 1; if (fTargetHeight > 0 && fTargetWidth < height) height = fTargetHeight; _CropImage(original, width, height, fTargetFolder, argv[i]); delete original; } } void Cropper::RefsReceived(BMessage* message) { printf("Cropper::RefsReceived()\n"); } void Cropper::_PrintUsage(const char* appPath) { printf("Usage: %s -o <target folder> -f <translator> -w <width> -h <height> [image files]\n", appPath); printf(" -o - The target folder to place the resized images in.\n"); printf(" -w - The width of the resulting images. No horizontal cropping if ommited.\n"); printf(" -h - The height of the resulting images. No vertical cropping if ommited.\n"); printf(" -f - Use the specified translator.\n"); printf("Usage: %s -l\n", appPath); printf(" -l - List all available translators.\n"); } status_t Cropper::_CropImage(const BBitmap* bitmap, int width, int height, BPath path, const char* originalPath) const { BRect croppedRect(0, 0, width - 1, height - 1); BBitmap* resultBitmap = new BBitmap(c
random
[ { "content": " class GradientF, \n", "file_path": "src/agg/include/agg_span_gradient.h", "rank": 0, "score": 99143.10744643904 }, { "content": " class ColorF>\n", "file_path": "src/agg/include/agg_span_gradient.h", "rank": 1, "score": 99143.10744643904 }, { "content": " class GradientF, \n", "file_path": "src/agg/include/agg_span_gradient_alpha.h", "rank": 2, "score": 95944.38938892087 }, { "content": " class AlphaF>\n", "file_path": "src/agg/include/agg_span_gradient_alpha.h", "rank": 3, "score": 95944.38938892087 }, { "content": "#define AGG_ARC_INCLUDED\n\n\n\n#include <math.h>\n\n#include \"agg_basics.h\"\n\n\n\nnamespace agg\n\n{\n\n\n\n //=====================================================================arc\n\n //\n\n // See Implementation agg_arc.cpp \n\n //\n", "file_path": "src/agg/include/agg_arc.h", "rank": 4, "score": 54463.13420013235 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n#ifndef AGG_ARRAY_INCLUDED\n\n#define AGG_ARRAY_INCLUDED\n\n\n\n#include <stddef.h>\n\n#include <string.h>\n\n#include \"agg_basics.h\"\n", "file_path": "src/agg/include/agg_array.h", "rank": 5, "score": 54462.54013414126 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n//\n\n// class ellipse\n\n//\n\n//----------------------------------------------------------------------------\n\n\n\n#ifndef AGG_ELLIPSE_INCLUDED\n\n#define AGG_ELLIPSE_INCLUDED\n\n\n\n#include \"agg_basics.h\"\n\n#include <math.h>\n\n\n\nnamespace agg\n\n{\n\n\n\n //----------------------------------------------------------------ellipse\n", "file_path": "src/agg/include/agg_ellipse.h", "rank": 6, "score": 54462.08636821656 }, { "content": "// Liberty Technology Systems, Inc., visit http://lib-sys.com\n\n//\n\n// Liberty Technology Systems, Inc. is the provider of\n\n// PostScript and PDF technology for software developers.\n\n// \n\n//----------------------------------------------------------------------------\n\n#ifndef AGG_SCANLINE_P_INCLUDED\n\n#define AGG_SCANLINE_P_INCLUDED\n\n\n\n#include \"agg_array.h\"\n\n\n\nnamespace agg\n\n{\n\n\n\n //=============================================================scanline_p8\n\n // \n\n // This is a general purpose scaline container which supports the interface \n\n // used in the rasterizer::render(). See description of scanline_u8\n\n // for details.\n\n // \n\n //------------------------------------------------------------------------\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 7, "score": 54461.86662257204 }, { "content": "// \n\n//----------------------------------------------------------------------------\n\n\n\n#ifndef AGG_SCANLINE_U_INCLUDED\n\n#define AGG_SCANLINE_U_INCLUDED\n\n\n\n#include \"agg_array.h\"\n\n\n\nnamespace agg\n\n{\n\n //=============================================================scanline_u8\n\n //\n\n // Unpacked scanline container class\n\n //\n\n // This class is used to transfer data from a scanline rasterizer \n\n // to the rendering buffer. It's organized very simple. The class stores \n\n // information of horizontal spans to render it into a pixel-map buffer. \n\n // Each span has staring X, length, and an array of bytes that determine the \n\n // cover-values for each pixel. \n\n // Before using this class you should know the minimal and maximal pixel \n", "file_path": "src/agg/include/agg_scanline_u.h", "rank": 8, "score": 54461.80380874497 }, { "content": "\n\n#include \"agg_basics.h\"\n\n\n\nnamespace agg\n\n{\n\n\n\n //===============================================================arrowhead\n\n //\n\n // See implementation agg_arrowhead.cpp \n\n //\n", "file_path": "src/agg/include/agg_arrowhead.h", "rank": 9, "score": 54461.6100845251 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n// Copyright (C) 2005 Tony Juricic ([email protected])\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n\n\n#ifndef AGG_CURVES_INCLUDED\n\n#define AGG_CURVES_INCLUDED\n\n\n\n#include \"agg_array.h\"\n", "file_path": "src/agg/include/agg_curves.h", "rank": 10, "score": 54461.48046407576 }, { "content": "/*\n\n * Copyright 2006-2008, Haiku. All rights reserved.\n\n * Distributed under the terms of the MIT License.\n\n */\n\n#ifndef _ICON_UTILS_H\n\n#define _ICON_UTILS_H\n\n\n\n\n\n#include <SupportDefs.h>\n\n\n\n\n", "file_path": "src/icon/include/IconUtils.h", "rank": 11, "score": 54460.98719338757 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n//\n\n// Simple arrowhead/arrowtail generator \n\n//\n\n//----------------------------------------------------------------------------\n\n#ifndef AGG_ARROWHEAD_INCLUDED\n\n#define AGG_ARROWHEAD_INCLUDED\n", "file_path": "src/agg/include/agg_arrowhead.h", "rank": 12, "score": 54460.77799610406 }, { "content": "#define AGG_BSPLINE_INCLUDED\n\n\n\n#include \"agg_array.h\"\n\n\n\nnamespace agg\n\n{\n\n //----------------------------------------------------------------bspline\n\n // A very simple class of Bi-cubic Spline interpolation.\n\n // First call init(num, x[], y[]) where num - number of source points, \n\n // x, y - arrays of X and Y values respectively. Here Y must be a function \n\n // of X. It means that all the X-coordinates must be arranged in the ascending\n\n // order. \n\n // Then call get(x) that calculates a value Y for the respective X. \n\n // The class supports extrapolation, i.e. you can call get(x) where x is\n\n // outside the given with init() X-range. Extrapolation is a simple linear \n\n // function.\n\n //\n\n // See Implementation agg_bspline.cpp\n\n //------------------------------------------------------------------------\n", "file_path": "src/agg/include/agg_bspline.h", "rank": 13, "score": 54460.53486925509 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n//\n\n// class bspline\n\n//\n\n//----------------------------------------------------------------------------\n\n\n\n#ifndef AGG_BSPLINE_INCLUDED\n", "file_path": "src/agg/include/agg_bspline.h", "rank": 14, "score": 54459.46894129206 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n//\n\n// Arc vertex generator\n\n//\n\n//----------------------------------------------------------------------------\n\n\n\n#ifndef AGG_ARC_INCLUDED\n", "file_path": "src/agg/include/agg_arc.h", "rank": 15, "score": 54459.401163670445 }, { "content": " m_max_len(0),\n\n m_last_x(0x7FFFFFF0),\n\n m_covers(),\n\n m_cover_ptr(0)\n\n {\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void reset(int min_x, int max_x)\n\n {\n\n unsigned max_len = max_x - min_x + 3;\n\n if(max_len > m_covers.size())\n\n {\n\n m_covers.resize(max_len);\n\n }\n\n m_last_x = 0x7FFFFFF0;\n\n m_cover_ptr = &m_covers[0];\n\n m_spans.remove_all();\n\n }\n\n\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 16, "score": 54455.838597505885 }, { "content": " double m_distance_tolerance_square;\n\n double m_angle_tolerance;\n\n unsigned m_count;\n\n pod_bvector<point_d> m_points;\n\n };\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n //-------------------------------------------------------------curve4_points\n\n struct curve4_points\n\n {\n\n double cp[8];\n\n curve4_points() {}\n\n curve4_points(double x1, double y1,\n\n double x2, double y2,\n\n double x3, double y3,\n", "file_path": "src/agg/include/agg_curves.h", "rank": 17, "score": 54455.838597505885 }, { "content": " template<class T> \n\n void pod_vector<T>::resize(unsigned new_size)\n\n {\n\n if(new_size > m_size)\n\n {\n\n if(new_size > m_capacity)\n\n {\n\n T* data = pod_allocator<T>::allocate(new_size);\n\n memcpy(data, m_array, m_size * sizeof(T));\n\n pod_allocator<T>::deallocate(m_array, m_capacity);\n\n m_array = data;\n\n }\n\n }\n\n else\n\n {\n\n m_size = new_size;\n\n }\n\n }\n\n\n\n //------------------------------------------------------------------------\n", "file_path": "src/agg/include/agg_array.h", "rank": 18, "score": 54455.838597505885 }, { "content": " {\n\n if(num_elements < block_size)\n\n {\n\n data_ptr(); // Allocate initial block if necessary\n\n unsigned rest = block_size - (m_size & block_mask);\n\n unsigned index;\n\n if(num_elements <= rest)\n\n {\n\n // The rest of the block is good, we can use it\n\n //-----------------\n\n index = m_size;\n\n m_size += num_elements;\n\n return index;\n\n }\n\n\n\n // New block\n\n //---------------\n\n m_size += rest;\n\n data_ptr();\n\n index = m_size;\n", "file_path": "src/agg/include/agg_array.h", "rank": 19, "score": 54455.838597505885 }, { "content": " const T& at(unsigned i) const { return m_array[i]; }\n\n T& at(unsigned i) { return m_array[i]; }\n\n T value_at(unsigned i) const { return m_array[i]; }\n\n\n\n const T* data() const { return m_array; }\n\n T* data() { return m_array; }\n\n\n\n void remove_all() { m_size = 0; }\n\n void clear() { m_size = 0; }\n\n void cut_at(unsigned num) { if(num < m_size) m_size = num; }\n\n\n\n private:\n\n unsigned m_size;\n\n unsigned m_capacity;\n\n T* m_array;\n\n };\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> \n\n void pod_vector<T>::capacity(unsigned cap, unsigned extra_tail)\n", "file_path": "src/agg/include/agg_array.h", "rank": 20, "score": 54455.838597505885 }, { "content": "\n\n void cusp_limit(double) {}\n\n double cusp_limit() const { return 0.0; }\n\n\n\n void rewind(unsigned path_id);\n\n unsigned vertex(double* x, double* y);\n\n\n\n private:\n\n int m_num_steps;\n\n int m_step;\n\n double m_scale;\n\n double m_start_x; \n\n double m_start_y;\n\n double m_end_x; \n\n double m_end_y;\n\n double m_fx; \n\n double m_fy;\n\n double m_dfx; \n\n double m_dfy;\n\n double m_ddfx; \n", "file_path": "src/agg/include/agg_curves.h", "rank": 21, "score": 54455.838597505885 }, { "content": "\n\n for(;;)\n\n {\n\n do i++; while( less(arr[i], arr[base]) );\n\n do j--; while( less(arr[base], arr[j]) );\n\n\n\n if( i > j )\n\n {\n\n break;\n\n }\n\n\n\n swap_elements(arr[i], arr[j]);\n\n }\n\n\n\n swap_elements(arr[base], arr[j]);\n\n\n\n // now, push the largest sub-array\n\n if(j - base > limit - i)\n\n {\n\n top[0] = base;\n", "file_path": "src/agg/include/agg_array.h", "rank": 22, "score": 54455.838597505885 }, { "content": " m_y = y;\n\n m_rx = rx;\n\n m_ry = ry;\n\n m_num = num_steps;\n\n m_step = 0;\n\n m_cw = cw;\n\n if(m_num == 0) calc_num_steps();\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n inline void ellipse::approximation_scale(double scale)\n\n { \n\n m_scale = scale;\n\n calc_num_steps();\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n inline void ellipse::calc_num_steps()\n\n {\n\n double ra = (fabs(m_rx) + fabs(m_ry)) / 2;\n", "file_path": "src/agg/include/agg_ellipse.h", "rank": 23, "score": 54455.838597505885 }, { "content": " //------------------------------------------------------------------------\n\n template<class T> class pod_vector\n\n {\n\n public:\n\n typedef T value_type;\n\n\n\n ~pod_vector() { pod_allocator<T>::deallocate(m_array, m_capacity); }\n\n pod_vector() : m_size(0), m_capacity(0), m_array(0) {}\n\n pod_vector(unsigned cap, unsigned extra_tail=0);\n\n\n\n // Copying\n\n pod_vector(const pod_vector<T>&);\n\n const pod_vector<T>& operator = (const pod_vector<T>&);\n\n\n\n // Set new capacity. All data is lost, size is set to zero.\n\n void capacity(unsigned cap, unsigned extra_tail=0);\n\n unsigned capacity() const { return m_capacity; }\n\n\n\n // Allocate n elements. All data is lost, \n\n // but elements can be accessed in range 0...size-1. \n", "file_path": "src/agg/include/agg_array.h", "rank": 24, "score": 54455.838597505885 }, { "content": " int8u* ptr;\n\n if(start + i < m_size)\n\n {\n\n ptr = (int8u*)(&((*this)[start + i]));\n\n }\n\n else\n\n {\n\n ptr = (int8u*)data_ptr();\n\n ++m_size;\n\n }\n\n for(unsigned j = 0; j < sizeof(T); ++j)\n\n {\n\n *ptr++ = *data;\n\n ++data;\n\n }\n\n }\n\n }\n\n\n\n const T* block(unsigned nb) const { return m_blocks[nb]; }\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 25, "score": 54455.838597505885 }, { "content": " }\n\n\n\n\n\n // Replace or add a number of elements starting from \"start\" position\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n void pod_bvector<T, S>::deserialize(unsigned start, const T& empty_val, \n\n const int8u* data, unsigned byte_size)\n\n {\n\n while(m_size < start)\n\n {\n\n add(empty_val);\n\n }\n\n\n\n byte_size /= sizeof(T);\n\n for(unsigned i = 0; i < byte_size; ++i)\n\n {\n\n if(start + i < m_size)\n\n {\n\n memcpy(&((*this)[start + i]), data, sizeof(T));\n", "file_path": "src/agg/include/agg_array.h", "rank": 26, "score": 54455.838597505885 }, { "content": " }\n\n\n\n //----------------------------------------------------------range_adaptor\n\n template<class Array> class range_adaptor\n\n {\n\n public:\n\n typedef typename Array::value_type value_type;\n\n\n\n range_adaptor(Array& array, unsigned start, unsigned size) :\n\n m_array(array), m_start(start), m_size(size)\n\n {}\n\n\n\n unsigned size() const { return m_size; }\n\n const value_type& operator [] (unsigned i) const { return m_array[m_start + i]; }\n\n value_type& operator [] (unsigned i) { return m_array[m_start + i]; }\n\n const value_type& at(unsigned i) const { return m_array[m_start + i]; }\n\n value_type& at(unsigned i) { return m_array[m_start + i]; }\n\n value_type value_at(unsigned i) const { return m_array[m_start + i]; }\n\n\n\n private:\n", "file_path": "src/agg/include/agg_array.h", "rank": 27, "score": 54455.838597505885 }, { "content": " Array& m_array;\n\n unsigned m_start;\n\n unsigned m_size;\n\n };\n\n\n\n //---------------------------------------------------------------int_less\n\n inline bool int_less(int a, int b) { return a < b; }\n\n\n\n //------------------------------------------------------------int_greater\n\n inline bool int_greater(int a, int b) { return a > b; }\n\n\n\n //----------------------------------------------------------unsigned_less\n\n inline bool unsigned_less(unsigned a, unsigned b) { return a < b; }\n\n\n\n //-------------------------------------------------------unsigned_greater\n\n inline bool unsigned_greater(unsigned a, unsigned b) { return a > b; }\n\n}\n\n\n\n#endif\n", "file_path": "src/agg/include/agg_array.h", "rank": 28, "score": 54455.838597505885 }, { "content": " m_tail_d2 = d2;\n\n m_tail_d3 = d3;\n\n m_tail_d4 = d4;\n\n m_tail_flag = true;\n\n }\n\n\n\n void tail() { m_tail_flag = true; }\n\n void no_tail() { m_tail_flag = false; }\n\n\n\n void rewind(unsigned path_id);\n\n unsigned vertex(double* x, double* y);\n\n\n\n private:\n\n double m_head_d1;\n\n double m_head_d2;\n\n double m_head_d3;\n\n double m_head_d4;\n\n double m_tail_d1;\n\n double m_tail_d2;\n\n double m_tail_d3;\n", "file_path": "src/agg/include/agg_arrowhead.h", "rank": 29, "score": 54455.838597505885 }, { "content": " T value_at(unsigned i) const\n\n { \n\n return m_blocks[i >> block_shift][i & block_mask];\n\n }\n\n\n\n const T& curr(unsigned idx) const\n\n {\n\n return (*this)[idx];\n\n }\n\n\n\n T& curr(unsigned idx)\n\n {\n\n return (*this)[idx];\n\n }\n\n\n\n const T& prev(unsigned idx) const\n\n {\n\n return (*this)[(idx + m_size - 1) % m_size];\n\n }\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 30, "score": 54455.838597505885 }, { "content": " T& prev(unsigned idx)\n\n {\n\n return (*this)[(idx + m_size - 1) % m_size];\n\n }\n\n\n\n const T& next(unsigned idx) const\n\n {\n\n return (*this)[(idx + 1) % m_size];\n\n }\n\n\n\n T& next(unsigned idx)\n\n {\n\n return (*this)[(idx + 1) % m_size];\n\n }\n\n\n\n const T& last() const\n\n {\n\n return (*this)[m_size - 1];\n\n }\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 31, "score": 54455.838597505885 }, { "content": " }\n\n\n\n //--------------------------------------------------------------------\n\n void add_cell(int x, unsigned cover)\n\n {\n\n *m_cover_ptr = (cover_type)cover;\n\n if(x == m_last_x+1 && m_cur_span->len > 0)\n\n {\n\n m_cur_span->len++;\n\n }\n\n else\n\n {\n\n m_cur_span++;\n\n m_cur_span->covers = m_cover_ptr;\n\n m_cur_span->x = (int16)x;\n\n m_cur_span->len = 1;\n\n }\n\n m_last_x = x;\n\n m_cover_ptr++;\n\n }\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 32, "score": 54455.838597505885 }, { "content": " {\n\n allocate_block(i);\n\n }\n\n for(i = 0; i < v.m_num_blocks; ++i)\n\n {\n\n memcpy(m_blocks[i], v.m_blocks[i], block_size * sizeof(T));\n\n }\n\n m_size = v.m_size;\n\n return *this;\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S>\n\n void pod_bvector<T, S>::allocate_block(unsigned nb)\n\n {\n\n if(nb >= m_max_blocks) \n\n {\n\n T** new_blocks = pod_allocator<T*>::allocate(m_max_blocks + m_block_ptr_inc);\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 33, "score": 54455.838597505885 }, { "content": "//----------------------------------------------------------------------------\n\n// Anti-Grain Geometry - Version 2.4\n\n// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)\n\n//\n\n// Permission to copy, use, modify, sell and distribute this software \n\n// is granted provided this copyright notice appears in all copies. \n\n// This software is provided \"as is\" without express or implied\n\n// warranty, and with no claim as to its suitability for any purpose.\n\n//\n\n//----------------------------------------------------------------------------\n\n// Contact: [email protected]\n\n// [email protected]\n\n// http://www.antigrain.com\n\n//----------------------------------------------------------------------------\n\n//\n\n// Class scanline_p - a general purpose scanline container with packed spans.\n\n//\n\n//----------------------------------------------------------------------------\n\n//\n\n// Adaptation for 32-bit screen coordinates (scanline32_p) has been sponsored by \n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 34, "score": 54455.838597505885 }, { "content": "\n\n m_num_blocks++;\n\n m_rest = size;\n\n }\n\n\n\n unsigned m_block_size;\n\n unsigned m_block_ptr_inc;\n\n unsigned m_num_blocks;\n\n unsigned m_max_blocks;\n\n block_type* m_blocks;\n\n int8u* m_buf_ptr;\n\n unsigned m_rest;\n\n };\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 35, "score": 54455.838597505885 }, { "content": " double m_ddfy;\n\n double m_dddfx; \n\n double m_dddfy;\n\n double m_saved_fx; \n\n double m_saved_fy;\n\n double m_saved_dfx; \n\n double m_saved_dfy;\n\n double m_saved_ddfx; \n\n double m_saved_ddfy;\n\n };\n\n\n\n\n\n\n\n //-------------------------------------------------------catrom_to_bezier\n\n inline curve4_points catrom_to_bezier(double x1, double y1, \n\n double x2, double y2, \n\n double x3, double y3,\n\n double x4, double y4)\n\n {\n\n // Trans. matrix Catmull-Rom to Bezier\n", "file_path": "src/agg/include/agg_curves.h", "rank": 36, "score": 54455.838597505885 }, { "content": " void init(double x1, double y1, \n\n double x2, double y2, \n\n double x3, double y3);\n\n\n\n void approximation_method(curve_approximation_method_e) {}\n\n curve_approximation_method_e approximation_method() const { return curve_div; }\n\n\n\n void approximation_scale(double s) { m_approximation_scale = s; }\n\n double approximation_scale() const { return m_approximation_scale; }\n\n\n\n void angle_tolerance(double a) { m_angle_tolerance = a; }\n\n double angle_tolerance() const { return m_angle_tolerance; }\n\n\n\n void cusp_limit(double) {}\n\n double cusp_limit() const { return 0.0; }\n\n\n\n void rewind(unsigned)\n\n {\n\n m_count = 0;\n\n }\n", "file_path": "src/agg/include/agg_curves.h", "rank": 37, "score": 54455.838597505885 }, { "content": "\n\n //------------------------------------------------------------------------\n\n enum quick_sort_threshold_e\n\n {\n\n quick_sort_threshold = 9\n\n };\n\n\n\n \n\n //-----------------------------------------------------------swap_elements\n\n template<class T> inline void swap_elements(T& a, T& b)\n\n {\n\n T temp = a;\n\n a = b;\n\n b = temp;\n\n }\n\n\n\n\n\n //--------------------------------------------------------------quick_sort\n\n template<class Array, class Less>\n\n void quick_sort(Array& arr, Less less)\n", "file_path": "src/agg/include/agg_array.h", "rank": 38, "score": 54455.838597505885 }, { "content": " //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n inline void pod_bvector<T, S>::remove_last()\n\n {\n\n if(m_size) --m_size;\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n void pod_bvector<T, S>::modify_last(const T& val)\n\n {\n\n remove_last();\n\n add(val);\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n int pod_bvector<T, S>::allocate_continuous_block(unsigned num_elements)\n", "file_path": "src/agg/include/agg_array.h", "rank": 39, "score": 54455.838597505885 }, { "content": " {\n\n if(arr.size() == 0) return 0;\n\n\n\n unsigned beg = 0;\n\n unsigned end = arr.size() - 1;\n\n\n\n if(less(val, arr[0])) return 0;\n\n if(less(arr[end], val)) return end + 1;\n\n\n\n while(end - beg > 1)\n\n {\n\n unsigned mid = (end + beg) >> 1;\n\n if(less(val, arr[mid])) end = mid; \n\n else beg = mid;\n\n }\n\n\n\n //if(beg <= 0 && less(val, arr[0])) return 0;\n\n //if(end >= arr.size() - 1 && less(arr[end], val)) ++end;\n\n\n\n return end;\n", "file_path": "src/agg/include/agg_array.h", "rank": 40, "score": 54455.838597505885 }, { "content": " curve_approximation_method_e approximation_method() const { return curve_inc; }\n\n\n\n void approximation_scale(double s);\n\n double approximation_scale() const;\n\n\n\n void angle_tolerance(double) {}\n\n double angle_tolerance() const { return 0.0; }\n\n\n\n void cusp_limit(double) {}\n\n double cusp_limit() const { return 0.0; }\n\n\n\n void rewind(unsigned path_id);\n\n unsigned vertex(double* x, double* y);\n\n\n\n private:\n\n int m_num_steps;\n\n int m_step;\n\n double m_scale;\n\n double m_start_x; \n\n double m_start_y;\n", "file_path": "src/agg/include/agg_curves.h", "rank": 41, "score": 54455.838597505885 }, { "content": " {\n\n m_size = 0;\n\n if(cap > m_capacity)\n\n {\n\n pod_allocator<T>::deallocate(m_array, m_capacity);\n\n m_capacity = cap + extra_tail;\n\n m_array = m_capacity ? pod_allocator<T>::allocate(m_capacity) : 0;\n\n }\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> \n\n void pod_vector<T>::allocate(unsigned size, unsigned extra_tail)\n\n {\n\n capacity(size, extra_tail);\n\n m_size = size;\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n", "file_path": "src/agg/include/agg_array.h", "rank": 42, "score": 54455.838597505885 }, { "content": " return *this;\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> void pod_vector<T>::serialize(int8u* ptr) const\n\n { \n\n if(m_size) memcpy(ptr, m_array, m_size * sizeof(T)); \n\n }\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> \n\n void pod_vector<T>::deserialize(const int8u* data, unsigned byte_size)\n\n {\n\n byte_size /= sizeof(T);\n\n allocate(byte_size);\n\n if(byte_size) memcpy(m_array, data, byte_size * sizeof(T));\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> \n", "file_path": "src/agg/include/agg_array.h", "rank": 43, "score": 54455.838597505885 }, { "content": " //--------------------------------------------------------------------\n\n void add_cell(int x, unsigned cover)\n\n {\n\n *m_cover_ptr = cover_type(cover);\n\n if(x == m_last_x+1 && m_spans.size() && m_spans.last().len > 0)\n\n {\n\n m_spans.last().len++;\n\n }\n\n else\n\n {\n\n m_spans.add(span(coord_type(x), 1, m_cover_ptr));\n\n }\n\n m_last_x = x;\n\n m_cover_ptr++;\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void add_cells(int x, unsigned len, const cover_type* covers)\n\n {\n\n memcpy(m_cover_ptr, covers, len * sizeof(cover_type));\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 44, "score": 54455.838597505885 }, { "content": " double m_end_x; \n\n double m_end_y;\n\n double m_fx; \n\n double m_fy;\n\n double m_dfx; \n\n double m_dfy;\n\n double m_ddfx; \n\n double m_ddfy;\n\n double m_saved_fx; \n\n double m_saved_fy;\n\n double m_saved_dfx; \n\n double m_saved_dfy;\n\n };\n\n\n\n\n\n\n\n\n\n\n", "file_path": "src/agg/include/agg_curves.h", "rank": 45, "score": 54455.838597505885 }, { "content": " double da = acos(ra / (ra + 0.125 / m_scale)) * 2;\n\n m_num = uround(2*pi / da);\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n inline void ellipse::rewind(unsigned)\n\n {\n\n m_step = 0;\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n inline unsigned ellipse::vertex(double* x, double* y)\n\n {\n\n if(m_step == m_num) \n\n {\n\n ++m_step;\n\n return path_cmd_end_poly | path_flags_close | path_flags_ccw;\n\n }\n\n if(m_step > m_num) return path_cmd_stop;\n\n double angle = double(m_step) / double(m_num) * 2.0 * pi;\n", "file_path": "src/agg/include/agg_ellipse.h", "rank": 46, "score": 54455.838597505885 }, { "content": " m_rest(0)\n\n {\n\n }\n\n \n\n\n\n int8u* allocate(unsigned size, unsigned alignment=1)\n\n {\n\n if(size == 0) return 0;\n\n if(size <= m_rest)\n\n {\n\n int8u* ptr = m_buf_ptr;\n\n if(alignment > 1)\n\n {\n\n unsigned align = \n\n (alignment - unsigned((size_t)ptr) % alignment) % alignment;\n\n\n\n size += align;\n\n ptr += align;\n\n if(size <= m_rest)\n\n {\n", "file_path": "src/agg/include/agg_array.h", "rank": 47, "score": 54455.838597505885 }, { "content": "\n\nnamespace agg\n\n{\n\n\n\n // See Implementation agg_curves.cpp\n\n\n\n //--------------------------------------------curve_approximation_method_e\n\n enum curve_approximation_method_e\n\n {\n\n curve_inc,\n\n curve_div\n\n };\n\n \n\n //--------------------------------------------------------------curve3_inc\n", "file_path": "src/agg/include/agg_curves.h", "rank": 48, "score": 54455.838597505885 }, { "content": " memcpy(m_array, c, sizeof(T) * Size);\n\n return *this;\n\n }\n\n\n\n static unsigned size() { return Size; }\n\n const T& operator [] (unsigned i) const { return m_array[i]; }\n\n T& operator [] (unsigned i) { return m_array[i]; }\n\n const T& at(unsigned i) const { return m_array[i]; }\n\n T& at(unsigned i) { return m_array[i]; }\n\n T value_at(unsigned i) const { return m_array[i]; }\n\n\n\n private:\n\n T m_array[Size];\n\n };\n\n\n\n\n\n //--------------------------------------------------------pod_auto_vector\n\n template<class T, unsigned Size> class pod_auto_vector\n\n {\n\n public:\n", "file_path": "src/agg/include/agg_array.h", "rank": 49, "score": 54455.838597505885 }, { "content": " //--------------------------------------------------------------------\n\n void finalize(int y) \n\n { \n\n m_y = y; \n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void reset_spans()\n\n {\n\n m_last_x = 0x7FFFFFF0;\n\n m_cover_ptr = &m_covers[0];\n\n m_cur_span = &m_spans[0];\n\n m_cur_span->len = 0;\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n int y() const { return m_y; }\n\n unsigned num_spans() const { return unsigned(m_cur_span - &m_spans[0]); }\n\n const_iterator begin() const { return &m_spans[1]; }\n\n\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 50, "score": 54455.838597505885 }, { "content": "\n\n void reset() { m_num_steps = 0; m_step = -1; }\n\n void init(double x1, double y1, \n\n double x2, double y2, \n\n double x3, double y3,\n\n double x4, double y4);\n\n\n\n void init(const curve4_points& cp)\n\n {\n\n init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);\n\n }\n\n\n\n void approximation_method(curve_approximation_method_e) {}\n\n curve_approximation_method_e approximation_method() const { return curve_inc; }\n\n\n\n void approximation_scale(double s);\n\n double approximation_scale() const;\n\n\n\n void angle_tolerance(double) {}\n\n double angle_tolerance() const { return 0.0; }\n", "file_path": "src/agg/include/agg_curves.h", "rank": 51, "score": 54455.838597505885 }, { "content": " }\n\n else\n\n {\n\n T* ptr = data_ptr();\n\n memcpy(ptr, data, sizeof(T));\n\n ++m_size;\n\n }\n\n data += sizeof(T);\n\n }\n\n }\n\n\n\n\n\n //---------------------------------------------------------block_allocator\n\n // Allocator for arbitrary POD data. Most usable in different cache\n\n // systems for efficient memory allocations. \n\n // Memory is allocated with blocks of fixed size (\"block_size\" in\n\n // the constructor). If required size exceeds the block size the allocator\n\n // creates a new block of the required size. However, the most efficient\n\n // use is when the average reqired size is much less than the block size. \n\n //------------------------------------------------------------------------\n", "file_path": "src/agg/include/agg_array.h", "rank": 52, "score": 54455.838597505885 }, { "content": " double m_tail_d4;\n\n bool m_head_flag;\n\n bool m_tail_flag;\n\n double m_coord[16];\n\n unsigned m_cmd[8];\n\n unsigned m_curr_id;\n\n unsigned m_curr_coord;\n\n };\n\n\n\n}\n\n\n\n#endif\n", "file_path": "src/agg/include/agg_arrowhead.h", "rank": 53, "score": 54455.838597505885 }, { "content": " {\n\n unsigned nb = m_size >> block_shift;\n\n if(nb >= m_num_blocks)\n\n {\n\n allocate_block(nb);\n\n }\n\n return m_blocks[nb] + (m_size & block_mask);\n\n }\n\n\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n inline void pod_bvector<T, S>::add(const T& val)\n\n {\n\n *data_ptr() = val;\n\n ++m_size;\n\n }\n\n\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 54, "score": 54455.838597505885 }, { "content": " pod_allocator<T*>::allocate(v.m_max_blocks) : \n\n 0),\n\n m_block_ptr_inc(v.m_block_ptr_inc)\n\n {\n\n unsigned i;\n\n for(i = 0; i < v.m_num_blocks; ++i)\n\n {\n\n m_blocks[i] = pod_allocator<T>::allocate(block_size);\n\n memcpy(m_blocks[i], v.m_blocks[i], block_size * sizeof(T));\n\n }\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n const pod_bvector<T, S>& \n\n pod_bvector<T, S>::operator = (const pod_bvector<T, S>& v)\n\n {\n\n unsigned i;\n\n for(i = m_num_blocks; i < v.m_num_blocks; ++i)\n", "file_path": "src/agg/include/agg_array.h", "rank": 55, "score": 54455.838597505885 }, { "content": "\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n pod_bvector<T, S>::pod_bvector(unsigned block_ptr_inc) :\n\n m_size(0),\n\n m_num_blocks(0),\n\n m_max_blocks(0),\n\n m_blocks(0),\n\n m_block_ptr_inc(block_ptr_inc)\n\n {\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n pod_bvector<T, S>::pod_bvector(const pod_bvector<T, S>& v) :\n\n m_size(v.m_size),\n\n m_num_blocks(v.m_num_blocks),\n\n m_max_blocks(v.m_max_blocks),\n\n m_blocks(v.m_max_blocks ? \n", "file_path": "src/agg/include/agg_array.h", "rank": 56, "score": 54455.838597505885 }, { "content": " pod_allocator<T>::deallocate(*blk, block_size);\n\n --blk;\n\n }\n\n }\n\n pod_allocator<T*>::deallocate(m_blocks, m_max_blocks);\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n void pod_bvector<T, S>::free_tail(unsigned size)\n\n {\n\n if(size < m_size)\n\n {\n\n unsigned nb = (size + block_mask) >> block_shift;\n\n while(m_num_blocks > nb)\n\n {\n\n pod_allocator<T>::deallocate(m_blocks[--m_num_blocks], block_size);\n\n }\n\n if(m_num_blocks == 0)\n", "file_path": "src/agg/include/agg_array.h", "rank": 57, "score": 54455.838597505885 }, { "content": " if(m_num_blocks >= m_max_blocks) \n\n {\n\n block_type* new_blocks = \n\n pod_allocator<block_type>::allocate(m_max_blocks + m_block_ptr_inc);\n\n\n\n if(m_blocks)\n\n {\n\n memcpy(new_blocks, \n\n m_blocks, \n\n m_num_blocks * sizeof(block_type));\n\n pod_allocator<block_type>::deallocate(m_blocks, m_max_blocks);\n\n }\n\n m_blocks = new_blocks;\n\n m_max_blocks += m_block_ptr_inc;\n\n }\n\n\n\n m_blocks[m_num_blocks].size = size;\n\n m_blocks[m_num_blocks].data = \n\n m_buf_ptr =\n\n pod_allocator<int8u>::allocate(size);\n", "file_path": "src/agg/include/agg_array.h", "rank": 58, "score": 54455.838597505885 }, { "content": " unsigned m_size;\n\n };\n\n\n\n\n\n //---------------------------------------------------------------pod_array\n\n template<class T> class pod_array\n\n {\n\n public:\n\n typedef T value_type;\n\n typedef pod_array<T> self_type;\n\n\n\n ~pod_array() { pod_allocator<T>::deallocate(m_array, m_size); }\n\n pod_array() : m_array(0), m_size(0) {}\n\n\n\n pod_array(unsigned size) : \n\n m_array(pod_allocator<T>::allocate(size)), \n\n m_size(size) \n\n {}\n\n\n\n pod_array(const self_type& v) : \n", "file_path": "src/agg/include/agg_array.h", "rank": 59, "score": 54455.838597505885 }, { "content": " m_array(pod_allocator<T>::allocate(v.m_size)), \n\n m_size(v.m_size) \n\n {\n\n memcpy(m_array, v.m_array, sizeof(T) * m_size);\n\n }\n\n\n\n void resize(unsigned size)\n\n {\n\n if(size != m_size)\n\n {\n\n pod_allocator<T>::deallocate(m_array, m_size);\n\n m_array = pod_allocator<T>::allocate(m_size = size);\n\n }\n\n }\n\n const self_type& operator = (const self_type& v)\n\n {\n\n resize(v.size());\n\n memcpy(m_array, v.m_array, sizeof(T) * m_size);\n\n return *this;\n\n }\n", "file_path": "src/agg/include/agg_array.h", "rank": 60, "score": 54455.838597505885 }, { "content": " unsigned vertex(double* x, double* y);\n\n\n\n private:\n\n void calc_num_steps();\n\n\n\n double m_x;\n\n double m_y;\n\n double m_rx;\n\n double m_ry;\n\n double m_scale;\n\n unsigned m_num;\n\n unsigned m_step;\n\n bool m_cw;\n\n };\n\n\n\n //------------------------------------------------------------------------\n\n inline void ellipse::init(double x, double y, double rx, double ry, \n\n unsigned num_steps, bool cw)\n\n {\n\n m_x = x;\n", "file_path": "src/agg/include/agg_ellipse.h", "rank": 61, "score": 54455.838597505885 }, { "content": " template<class T> pod_vector<T>::pod_vector(unsigned cap, unsigned extra_tail) :\n\n m_size(0), \n\n m_capacity(cap + extra_tail), \n\n m_array(pod_allocator<T>::allocate(m_capacity)) {}\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> pod_vector<T>::pod_vector(const pod_vector<T>& v) :\n\n m_size(v.m_size),\n\n m_capacity(v.m_capacity),\n\n m_array(v.m_capacity ? pod_allocator<T>::allocate(v.m_capacity) : 0)\n\n {\n\n memcpy(m_array, v.m_array, sizeof(T) * v.m_size);\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n template<class T> const pod_vector<T>& \n\n pod_vector<T>::operator = (const pod_vector<T>&v)\n\n {\n\n allocate(v.m_size);\n\n if(v.m_size) memcpy(m_array, v.m_array, sizeof(T) * v.m_size);\n", "file_path": "src/agg/include/agg_array.h", "rank": 62, "score": 54455.838597505885 }, { "content": " }\n\n\n\n\n\n\n\n\n\n //------------------------------------------------------remove_duplicates\n\n // Remove duplicates from a sorted array. It doesn't cut the \n\n // tail of the array, it just returns the number of remaining elements.\n\n //-----------------------------------------------------------------------\n\n template<class Array, class Equal>\n\n unsigned remove_duplicates(Array& arr, Equal equal)\n\n {\n\n if(arr.size() < 2) return arr.size();\n\n\n\n unsigned i, j;\n\n for(i = 1, j = 1; i < arr.size(); i++)\n\n {\n\n typename Array::value_type& e = arr[i];\n\n if(!equal(e, arr[i - 1]))\n\n {\n", "file_path": "src/agg/include/agg_array.h", "rank": 63, "score": 54455.838597505885 }, { "content": "\n\nnamespace agg\n\n{\n\n\n\n //-------------------------------------------------------pod_array_adaptor\n\n template<class T> class pod_array_adaptor\n\n {\n\n public:\n\n typedef T value_type;\n\n pod_array_adaptor(T* array, unsigned size) : \n\n m_array(array), m_size(size) {}\n\n\n\n unsigned size() const { return m_size; }\n\n const T& operator [] (unsigned i) const { return m_array[i]; }\n\n T& operator [] (unsigned i) { return m_array[i]; }\n\n const T& at(unsigned i) const { return m_array[i]; }\n\n T& at(unsigned i) { return m_array[i]; }\n\n T value_at(unsigned i) const { return m_array[i]; }\n\n\n\n private:\n", "file_path": "src/agg/include/agg_array.h", "rank": 64, "score": 54455.838597505885 }, { "content": " arr[j++] = e;\n\n }\n\n }\n\n return j;\n\n }\n\n\n\n //--------------------------------------------------------invert_container\n\n template<class Array> void invert_container(Array& arr)\n\n {\n\n int i = 0;\n\n int j = arr.size() - 1;\n\n while(i < j)\n\n {\n\n swap_elements(arr[i++], arr[j--]);\n\n }\n\n }\n\n\n\n //------------------------------------------------------binary_search_pos\n\n template<class Array, class Value, class Less>\n\n unsigned binary_search_pos(const Array& arr, const Value& val, Less less)\n", "file_path": "src/agg/include/agg_array.h", "rank": 65, "score": 54455.838597505885 }, { "content": "\n\n unsigned vertex(double* x, double* y)\n\n {\n\n if(m_count >= m_points.size()) return path_cmd_stop;\n\n const point_d& p = m_points[m_count++];\n\n *x = p.x;\n\n *y = p.y;\n\n return (m_count == 1) ? path_cmd_move_to : path_cmd_line_to;\n\n }\n\n\n\n private:\n\n void bezier(double x1, double y1, \n\n double x2, double y2, \n\n double x3, double y3);\n\n void recursive_bezier(double x1, double y1, \n\n double x2, double y2, \n\n double x3, double y3,\n\n unsigned level);\n\n\n\n double m_approximation_scale;\n", "file_path": "src/agg/include/agg_curves.h", "rank": 66, "score": 54455.838597505885 }, { "content": " void pod_vector<T>::insert_at(unsigned pos, const T& val)\n\n {\n\n if(pos >= m_size) \n\n {\n\n m_array[m_size] = val;\n\n }\n\n else\n\n {\n\n memmove(m_array + pos + 1, m_array + pos, (m_size - pos) * sizeof(T));\n\n m_array[pos] = val;\n\n }\n\n ++m_size;\n\n }\n\n\n\n //---------------------------------------------------------------pod_bvector\n\n // A simple class template to store Plain Old Data, similar to std::deque\n\n // It doesn't reallocate memory but instead, uses blocks of data of size \n\n // of (1 << S), that is, power of two. The data is NOT contiguous in memory, \n\n // so the only valid access method is operator [] or curr(), prev(), next()\n\n // \n", "file_path": "src/agg/include/agg_array.h", "rank": 67, "score": 54455.838597505885 }, { "content": " if(m_cw) angle = 2.0 * pi - angle;\n\n *x = m_x + cos(angle) * m_rx;\n\n *y = m_y + sin(angle) * m_ry;\n\n m_step++;\n\n return ((m_step == 1) ? path_cmd_move_to : path_cmd_line_to);\n\n }\n\n\n\n}\n\n\n\n\n\n\n\n#endif\n\n\n\n\n", "file_path": "src/agg/include/agg_ellipse.h", "rank": 68, "score": 54455.838597505885 }, { "content": "\n\n // Copying\n\n pod_bvector(const pod_bvector<T, S>& v);\n\n const pod_bvector<T, S>& operator = (const pod_bvector<T, S>& v);\n\n\n\n void remove_all() { m_size = 0; }\n\n void clear() { m_size = 0; }\n\n void free_all() { free_tail(0); }\n\n void free_tail(unsigned size);\n\n void add(const T& val);\n\n void push_back(const T& val) { add(val); }\n\n void modify_last(const T& val);\n\n void remove_last();\n\n\n\n int allocate_continuous_block(unsigned num_elements);\n\n\n\n void add_array(const T* ptr, unsigned num_elem)\n\n {\n\n while(num_elem--)\n\n {\n", "file_path": "src/agg/include/agg_array.h", "rank": 69, "score": 54455.838597505885 }, { "content": " const T& operator [] (unsigned i) const\n\n {\n\n return m_blocks[i >> block_shift][i & block_mask];\n\n }\n\n\n\n T& operator [] (unsigned i)\n\n {\n\n return m_blocks[i >> block_shift][i & block_mask];\n\n }\n\n\n\n const T& at(unsigned i) const\n\n { \n\n return m_blocks[i >> block_shift][i & block_mask];\n\n }\n\n\n\n T& at(unsigned i) \n\n { \n\n return m_blocks[i >> block_shift][i & block_mask];\n\n }\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 70, "score": 54455.838597505885 }, { "content": "\n\n //--------------------------------------------------------------------\n\n void add_cells(int x, unsigned len, const cover_type* covers)\n\n {\n\n memcpy(m_cover_ptr, covers, len * sizeof(cover_type));\n\n if(x == m_last_x+1 && m_cur_span->len > 0)\n\n {\n\n m_cur_span->len += (int16)len;\n\n }\n\n else\n\n {\n\n m_cur_span++;\n\n m_cur_span->covers = m_cover_ptr;\n\n m_cur_span->x = (int16)x;\n\n m_cur_span->len = (int16)len;\n\n }\n\n m_cover_ptr += len;\n\n m_last_x = x + len - 1;\n\n }\n\n\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 71, "score": 54455.838597505885 }, { "content": " T* m_array;\n\n unsigned m_size;\n\n };\n\n\n\n\n\n //---------------------------------------------------------pod_auto_array\n\n template<class T, unsigned Size> class pod_auto_array\n\n {\n\n public:\n\n typedef T value_type;\n\n typedef pod_auto_array<T, Size> self_type;\n\n\n\n pod_auto_array() {}\n\n explicit pod_auto_array(const T* c)\n\n {\n\n memcpy(m_array, c, sizeof(T) * Size);\n\n }\n\n\n\n const self_type& operator = (const T* c)\n\n {\n", "file_path": "src/agg/include/agg_array.h", "rank": 72, "score": 54455.838597505885 }, { "content": " top[1] = j;\n\n base = i;\n\n }\n\n else\n\n {\n\n top[0] = i;\n\n top[1] = limit;\n\n limit = j;\n\n }\n\n top += 2;\n\n }\n\n else\n\n {\n\n // the sub-array is small, perform insertion sort\n\n j = base;\n\n i = j + 1;\n\n\n\n for(; i < limit; j = i, i++)\n\n {\n\n for(; less(*(e1 = &(arr[j + 1])), *(e2 = &(arr[j]))); j--)\n", "file_path": "src/agg/include/agg_array.h", "rank": 73, "score": 54455.838597505885 }, { "content": " double x4, double y4)\n\n {\n\n cp[0] = x1; cp[1] = y1; cp[2] = x2; cp[3] = y2;\n\n cp[4] = x3; cp[5] = y3; cp[6] = x4; cp[7] = y4;\n\n }\n\n void init(double x1, double y1,\n\n double x2, double y2,\n\n double x3, double y3,\n\n double x4, double y4)\n\n {\n\n cp[0] = x1; cp[1] = y1; cp[2] = x2; cp[3] = y2;\n\n cp[4] = x3; cp[5] = y3; cp[6] = x4; cp[7] = y4;\n\n }\n\n double operator [] (unsigned i) const { return cp[i]; }\n\n double& operator [] (unsigned i) { return cp[i]; }\n\n };\n\n\n\n\n\n\n", "file_path": "src/agg/include/agg_curves.h", "rank": 74, "score": 54455.838597505885 }, { "content": " m_covers(),\n\n m_cover_ptr(0),\n\n m_spans(),\n\n m_cur_span(0)\n\n {\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void reset(int min_x, int max_x)\n\n {\n\n unsigned max_len = max_x - min_x + 3;\n\n if(max_len > m_spans.size())\n\n {\n\n m_spans.resize(max_len);\n\n m_covers.resize(max_len);\n\n }\n\n m_last_x = 0x7FFFFFF0;\n\n m_cover_ptr = &m_covers[0];\n\n m_cur_span = &m_spans[0];\n\n m_cur_span->len = 0;\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 75, "score": 54455.838597505885 }, { "content": " {\n\n if(arr.size() < 2) return;\n\n\n\n typename Array::value_type* e1;\n\n typename Array::value_type* e2;\n\n\n\n int stack[80];\n\n int* top = stack; \n\n int limit = arr.size();\n\n int base = 0;\n\n\n\n for(;;)\n\n {\n\n int len = limit - base;\n\n\n\n int i;\n\n int j;\n\n int pivot;\n\n\n\n if(len > quick_sort_threshold)\n", "file_path": "src/agg/include/agg_array.h", "rank": 76, "score": 54455.838597505885 }, { "content": " private:\n\n void normalize(double a1, double a2, bool ccw);\n\n\n\n double m_x;\n\n double m_y;\n\n double m_rx;\n\n double m_ry;\n\n double m_angle;\n\n double m_start;\n\n double m_end;\n\n double m_scale;\n\n double m_da;\n\n bool m_ccw;\n\n bool m_initialized;\n\n unsigned m_path_cmd;\n\n };\n\n\n\n\n\n}\n\n\n\n\n\n#endif\n", "file_path": "src/agg/include/agg_arc.h", "rank": 77, "score": 54455.838597505885 }, { "content": " }\n\n m_num_blocks = 0;\n\n m_max_blocks = 0;\n\n m_blocks = 0;\n\n m_buf_ptr = 0;\n\n m_rest = 0;\n\n }\n\n\n\n ~block_allocator()\n\n {\n\n remove_all();\n\n }\n\n\n\n block_allocator(unsigned block_size, unsigned block_ptr_inc=256-8) :\n\n m_block_size(block_size),\n\n m_block_ptr_inc(block_ptr_inc),\n\n m_num_blocks(0),\n\n m_max_blocks(0),\n\n m_blocks(0),\n\n m_buf_ptr(0),\n", "file_path": "src/agg/include/agg_array.h", "rank": 78, "score": 54455.838597505885 }, { "content": " add(*ptr++);\n\n }\n\n }\n\n\n\n template<class DataAccessor> void add_data(DataAccessor& data)\n\n {\n\n while(data.size())\n\n {\n\n add(*data);\n\n ++data;\n\n }\n\n }\n\n\n\n void cut_at(unsigned size)\n\n {\n\n if(size < m_size) m_size = size;\n\n }\n\n\n\n unsigned size() const { return m_size; }\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 79, "score": 54455.838597505885 }, { "content": "\n\n unsigned size() const { return m_size; }\n\n const T& operator [] (unsigned i) const { return m_array[i]; }\n\n T& operator [] (unsigned i) { return m_array[i]; }\n\n const T& at(unsigned i) const { return m_array[i]; }\n\n T& at(unsigned i) { return m_array[i]; }\n\n T value_at(unsigned i) const { return m_array[i]; }\n\n\n\n const T* data() const { return m_array; }\n\n T* data() { return m_array; }\n\n private:\n\n T* m_array;\n\n unsigned m_size;\n\n };\n\n\n\n\n\n\n\n //--------------------------------------------------------------pod_vector\n\n // A simple class template to store Plain Old Data, a vector\n\n // of a fixed size. The data is continous in memory\n", "file_path": "src/agg/include/agg_array.h", "rank": 80, "score": 54455.838597505885 }, { "content": " for(unsigned j = 0; j < sizeof(T); ++j)\n\n {\n\n *ptr++ = *data;\n\n ++data;\n\n }\n\n ++m_size;\n\n }\n\n }\n\n\n\n template<class ByteAccessor>\n\n void deserialize(unsigned start, const T& empty_val, ByteAccessor data)\n\n {\n\n while(m_size < start)\n\n {\n\n add(empty_val);\n\n }\n\n\n\n unsigned elem_size = data.size() / sizeof(T);\n\n for(unsigned i = 0; i < elem_size; ++i)\n\n {\n", "file_path": "src/agg/include/agg_array.h", "rank": 81, "score": 54455.838597505885 }, { "content": " {\n\n // we use base + len/2 as the pivot\n\n pivot = base + len / 2;\n\n swap_elements(arr[base], arr[pivot]);\n\n\n\n i = base + 1;\n\n j = limit - 1;\n\n\n\n // now ensure that *i <= *base <= *j \n\n e1 = &(arr[j]); \n\n e2 = &(arr[i]);\n\n if(less(*e1, *e2)) swap_elements(*e1, *e2);\n\n\n\n e1 = &(arr[base]); \n\n e2 = &(arr[i]);\n\n if(less(*e1, *e2)) swap_elements(*e1, *e2);\n\n\n\n e1 = &(arr[j]); \n\n e2 = &(arr[base]);\n\n if(less(*e1, *e2)) swap_elements(*e1, *e2);\n", "file_path": "src/agg/include/agg_array.h", "rank": 82, "score": 54455.838597505885 }, { "content": " T& last()\n\n {\n\n return (*this)[m_size - 1];\n\n }\n\n\n\n unsigned byte_size() const;\n\n void serialize(int8u* ptr) const;\n\n void deserialize(const int8u* data, unsigned byte_size);\n\n void deserialize(unsigned start, const T& empty_val, \n\n const int8u* data, unsigned byte_size);\n\n\n\n template<class ByteAccessor> \n\n void deserialize(ByteAccessor data)\n\n {\n\n remove_all();\n\n unsigned elem_size = data.size() / sizeof(T);\n\n\n\n for(unsigned i = 0; i < elem_size; ++i)\n\n {\n\n int8u* ptr = (int8u*)data_ptr();\n", "file_path": "src/agg/include/agg_array.h", "rank": 83, "score": 54455.838597505885 }, { "content": " if(x == m_last_x+1 && m_spans.size() && m_spans.last().len > 0)\n\n {\n\n m_spans.last().len += coord_type(len);\n\n }\n\n else\n\n {\n\n m_spans.add(span(coord_type(x), coord_type(len), m_cover_ptr));\n\n }\n\n m_cover_ptr += len;\n\n m_last_x = x + len - 1;\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void add_span(int x, unsigned len, unsigned cover)\n\n {\n\n if(x == m_last_x+1 && \n\n m_spans.size() &&\n\n m_spans.last().len < 0 && \n\n cover == *m_spans.last().covers)\n\n {\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 84, "score": 54455.838597505885 }, { "content": " for(i = 0; i < m_size; i++)\n\n {\n\n memcpy(ptr, &(*this)[i], sizeof(T));\n\n ptr += sizeof(T);\n\n }\n\n }\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n void pod_bvector<T, S>::deserialize(const int8u* data, unsigned byte_size)\n\n {\n\n remove_all();\n\n byte_size /= sizeof(T);\n\n for(unsigned i = 0; i < byte_size; ++i)\n\n {\n\n T* ptr = data_ptr();\n\n memcpy(ptr, data, sizeof(T));\n\n ++m_size;\n\n data += sizeof(T);\n\n }\n", "file_path": "src/agg/include/agg_array.h", "rank": 85, "score": 54455.838597505885 }, { "content": " m_cover_ptr = &m_covers[0];\n\n m_spans.remove_all();\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n int y() const { return m_y; }\n\n unsigned num_spans() const { return m_spans.size(); }\n\n const_iterator begin() const { return const_iterator(m_spans); }\n\n\n\n private:\n\n scanline32_p8(const self_type&);\n\n const self_type& operator = (const self_type&);\n\n\n\n unsigned m_max_len;\n\n int m_last_x;\n\n int m_y;\n\n pod_array<cover_type> m_covers;\n\n cover_type* m_cover_ptr;\n\n span_array_type m_spans;\n\n };\n\n\n\n\n\n}\n\n\n\n\n\n#endif\n\n\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 86, "score": 54455.838597505885 }, { "content": " if(m_blocks)\n\n {\n\n memcpy(new_blocks, \n\n m_blocks, \n\n m_num_blocks * sizeof(T*));\n\n\n\n pod_allocator<T*>::deallocate(m_blocks, m_max_blocks);\n\n }\n\n m_blocks = new_blocks;\n\n m_max_blocks += m_block_ptr_inc;\n\n }\n\n m_blocks[nb] = pod_allocator<T>::allocate(block_size);\n\n m_num_blocks++;\n\n }\n\n\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S>\n\n inline T* pod_bvector<T, S>::data_ptr()\n", "file_path": "src/agg/include/agg_array.h", "rank": 87, "score": 54455.838597505885 }, { "content": " m_spans.last().len -= coord_type(len);\n\n }\n\n else\n\n {\n\n *m_cover_ptr = cover_type(cover);\n\n m_spans.add(span(coord_type(x), -coord_type(len), m_cover_ptr++));\n\n }\n\n m_last_x = x + len - 1;\n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void finalize(int y) \n\n { \n\n m_y = y; \n\n }\n\n\n\n //--------------------------------------------------------------------\n\n void reset_spans()\n\n {\n\n m_last_x = 0x7FFFFFF0;\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 88, "score": 54455.838597505885 }, { "content": " //--------------------------------------------------------------------\n\n void add_span(int x, unsigned len, unsigned cover)\n\n {\n\n if(x == m_last_x+1 && \n\n m_cur_span->len < 0 && \n\n cover == *m_cur_span->covers)\n\n {\n\n m_cur_span->len -= (int16)len;\n\n }\n\n else\n\n {\n\n *m_cover_ptr = (cover_type)cover;\n\n m_cur_span++;\n\n m_cur_span->covers = m_cover_ptr++;\n\n m_cur_span->x = (int16)x;\n\n m_cur_span->len = (int16)(-int(len));\n\n }\n\n m_last_x = x + len - 1;\n\n }\n\n\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 89, "score": 54455.838597505885 }, { "content": " private:\n\n void allocate_block(unsigned nb);\n\n T* data_ptr();\n\n\n\n unsigned m_size;\n\n unsigned m_num_blocks;\n\n unsigned m_max_blocks;\n\n T** m_blocks;\n\n unsigned m_block_ptr_inc;\n\n };\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> pod_bvector<T, S>::~pod_bvector()\n\n {\n\n if(m_num_blocks)\n\n {\n\n T** blk = m_blocks + m_num_blocks - 1;\n\n while(m_num_blocks--)\n\n {\n", "file_path": "src/agg/include/agg_array.h", "rank": 90, "score": 54455.838597505885 }, { "content": " {\n\n swap_elements(*e1, *e2);\n\n if(j == base)\n\n {\n\n break;\n\n }\n\n }\n\n }\n\n if(top > stack)\n\n {\n\n top -= 2;\n\n base = top[0];\n\n limit = top[1];\n\n }\n\n else\n\n {\n\n break;\n\n }\n\n }\n\n }\n", "file_path": "src/agg/include/agg_array.h", "rank": 91, "score": 54455.838597505885 }, { "content": " typedef T value_type;\n\n typedef pod_auto_vector<T, Size> self_type;\n\n\n\n pod_auto_vector() : m_size(0) {}\n\n\n\n void remove_all() { m_size = 0; }\n\n void clear() { m_size = 0; }\n\n void add(const T& v) { m_array[m_size++] = v; }\n\n void push_back(const T& v) { m_array[m_size++] = v; }\n\n void inc_size(unsigned size) { m_size += size; }\n\n \n\n unsigned size() const { return m_size; }\n\n const T& operator [] (unsigned i) const { return m_array[i]; }\n\n T& operator [] (unsigned i) { return m_array[i]; }\n\n const T& at(unsigned i) const { return m_array[i]; }\n\n T& at(unsigned i) { return m_array[i]; }\n\n T value_at(unsigned i) const { return m_array[i]; }\n\n\n\n private:\n\n T m_array[Size];\n", "file_path": "src/agg/include/agg_array.h", "rank": 92, "score": 54455.838597505885 }, { "content": " static void bsearch(int n, const double *x, double x0, int *i);\n\n double extrapolation_left(double x) const;\n\n double extrapolation_right(double x) const;\n\n double interpolation(double x, int i) const;\n\n\n\n int m_max;\n\n int m_num;\n\n double* m_x;\n\n double* m_y;\n\n pod_array<double> m_am;\n\n mutable int m_last_idx;\n\n };\n\n\n\n\n\n}\n\n\n\n#endif\n", "file_path": "src/agg/include/agg_bspline.h", "rank": 93, "score": 54455.838597505885 }, { "content": " void allocate(unsigned size, unsigned extra_tail=0);\n\n\n\n // Resize keeping the content.\n\n void resize(unsigned new_size);\n\n\n\n void zero()\n\n {\n\n memset(m_array, 0, sizeof(T) * m_size);\n\n }\n\n\n\n void add(const T& v) { m_array[m_size++] = v; }\n\n void push_back(const T& v) { m_array[m_size++] = v; }\n\n void insert_at(unsigned pos, const T& val);\n\n void inc_size(unsigned size) { m_size += size; }\n\n unsigned size() const { return m_size; }\n\n unsigned byte_size() const { return m_size * sizeof(T); }\n\n void serialize(int8u* ptr) const;\n\n void deserialize(const int8u* data, unsigned byte_size);\n\n const T& operator [] (unsigned i) const { return m_array[i]; }\n\n T& operator [] (unsigned i) { return m_array[i]; }\n", "file_path": "src/agg/include/agg_array.h", "rank": 94, "score": 54455.838597505885 }, { "content": " private:\n\n scanline_p8(const self_type&);\n\n const self_type& operator = (const self_type&);\n\n\n\n int m_last_x;\n\n int m_y;\n\n pod_array<cover_type> m_covers;\n\n cover_type* m_cover_ptr;\n\n pod_array<span> m_spans;\n\n span* m_cur_span;\n\n };\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "src/agg/include/agg_scanline_p.h", "rank": 95, "score": 54455.838597505885 }, { "content": " m_rest -= size;\n\n m_buf_ptr += size;\n\n return ptr;\n\n }\n\n allocate_block(size);\n\n return allocate(size - align, alignment);\n\n }\n\n m_rest -= size;\n\n m_buf_ptr += size;\n\n return ptr;\n\n }\n\n allocate_block(size + alignment - 1);\n\n return allocate(size, alignment);\n\n }\n\n\n\n\n\n private:\n\n void allocate_block(unsigned size)\n\n {\n\n if(size < m_block_size) size = m_block_size;\n", "file_path": "src/agg/include/agg_array.h", "rank": 96, "score": 54455.838597505885 }, { "content": " // There reallocs occure only when the pool of pointers to blocks needs \n\n // to be extended (it happens very rarely). You can control the value \n\n // of increment to reallocate the pointer buffer. See the second constructor.\n\n // By default, the incremeent value equals (1 << S), i.e., the block size.\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S=6> class pod_bvector\n\n {\n\n public:\n\n enum block_scale_e\n\n { \n\n block_shift = S,\n\n block_size = 1 << block_shift,\n\n block_mask = block_size - 1\n\n };\n\n\n\n typedef T value_type;\n\n\n\n ~pod_bvector();\n\n pod_bvector();\n\n pod_bvector(unsigned block_ptr_inc);\n", "file_path": "src/agg/include/agg_array.h", "rank": 97, "score": 54455.838597505885 }, { "content": " {\n\n pod_allocator<T*>::deallocate(m_blocks, m_max_blocks);\n\n m_blocks = 0;\n\n m_max_blocks = 0;\n\n }\n\n m_size = size;\n\n }\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> pod_bvector<T, S>::pod_bvector() :\n\n m_size(0),\n\n m_num_blocks(0),\n\n m_max_blocks(0),\n\n m_blocks(0),\n\n m_block_ptr_inc(block_size)\n\n {\n\n }\n\n\n", "file_path": "src/agg/include/agg_array.h", "rank": 98, "score": 54455.838597505885 }, { "content": " m_size += num_elements;\n\n return index;\n\n }\n\n return -1; // Impossible to allocate\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n unsigned pod_bvector<T, S>::byte_size() const\n\n {\n\n return m_size * sizeof(T);\n\n }\n\n\n\n\n\n //------------------------------------------------------------------------\n\n template<class T, unsigned S> \n\n void pod_bvector<T, S>::serialize(int8u* ptr) const\n\n {\n\n unsigned i;\n", "file_path": "src/agg/include/agg_array.h", "rank": 99, "score": 54455.838597505885 } ]
C++
kernel/arch/amd64/mp/mp.cpp
griwes/reaveros
01cc1be330e920d45445db32e44eb4b91491f36c
#include "mp.h" #include "../../../memory/vm.h" #include "../../../scheduler/thread.h" #include "../../../time/time.h" #include "../cpu/cpu.h" #include "../cpu/lapic.h" #include "../memory/vm.h" #include <cstddef> #include <cstdint> extern "C" std::uint8_t trampoline_start[]; extern "C" std::uint8_t trampoline_end[]; extern "C" std::uint8_t trampoline_asid_slot[]; extern "C" std::uint8_t trampoline_stack_slot[]; extern "C" std::uint8_t trampoline_flag_slot[]; namespace kernel::amd64::mp { void boot() { log::println("[CPU] Booting APs..."); auto trampoline_size = trampoline_end - trampoline_start; trampoline_size += 4095; trampoline_size &= ~4095ull; auto asid_slot_offset = trampoline_asid_slot - trampoline_start; auto stack_slot_offset = trampoline_stack_slot - trampoline_start; auto flag_slot_offset = trampoline_flag_slot - trampoline_start; auto & core_count = cpu::detail_for_mp::get_core_count_ref(); auto cores = cpu::detail_for_mp::get_core_array(); for (std::size_t i = 0; i < core_count; ++i) { auto apic_id = cores[i].apic_id(); if (apic_id == cpu::get_current_core()->apic_id()) { continue; } log::println(" > Sending INIT IPI to core #{} (APIC ID: {})...", i, apic_id); lapic::ipi(apic_id, lapic::ipi_type::init, 0); } volatile bool timer_triggered = false; auto handler = +[](volatile bool * flag) { *flag = true; }; using namespace std::literals; time::get_high_precision_timer().one_shot(10ms, handler, &timer_triggered); asm volatile("sti"); while (!timer_triggered) { asm volatile("hlt"); } timer_triggered = false; auto base_raw = pmm::get_sub_1M_bottom(); base_raw = base_raw ? base_raw : 0x1000; auto top = pmm::get_sub_1M_top(); auto base = phys_ptr_t<std::uint8_t>(phys_addr_t(base_raw)); log::println(" > Using memory range from {:#010x} to {:#010x}.", base_raw, top); vm::map_physical(virt_addr_t(base_raw), virt_addr_t(top), phys_addr_t(base_raw)); auto boot_at_once = (top - base_raw) / trampoline_size; for (std::size_t booted = 0; booted < core_count; booted += boot_at_once) { for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { if (cores[i].apic_id() == cpu::get_current_core()->apic_id()) { continue; } std::memcpy((base + trampoline_size * (i - booted)).value(), trampoline_start, trampoline_size); *phys_ptr_t<std::uint64_t>(base + trampoline_size * (i - booted) + asid_slot_offset) = vm::get_asid().value(); cores[i]._boot_flag = const_cast<volatile std::uint8_t *>( (base + trampoline_size * (i - booted) + flag_slot_offset).value()); auto stack = kernel::vm::allocate_address_range(32 * 4096); for (int j = 1; j < 32; ++j) { vm::map_physical(stack + j * 4096, stack + (j + 1) * 4096, pmm::pop(0)); } *phys_ptr_t<std::uint64_t>(base + trampoline_size * (i - booted) + stack_slot_offset) = (stack + 32 * 1024).value(); } for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { auto apic_id = cores[i].apic_id(); if (apic_id == cpu::get_current_core()->apic_id()) { continue; } log::println(" > Sending Startup IPI to core #{} (APIC ID: {})...", i, apic_id); lapic::ipi(apic_id, lapic::ipi_type::sipi, (0x1000 + trampoline_size * (i - booted)) >> 12); } time::get_high_precision_timer().one_shot(500us, handler, &timer_triggered); while (!timer_triggered) { asm volatile("hlt"); } timer_triggered = false; for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { auto apic_id = cores[i].apic_id(); if (apic_id == cpu::get_current_core()->apic_id()) { continue; } if (!*(cores[i]._boot_flag)) { log::println(" > Sending secondary Startup IPI to core #{} (APIC ID: {})...", i, apic_id); lapic::ipi(apic_id, lapic::ipi_type::sipi, (0x1000 + trampoline_size * (i - booted)) >> 12); } } time::get_high_precision_timer().one_shot(500us, handler, &timer_triggered); while (!timer_triggered) { asm volatile("hlt"); } timer_triggered = false; for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { if (cores[i].apic_id() == cpu::get_current_core()->apic_id()) { continue; } if (*(cores[i]._boot_flag)) { log::println(" > CPU #{} (APIC ID: {}) started up...", i, cores[i].apic_id()); while (*cores[i]._boot_flag != 2) { asm volatile("pause"); } log::println(" > CPU #{} (APIC ID: {}) booted successfully.", i, cores[i].apic_id()); cores[i]._id = i; } else { log::println(" > CPU#{} failed to boot!", cores[i].apic_id()); for (std::size_t j = i; j < core_count - 1; ++j) { log::println( " > Moving CPU #{} (APIC ID: {}) into place of CPU #{} (APIC ID: {}).", j + 1, cores[j + 1].apic_id(), j, cores[j].apic_id()); cores[j] = cores[j + 1]; } --i; --core_count; --booted; } } } for (std::size_t i = 0; i < core_count; ++i) { if (cores[i].apic_id() == cpu::get_current_core()->apic_id()) { cores[i]._id = i; break; } } vm::unmap(virt_addr_t(base_raw), virt_addr_t(top), false); } }
#include "mp.h" #include "../../../memory/vm.h" #include "../../../scheduler/thread.h" #include "../../../time/time.h" #include "../cpu/cpu.h" #include "../cpu/lapic.h" #include "../memory/vm.h" #include <cstddef> #include <cstdint> extern "C" std::uint8_t trampoline_start[]; extern "C" std::uint8_t trampoline_end[]; extern "C" std::uint8_t trampoline_asid_slot[]; extern "C" std::uint8_t trampoline_stack_slot[]; extern "C" std::uint8_t trampoline_flag_slot[]; namespace kernel::amd64::mp { void boot() { log::println("[CPU] Booting APs..."); auto trampoline_size = trampoline_end - trampoline_start; trampoline_size += 4095; trampoline_size &= ~4095ull; auto asid_slot_offset = trampoline_asid_slot - trampoline_start; auto stack_slot_offset = trampoline_stack_slot - trampoline_start; auto flag_slot_offset = trampoline_flag_slot - trampoline_start; auto & core_count = cpu::detail_for_mp::get_core_count_ref(); auto cores = cpu::detail_for_mp::get_core_array(); for (std::size_t i = 0; i < core_count; ++i) { auto apic_id = cores[i].apic_id(); if (apic_id == cpu::get_current_core()->apic_id()) { continue; } log::println(" > Sending INIT IPI to core #{} (APIC ID: {})...", i, apic_id); lapic::ipi(apic_id, lapic::
ase_raw) / trampoline_size; for (std::size_t booted = 0; booted < core_count; booted += boot_at_once) { for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { if (cores[i].apic_id() == cpu::get_current_core()->apic_id()) { continue; } std::memcpy((base + trampoline_size * (i - booted)).value(), trampoline_start, trampoline_size); *phys_ptr_t<std::uint64_t>(base + trampoline_size * (i - booted) + asid_slot_offset) = vm::get_asid().value(); cores[i]._boot_flag = const_cast<volatile std::uint8_t *>( (base + trampoline_size * (i - booted) + flag_slot_offset).value()); auto stack = kernel::vm::allocate_address_range(32 * 4096); for (int j = 1; j < 32; ++j) { vm::map_physical(stack + j * 4096, stack + (j + 1) * 4096, pmm::pop(0)); } *phys_ptr_t<std::uint64_t>(base + trampoline_size * (i - booted) + stack_slot_offset) = (stack + 32 * 1024).value(); } for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { auto apic_id = cores[i].apic_id(); if (apic_id == cpu::get_current_core()->apic_id()) { continue; } log::println(" > Sending Startup IPI to core #{} (APIC ID: {})...", i, apic_id); lapic::ipi(apic_id, lapic::ipi_type::sipi, (0x1000 + trampoline_size * (i - booted)) >> 12); } time::get_high_precision_timer().one_shot(500us, handler, &timer_triggered); while (!timer_triggered) { asm volatile("hlt"); } timer_triggered = false; for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { auto apic_id = cores[i].apic_id(); if (apic_id == cpu::get_current_core()->apic_id()) { continue; } if (!*(cores[i]._boot_flag)) { log::println(" > Sending secondary Startup IPI to core #{} (APIC ID: {})...", i, apic_id); lapic::ipi(apic_id, lapic::ipi_type::sipi, (0x1000 + trampoline_size * (i - booted)) >> 12); } } time::get_high_precision_timer().one_shot(500us, handler, &timer_triggered); while (!timer_triggered) { asm volatile("hlt"); } timer_triggered = false; for (std::size_t i = booted; i < booted + boot_at_once && i < core_count; ++i) { if (cores[i].apic_id() == cpu::get_current_core()->apic_id()) { continue; } if (*(cores[i]._boot_flag)) { log::println(" > CPU #{} (APIC ID: {}) started up...", i, cores[i].apic_id()); while (*cores[i]._boot_flag != 2) { asm volatile("pause"); } log::println(" > CPU #{} (APIC ID: {}) booted successfully.", i, cores[i].apic_id()); cores[i]._id = i; } else { log::println(" > CPU#{} failed to boot!", cores[i].apic_id()); for (std::size_t j = i; j < core_count - 1; ++j) { log::println( " > Moving CPU #{} (APIC ID: {}) into place of CPU #{} (APIC ID: {}).", j + 1, cores[j + 1].apic_id(), j, cores[j].apic_id()); cores[j] = cores[j + 1]; } --i; --core_count; --booted; } } } for (std::size_t i = 0; i < core_count; ++i) { if (cores[i].apic_id() == cpu::get_current_core()->apic_id()) { cores[i]._id = i; break; } } vm::unmap(virt_addr_t(base_raw), virt_addr_t(top), false); } }
ipi_type::init, 0); } volatile bool timer_triggered = false; auto handler = +[](volatile bool * flag) { *flag = true; }; using namespace std::literals; time::get_high_precision_timer().one_shot(10ms, handler, &timer_triggered); asm volatile("sti"); while (!timer_triggered) { asm volatile("hlt"); } timer_triggered = false; auto base_raw = pmm::get_sub_1M_bottom(); base_raw = base_raw ? base_raw : 0x1000; auto top = pmm::get_sub_1M_top(); auto base = phys_ptr_t<std::uint8_t>(phys_addr_t(base_raw)); log::println(" > Using memory range from {:#010x} to {:#010x}.", base_raw, top); vm::map_physical(virt_addr_t(base_raw), virt_addr_t(top), phys_addr_t(base_raw)); auto boot_at_once = (top - b
random
[ { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#pragma once\n\n\n\n#include \"boot-memmap.h\"\n\n#include \"boot-video.h\"\n\n\n\nnamespace boot_protocol\n\n{\n", "file_path": "libraries/boot-protocol/include/boot-arguments.h", "rank": 0, "score": 85377.34469361232 }, { "content": "struct kernel_arguments\n\n{\n\n std::size_t memory_map_size;\n\n memory_map_entry * memory_map_entries;\n\n\n\n bool has_video_mode;\n", "file_path": "libraries/boot-protocol/include/boot-arguments.h", "rank": 1, "score": 81460.01217787663 }, { "content": "namespace boot_protocol\n\n{\n\n#ifdef __amd64__\n\ninline constexpr auto kernel_base = 0xffffffff80000000;\n\ninline constexpr auto physmem_base = 0xffff800000000000;\n\n#else\n\n#error unknown architecture\n\n#endif\n", "file_path": "libraries/boot-protocol/include/boot-constants.h", "rank": 2, "score": 81245.02890307008 }, { "content": "namespace boot_protocol\n\n{\n\nenum class memory_type : std::uint32_t\n\n{\n\n unusable,\n\n free,\n\n loader,\n\n preserve,\n\n acpi_reclaimable,\n\n persistent,\n\n\n\n kernel, // must be present exactly once\n\n initrd, // must be present exactly once\n\n paging, // may be present an arbitrary number of times\n\n memory_map, // must be present exactly once\n\n backbuffer, // must be present exactly once if video mode information is passed to the kernel\n\n log_buffer, // must be present exactly once and be exactly 2MiB in size\n\n working_stack\n\n};\n\n\n\nstruct memory_map_entry\n\n{\n\n std::uintptr_t physical_start;\n\n std::size_t length;\n\n memory_type type;\n\n std::uint32_t attributes;\n\n};\n\n\n\ninline memory_map_entry * find_entry(\n\n std::size_t memmap_size,\n\n memory_map_entry * memmap,\n\n boot_protocol::memory_type type)\n\n{\n\n for (auto i = 0ull; i < memmap_size; ++i)\n\n {\n\n if (memmap[i].type == type)\n\n {\n\n return memmap + i;\n\n }\n\n }\n\n\n\n return nullptr;\n\n}\n", "file_path": "libraries/boot-protocol/include/boot-memmap.h", "rank": 3, "score": 81245.02890307008 }, { "content": "namespace boot_protocol\n\n{\n\nenum class pixel_format\n\n{\n\n rgb,\n\n bgr,\n\n mask\n\n};\n\n\n\nstruct pixel_format_masks\n\n{\n\n std::uint32_t red;\n\n std::uint32_t green;\n\n std::uint32_t blue;\n\n};\n\n\n\nstruct video_mode\n\n{\n\n void * framebuffer_base;\n\n std::size_t framebuffer_size;\n\n std::uint32_t x;\n\n std::uint32_t y;\n\n std::uint32_t ppl;\n\n pixel_format format;\n\n pixel_format_masks masks;\n\n};\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 4, "score": 81245.02890307008 }, { "content": " std::uint32_t x;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 5, "score": 79644.34005702061 }, { "content": " std::uint32_t y;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 6, "score": 79644.34005702061 }, { "content": "namespace kernel::arch::ipi\n\n{\n\nenum class broadcast_target\n\n{\n\n self = 1,\n\n all,\n\n others\n\n};\n\n}\n\n\n\n#ifdef __amd64__\n\n\n\n#include \"amd64/cpu/cpu.h\"\n\n#include \"amd64/cpu/lapic.h\"\n\n\n\nnamespace kernel::arch::ipi\n\n{\n\ninline auto to_arch_target(broadcast_target target)\n\n{\n\n switch (target)\n\n {\n\n case broadcast_target::self:\n\n return amd64::lapic::broadcast_target::self;\n\n case broadcast_target::all:\n\n return amd64::lapic::broadcast_target::all;\n\n case broadcast_target::others:\n\n return amd64::lapic::broadcast_target::others;\n\n default:\n\n PANIC(\"Unknown broadcast target!\");\n\n }\n\n}\n\n\n\ninline void ipi(std::size_t target_cpu_id, std::uint8_t irq)\n\n{\n\n amd64::lapic::ipi(\n\n amd64::cpu::get_core_by_id(target_cpu_id)->apic_id(), amd64::lapic::ipi_type::generic, irq);\n\n}\n\n\n\ninline void ipi_nmi(std::size_t target_cpu_id);\n\n\n\ninline void broadcast(broadcast_target target, std::uint8_t irq)\n\n{\n\n amd64::lapic::broadcast(to_arch_target(target), amd64::lapic::ipi_type::generic, irq);\n\n}\n\n\n\ninline void broadcast_nmi(broadcast_target target);\n\n}\n\n#else\n\n\n\n#error \"unknown architecture\"\n\n\n", "file_path": "kernel/arch/ipi.h", "rank": 7, "score": 78979.89502496437 }, { "content": " std::uint32_t blue;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 8, "score": 77911.55173554759 }, { "content": " std::uint32_t red;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 9, "score": 77911.55173554759 }, { "content": " class video_mode * video_mode;\n\n\n\n std::size_t acpi_revision;\n\n std::uintptr_t acpi_root;\n\n};\n\n}\n", "file_path": "libraries/boot-protocol/include/boot-arguments.h", "rank": 10, "score": 77911.55173554759 }, { "content": " std::uint32_t attributes;\n", "file_path": "libraries/boot-protocol/include/boot-memmap.h", "rank": 11, "score": 77911.55173554759 }, { "content": " memory_type type;\n", "file_path": "libraries/boot-protocol/include/boot-memmap.h", "rank": 12, "score": 77911.55173554759 }, { "content": " std::uint32_t ppl;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 13, "score": 77911.55173554759 }, { "content": " std::uint32_t green;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 14, "score": 77911.55173554759 }, { "content": " pixel_format_masks masks;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 15, "score": 77911.55173554759 }, { "content": " std::size_t length;\n", "file_path": "libraries/boot-protocol/include/boot-memmap.h", "rank": 16, "score": 77911.55173554759 }, { "content": " pixel_format format;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 17, "score": 77911.55173554759 }, { "content": " std::uintptr_t physical_start;\n", "file_path": "libraries/boot-protocol/include/boot-memmap.h", "rank": 18, "score": 76255.87101705423 }, { "content": " void * framebuffer_base;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 19, "score": 76255.87101705423 }, { "content": " std::size_t framebuffer_size;\n", "file_path": "libraries/boot-protocol/include/boot-video.h", "rank": 20, "score": 76255.87101705423 }, { "content": "class core\n\n{\n\npublic:\n\n core()\n\n {\n\n _cls_ptr = &_cls;\n\n _cls.current_core = this;\n\n }\n\n\n\n void initialize_ids(std::uint32_t apic_id, std::uint32_t acpi_id)\n\n {\n\n _is_valid = true;\n\n _apic_id = apic_id;\n\n _acpi_id = acpi_id;\n\n }\n\n\n\n void set_nmi(std::uint32_t interrupt, std::uint16_t flags)\n\n {\n\n _nmi_valid = true;\n\n _nmi_vector = interrupt;\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 21, "score": 74163.25133097741 }, { "content": "class core;\n\n\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 22, "score": 74163.25133097741 }, { "content": " std::size_t core_count;\n", "file_path": "kernel/arch/common/acpi/acpi.h", "rank": 23, "score": 66189.64028469723 }, { "content": "struct core_local_storage\n\n{\n\n core_local_storage();\n\n ~core_local_storage();\n\n\n\n core * current_core = nullptr;\n\n util::intrusive_ptr<scheduler::thread> current_thread;\n\n};\n\n\n\ncore_local_storage * get_core_local_storage();\n\n\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 24, "score": 45852.96467386387 }, { "content": "namespace kernel::boot_screen\n\n{\n\nvoid initialize(\n\n boot_protocol::video_mode * mode,\n\n std::size_t memmap_size,\n\n boot_protocol::memory_map_entry * memmap);\n\n\n\nvoid clear();\n\nvoid scroll();\n\nvoid put_char(char c);\n", "file_path": "kernel/boot/screen.h", "rank": 25, "score": 45527.70717330632 }, { "content": "namespace kernel::boot_serial\n\n{\n\nvoid put_char(char c);\n", "file_path": "kernel/arch/amd64/boot/serial.h", "rank": 26, "score": 43926.01205041157 }, { "content": "#include <cstring>\n\n#include \"../util/log.h\"\n\n\n\nasm(\"bitmap_font:\\n\"\n\n \".incbin \\\"\" REAVEROS_KERNEL_SOURCE_ROOT \"/boot/IBM_VGA_8x16.bin\\\"\\n\");\n\n\n\nnamespace kernel::boot_screen\n\n{\n\nnamespace\n\n{\n\n bool valid = false;\n\n\n\n boot_protocol::video_mode mode;\n\n std::uint32_t * framebuffer_base = nullptr;\n\n std::uint32_t * backbuffer_base = nullptr;\n\n extern \"C\" char bitmap_font[];\n\n\n\n std::uint16_t x = 0, y = 0;\n\n std::uint16_t maxx = 0, maxy = 0;\n\n}\n", "file_path": "kernel/boot/screen.cpp", "rank": 27, "score": 40406.49334370495 }, { "content": "\n\nvoid initialize(\n\n boot_protocol::video_mode * loader_mode,\n\n std::size_t memmap_size,\n\n boot_protocol::memory_map_entry * memmap)\n\n{\n\n valid = true;\n\n\n\n mode = *loader_mode;\n\n framebuffer_base = reinterpret_cast<std::uint32_t *>(\n\n reinterpret_cast<std::uint8_t *>(mode.framebuffer_base) + boot_protocol::physmem_base);\n\n\n\n auto backbuffer_entry =\n\n boot_protocol::find_entry(memmap_size, memmap, boot_protocol::memory_type::backbuffer);\n\n backbuffer_base = reinterpret_cast<std::uint32_t *>(\n\n reinterpret_cast<std::uint8_t *>(backbuffer_entry->physical_start) + boot_protocol::physmem_base);\n\n\n\n maxx = mode.x / 8;\n\n maxy = mode.y / 16;\n\n\n", "file_path": "kernel/boot/screen.cpp", "rank": 28, "score": 40397.70645330518 }, { "content": "\n\n else\n\n {\n\n auto char_data = &bitmap_font[c * 16];\n\n auto dest = framebuffer_base + y * mode.ppl * 16 + x * 8;\n\n auto backdest = backbuffer_base + y * mode.ppl * 16 + x * 8;\n\n\n\n std::uint32_t color = 0;\n\n\n\n switch (mode.format)\n\n {\n\n case boot_protocol::pixel_format::rgb:\n\n [[fallthrough]];\n\n case boot_protocol::pixel_format::bgr:\n\n color = 0x00ffffff;\n\n break;\n\n\n\n case boot_protocol::pixel_format::mask:;\n\n color = 0xffffffff & (mode.masks.red | mode.masks.green | mode.masks.blue);\n\n break;\n", "file_path": "kernel/boot/screen.cpp", "rank": 29, "score": 40396.308419352994 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#include \"screen.h\"\n\n\n\n#include <boot-constants.h>\n\n\n", "file_path": "kernel/boot/screen.cpp", "rank": 30, "score": 40394.673518445066 }, { "content": " }\n\n\n\n for (auto row = 0; row < 16; ++row)\n\n {\n\n auto row_data = char_data[row];\n\n\n\n for (auto column = 0; column < 8; ++column)\n\n {\n\n backdest[column] = (row_data >> (7 - column)) & 1 ? color : 0;\n\n dest[column] = backdest[column];\n\n }\n\n\n\n backdest += mode.ppl;\n\n dest += mode.ppl;\n\n }\n\n\n\n ++x;\n\n }\n\n\n\n if (x == maxx)\n", "file_path": "kernel/boot/screen.cpp", "rank": 31, "score": 40392.24845551828 }, { "content": " clear();\n\n}\n\n\n\nvoid put_char(char c)\n\n{\n\n if (!valid)\n\n {\n\n return;\n\n }\n\n\n\n if (c == '\\n')\n\n {\n\n ++y;\n\n x = 0;\n\n }\n\n\n\n else if (c == '\\t')\n\n {\n\n x += 8 - x % 8;\n\n }\n", "file_path": "kernel/boot/screen.cpp", "rank": 32, "score": 40391.77794113855 }, { "content": " {\n\n x = 0;\n\n ++y;\n\n }\n\n\n\n while (y >= maxy)\n\n {\n\n scroll();\n\n }\n\n}\n\n\n\nvoid clear()\n\n{\n\n if (!valid)\n\n {\n\n return;\n\n }\n\n\n\n std::memset(framebuffer_base, 0, mode.framebuffer_size);\n\n std::memset(backbuffer_base, 0, mode.framebuffer_size);\n", "file_path": "kernel/boot/screen.cpp", "rank": 33, "score": 40391.412004470214 }, { "content": " x = 0;\n\n y = 0;\n\n}\n\n\n\nvoid scroll()\n\n{\n\n if (!valid)\n\n {\n\n return;\n\n }\n\n\n\n std::memcpy(\n\n backbuffer_base,\n\n backbuffer_base + mode.ppl * 16,\n\n (maxy - 1) * mode.ppl * 16 * sizeof(*backbuffer_base));\n\n std::memset(backbuffer_base + (maxy - 1) * mode.ppl * 16, 0, mode.ppl * 16 * sizeof(*backbuffer_base));\n\n std::memcpy(framebuffer_base, backbuffer_base, mode.framebuffer_size);\n\n\n\n --y;\n\n}\n\n}\n", "file_path": "kernel/boot/screen.cpp", "rank": 34, "score": 40390.98376809908 }, { "content": "#include \"../../../scheduler/instance.h\"\n\n#include \"../timers/lapic.h\"\n\n\n\n#include <cstdint>\n\n\n\nnamespace kernel::amd64::mp\n\n{\n\nvoid boot();\n\n}\n\n\n\nnamespace kernel::amd64::cpu\n\n{\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 35, "score": 39426.463671312296 }, { "content": " _nmi_flags = flags;\n\n }\n\n\n\n auto id()\n\n {\n\n return _id;\n\n }\n\n\n\n auto apic_id()\n\n {\n\n return _apic_id;\n\n }\n\n\n\n auto acpi_id()\n\n {\n\n return _acpi_id;\n\n }\n\n\n\n lapic_timer::timer * get_timer()\n\n {\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 36, "score": 39420.052783389765 }, { "content": " void initialize_idt();\n\n void load_idt();\n\n\n\n friend void ::kernel::amd64::mp::boot();\n\n\n\nprivate:\n\n std::uint32_t _is_valid : 1 = false;\n\n std::uint32_t _nmi_valid : 1 = false;\n\n\n\n std::uint32_t _id = -1;\n\n std::uint32_t _apic_id = 0;\n\n std::uint32_t _acpi_id = 0;\n\n\n\n std::uint32_t _nmi_vector = 0;\n\n std::uint16_t _nmi_flags = 0;\n\n\n\n volatile std::uint8_t * _boot_flag = nullptr;\n\n\n\n gdt::entry _gdt[7];\n\n gdt::gdtr_t _gdtr;\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 37, "score": 39417.63043987561 }, { "content": " return &_preempt_timer;\n\n }\n\n\n\n scheduler::instance * get_scheduler()\n\n {\n\n return &_local_scheduler;\n\n }\n\n\n\n core_local_storage * get_core_local_storage()\n\n {\n\n return &_cls;\n\n }\n\n\n\n core_local_storage ** get_core_local_storage_ptr()\n\n {\n\n return &_cls_ptr;\n\n }\n\n\n\n void initialize_gdt();\n\n void load_gdt();\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 38, "score": 39410.88190740159 }, { "content": "\n\n lapic_timer::timer _preempt_timer;\n\n\n\n scheduler::instance _local_scheduler;\n\n\n\n core_local_storage _cls;\n\n core_local_storage * _cls_ptr;\n\n};\n\n}\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 39, "score": 39410.286289086725 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#pragma once\n\n\n\n#include \"gdt.h\"\n\n\n", "file_path": "kernel/arch/amd64/cpu/core.h", "rank": 40, "score": 39404.79810112802 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#pragma once\n\n\n\n#include \"../../../time/time.h\"\n\n\n\nnamespace kernel::amd64::lapic_timer\n\n{\n\nvoid initialize();\n\nvoid ap_initialize();\n\n\n", "file_path": "kernel/arch/amd64/timers/lapic.h", "rank": 41, "score": 39184.90606708597 }, { "content": "namespace kernel::amd64::cpu\n\n{\n\ncore_local_storage::core_local_storage() = default;\n\n\n\ncore_local_storage::~core_local_storage() = default;\n\n\n\ncore_local_storage * get_core_local_storage()\n\n{\n\n core_local_storage * ret;\n\n asm volatile(\"mov %%gs:0, %0\" : \"=r\"(ret));\n\n return ret;\n\n}\n\n\n\nvoid core::initialize_gdt()\n\n{\n\n gdt::initialize(_gdt, _gdtr);\n\n}\n\n\n\nvoid core::load_gdt()\n\n{\n\n gdt::load_gdt(_gdtr);\n\n}\n\n}\n", "file_path": "kernel/arch/amd64/cpu/core.cpp", "rank": 42, "score": 38216.909364854044 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#include \"core.h\"\n\n\n\n#include \"../../../scheduler/thread.h\"\n\n\n", "file_path": "kernel/arch/amd64/cpu/core.cpp", "rank": 43, "score": 38211.63437252227 }, { "content": "{\n\n return x2apic_enabled ? lapic_storage.x2apic.read(x2apic_t::registers_r::timer_current_count)\n\n : lapic_storage.xapic.read(xapic_t::registers_r::timer_current_count);\n\n}\n\n\n\nvoid ipi(std::uint32_t target_apic_id, ipi_type type, std::uint8_t data)\n\n{\n\n std::uint32_t cmd_low = 0;\n\n\n\n switch (type)\n\n {\n\n case ipi_type::init:\n\n cmd_low = 5 << 8;\n\n break;\n\n\n\n case ipi_type::sipi:\n\n cmd_low = (6 << 8) | data;\n\n break;\n\n\n\n case ipi_type::generic:\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 44, "score": 38000.723199531545 }, { "content": "#include \"../cpu/cpu.h\"\n\n#include \"../cpu/irqs.h\"\n\n#include \"../cpu/lapic.h\"\n\n\n\nnamespace kernel::amd64::lapic_timer\n\n{\n\nnamespace\n\n{\n\n lapic_timer::timer * bsp_timer;\n\n}\n\n\n\nvoid initialize()\n\n{\n\n bsp_timer = cpu::get_current_core()->get_timer();\n\n bsp_timer->bsp_initialize();\n\n\n\n irq::register_handler(\n\n irq::lapic_timer, +[](irq::context &) { time::timer::handle(cpu::get_current_core()->get_timer()); });\n\n}\n\n\n", "file_path": "kernel/arch/amd64/timers/lapic.cpp", "rank": 45, "score": 37999.861333815934 }, { "content": " if (ecx & (1ull << 21))\n\n {\n\n log::println(\" > Enabling x2APIC mode.\");\n\n new (&lapic_storage.x2apic) x2apic_t();\n\n x2apic_enabled = true;\n\n }\n\n\n\n else\n\n {\n\n log::println(\" > Enabling xAPIC mode.\");\n\n new (&lapic_storage.xapic) xapic_t(lapic_base);\n\n }\n\n}\n\n\n\nvoid ap_initialize()\n\n{\n\n x2apic_enabled ? lapic_storage.x2apic.ap_initialize() : lapic_storage.xapic.ap_initialize();\n\n}\n\n\n\nstd::uint32_t id()\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 46, "score": 37999.74678322583 }, { "content": "void ap_initialize()\n\n{\n\n cpu::get_current_core()->get_timer()->initialize(bsp_timer);\n\n}\n\n\n\nvoid timer::bsp_initialize()\n\n{\n\n log::println(\" > Initializing LAPIC timer...\");\n\n\n\n log::println(\" >> Estimating tick period...\");\n\n lapic::write_timer_divisor(1);\n\n lapic::write_timer_counter(-1);\n\n\n\n volatile bool interrupt_fired = false;\n\n\n\n using namespace std::literals;\n\n time::get_high_precision_timer().one_shot(\n\n 50ms, +[](volatile bool * fired) { *fired = true; }, &interrupt_fired);\n\n\n\n asm volatile(\"sti\");\n", "file_path": "kernel/arch/amd64/timers/lapic.cpp", "rank": 47, "score": 37996.67326556569 }, { "content": "{\n\n return x2apic_enabled ? lapic_storage.x2apic.read(x2apic_t::registers_r::local_apic_id)\n\n : (lapic_storage.xapic.read(xapic_t::registers_rw::local_apic_id) >> 24);\n\n}\n\n\n\nvoid eoi(std::uint8_t number)\n\n{\n\n if (number != irq::lapic_spurious)\n\n {\n\n x2apic_enabled ? lapic_storage.x2apic.write(x2apic_t::registers_w::eoi, 0)\n\n : lapic_storage.xapic.write(xapic_t::registers_w::eoi, 0);\n\n }\n\n}\n\n\n\nvoid write_timer_divisor(std::uint8_t val)\n\n{\n\n std::uint32_t bit_pattern;\n\n switch (val)\n\n {\n\n case 1:\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 48, "score": 37996.117151069455 }, { "content": " cmd_low = (1 << 14) | data;\n\n break;\n\n\n\n case ipi_type::nmi:\n\n PANIC(\"Unsupported IPI type selected.\");\n\n }\n\n\n\n if (x2apic_enabled)\n\n {\n\n lapic_storage.x2apic.write(\n\n x2apic_t::registers_rw::interrupt_command,\n\n (static_cast<std::uint64_t>(target_apic_id) << 32) | cmd_low);\n\n }\n\n else\n\n {\n\n lapic_storage.xapic.write(xapic_t::registers_rw::interrupt_command_high, target_apic_id << 24);\n\n lapic_storage.xapic.write(xapic_t::registers_rw::interrupt_command_low, cmd_low);\n\n }\n\n}\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 49, "score": 37996.11608259674 }, { "content": " write(registers_rw::lvt_timer, irq::lapic_timer);\n\n\n\n write(registers_rw::spurious_interrupt_vector, irq::lapic_spurious | 0x100);\n\n }\n\n\n\n x2apic_t()\n\n {\n\n ap_initialize();\n\n log::println(\n\n \" > Initialized x2APIC. BSP ID: {}, APIC version: {}, number of LVTs: {}.\",\n\n read(registers_r::local_apic_id),\n\n read(registers_r::local_apic_version) & 0xFF,\n\n ((read(registers_r::local_apic_version) >> 16) & 0xFF) + 1);\n\n }\n\n\n\n std::uint64_t read(registers_r reg) const\n\n {\n\n return cpu::rdmsr(static_cast<std::uint32_t>(reg));\n\n }\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 50, "score": 37995.353193519535 }, { "content": " write(registers_rw::lvt_timer, irq::lapic_timer);\n\n\n\n write(registers_rw::spurious_interrupt_vector, irq::lapic_spurious | 0x100);\n\n }\n\n\n\n xapic_t(kernel::phys_addr_t base) : _register{ base }\n\n {\n\n ap_initialize();\n\n log::println(\n\n \" > Initialized xAPIC. BSP ID: {}, APIC version: {}, number of LVTs: {}.\",\n\n read(registers_rw::local_apic_id),\n\n read(registers_r::local_apic_version) & 0xFF,\n\n ((read(registers_r::local_apic_version) >> 16) & 0xFF) + 1);\n\n }\n\n\n\n private:\n\n phys_addr_t _register;\n\n\n\n public:\n\n std::uint32_t read(registers_r reg) const\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 51, "score": 37995.24840011046 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#include \"lapic.h\"\n\n#include \"../../../util/log.h\"\n\n#include \"../../../util/pointer_types.h\"\n\n#include \"cpu.h\"\n\n#include \"irqs.h\"\n\n\n\n#include <cstdint>\n\n#include <new>\n\n\n\nnamespace kernel::amd64::lapic\n\n{\n\nnamespace\n\n{\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 52, "score": 37994.85133816723 }, { "content": " }\n\n\n\n ~lapic_storage_t()\n\n {\n\n }\n\n\n\n xapic_t xapic;\n\n x2apic_t x2apic;\n\n } lapic_storage;\n\n\n\n bool x2apic_enabled = false;\n\n}\n\n\n\n#define cpuid(id, a, b, c, d) asm volatile(\"cpuid\" : \"=a\"(a), \"=b\"(b), \"=c\"(c), \"=d\"(d) : \"a\"(id))\n\n\n\nvoid initialize(phys_addr_t lapic_base)\n\n{\n\n std::uint32_t _, ecx;\n\n cpuid(1, _, _, ecx, _);\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 53, "score": 37992.21028322078 }, { "content": "void broadcast(broadcast_target target, ipi_type type, std::uint8_t data)\n\n{\n\n std::uint32_t cmd_low = 0;\n\n\n\n switch (type)\n\n {\n\n case ipi_type::generic:\n\n cmd_low = (static_cast<std::uint64_t>(target) << 18) | (1 << 14) | data;\n\n break;\n\n\n\n default:\n\n PANIC(\"Unsupported broadcast type selected.\");\n\n }\n\n\n\n if (x2apic_enabled)\n\n {\n\n lapic_storage.x2apic.write(x2apic_t::registers_rw::interrupt_command, cmd_low);\n\n }\n\n else\n\n {\n\n lapic_storage.xapic.write(xapic_t::registers_rw::interrupt_command_low, cmd_low);\n\n }\n\n}\n\n}\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 54, "score": 37990.51822626394 }, { "content": "\n\nvoid timer::initialize(timer * bsp)\n\n{\n\n _period = bsp->_period;\n\n}\n\n\n\nvoid timer::_update_now()\n\n{\n\n auto current = lapic::read_timer_counter();\n\n auto last = std::exchange(_last_written, current);\n\n\n\n _fine_now += static_cast<std::int64_t>(last - current) * _last_divisor * _period;\n\n _now = std::chrono::time_point<time::timer>{ std::chrono::duration_cast<std::chrono::nanoseconds>(\n\n _fine_now.time_since_epoch()) };\n\n}\n\n\n\nvoid timer::_one_shot_after(std::chrono::nanoseconds duration_ns)\n\n{\n\n std::uint8_t divisor = 1;\n\n while ((duration_ns / (divisor * _period)) > ~static_cast<std::uint32_t>(0) && divisor != 128)\n", "file_path": "kernel/arch/amd64/timers/lapic.cpp", "rank": 55, "score": 37989.87957694214 }, { "content": " std::uint64_t read(registers_rw reg) const\n\n {\n\n return cpu::rdmsr(static_cast<std::uint32_t>(reg));\n\n }\n\n\n\n void write(registers_rw reg, std::uint64_t value) const\n\n {\n\n cpu::wrmsr(static_cast<std::uint32_t>(reg), value);\n\n }\n\n\n\n void write(registers_w reg, std::uint64_t value) const\n\n {\n\n cpu::wrmsr(static_cast<std::uint32_t>(reg), value);\n\n }\n\n };\n\n\n\n union lapic_storage_t\n\n {\n\n lapic_storage_t()\n\n {\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 56, "score": 37987.644088973226 }, { "content": " {\n\n divisor *= 2;\n\n }\n\n\n\n auto count = duration_ns / (divisor * _period);\n\n if (count > ~0u)\n\n {\n\n count = ~0u;\n\n }\n\n\n\n lapic::write_timer_divisor(divisor);\n\n lapic::write_timer_counter(count);\n\n\n\n _last_written = count;\n\n _last_divisor = divisor;\n\n}\n\n}\n", "file_path": "kernel/arch/amd64/timers/lapic.cpp", "rank": 57, "score": 37987.63851976256 }, { "content": " case 128:\n\n bit_pattern = 0b1010;\n\n break;\n\n\n\n default:\n\n PANIC(\"Invalid LAPIC timer divisor requested: {}!\", val);\n\n }\n\n\n\n x2apic_enabled\n\n ? lapic_storage.x2apic.write(x2apic_t::registers_rw::timer_divide_configuration, bit_pattern)\n\n : lapic_storage.xapic.write(xapic_t::registers_rw::timer_divide_configuration, bit_pattern);\n\n}\n\n\n\nvoid write_timer_counter(std::uint32_t val)\n\n{\n\n x2apic_enabled ? lapic_storage.x2apic.write(x2apic_t::registers_rw::timer_initial_count, val)\n\n : lapic_storage.xapic.write(xapic_t::registers_rw::timer_initial_count, val);\n\n}\n\n\n\nstd::uint32_t read_timer_counter()\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 58, "score": 37987.0222209053 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#include \"lapic.h\"\n\n\n\n#include \"../../../time/time.h\"\n\n#include \"../../../util/log.h\"\n", "file_path": "kernel/arch/amd64/timers/lapic.cpp", "rank": 59, "score": 37986.979504795425 }, { "content": "\n\n while (!interrupt_fired)\n\n {\n\n asm volatile(\"hlt\");\n\n }\n\n\n\n asm volatile(\"cli\");\n\n\n\n std::uint32_t ticks = -1;\n\n ticks -= lapic::read_timer_counter();\n\n\n\n lapic::write_timer_counter(0);\n\n\n\n log::println(\" >> Tick rate estimate: {} per 50ms.\", ticks);\n\n\n\n _period = std::chrono::duration_cast<std::chrono::duration<std::int64_t, std::femto>>(50ms) / ticks;\n\n log::println(\" >> Tick period estimate: {}fs.\", _period.count());\n\n auto frequency = static_cast<std::uint64_t>(std::femto::den) / _period.count();\n\n log::println(\" >> Tick frequency estimate: {}Hz.\", frequency);\n\n}\n", "file_path": "kernel/arch/amd64/timers/lapic.cpp", "rank": 60, "score": 37986.183726418116 }, { "content": " {\n\n return *phys_ptr_t<std::uint32_t>{ _register + static_cast<std::uintptr_t>(reg) };\n\n }\n\n\n\n std::uint32_t read(registers_rw reg) const\n\n {\n\n return *phys_ptr_t<std::uint32_t>{ _register + static_cast<std::uintptr_t>(reg) };\n\n }\n\n\n\n void write(registers_rw reg, std::uint32_t value) const\n\n {\n\n *phys_ptr_t<std::uint32_t>{ _register + static_cast<std::uintptr_t>(reg) } = value;\n\n }\n\n\n\n void write(registers_w reg, std::uint32_t value) const\n\n {\n\n *phys_ptr_t<std::uint32_t>{ _register + static_cast<std::uintptr_t>(reg) } = value;\n\n }\n\n };\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 61, "score": 37983.366562000905 }, { "content": " trigger_mode_223_192 = 0x81e,\n\n trigger_mode_255_224 = 0x81f,\n\n interrupt_request_31_0 = 0x820,\n\n interrupt_request_63_32 = 0x821,\n\n interrupt_request_95_64 = 0x822,\n\n interrupt_request_127_96 = 0x823,\n\n interrupt_request_159_128 = 0x824,\n\n interrupt_request_191_160 = 0x825,\n\n interrupt_request_223_192 = 0x826,\n\n interrupt_request_255_224 = 0x827,\n\n timer_current_count = 0x839\n\n };\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 62, "score": 37979.705325782656 }, { "content": " bit_pattern = 0b1011;\n\n break;\n\n case 2:\n\n bit_pattern = 0b0000;\n\n break;\n\n case 4:\n\n bit_pattern = 0b0001;\n\n break;\n\n case 8:\n\n bit_pattern = 0b0010;\n\n break;\n\n case 16:\n\n bit_pattern = 0b0011;\n\n break;\n\n case 32:\n\n bit_pattern = 0b1000;\n\n break;\n\n case 64:\n\n bit_pattern = 0b1001;\n\n break;\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 63, "score": 37979.705325782656 }, { "content": " trigger_mode_223_192 = 0x1e0,\n\n trigger_mode_255_224 = 0x1f0,\n\n interrupt_request_31_0 = 0x200,\n\n interrupt_request_63_32 = 0x210,\n\n interrupt_request_95_64 = 0x220,\n\n interrupt_request_127_96 = 0x230,\n\n interrupt_request_159_128 = 0x240,\n\n interrupt_request_191_160 = 0x250,\n\n interrupt_request_223_192 = 0x260,\n\n interrupt_request_255_224 = 0x270,\n\n error_status = 0x280,\n\n timer_current_count = 0x390\n\n };\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 64, "score": 37979.705325782656 }, { "content": "namespace kernel::boot_serial\n\n{\n\nnamespace\n\n{\n\n void outb(std::uint16_t port, std::uint8_t byte)\n\n {\n\n asm volatile(\"outb %1, %0;\" ::\"dN\"(port), \"a\"(byte));\n\n }\n\n}\n\n\n\nvoid put_char(char c)\n\n{\n\n outb(0x3f8, c);\n\n}\n\n}\n", "file_path": "kernel/arch/amd64/boot/serial.cpp", "rank": 65, "score": 37946.042219257615 }, { "content": "/*\n\n * Copyright © 2021 Michał 'Griwes' Dominiak\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#include \"serial.h\"\n\n\n\n#include <cstdint>\n\n\n", "file_path": "kernel/arch/amd64/boot/serial.cpp", "rank": 66, "score": 37940.71996299319 }, { "content": " class x2apic_t\n\n {\n\n public:\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 67, "score": 36859.85161380564 }, { "content": " class xapic_t\n\n {\n\n public:\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 68, "score": 36859.85161380564 }, { "content": " enum class registers_w\n\n {\n\n eoi = 0x80b,\n\n self_ipi = 0x83f\n\n };\n\n\n\n void ap_initialize()\n\n {\n\n write(registers_rw::apic_base, read(registers_rw::apic_base) | (1 << 10));\n\n\n\n if (((read(registers_r::local_apic_version) >> 16) & 0xFF) == 6)\n\n {\n\n write(registers_rw::lvt_cmci, 0x10000);\n\n }\n\n\n\n write(registers_rw::lvt_error, 0x10000);\n\n write(registers_rw::lvt_lint0, 0x10000);\n\n write(registers_rw::lvt_lint1, 0x10000);\n\n write(registers_rw::lvt_pmc, 0x10000);\n\n write(registers_rw::lvt_thermal_sensor, 0x10000);\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 69, "score": 35804.14554784261 }, { "content": " enum class registers_r\n\n {\n\n local_apic_id = 0x802,\n\n local_apic_version = 0x803,\n\n processor_priority_register = 0x80a,\n\n logical_destination = 0x80d,\n\n in_service_31_0 = 0x810,\n\n in_service_63_32 = 0x811,\n\n in_service_95_64 = 0x812,\n\n in_service_127_96 = 0x813,\n\n in_service_159_128 = 0x814,\n\n in_service_191_160 = 0x815,\n\n in_service_223_192 = 0x816,\n\n in_service_255_224 = 0x817,\n\n trigger_mode_31_0 = 0x818,\n\n trigger_mode_63_32 = 0x819,\n\n trigger_mode_95_64 = 0x81a,\n\n trigger_mode_127_96 = 0x81b,\n\n trigger_mode_159_128 = 0x81c,\n\n trigger_mode_191_160 = 0x81d,\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 70, "score": 35804.14554784261 }, { "content": "struct EFI_BOOT_SERVICES\n\n{\n\n EFI_TABLE_HEADER header;\n\n\n\n EFI_RAISE_TPL raise_tpl;\n\n EFI_RESTORE_TPL restore_tpl;\n\n\n\n EFI_ALLOCATE_PAGES allocate_pages;\n\n EFI_FREE_PAGES free_pages;\n\n EFI_GET_MEMORY_MAP get_memory_map;\n\n EFI_ALLOCATE_POOL allocate_pool;\n\n EFI_FREE_POOL free_pool;\n\n\n\n EFI_CREATE_EVENT create_event;\n\n EFI_SET_TIMER set_timer;\n\n EFI_WAIT_FOR_EVENT wait_forEvent;\n\n EFI_SIGNAL_EVENT signal_event;\n\n EFI_CLOSE_EVENT close_event;\n\n EFI_CHECK_EVENT check_event;\n\n\n", "file_path": "loaders/uefi/efi/efi.cpp", "rank": 71, "score": 35760.79268372622 }, { "content": " enum class registers_rw\n\n {\n\n apic_base = 0x01b,\n\n task_priority = 0x808,\n\n spurious_interrupt_vector = 0x80f,\n\n error_status = 0x828,\n\n lvt_cmci = 0x82f,\n\n interrupt_command = 0x830,\n\n lvt_timer = 0x832,\n\n lvt_thermal_sensor = 0x833,\n\n lvt_pmc = 0x834,\n\n lvt_lint0 = 0x835,\n\n lvt_lint1 = 0x836,\n\n lvt_error = 0x837,\n\n timer_initial_count = 0x838,\n\n timer_divide_configuration = 0x83e\n\n };\n\n\n", "file_path": "kernel/arch/amd64/cpu/lapic.cpp", "rank": 72, "score": 34807.22882144959 }, { "content": "class timer : public time::timer\n\n{\n\npublic:\n\n void bsp_initialize();\n\n void initialize(timer * bsp);\n\n\n\nprotected:\n\n virtual void _update_now() override final;\n\n virtual void _one_shot_after(std::chrono::nanoseconds) override final;\n\n\n\nprivate:\n\n std::chrono::time_point<time::timer, std::chrono::duration<__int128, std::femto>> _fine_now;\n\n std::chrono::duration<std::int64_t, std::femto> _period;\n\n std::uint32_t _last_written = 0;\n\n std::uint8_t _last_divisor = 0;\n\n};\n\n}\n", "file_path": "kernel/arch/amd64/timers/lapic.h", "rank": 73, "score": 34807.22882144959 }, { "content": " phys_addr_t lapic_base;\n", "file_path": "kernel/arch/common/acpi/acpi.h", "rank": 74, "score": 33864.3237402616 }, { "content": "void exit_boot_services(const memory_map &);\n", "file_path": "loaders/uefi/efi/efi.h", "rank": 75, "score": 33823.319677658204 }, { "content": " EFI_BOOT_SERVICES * boot_services;\n", "file_path": "loaders/uefi/efi/system_table.h", "rank": 76, "score": 33823.319677658204 }, { "content": "# Kernel early boot functions\n\n\n\nThis directory contains functionalities that are necessary inside the kernel before their respective services become available.\n\n\n\nCurrently, this includes:\n\n\n\n * `kernel::boot_screen`, which contains a rudimentary framebuffer console for printing messages for the user.\n", "file_path": "kernel/boot/README.md", "rank": 77, "score": 29796.535433112946 }, { "content": "#include \"memory/pmm.h\"\n\n#include \"scheduler/scheduler.h\"\n\n#include \"scheduler/thread.h\"\n\n#include \"time/time.h\"\n\n#include \"util/initrd.h\"\n\n#include \"util/log.h\"\n\n#include \"util/mp.h\"\n\n\n\n#include <boot-arguments.h>\n\n#include <boot-constants.h>\n\n#include <boot-memmap.h>\n\n#include <boot-video.h>\n\n\n\n#include <cstddef>\n\n#include <cstdint>\n\n\n\nusing ctor_t = void (*)();\n\nextern \"C\" ctor_t __start_ctors;\n\nextern \"C\" ctor_t __end_ctors;\n\n\n", "file_path": "kernel/main.cpp", "rank": 82, "score": 27.650760502986035 }, { "content": "{\n\n lapic::ap_initialize();\n\n\n\n auto core = get_core_by_apic_id(lapic::id());\n\n core->initialize_gdt();\n\n core->load_gdt();\n\n idt::load();\n\n\n\n wrmsr(0xc0000101, reinterpret_cast<std::uint64_t>(core->get_core_local_storage_ptr()));\n\n wrmsr(0xc0000102, reinterpret_cast<std::uint64_t>(core->get_core_local_storage_ptr()));\n\n\n\n lapic_timer::ap_initialize();\n\n\n\n idle();\n\n}\n\n\n\nvoid switch_to_clean_state()\n\n{\n\n log::println(\"[CPU] Switching to clean state...\");\n\n\n", "file_path": "kernel/arch/amd64/cpu/cpu.cpp", "rank": 84, "score": 26.22046211299397 }, { "content": "extern \"C\" void __init()\n\n{\n\n for (auto ctor = &__start_ctors; ctor != &__end_ctors; ++ctor)\n\n {\n\n (*ctor)();\n\n }\n\n}\n\n\n\nextern \"C\" void __cxa_atexit(void (*)(void *), void *, void *)\n\n{\n\n}\n\n\n\n[[noreturn]] extern \"C\" void __cxa_pure_virtual()\n\n{\n\n PANIC(\"Pure virtual method called!\");\n\n}\n\n\n\n[[gnu::section(\".reaveros_entry\")]] extern \"C\" void kernel_main(boot_protocol::kernel_arguments args)\n\n{\n\n __init();\n", "file_path": "kernel/main.cpp", "rank": 85, "score": 24.910207337367382 }, { "content": " return cores;\n\n }\n\n\n\n std::size_t & get_core_count_ref()\n\n {\n\n return core_count;\n\n }\n\n}\n\n\n\nvoid initialize()\n\n{\n\n log::println(\"[CPU] Initializing CPU...\");\n\n\n\n auto madt_result = acpi::parse_madt(cores, core_count);\n\n core_count = madt_result.core_count;\n\n\n\n lapic::initialize(madt_result.lapic_base);\n\n\n\n auto bsp_core = get_core_by_apic_id(lapic::id());\n\n bsp_core->initialize_gdt();\n", "file_path": "kernel/arch/amd64/cpu/cpu.cpp", "rank": 86, "score": 23.821374243923756 }, { "content": " auto lapic = static_cast<madt_lapic *>(entry);\n\n if (lapic->flags & 1)\n\n {\n\n log::println(\n\n \" > Found an active LAPIC entry, ID: {}, UID: {}.\", lapic->apic_id, lapic->acpi_id);\n\n cores_storage[detected_cores++].initialize_ids(lapic->apic_id, lapic->acpi_id);\n\n }\n\n\n\n break;\n\n }\n\n\n\n case 1:\n\n {\n\n auto ioapic = static_cast<madt_ioapic *>(entry);\n\n log::println(\n\n \" > Found an I/O APIC entry, ID: {}, handling vectors from: {}.\",\n\n ioapic->ioapic_id,\n\n ioapic->interrupt_base);\n\n break;\n\n }\n", "file_path": "kernel/arch/common/acpi/acpi.cpp", "rank": 89, "score": 22.30123664337495 }, { "content": "#include \"../../../util/log.h\"\n\n#include \"../../common/acpi/acpi.h\"\n\n#include \"core.h\"\n\n#include \"gdt.h\"\n\n#include \"idt.h\"\n\n#include \"lapic.h\"\n\n\n\nnamespace kernel::amd64::cpu\n\n{\n\nnamespace\n\n{\n\n static const constexpr auto max_core_count = 1024;\n\n core cores[max_core_count];\n\n std::size_t core_count = max_core_count;\n\n}\n\n\n\nnamespace detail_for_mp\n\n{\n\n core * get_core_array()\n\n {\n", "file_path": "kernel/arch/amd64/cpu/cpu.cpp", "rank": 90, "score": 21.06316878389375 }, { "content": "\n\n for (auto idx = 0ull; idx < detected_cores; ++idx)\n\n {\n\n if (cores_storage[idx].acpi_id() == x2apic_nmi->acpi_id)\n\n {\n\n log::println(\n\n \" > Found a x2APIC NMI entry for core {}: {}.\",\n\n cores_storage[idx].apic_id(),\n\n x2apic_nmi->lapic_interrupt);\n\n cores_storage[idx].set_nmi(x2apic_nmi->lapic_interrupt, x2apic_nmi->flags);\n\n break;\n\n }\n\n\n\n if (idx == detected_cores - 1)\n\n {\n\n log::println(\n\n \" > Warning: found a x2APIC NMI entry {} for an unknown ACPI ID {}.\",\n\n x2apic_nmi->lapic_interrupt,\n\n x2apic_nmi->acpi_id);\n\n }\n", "file_path": "kernel/arch/common/acpi/acpi.cpp", "rank": 91, "score": 20.970942848324952 }, { "content": "#include \"log.h\"\n\n#include \"pointer_types.h\"\n\n\n\nnamespace kernel::initrd\n\n{\n\nnamespace\n\n{\n\n phys_addr_t bootinit_address;\n\n std::size_t bootinit_physical_size;\n\n std::size_t nested_initrd_physical_size;\n\n}\n\n\n\nvoid initialize(std::size_t memmap_size, boot_protocol::memory_map_entry * memmap)\n\n{\n\n log::println(\"[BOOT] Finding and starting the boot init process...\");\n\n auto entry = boot_protocol::find_entry(memmap_size, memmap, boot_protocol::memory_type::initrd);\n\n if (!entry)\n\n {\n\n PANIC(\"Initrd not found!\");\n\n }\n", "file_path": "kernel/util/initrd.cpp", "rank": 92, "score": 20.95520946705314 }, { "content": " }\n\n\n\n for (auto idx = 0ull; idx < detected_cores; ++idx)\n\n {\n\n if (cores_storage[idx].acpi_id() == lapic_nmi->acpi_id)\n\n {\n\n log::println(\n\n \" > Found a LAPIC NMI entry for core {}: {}.\",\n\n cores_storage[idx].apic_id(),\n\n lapic_nmi->lapic_interrupt);\n\n cores_storage[idx].set_nmi(lapic_nmi->lapic_interrupt, lapic_nmi->flags);\n\n break;\n\n }\n\n\n\n if (idx == detected_cores - 1)\n\n {\n\n log::println(\n\n \" > Warning: found a LAPIC NMI entry {} for an unknown ACPI ID {}.\",\n\n lapic_nmi->lapic_interrupt,\n\n lapic_nmi->acpi_id);\n", "file_path": "kernel/arch/common/acpi/acpi.cpp", "rank": 93, "score": 20.58227832459661 }, { "content": "#include \"lapic.h\"\n\n\n\nnamespace kernel::amd64::timers\n\n{\n\nvoid initialize()\n\n{\n\n hpet::initialize();\n\n lapic_timer::initialize();\n\n}\n\n\n\nvoid multicore_initialize()\n\n{\n\n hpet::rebalance();\n\n}\n\n\n\ntime::timer * get_high_precision_timer_for(std::size_t id)\n\n{\n\n return hpet::comparator_for(id);\n\n}\n\n}\n", "file_path": "kernel/arch/amd64/timers/timers.cpp", "rank": 95, "score": 19.913003419844397 }, { "content": " }\n\n }\n\n\n\n break;\n\n }\n\n\n\n case 10:\n\n {\n\n auto x2apic_nmi = static_cast<madt_x2apic_nmi *>(entry);\n\n\n\n if (x2apic_nmi->acpi_id == 0xff)\n\n {\n\n log::println(\n\n \" > Found a x2APIC NMI entry for all cores: {}.\", x2apic_nmi->lapic_interrupt);\n\n for (auto i = 0ull; i < detected_cores; ++i)\n\n {\n\n cores_storage[i].set_nmi(x2apic_nmi->lapic_interrupt, x2apic_nmi->flags);\n\n }\n\n break;\n\n }\n", "file_path": "kernel/arch/common/acpi/acpi.cpp", "rank": 96, "score": 19.172658634189567 }, { "content": "#include <cstddef>\n\n#include <cstdint>\n\n\n\nnamespace kernel::acpi\n\n{\n\nnamespace\n\n{\n\n struct [[gnu::packed]] description_header\n\n {\n\n char signature[4];\n\n std::uint32_t length;\n\n std::uint8_t revision;\n\n std::uint8_t checksum;\n\n char oemid[6];\n\n std::uint64_t oem_table_id;\n\n std::uint32_t oem_revision;\n\n std::uint32_t creator_id;\n\n std::uint32_t creator_revision;\n\n\n\n bool validate(const char (&sign)[5])\n", "file_path": "kernel/arch/common/acpi/acpi.cpp", "rank": 97, "score": 18.788863313080036 }, { "content": "#include \"cpu/paging.h\"\n\n#include \"efi/console.h\"\n\n#include \"efi/efi.h\"\n\n#include \"efi/filesystem.h\"\n\n#include \"efi/system_table.h\"\n\n#include \"efi/video_mode.h\"\n\n\n\n#include <boot-arguments.h>\n\n#include <boot-constants.h>\n\n\n\n#include <cstring>\n\n\n\nextern \"C\" char image_base[];\n\nextern \"C\" char image_end[];\n\n\n\nextern \"C\" efi_loader::EFI_STATUS efi_main(\n\n efi_loader::EFI_HANDLE image_handle,\n\n efi_loader::EFI_SYSTEM_TABLE * system_table)\n\n{\n\n efi_loader::video_mode video_mode;\n", "file_path": "loaders/uefi/main.cpp", "rank": 99, "score": 17.67431054426418 } ]
C++
fulanghua_ekf_2d/src/pose_estimator.cpp
hoshianaaa/fulanghua_navigation
f6b5f5289c1b27ad45b6db6b6535b01ba4203001
#include <fulanghua_ekf_2d/pose_estimator.h> #include <boost/assign.hpp> #include <Eigen/LU> #include <Eigen/Dense> namespace fulanghua { double normalize_rad(double th) { while(th > M_PI) th -= 2 * M_PI; while(th < -M_PI) th += 2 * M_PI; return th; } PoseEstimator::PoseEstimator(ros::NodeHandle &node) : publish_pose_topic_(true), publish_odom_topic_(false), update_rate_(100), output_frame_("odom"), base_frame_("base_link"), world_frame_("map"), x_est_(Eigen::Vector4d::Zero()), cov_est_(Eigen::Matrix4d::Identity()) { ros::NodeHandle nh_private("~"); nh_private.param("output_frame", output_frame_, output_frame_); nh_private.param("base_frame", base_frame_, base_frame_); double motion_x_err, motion_y_err, motion_ang_err, motion_vel_err; double observation_x_err, observation_y_err, observation_ang_err, observation_vel_err; nh_private.param("motion_x_err", motion_x_err, 0.1); nh_private.param("motion_y_err", motion_y_err, 0.1); nh_private.param("motion_ang_err", motion_ang_err, 0.1); nh_private.param("motion_vel_err", motion_vel_err, 0.05); nh_private.param("observation_x_err", observation_x_err, 0.1); nh_private.param("observation_y_err", observation_y_err, 0.1); nh_private.param("observation_ang_err", observation_ang_err, 0.1); nh_private.param("observation_vel_err", observation_vel_err, 0.05); motion_cov_ << motion_x_err * motion_x_err, 0.0, 0.0, 0.0, 0.0, motion_y_err * motion_y_err, 0.0, 0.0, 0.0, 0.0, motion_ang_err * motion_ang_err, 0.0, 0.0, 0.0, 0.0, motion_vel_err * motion_vel_err; observation_cov_ << observation_x_err * observation_x_err, 0.0, 0.0, 0.0, 0.0, observation_y_err * observation_y_err, 0.0, 0.0, 0.0, 0.0, observation_ang_err * observation_ang_err, 0.0, 0.0, 0.0, 0.0, observation_vel_err * observation_vel_err; nh_private.param("publish_pose_topic", publish_pose_topic_, publish_pose_topic_); nh_private.param("publish_odom_topic", publish_odom_topic_, publish_odom_topic_); imu_sub_ = node.subscribe("imu", 10, &PoseEstimator::imu_callback, this); odom_sub_ = node.subscribe("odom", 10, &PoseEstimator::odom_callback, this); gpos_meas_sub_ = node.subscribe("meas_gpos", 10, &PoseEstimator::gpos_meas_callback, this); if(publish_odom_topic_) odom_pub_ = node.advertise<nav_msgs::Odometry>("combined_odom", 10); if(publish_pose_topic_) pose_pub_ = node.advertise<geometry_msgs::PoseWithCovarianceStamped>("self_pose", 10); } void PoseEstimator::spin() { ros::Rate rate(update_rate_); ros::Time old_filter_stamp(0); bool meas_initialized = false; while(ros::ok()) { ros::spinOnce(); rate.sleep(); if(old_filter_stamp != ros::Time(0) && imu_stamp_ != ros::Time(0) && odom_stamp_ != ros::Time(0)) { meas_initialized = true; } else { meas_initialized = false; } if(meas_initialized) { ros::Time now = ros::Time::now(); ros::Time filter_stamp = now; filter_stamp = std::min(filter_stamp, odom_stamp_); filter_stamp = std::min(filter_stamp, imu_stamp_); filter_stamp = std::min(filter_stamp, gpos_meas_stamp_); double dt = (now - old_filter_stamp).toSec(); if(fabs(dt) < 0.0001) continue; if((ros::Time::now() - filter_stamp).toSec() > 1.0) { ROS_WARN("receive data are too old!"); continue; } Eigen::Vector2d est_pos; double est_yaw; Eigen::Matrix3d est_cov; if(!estimate(est_pos, est_yaw, est_cov, filter_stamp, dt)) continue; if(publish_odom_topic_) publish_odom(filter_stamp, est_pos, est_yaw, est_cov); if(publish_pose_topic_) publish_pose(filter_stamp, est_pos, est_yaw, est_cov); geometry_msgs::TransformStamped tran; tran.header.stamp = filter_stamp; tran.header.frame_id = output_frame_; tran.child_frame_id = base_frame_; tran.transform.translation.x = est_pos.x(); tran.transform.translation.y = est_pos.y(); tran.transform.translation.z = 0.0; tran.transform.rotation = tf::createQuaternionMsgFromYaw(est_yaw); tf_broadcaster_.sendTransform(tran); old_filter_stamp = now; } else { old_filter_stamp = ros::Time::now(); if(transformer_.canTransform(world_frame_, "odom", old_filter_stamp)) { transformer_.lookupTransform("odom", world_frame_, old_filter_stamp, old_odom_meas_); } } } } bool PoseEstimator::estimate(Eigen::Vector2d &pos, double &yaw, Eigen::Matrix3d &cov_xy_th, const ros::Time &filter_stamp, double dt) { tf::StampedTransform odom_meas; if(!transformer_.canTransform(world_frame_, "odom", filter_stamp)) { ROS_WARN("Failed transform of odom data"); return false; } else { transformer_.lookupTransform("odom", world_frame_, filter_stamp, odom_meas); } double gpos_meas_x, gpos_meas_y; tf::StampedTransform gpos_meas; if(!transformer_.canTransform(world_frame_, "gpos_meas", filter_stamp)) { ROS_WARN("Failed transform of gpos_meas data"); return false; } else { transformer_.lookupTransform("gpos_meas", world_frame_, filter_stamp, gpos_meas); } gpos_meas_x = gpos_meas.getOrigin().x(); gpos_meas_y = gpos_meas.getOrigin().y(); tf::StampedTransform imu_meas; if(!transformer_.canTransform(world_frame_, "imu", filter_stamp)) { ROS_WARN("Failed transform of imu data"); return false; } else { transformer_.lookupTransform("imu", world_frame_, filter_stamp, imu_meas); } double odom_linear_x = (odom_meas.getOrigin().x() - old_odom_meas_.getOrigin().x()) / dt; double odom_angular_z; double tmp_r, tmp_p, odom_yaw; odom_meas.getBasis().getEulerYPR(odom_yaw, tmp_p, tmp_r); double tmp_old_r, tmp_old_p, old_odom_yaw; old_odom_meas_.getBasis().getEulerYPR(old_odom_yaw, tmp_old_p, tmp_old_r); odom_angular_z = (odom_yaw - old_odom_yaw) / dt; double imu_roll, imu_pitch, imu_yaw; imu_meas.getBasis().getEulerYPR(imu_yaw, imu_pitch, imu_roll); Eigen::Vector2d u(odom_linear_x, odom_angular_z); Eigen::Vector4d x_pred = motion_model(x_est_, u, dt); Eigen::Matrix4d JF = jacob_motion_model(x_pred, u, dt); Eigen::Matrix4d cov_pred = JF * cov_est_ * JF.transpose() + motion_cov_; Eigen::Vector4d x(gpos_meas_x, gpos_meas_y, imu_yaw, odom_linear_x); Eigen::Vector4d z = observation_model(x); Eigen::Matrix4d H = jacob_observation_model(x_pred); Eigen::Vector4d y = z - observation_model(x_pred); y(2) = normalize_rad(y(2)); Eigen::Matrix4d S = H * cov_pred * H.transpose() + observation_cov_; Eigen::Matrix4d K = cov_pred * H.transpose() * S.inverse(); x_est_ = x_pred + K * y; cov_est_ = (Eigen::Matrix4d::Identity() - K * H) * cov_pred; old_odom_meas_ = odom_meas; pos.x() = x_est_(0); pos.y() = x_est_(1); yaw = x_est_(2); cov_xy_th = cov_est_.block(0, 0, 3, 3); return true; } void PoseEstimator::publish_odom(const ros::Time &stamp, const Eigen::Vector2d &pos, double yaw, const Eigen::Matrix3d &cov_xy_th) { nav_msgs::Odometry est_odom; est_odom.header.stamp = stamp; est_odom.header.frame_id = output_frame_; est_odom.child_frame_id = base_frame_; est_odom.pose.pose.position.x = pos.x(); est_odom.pose.pose.position.y = pos.y(); est_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw); est_odom.pose.covariance = boost::assign::list_of (cov_xy_th(0)) (0) (0) (0) (0) (0) (0) (cov_xy_th(1)) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (0) (cov_xy_th(2)); odom_pub_.publish(est_odom); } void PoseEstimator::publish_pose(const ros::Time &stamp, const Eigen::Vector2d &pos, double yaw, const Eigen::Matrix3d &cov_xy_th) { geometry_msgs::PoseWithCovarianceStamped est_pose; est_pose.header.stamp = stamp; est_pose.header.frame_id = base_frame_; est_pose.pose.pose.position.x = pos.x(); est_pose.pose.pose.position.y = pos.y(); est_pose.pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw); est_pose.pose.covariance = boost::assign::list_of (cov_xy_th(0)) (0) (0) (0) (0) (0) (0) (cov_xy_th(1)) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (0) (cov_xy_th(2)); pose_pub_.publish(est_pose); } } int main(int argc, char *argv[]) { ros::init(argc, argv, "pose_estimator"); ros::NodeHandle nh; fulanghua::PoseEstimator estimator(nh); estimator.spin(); return 0; }
#include <fulanghua_ekf_2d/pose_estimator.h> #include <boost/assign.hpp> #include <Eigen/LU> #include <Eigen/Dense> namespace fulanghua { double normalize_rad(double th) { while(th > M_PI) th -= 2 * M_PI; while(th < -M_PI) th += 2 * M_PI; return th; } PoseEstimator::PoseEstimator(ros::NodeHandle &node) : publish_pose_topic_(true), publish_odom_topic_(false), update_rate_(100), output_frame_("odom"), base_frame_("base_link"), world_frame_("map"), x_est_(Eigen::Vector4d::Zero()), cov_est_(Eigen::Matrix4d::Identity()) { ros::NodeHandle nh_private("~"); nh_private.param("output_frame", output_frame_, output_frame_); nh_private.param("base_frame", base_frame_, base_frame_); double motion_x_err, motion_y_err, motion_ang_err, motion_vel_err; double observation_x_err, observation_y_err, observation_ang_err, observation_vel_err; nh_private.param("motion_x_err", motion_x_err, 0.1); nh_private.param("motion_y_err", motion_y_err, 0.1); nh_private.param("motion_ang_err", motion_ang_err, 0.1); nh_private.param("motion_vel_err", motion_vel_err, 0.05); nh_private.param("observation_x_err", observation_x_err, 0.1); nh_private.param("observation_y_err", observation_y_err, 0.1); nh_private.param("observation_ang_err", observation_ang_err, 0.1); nh_private.param("observation_vel_err", observation_vel_err, 0.05); motion_cov_ << motion_x_err * motion_x_err, 0.0, 0.0, 0.0, 0.0, motion_y_err * motion_y_err, 0.0, 0.0, 0.0, 0.0, motion_ang_err * motion_ang_err, 0.0, 0.0, 0.0, 0.0, motion_vel_err * motion_vel_err; observation_cov_ << observation_x_err * observation_x_err, 0.0, 0.0, 0.0, 0.0, observation_y_err * observation_y_err, 0.0, 0.0, 0.0, 0.0, observation_ang_err * observation_ang_err, 0.0, 0.0, 0.0, 0.0, observation_vel_err * observation_vel_err; nh_private.param("publish_pose_topic", publish_pose_topic_, publish_pose_topic_); nh_private.param("publish_odom_topic", publish_odom_topic_, publish_odom_topic_); imu_sub_ = node.subscribe("imu", 10, &PoseEstimator::imu_callback, this); odom_sub_ = node.subscribe("odom", 10, &PoseEstimator::odom_callback, this); gpos_meas_sub_ = node.subscribe("meas_gpos", 10, &PoseEstimator::gpos_meas_callback, this); if(publish_odom_topic_) odom_pub_ = node.advertise<nav_msgs::Odometry>("combined_odom", 10); if(publish_pose_topic_) pose_pub_ = node.advertise<geometry_msgs::PoseWithCovarianceStamped>("self_pose", 10); } void PoseEstimator::spin() { ros::Rate rate(update_rate_); ros::Time old_filter_stamp(0); bool meas_initialized = false; while(ros::ok()) { ros::spinOnce(); rate.sleep(); if(old_filter_stamp != ros::Time(0) && imu_stamp_ != ros::Time(0) && odom_stamp_ != ros::Time(0)) { meas_initialized = true; } else { meas_initialized = false; } if(meas_initialized) { ros::Time now = ros::Time::now(); ros::Time filter_stamp = now; filter_stamp = std::min(filter_stamp, odom_stamp_); filter_stamp = std::min(filter_stamp, imu_stamp_); filter_stamp = std::min(filter_stamp, gpos_meas_stamp_); double dt = (now - old_filter_stamp).toSec(); if(fabs(dt) < 0.0001) continue; if((ros::Time::now() - filter_stamp).toSec() > 1.0) { ROS_WARN("receive data are too old!"); continue; } Eigen::Vector2d est_pos; double est_yaw; Eigen::Matrix3d est_cov; if(!estimate(est_pos, est_yaw, est_cov, filter_stamp, dt)) continue; if(publish_odom_topic_) publish_odom(filter_stamp, est_pos, est_yaw, est_cov); if(publish_pose_topic_) publish_pose(filter_stamp, est_pos, est_yaw, est_cov); geometry_msgs::TransformStamped tran; tran.header.stamp = filter_stamp; tran.header.frame_id = output_frame_; tran.child_frame_id = base_frame_; tran.transform.translation.x = est_pos.x(); tran.transform.translation.y = est_pos.y(); tran.transform.translation.z = 0.0; tran.transform.rotation = tf::createQuaternionMsgFromYaw(est_yaw); tf_broadcaster_.sendTransform(tran); old_filter_stamp = now; } else { old_filter_stamp = ros::Time::now(); if(transformer_.canTransform(world_frame_, "odom", old_filter_stamp)) { transformer_.lookupTransform("odom", world_frame_, old_filter_stamp, old_odom_meas_); } } } } bool PoseEstimator::estimate(Eigen::Vector2d &pos, double &yaw, Eigen::Matrix3d &cov_xy_th, const ros::Time &filter_stamp, double dt) { tf::StampedTransform odom_meas; if(!transformer_.canTransform(world_frame_, "odom", filter_stamp)) { ROS_WARN("Failed transform of odom data"); return false; } else { transformer_.lookupTransform("odom", world_frame_, filter_stamp, odom_meas); } double gpos_meas_x, gpos_meas_y; tf::StampedTransform gpos_meas; if(!transformer_.canTransform(world_frame_, "gpos_meas", filter_stamp)) { ROS_WARN("Failed transform of gpos_meas data"); return false; } else { transformer_.lookupTransform("gpos_meas", world_frame_, filter_stamp, gpos_meas); } gpos_meas_x = gpos_meas.getOrigin().x(); gpos_meas_y = gpos_meas.getOrigin().y(); tf::StampedTransform imu_meas; if(!transformer_.canTransform(world_frame_, "imu", filter_stamp)) { ROS_WARN("Failed transform of imu data"); return false; } else { transformer_.lookupTransform("imu", world_frame_, filter_stamp, imu_meas); } double odom_linear_x = (odom_meas.getOrigin().x() - old_odom_meas_.getOrigin().x()) / dt; double odom_angular_z; double tmp_r, tmp_p, odom_yaw; odom_meas.getBasis().getEulerYPR(odom_yaw, tmp_p, tmp_r); double tmp_old_r, tmp_old_p, old_odom_yaw; old_odom_meas_.getBasis().getEulerYPR(old_odom_yaw, tmp_old_p, tmp_old_r); odom_angular_z = (odom_yaw - old_odom_yaw) / dt; double imu_roll, imu_pitch, imu_yaw; imu_meas.getBasis().getEulerYPR(imu_yaw, imu_pitch, imu_roll); Eigen::Vector2d u(odom_linear_x, odom_angular_z); Eigen::Vector4d x_pred = motion_model(x_est_, u, dt); Eigen::Matrix4d JF = jacob_motion_model(x_pred, u, dt); Eigen::Matrix4d cov_pred = JF * cov_est_ * JF.transpose() + motion_cov_; Eigen::Vector4d x(gpos_meas_x, gpos_meas_y, imu_yaw, odom_linear_x); Eigen::Vector4d z = observation_model(x); Eigen::Matrix4d H = jacob_observation_model(x_pred); Eigen::Vector4d y = z - observation_model(x_pred); y(2) = normalize_rad(y(2)); Eigen::Matrix4d S = H * cov_pred * H.transpose() + observation_cov_; Eigen::Matrix4d K = cov_pred * H.transpose() * S.inverse(); x_est_ = x_pred + K * y; cov_est_ = (Eigen::Matrix4d::Identity() - K * H) * cov_pred; old_odom_meas_ = odom_meas; pos.x() = x_est_(0); pos.y() = x_est_(1); yaw = x_est_(2); cov_xy_th = cov_est_.block(0, 0, 3, 3); return true; } void PoseEstimator::publish_odom(const ros::Time &stamp, const Eigen::Vector2d &pos, double yaw, const Eigen::Matrix3d &cov_xy_th) { nav_msgs::Odometry est_odom; est_odom.header.stamp = stamp; est_odom.header.frame_id = output_frame_; est_odom.child_frame_id = base_frame_; est_odom.pose.pose.position.x = pos.x(); est_odom.pose.pose.position.y = pos.y(); est_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw); est_odom.pose.covariance = boost::assign::list_of (cov_xy_th(0)) (0) (0) (0) (0) (0) (0) (cov_xy_th(1)) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (0) (cov_xy_th(2)); odom_pub_.publish(est_odom); } void PoseEstimator::publish_pose(const ros::Time &stamp, const Eigen::Vector2d &pos, double yaw, const Eigen::Matrix3d &cov_xy_th) { geometry_msgs::PoseWithCovarianceStamped est_pose; est_pose.header.stamp = stamp; est_pose.header.frame_id = base_frame_; est_pose.pose.pose.position.x = pos.x(); est_pose.pose.pose.position.y = pos.y(); est_pose.pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw);
} int main(int argc, char *argv[]) { ros::init(argc, argv, "pose_estimator"); ros::NodeHandle nh; fulanghua::PoseEstimator estimator(nh); estimator.spin(); return 0; }
est_pose.pose.covariance = boost::assign::list_of (cov_xy_th(0)) (0) (0) (0) (0) (0) (0) (cov_xy_th(1)) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (999999.9) (0) (0) (0) (0) (0) (0) (0) (cov_xy_th(2)); pose_pub_.publish(est_pose); }
function_block-function_prefix_line
[ { "content": " Eigen::Matrix4d motion_cov_;\n\n Eigen::Matrix4d observation_cov_;\n\n\n\n tf::StampedTransform old_odom_meas_;\n\n tf::Transformer transformer_;\n\n tf::TransformBroadcaster tf_broadcaster_;\n\n \n\n bool publish_odom_topic_;\n\n bool publish_pose_topic_;\n\n double update_rate_;\n\n std::string output_frame_;\n\n std::string base_frame_;\n\n std::string world_frame_;\n\n\n\n ros::Time odom_stamp_;\n\n ros::Time gpos_meas_stamp_;\n\n ros::Time imu_stamp_;\n\n\n\n};\n\n\n\n} //namespace fulanghua\n\n\n\n#endif //FULANGHUA_EKF_2d__POSE_ESTIMATOR_H\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 0, "score": 21914.525775406564 }, { "content": " quaternionMsgToTF(msg.orientation, q);\n\n tf::Transform trans(q, tf::Vector3(0, 0, 0));\n\n tf::StampedTransform meas(trans.inverse(), msg.header.stamp, world_frame_, \"imu\");\n\n \n\n transformer_.setTransform(meas);\n\n }\n\n\n\n void odom_callback(const nav_msgs::Odometry &msg) {\n\n odom_stamp_ = msg.header.stamp;\n\n\n\n tf::Quaternion q;\n\n tf::quaternionMsgToTF(msg.pose.pose.orientation, q);\n\n tf::Transform trans(q, tf::Vector3(msg.pose.pose.position.x, msg.pose.pose.position.y, 0));\n\n tf::StampedTransform meas(trans.inverse(), msg.header.stamp, world_frame_, \"odom\");\n\n \n\n transformer_.setTransform(meas);\n\n }\n\n\n\n void gpos_meas_callback(const nav_msgs::Odometry &msg) {\n\n gpos_meas_stamp_ = msg.header.stamp;\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 1, "score": 21910.390196682478 }, { "content": " * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#ifndef FULANGHUA_EKF_2D__POSE_ESTIMATOR_H\n\n#define FULANGHUA_EKF_2D__POSE_ESTIMATOR_H\n\n\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n\n#include <sensor_msgs/Imu.h>\n\n#include <nav_msgs/Odometry.h>\n\n#include <tf/tf.h>\n\n#include <tf/transform_broadcaster.h>\n\n\n\n#include <Eigen/Core>\n\n#include <Eigen/Geometry>\n\n\n\n#include <string>\n\n\n\nnamespace fulanghua {\n\n\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 2, "score": 21910.15042521707 }, { "content": "\n\n tf::Quaternion q(0, 0, 0, 1);\n\n tf::Transform trans(q, tf::Vector3(msg.pose.pose.position.x, msg.pose.pose.position.y, 0));\n\n tf::StampedTransform meas(trans.inverse(), msg.header.stamp, world_frame_, \"gpos_meas\");\n\n\n\n transformer_.setTransform(meas);\n\n }\n\n\n\n Eigen::Matrix4d jacob_motion_model(const Eigen::Vector4d &x, const Eigen::Vector2d &u, double dt) {\n\n Eigen::Matrix4d J;\n\n J << 1.0, 0.0, 0.0, 0.0,\n\n 0.0, 1.0, 0.0, 0.0,\n\n -dt*u(0)*sin(x(2)), dt*cos(x(2)), 1.0, 0.0,\n\n dt*u(0)*cos(x(2)), dt*sin(x(2)), 0.0, 1.0;\n\n\n\n return J;\n\n\n\n }\n\n\n\n Eigen::Vector4d motion_model(const Eigen::Vector4d &x, const Eigen::Vector2d &u, double dt) {\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 3, "score": 21906.801522435122 }, { "content": " 0.0, 0.0, 0.0, 1.0;\n\n \n\n return J;\n\n }\n\n\n\n Eigen::Vector4d observation_model(const Eigen::Vector4d &x) {\n\n Eigen::Matrix4d H;\n\n H << 1.0, 0.0, 0.0, 0.0,\n\n 0.0, 1.0, 0.0, 0.0,\n\n 0.0, 0.0, 1.0, 0.0,\n\n 0.0, 0.0, 0.0, 1.0;\n\n\n\n return H*x;\n\n }\n\n\n\n ros::Publisher pose_pub_, odom_pub_;\n\n ros::Subscriber odom_sub_, imu_sub_, gpos_meas_sub_;\n\n \n\n Eigen::Matrix4d cov_est_;\n\n Eigen::Vector4d x_est_;\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 4, "score": 21904.453225048183 }, { "content": " Eigen::Matrix4d F;\n\n F << 1.0, 0.0, 0.0, 0.0,\n\n 0.0, 1.0, 0.0, 0.0,\n\n 0.0, 0.0, 1.0, 0.0,\n\n 0.0, 0.0, 0.0, 0.0;\n\n\n\n Eigen::MatrixXd B(4, 2);\n\n B << dt*cos(x(2)), 0.0,\n\n dt*sin(x(2)), 0.0,\n\n 0.0, dt,\n\n 1.0, 0.0;\n\n\n\n return F*x + B*u;\n\n }\n\n\n\n Eigen::Matrix4d jacob_observation_model(const Eigen::Vector4d &x) {\n\n Eigen::Matrix4d J;\n\n J << 1.0, 0.0, 0.0, 0.0,\n\n 0.0, 1.0, 0.0, 0.0,\n\n 0.0, 0.0, 1.0, 0.0,\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 5, "score": 21900.182693553234 }, { "content": "/*\n\n * Software License Agreement (BSD License)\n\n *\n\n * Copyright (c) 2015, Daiki Maekawa and Chiba Institute of Technology.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions\n\n * are met:\n\n *\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above\n\n * copyright notice, this list of conditions and the following\n\n * disclaimer in the documentation and/or other materials provided\n\n * with the distribution.\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 6, "score": 21898.543844985634 }, { "content": "class PoseEstimator\n\n{\n\npublic:\n\n PoseEstimator(ros::NodeHandle &node);\n\n \n\n void spin();\n\n\n\n bool estimate(Eigen::Vector2d &pos, double &yaw, Eigen::Matrix3d &cov_xy_th, const ros::Time &filter_stamp, double dt);\n\n\n\nprivate:\n\n void publish_odom(const ros::Time &stamp, const Eigen::Vector2d &pos, double yaw\n\n , const Eigen::Matrix3d &cov_xy_th);\n\n\n\n void publish_pose(const ros::Time &stamp, const Eigen::Vector2d &pos, double yaw\n\n , const Eigen::Matrix3d &cov_xy_th);\n\n\n\n void imu_callback(const sensor_msgs::Imu &msg) {\n\n imu_stamp_ = msg.header.stamp;\n\n\n\n tf::Quaternion q;\n", "file_path": "fulanghua_ekf_2d/include/fulanghua_ekf_2d/pose_estimator.h", "rank": 7, "score": 19940.01032931369 }, { "content": "#include <ros/ros.h>\n\n#include <nav_msgs/Path.h>\n\n#include <geometry_msgs/Pose.h>\n\n#include <visualization_msgs/MarkerArray.h>\n\n\n\n#include <vector>\n\n\n\nnamespace fulanghua {\n\n\n", "file_path": "fulanghua_evaluator/src/path_similarity.cpp", "rank": 20, "score": 3298.916418436128 }, { "content": " path_b_ = msg;\n\n }\n\n\n\n nav_msgs::Path path_a_, path_b_;\n\n ros::Publisher path_markers_pub_;\n\n ros::Subscriber path_a_sub_, path_b_sub_;\n\n};\n\n\n\n} //namespace fulanghua\n\n\n\nint main(int argc, char *argv[]) {\n\n ros::init(argc, argv, \"path_similarity\");\n\n\n\n ros::NodeHandle nh;\n\n fulanghua::PathSimilarity similarity_evaluator(nh);\n\n similarity_evaluator.spin();\n\n\n\n return 0;\n\n}\n", "file_path": "fulanghua_evaluator/src/path_similarity.cpp", "rank": 21, "score": 3296.8673056761136 }, { "content": " }\n\n }\n\n path_markers_pub_.publish(viz_markers);\n\n\n\n r.sleep();\n\n }\n\n }\n\n\n\nprivate:\n\n double get_distance(const geometry_msgs::Point &pose1, const geometry_msgs::Point &pose2) {\n\n return sqrt(pow(pose1.x - pose2.x, 2) + \n\n pow(pose1.y - pose2.y, 2) + \n\n pow(pose1.z - pose2.z, 2));\n\n }\n\n\n\n void pathACallback(const nav_msgs::Path &msg) {\n\n path_a_ = msg;\n\n }\n\n\n\n void pathBCallback(const nav_msgs::Path &msg) {\n", "file_path": "fulanghua_evaluator/src/path_similarity.cpp", "rank": 22, "score": 3293.4212730664326 }, { "content": " if(pose_len <= get_distance(std::begin(path_b_.poses)->pose.position, pose_b.pose.position)) {\n\n visualization_msgs::Marker line_strip;\n\n line_strip.header.frame_id = \"map\";\n\n line_strip.header.stamp = ros::Time::now();\n\n line_strip.ns = \"fulanghua_evaluator\";\n\n \n\n line_strip.id = marker_id;\n\n marker_id++;\n\n\n\n line_strip.scale.x = 0.05;\n\n line_strip.type = visualization_msgs::Marker::LINE_STRIP;\n\n line_strip.action = visualization_msgs::Marker::ADD;\n\n line_strip.color.b = 1.0;\n\n line_strip.color.a = 1.0;\n\n line_strip.points.push_back(pose_a.pose.position);\n\n line_strip.points.push_back(pose_b.pose.position);\n\n viz_markers.markers.push_back(line_strip);\n\n \n\n break;\n\n }\n", "file_path": "fulanghua_evaluator/src/path_similarity.cpp", "rank": 23, "score": 3293.4064351609704 }, { "content": "#include <visualization_msgs/MarkerArray.h>\n\n#include <fulanghua_srvs/Pose.h>\n\n\n\n#include <yaml-cpp/yaml.h>\n\n\n\n#include <vector>\n\n#include <fstream>\n\n#include <string>\n\n#include <exception>\n\n#include <math.h>\n\n#include <limits>\n\n\n\n#ifdef NEW_YAMLCPP\n\ntemplate<typename T>\n\nvoid operator >> (const YAML::Node& node, T& i)\n\n{\n\n i = node.as<T>();\n\n}\n\n#endif\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 26, "score": 3128.550548588537 }, { "content": " * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <tf/transform_listener.h>\n\n\n\n#include <sensor_msgs/Joy.h>\n\n#include <geometry_msgs/PointStamped.h>\n\n#include <geometry_msgs/PoseStamped.h>\n\n\n\n#include <vector>\n\n#include <fstream>\n\n#include <string>\n\n\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 27, "score": 3126.6759508987257 }, { "content": " if(dist < min_dist) {\n\n min_dist = dist;\n\n current_waypoint_ = it;\n\n }\n\n }\n\n \n\n response.status = true;\n\n has_activate_ = true;\n\n\n\n return true;\n\n }\n\n\n\n bool suspendPoseCallback(fulanghua_srvs::Pose::Request &request, fulanghua_srvs::Pose::Response &response) {\n\n if(!has_activate_) {\n\n response.status = false;\n\n return false;\n\n }\n\n \n\n //move_base_action_.cancelAllGoals();\n\n startNavigationGL(request.pose);\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 28, "score": 3125.716480374224 }, { "content": " return true;\n\n }\n\n\n\n void computeWpOrientation(){\n\n for(std::vector<geometry_msgs::Pose>::iterator it = waypoints_.poses.begin(); it != finish_pose_; it++) {\n\n double goal_direction = atan2((it+1)->position.y - (it)->position.y,\n\n (it+1)->position.x - (it)->position.x);\n\n (it)->orientation = tf::createQuaternionMsgFromYaw(goal_direction);\n\n }\n\n waypoints_.header.frame_id = world_frame_;\n\n }\n\n\n\n bool shouldSendGoal(){\n\n bool ret = true;\n\n actionlib::SimpleClientGoalState state = move_base_action_.getState();\n\n if((state != actionlib::SimpleClientGoalState::ACTIVE) &&\n\n (state != actionlib::SimpleClientGoalState::PENDING) && \n\n (state != actionlib::SimpleClientGoalState::RECALLED) &&\n\n (state != actionlib::SimpleClientGoalState::PREEMPTED))\n\n {\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 29, "score": 3125.1246330701138 }, { "content": " const double ry = robot_gl.getOrigin().y();\n\n const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));\n\n\n\n return dist < dist_err;\n\n }\n\n\n\n tf::StampedTransform getRobotPosGL(){\n\n tf::StampedTransform robot_gl;\n\n try{\n\n tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);\n\n }catch(tf::TransformException &e){\n\n ROS_WARN_STREAM(\"tf::TransformException: \" << e.what());\n\n }\n\n\n\n return robot_gl;\n\n }\n\n\n\n void sleep(){\n\n rate_.sleep();\n\n ros::spinOnce();\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 30, "score": 3125.0342816304537 }, { "content": " tf::StampedTransform robot_gl;\n\n try{\n\n tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);\n\n geometry_msgs::PointStamped point;\n\n point.point.x = robot_gl.getOrigin().x();\n\n point.point.y = robot_gl.getOrigin().y();\n\n point.point.z = robot_gl.getOrigin().z();\n\n waypoints_.push_back(point);\n\n saved_time = ros::Time::now();\n\n }catch(tf::TransformException &e){\n\n ROS_WARN_STREAM(\"tf::TransformException: \" << e.what());\n\n }\n\n }\n\n }\n\n \n\n void waypointsVizCallback(const geometry_msgs::PointStamped &msg){\n\n ROS_INFO_STREAM(\"point = \" << msg);\n\n waypoints_.push_back(msg);\n\n }\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 31, "score": 3124.797831579361 }, { "content": " * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <std_srvs/Trigger.h>\n\n#include <std_srvs/Empty.h>\n\n#include <geometry_msgs/Pose.h>\n\n#include <geometry_msgs/PoseArray.h>\n\n#include <geometry_msgs/Twist.h>\n\n#include <move_base_msgs/MoveBaseAction.h>\n\n#include <actionlib/client/simple_action_client.h>\n\n#include <tf/tf.h>\n\n#include <tf/transform_listener.h>\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 32, "score": 3124.5183689230134 }, { "content": " current_waypoint_ = waypoints_.poses.begin();\n\n has_activate_ = true;\n\n response.success = true;\n\n return true;\n\n }\n\n\n\n bool resumePoseCallback(fulanghua_srvs::Pose::Request &request, fulanghua_srvs::Pose::Response &response) {\n\n if(has_activate_) {\n\n response.status = false;\n\n return false;\n\n }\n\n \n\n std_srvs::Empty empty;\n\n clear_costmaps_srv_.call(empty);\n\n //move_base_action_.cancelAllGoals();\n\n \n\n ///< @todo calculating metric with request orientation\n\n double min_dist = std::numeric_limits<double>::max();\n\n for(std::vector<geometry_msgs::Pose>::iterator it = current_waypoint_; it != finish_pose_; it++) {\n\n double dist = hypot(it->position.x - request.pose.position.x, it->position.y - request.pose.position.y);\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 33, "score": 3124.4300002572113 }, { "content": " bool isNavigationFinished = false;\n\n while(!isNavigationFinished && ros::ok()) {\n\n actionlib::SimpleClientGoalState state = move_base_action_.getState();\n\n if(state == actionlib::SimpleClientGoalState::SUCCEEDED){\n\n isNavigationFinished = true;\n\n response.status = true;\n\n }else if(state == actionlib::SimpleClientGoalState::ABORTED){\n\n isNavigationFinished = true;\n\n response.status = false;\n\n }\n\n sleep();\n\n }\n\n has_activate_ = false;\n\n\n\n return true;\n\n }\n\n \n\n void cmdVelCallback(const geometry_msgs::Twist &msg){\n\n if(msg.linear.x > -0.001 && msg.linear.x < 0.001 &&\n\n msg.linear.y > -0.001 && msg.linear.y < 0.001 &&\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 34, "score": 3124.417473896041 }, { "content": " ret = false;\n\n }\n\n\n\n if(waypoints_.poses.empty()){\n\n ret = false;\n\n }\n\n\n\n return ret;\n\n }\n\n\n\n bool navigationFinished(){\n\n return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;\n\n }\n\n\n\n bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.8){\n\n tf::StampedTransform robot_gl = getRobotPosGL();\n\n\n\n const double wx = dest.x;\n\n const double wy = dest.y;\n\n const double rx = robot_gl.getOrigin().x();\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 35, "score": 3124.0654953353023 }, { "content": " }\n\n \n\nprivate:\n\n ros::Subscriber waypoints_viz_sub_;\n\n ros::Subscriber waypoints_joy_sub_;\n\n ros::Subscriber finish_pose_sub_;\n\n std::vector<geometry_msgs::PointStamped> waypoints_;\n\n geometry_msgs::PoseStamped finish_pose_;\n\n tf::TransformListener tf_listener_;\n\n int save_joy_button_;\n\n ros::NodeHandle nh_;\n\n std::string filename_;\n\n std::string world_frame_;\n\n std::string robot_frame_;\n\n};\n\n\n\nint main(int argc, char *argv[]){\n\n ros::init(argc, argv, \"waypoints_saver\");\n\n WaypointsSaver saver;\n\n saver.run();\n\n\n\n return 0;\n\n}\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 36, "score": 3123.453105086891 }, { "content": " publishPoseArray();\n\n }\n\n\n\n void startNavigationGL(const geometry_msgs::Point &dest){\n\n geometry_msgs::Pose pose;\n\n pose.position = dest;\n\n pose.orientation = tf::createQuaternionMsgFromYaw(0.0);\n\n startNavigationGL(pose);\n\n }\n\n\n\n void startNavigationGL(const geometry_msgs::Pose &dest){\n\n move_base_msgs::MoveBaseGoal move_base_goal;\n\n move_base_goal.target_pose.header.stamp = ros::Time::now();\n\n move_base_goal.target_pose.header.frame_id = world_frame_;\n\n move_base_goal.target_pose.pose.position = dest.position;\n\n move_base_goal.target_pose.pose.orientation = dest.orientation;\n\n \n\n move_base_action_.sendGoal(move_base_goal);\n\n }\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 37, "score": 3122.890718314097 }, { "content": " msg.linear.z > -0.001 && msg.linear.z < 0.001 &&\n\n msg.angular.x > -0.001 && msg.angular.x < 0.001 &&\n\n msg.angular.y > -0.001 && msg.angular.y < 0.001 &&\n\n msg.angular.z > -0.001 && msg.angular.z < 0.001){\n\n \n\n ROS_INFO(\"command velocity all zero\");\n\n }else{\n\n last_moved_time_ = ros::Time::now().toSec();\n\n }\n\n }\n\n\n\n bool readFile(const std::string &filename){\n\n waypoints_.poses.clear();\n\n try{\n\n std::ifstream ifs(filename.c_str(), std::ifstream::in);\n\n if(ifs.good() == false){\n\n return false;\n\n }\n\n\n\n YAML::Node node;\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 38, "score": 3122.7766217729045 }, { "content": " void finishPoseCallback(const geometry_msgs::PoseStamped &msg){\n\n finish_pose_ = msg;\n\n save();\n\n waypoints_.clear();\n\n }\n\n \n\n void save(){\n\n std::ofstream ofs(filename_.c_str(), std::ios::out);\n\n \n\n ofs << \"waypoints:\" << std::endl;\n\n for(int i=0; i < waypoints_.size(); i++){\n\n ofs << \" \" << \"- point:\" << std::endl;\n\n ofs << \" x: \" << waypoints_[i].point.x << std::endl;\n\n ofs << \" y: \" << waypoints_[i].point.y << std::endl;\n\n ofs << \" z: \" << waypoints_[i].point.z << std::endl;\n\n }\n\n \n\n ofs << \"finish_pose:\" << std::endl;\n\n ofs << \" header:\" << std::endl;\n\n ofs << \" seq: \" << finish_pose_.header.seq << std::endl;\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 39, "score": 3122.354018377797 }, { "content": " \n\n #ifdef NEW_YAMLCPP\n\n node = YAML::Load(ifs);\n\n #else\n\n YAML::Parser parser(ifs);\n\n parser.GetNextDocument(node);\n\n #endif\n\n\n\n #ifdef NEW_YAMLCPP\n\n const YAML::Node &wp_node_tmp = node[\"waypoints\"];\n\n const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;\n\n #else\n\n const YAML::Node *wp_node = node.FindValue(\"waypoints\");\n\n #endif\n\n\n\n geometry_msgs::Pose pose;\n\n if(wp_node != NULL){\n\n for(int i=0; i < wp_node->size(); i++){\n\n\n\n (*wp_node)[i][\"point\"][\"x\"] >> pose.position.x;\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 40, "score": 3122.3245997620274 }, { "content": " (*wp_node)[i][\"point\"][\"y\"] >> pose.position.y;\n\n (*wp_node)[i][\"point\"][\"z\"] >> pose.position.z;\n\n\n\n waypoints_.poses.push_back(pose);\n\n\n\n }\n\n }else{\n\n return false;\n\n }\n\n \n\n #ifdef NEW_YAMLCPP\n\n const YAML::Node &fp_node_tmp = node[\"finish_pose\"];\n\n const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;\n\n #else\n\n const YAML::Node *fp_node = node.FindValue(\"finish_pose\");\n\n #endif\n\n\n\n if(fp_node != NULL){\n\n (*fp_node)[\"pose\"][\"position\"][\"x\"] >> pose.position.x;\n\n (*fp_node)[\"pose\"][\"position\"][\"y\"] >> pose.position.y;\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 41, "score": 3122.3114364395724 }, { "content": " \n\n void publishPoseArray(){\n\n waypoints_.header.stamp = ros::Time::now();\n\n wp_pub_.publish(waypoints_);\n\n }\n\n\n\n void run(){\n\n while(ros::ok()){\n\n try {\n\n if(has_activate_) {\n\n if(current_waypoint_ == last_waypoint_) {\n\n ROS_INFO(\"prepare finish pose\");\n\n } else {\n\n ROS_INFO(\"calculate waypoint direction\");\n\n ROS_INFO_STREAM(\"goal_direction = \" << current_waypoint_->orientation);\n\n ROS_INFO_STREAM(\"current_waypoint_+1 \" << (current_waypoint_+1)->position.y);\n\n ROS_INFO_STREAM(\"current_waypoint_\" << current_waypoint_->position.y);\n\n }\n\n\n\n startNavigationGL(*current_waypoint_);\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 42, "score": 3122.2838218420884 }, { "content": " (*fp_node)[\"pose\"][\"position\"][\"z\"] >> pose.position.z;\n\n\n\n (*fp_node)[\"pose\"][\"orientation\"][\"x\"] >> pose.orientation.x;\n\n (*fp_node)[\"pose\"][\"orientation\"][\"y\"] >> pose.orientation.y;\n\n (*fp_node)[\"pose\"][\"orientation\"][\"z\"] >> pose.orientation.z;\n\n (*fp_node)[\"pose\"][\"orientation\"][\"w\"] >> pose.orientation.w;\n\n\n\n waypoints_.poses.push_back(pose);\n\n\n\n }else{\n\n return false;\n\n }\n\n\n\n }catch(YAML::ParserException &e){\n\n return false;\n\n\n\n }catch(YAML::RepresentationException &e){\n\n return false;\n\n }\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 43, "score": 3121.930039001775 }, { "content": " ofs << \" stamp: \" << finish_pose_.header.stamp << std::endl;\n\n ofs << \" frame_id: \" << finish_pose_.header.frame_id << std::endl;;\n\n ofs << \" pose:\" << std::endl;\n\n ofs << \" position:\" << std::endl;\n\n ofs << \" x: \" << finish_pose_.pose.position.x << std::endl;\n\n ofs << \" y: \" << finish_pose_.pose.position.y << std::endl;\n\n ofs << \" z: \" << finish_pose_.pose.position.z << std::endl;\n\n ofs << \" orientation:\" << std::endl;\n\n ofs << \" x: \" << finish_pose_.pose.orientation.x << std::endl;\n\n ofs << \" y: \" << finish_pose_.pose.orientation.y << std::endl;\n\n ofs << \" z: \" << finish_pose_.pose.orientation.z << std::endl;\n\n ofs << \" w: \" << finish_pose_.pose.orientation.w << std::endl;\n\n\n\n ofs.close();\n\n\n\n ROS_INFO_STREAM(\"write success\");\n\n }\n\n \n\n void run(){\n\n ros::spin();\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 44, "score": 3121.9174528333556 }, { "content": " rate_ = ros::Rate(max_update_rate);\n\n std::string filename = \"\";\n\n private_nh.param(\"filename\", filename, filename);\n\n if(filename != \"\"){\n\n ROS_INFO_STREAM(\"Read waypoints data from \" << filename);\n\n if(!readFile(filename)) {\n\n ROS_ERROR(\"Failed loading waypoints file\");\n\n } else {\n\n last_waypoint_ = waypoints_.poses.end()-2;\n\n finish_pose_ = waypoints_.poses.end()-1;\n\n computeWpOrientation();\n\n }\n\n current_waypoint_ = waypoints_.poses.begin();\n\n } else {\n\n ROS_ERROR(\"waypoints file doesn't have name\");\n\n }\n\n\n\n private_nh.param(\"dist_err\", dist_err_, dist_err_);\n\n \n\n ros::NodeHandle nh;\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 45, "score": 3121.742283654825 }, { "content": " geometry_msgs::PoseArray waypoints_;\n\n std::vector<geometry_msgs::Pose>::iterator current_waypoint_;\n\n std::vector<geometry_msgs::Pose>::iterator last_waypoint_;\n\n std::vector<geometry_msgs::Pose>::iterator finish_pose_;\n\n bool has_activate_;\n\n std::string robot_frame_, world_frame_;\n\n tf::TransformListener tf_listener_;\n\n ros::Rate rate_;\n\n ros::ServiceServer start_server_, suspend_server_, resume_server_;\n\n ros::Subscriber cmd_vel_sub_;\n\n ros::Publisher wp_pub_;\n\n ros::ServiceClient clear_costmaps_srv_;\n\n double last_moved_time_, dist_err_;\n\n\n\n};\n\n\n\nint main(int argc, char *argv[]){\n\n ros::init(argc, argv, ROS_PACKAGE_NAME);\n\n WaypointsNavigation w_nav;\n\n w_nav.run();\n\n\n\n return 0;\n\n}\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 46, "score": 3121.1757157692396 }, { "content": "/*\n\n * Software License Agreement (BSD License)\n\n *\n\n * Copyright (c) 2015, Daiki Maekawa and Chiba Institute of Technology.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions\n\n * are met:\n\n *\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above\n\n * copyright notice, this list of conditions and the following\n\n * disclaimer in the documentation and/or other materials provided\n\n * with the distribution.\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 47, "score": 3120.270976799142 }, { "content": "/*\n\n * Software License Agreement (BSD License)\n\n *\n\n * Copyright (c) 2015, Daiki Maekawa and Chiba Institute of Technology.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions\n\n * are met:\n\n *\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above\n\n * copyright notice, this list of conditions and the following\n\n * disclaimer in the documentation and/or other materials provided\n\n * with the distribution.\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 48, "score": 3120.270976799142 }, { "content": " start_server_ = nh.advertiseService(\"start_wp_nav\", &WaypointsNavigation::startNavigationCallback, this);\n\n suspend_server_ = nh.advertiseService(\"suspend_wp_pose\", &WaypointsNavigation::suspendPoseCallback, this);\n\n resume_server_ = nh.advertiseService(\"resume_wp_pose\", &WaypointsNavigation::resumePoseCallback, this);\n\n cmd_vel_sub_ = nh.subscribe(\"icart_mini/cmd_vel\", 1, &WaypointsNavigation::cmdVelCallback, this);\n\n wp_pub_ = nh.advertise<geometry_msgs::PoseArray>(\"waypoints\", 10);\n\n clear_costmaps_srv_ = nh.serviceClient<std_srvs::Empty>(\"/move_base/clear_costmaps\");\n\n }\n\n\n\n bool startNavigationCallback(std_srvs::Trigger::Request &request, std_srvs::Trigger::Response &response) {\n\n if(has_activate_) {\n\n response.success = false;\n\n return false;\n\n }\n\n \n\n std_srvs::Empty empty;\n\n while(!clear_costmaps_srv_.call(empty)) {\n\n ROS_WARN(\"Resend clear costmap service\");\n\n sleep();\n\n }\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 49, "score": 3119.9351118991194 }, { "content": " sleep();\n\n }\n\n\n\n current_waypoint_++;\n\n if(current_waypoint_ == finish_pose_) {\n\n startNavigationGL(*current_waypoint_);\n\n while(!navigationFinished() && ros::ok()) sleep();\n\n has_activate_ = false;\n\n }\n\n }\n\n } catch(const SwitchRunningStatus &e) {\n\n ROS_INFO_STREAM(\"running status switched\");\n\n }\n\n\n\n sleep();\n\n }\n\n }\n\n\n\nprivate:\n\n actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 50, "score": 3118.8948229668176 }, { "content": " int resend_goal = 0;\n\n double start_nav_time = ros::Time::now().toSec();\n\n while(!onNavigationPoint(current_waypoint_->position, dist_err_)) {\n\n if(!has_activate_)\n\n throw SwitchRunningStatus();\n\n \n\n double time = ros::Time::now().toSec();\n\n if(time - start_nav_time > 10.0 && time - last_moved_time_ > 10.0) {\n\n ROS_WARN(\"Resend the navigation goal.\");\n\n std_srvs::Empty empty;\n\n clear_costmaps_srv_.call(empty);\n\n startNavigationGL(*current_waypoint_);\n\n resend_goal++;\n\n if(resend_goal == 3) {\n\n ROS_WARN(\"Skip waypoint.\");\n\n current_waypoint_++;\n\n startNavigationGL(*current_waypoint_);\n\n }\n\n start_nav_time = time;\n\n }\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 51, "score": 3118.8948229668176 }, { "content": "class PathSimilarity {\n\npublic:\n\n PathSimilarity(ros::NodeHandle &nh) : \n\n path_markers_pub_(nh.advertise<visualization_msgs::MarkerArray>(\"path_markers\", 10)),\n\n path_a_sub_(nh.subscribe(\"path_a\", 1, &PathSimilarity::pathACallback, this)),\n\n path_b_sub_(nh.subscribe(\"path_b\", 1, &PathSimilarity::pathBCallback, this))\n\n {\n\n\n\n }\n\n\n\n void spin() {\n\n ros::Rate r(100);\n\n while(ros::ok()) {\n\n ros::spinOnce();\n\n visualization_msgs::MarkerArray viz_markers;\n\n int marker_id = 0;\n\n \n\n for(auto pose_a : path_a_.poses) {\n\n double pose_len = get_distance(std::begin(path_a_.poses)->pose.position, pose_a.pose.position);\n\n for(auto pose_b : path_b_.poses) {\n", "file_path": "fulanghua_evaluator/src/path_similarity.cpp", "rank": 52, "score": 2963.782104065457 }, { "content": "class WaypointsSaver{\n\npublic:\n\n WaypointsSaver() : \n\n filename_(\"waypoints.yaml\")\n\n {\n\n waypoints_viz_sub_ = nh_.subscribe(\"waypoints_viz\", 1, &WaypointsSaver::waypointsVizCallback, this);\n\n waypoints_joy_sub_ = nh_.subscribe(\"waypoints_joy\", 1, &WaypointsSaver::waypointsJoyCallback, this);\n\n finish_pose_sub_ = nh_.subscribe(\"finish_pose\", 1, &WaypointsSaver::finishPoseCallback, this);\n\n\n\n ros::NodeHandle private_nh(\"~\");\n\n private_nh.param(\"filename\", filename_, filename_);\n\n private_nh.param(\"save_joy_button\", save_joy_button_, 0);\n\n private_nh.param(\"robot_frame\", robot_frame_, std::string(\"/base_link\"));\n\n private_nh.param(\"world_frame\", world_frame_, std::string(\"/map\"));\n\n }\n\n\n\n void waypointsJoyCallback(const sensor_msgs::Joy &msg){\n\n static ros::Time saved_time(0.0);\n\n //ROS_INFO_STREAM(\"joy = \" << msg);\n\n if(msg.buttons[save_joy_button_] == 1 && (ros::Time::now() - saved_time).toSec() > 3.0){\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_saver.cpp", "rank": 53, "score": 2823.3669417563115 }, { "content": "class WaypointsNavigation{\n\npublic:\n\n WaypointsNavigation() :\n\n has_activate_(false),\n\n move_base_action_(\"move_base\", true),\n\n rate_(10),\n\n last_moved_time_(0),\n\n dist_err_(0.8)\n\n {\n\n while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))\n\n {\n\n ROS_INFO(\"Waiting...\");\n\n }\n\n \n\n ros::NodeHandle private_nh(\"~\");\n\n private_nh.param(\"robot_frame\", robot_frame_, std::string(\"/base_link\"));\n\n private_nh.param(\"world_frame\", world_frame_, std::string(\"/map\"));\n\n \n\n double max_update_rate;\n\n private_nh.param(\"max_update_rate\", max_update_rate, 10.0);\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 54, "score": 2823.3669417563115 }, { "content": "class SwitchRunningStatus : public std::exception {\n\npublic:\n\n SwitchRunningStatus() : std::exception() { }\n\n};\n\n\n", "file_path": "fulanghua_waypoints_nav/src/waypoints_nav.cpp", "rank": 55, "score": 2373.5584437868943 }, { "content": "# fulanghua_navigation [![Build Status](https://travis-ci.org/open-rdc/fulanghua_navigation.svg?branch=indigo-devel)](https://travis-ci.org/open-rdc/fulanghua_navigation)\n\n\n\n![](docs/fulanghua_icon.jpg)\n\n\n\n## About\n\n\n\nfulanghua_navigation provides mobile robot navigation tools on ros.\n\n\n\n### [Waypoints Navigation](fulanghua_waypoints_nav/)\n\n\n\n### [Static Path Publisher](fulanghua_static_path_publisher/)\n\n\n\n![](docs/lissajous_curve.png)\n\n\n\n![](docs/astroid_curve.png)\n\n\n\n### [Pose Estimation by using EKF for a ground vehicle](fulanghua_ekf_2d/)\n\n\n\n### [Evaluation Tools](fulanghua_evaluator/)\n\n\n\n## Requirements\n\n\n\nInstall dependencies (listed in the package.xml and CMakeLists.txt file) using rosdep:\n\n\n\n```sh\n\n$ rosdep install fulanghua_navigation\n\n```\n\n\n\n## Bugs\n\n\n\nIf you find a bug please let me know by opening an issue at [here](https://github.com/DaikiMaekawa/fulanghua_navigation/issues).\n\n\n\n## License \n\n\n\n![BSD](http://img.shields.io/badge/license-BSD-green.svg)\n\n\n\nCopyright (c) 2014, Daiki Maekawa and Chiba Institute of Technology.\n\n\n\nSee LICENSE for more info.\n", "file_path": "README.md", "rank": 56, "score": 2285.639687147005 } ]
C++
drone_controller/src/proportional_rotate.cpp
MikeS96/autonomous_landing_uav
c402bc38119dfc1e9c09746e8376356ddabde07e
#include <ros/ros.h> #include <stdio.h> #include <math.h> #include "mavros_msgs/PositionTarget.h" #include "object_detector/States.h" #include "drone_controller/Error.h" #define FACTORX 0.0015625 // Vx proportional gain #define FACTORY 0.0020833 // Vy proportional gain #define FACTORTH 0.0055 // Theta proportional gain #define FACTORZ 0.05 // Descend Factor #define MAXV 0.5 // Max Vx and Vy speed #define MINV -0.5 // Min Vx and Vy speed #define MAXR 0.5 // Max Yaw rate #define MINR -0.5 // Min Yaw rate class Controller { private: ros::NodeHandle po_nh; ros::Subscriber sub; ros::Publisher pub; ros::Publisher pub1; ros::Time lastTime; float imageW; float imageH; float zini; public: Controller(ros::NodeHandle ao_nh) : po_nh(ao_nh) { pub = po_nh.advertise<mavros_msgs::PositionTarget>("/mavros/setpoint_raw/local",10) ; pub1 = po_nh.advertise<drone_controller::Error>("/error",10) ; sub = po_nh.subscribe("/predicted_states", 10, &Controller::controllerCallBack, this); lastTime = ros::Time::now(); imageW = 640/2; imageH = 480/2; } void controllerCallBack(const object_detector::States& msg) { float ErX = imageW - msg.Xc; float ErY = imageH - msg.Yc; float ErTheta = msg.Theta; drone_controller::Error er; er.errorX = ErX; er.errorY = ErY; er.errorT = ErTheta; er.errorS = 0; float vx = 0; float vy = 0; float vthe = 0; vy = ErX * FACTORX; vx = ErY * FACTORY; vthe = ErTheta * FACTORTH; max_output(MAXV, MINV, vx); max_output(MAXV, MINV, vy); max_output(MAXR, MINR, vthe); mavros_msgs::PositionTarget pos; pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED; pos.header.stamp = ros::Time::now(); pos.header.frame_id = "base_link"; pos.type_mask = 1987; pos.position.z = 2.0; pos.velocity.x = vx; pos.velocity.y = vy; pos.yaw_rate = vthe; printf("Dany Vx, Vy, Vthe values at (%f,%f,%f) \n", vx, vy, vthe); pub.publish(pos); printf("Error at Vx, Vy and Theta (%f,%f,%f) \n", ErX, ErY, ErTheta); pub1.publish(er); } void max_output(const float& max_v, const float& min_v, float& out) { if (out > max_v) { out = max_v; } else if (out < min_v) { out = min_v; } } }; int main(int argc, char** argv) { ros::init(argc, argv, "trejos_controller_node"); ros::NodeHandle n; Controller cont(n); ros::spin(); return 0; }
#include <ros/ros.h> #include <stdio.h> #include <math.h> #include "mavros_msgs/PositionTarget.h" #include "object_detector/States.h" #include "drone_controller/Error.h" #define FACTORX 0.0015625 // Vx proportional gain #define FACTORY 0.0020833 // Vy proportional gain #define FACTORTH 0.0055 // Theta proportional gain #define FACTORZ 0.05 // Descend Factor #define MAXV 0.5 // Max Vx and Vy speed #define MINV -0.5 // Min Vx and Vy speed #define MAXR 0.5 // Max Yaw rate #define MINR -0.5 // Min Yaw rate class Controller { private: ros::NodeHandle po_nh; ros::Subscriber sub; ros::Publisher pub; ros::Publisher pub1; ros::Time lastTime; float imageW; float imageH; float zini; public: Controller(ros::NodeHandle ao_nh) : po_nh(ao_nh) {
void controllerCallBack(const object_detector::States& msg) { float ErX = imageW - msg.Xc; float ErY = imageH - msg.Yc; float ErTheta = msg.Theta; drone_controller::Error er; er.errorX = ErX; er.errorY = ErY; er.errorT = ErTheta; er.errorS = 0; float vx = 0; float vy = 0; float vthe = 0; vy = ErX * FACTORX; vx = ErY * FACTORY; vthe = ErTheta * FACTORTH; max_output(MAXV, MINV, vx); max_output(MAXV, MINV, vy); max_output(MAXR, MINR, vthe); mavros_msgs::PositionTarget pos; pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED; pos.header.stamp = ros::Time::now(); pos.header.frame_id = "base_link"; pos.type_mask = 1987; pos.position.z = 2.0; pos.velocity.x = vx; pos.velocity.y = vy; pos.yaw_rate = vthe; printf("Dany Vx, Vy, Vthe values at (%f,%f,%f) \n", vx, vy, vthe); pub.publish(pos); printf("Error at Vx, Vy and Theta (%f,%f,%f) \n", ErX, ErY, ErTheta); pub1.publish(er); } void max_output(const float& max_v, const float& min_v, float& out) { if (out > max_v) { out = max_v; } else if (out < min_v) { out = min_v; } } }; int main(int argc, char** argv) { ros::init(argc, argv, "trejos_controller_node"); ros::NodeHandle n; Controller cont(n); ros::spin(); return 0; }
pub = po_nh.advertise<mavros_msgs::PositionTarget>("/mavros/setpoint_raw/local",10) ; pub1 = po_nh.advertise<drone_controller::Error>("/error",10) ; sub = po_nh.subscribe("/predicted_states", 10, &Controller::controllerCallBack, this); lastTime = ros::Time::now(); imageW = 640/2; imageH = 480/2; }
function_block-function_prefix_line
[ { "content": "class Controller // Controller class\n\n{\n\n private: \n\n //Private class atributes\n\n ros::NodeHandle po_nh;\n\n ros::Subscriber sub;\n\n ros::Publisher pub;\n\n ros::Publisher pub1;\n\n ros::Time lastTime;\n\n float imageW; // Image Width\n\n float imageH; // Image Height\n\n float zini; // Initial height pos\n\n\n\n public:\n\n // Public class attributes and methods\n\n Controller(ros::NodeHandle ao_nh) : po_nh(ao_nh) \n\n {\n\n // Publisher type mavros_msgs::PositionTarget, it publishes in /mavros/setpoint_raw/local topic\n\n pub = po_nh.advertise<mavros_msgs::PositionTarget>(\"/mavros/setpoint_raw/local\",10) ; \n\n // Publisher type drone_controller::Error, it publishes in /error topic\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 1, "score": 101527.2541190846 }, { "content": "class Controller \n\n{\n\n private: \n\n //Private class atributes\n\n ros::NodeHandle po_nh;\n\n ros::Subscriber sub;\n\n ros::Publisher pub;\n\n ros::Publisher pub1;\n\n ros::Time lastTime;\n\n ros::ServiceClient land_client;\n\n\n\n float imageW; // Image Width\n\n float imageH; // Image Height\n\n float zini; // Initial height pos\n\n\n\n public: \n\n // Public class attributes and methods\n\n Controller(ros::NodeHandle ao_nh) : po_nh(ao_nh) \n\n {\n\n // Publisher type mavros_msgs::PositionTarget, it publishes in /mavros/setpoint_raw/local topic\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 2, "score": 97345.15323676432 }, { "content": "class PID\n\n{\n\n private:\n\n double max; // max - maximum output value\n\n double min; // min - minimum output value\n\n double kp; // Kp - proportional gain\n\n double kd; // Kd - derivative gain\n\n double ki; // Ki - Integral gain\n\n double pre_error; // Error at (t-1)\n\n double integral; // Integral term\n\n double pre_integral; // Integral term at (t-1)\n\n\n\n public:\n\n // Class constructor\n\n PID(double cmax, double cmin, double ckp, double ckd, double cki);\n\n // Compute PID output\n\n double calculate( double setpoint, double pv, double cdt);\n\n // Class destructor\n\n ~PID();\n\n\n\n \n\n};\n\n\n\n#endif\n", "file_path": "drone_controller/include/drone_controller/pid.h", "rank": 3, "score": 94875.98878652952 }, { "content": "class Controller\n\n{\n\n private: \n\n //Private class atributes\n\n ros::NodeHandle po_nh;\n\n ros::Subscriber sub;\n\n ros::Publisher pub;\n\n ros::Publisher pub1;\n\n ros::Time lastTime;\n\n double imageW;\n\n double imageH;\n\n PID* pidx; // PID objects\n\n PID* pidy;\n\n PID* pidth;\n\n\n\n public:\n\n // Public class attributes and methods\n\n Controller(ros::NodeHandle ao_nh) : po_nh(ao_nh) \n\n {\n\n // PID controllers objects\n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 4, "score": 71525.04279903036 }, { "content": "class Controller\n\n{\n\n\tprivate: \n\n\t\t//Private class atributes\n\n\t\tros::NodeHandle po_nh;\n\n\t\tros::Subscriber sub;\n\n\t\tros::Publisher pub;\n\n\t\tros::Publisher pub1;\n\n\t\tros::Time lastTime;\n\n\t\tros::ServiceClient land_client;\n\n\t\tfloat imageW; // Image Width\n\n float imageH; // Image Height\n\n float zini; // Initial height pos\n\n PID* pidx; // PID objects\n\n PID* pidy;\n\n PID* pidth;\n\n\n\n\tpublic:\n\n\t\t// Public class attributes and methods\n\n\t\tController(ros::NodeHandle ao_nh) : po_nh(ao_nh)\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 5, "score": 71525.04279903036 }, { "content": "class Controller\n\n{\n\n\tprivate: \n\n\t\t//Private class atributes\n\n\t\tros::NodeHandle po_nh;\n\n\t\tros::Subscriber sub;\n\n\t\tros::Publisher pub;\n\n\t\tros::Publisher pub1;\n\n\t\tros::Time lastTime;\n\n\t\tfloat imageW; // Image Width\n\n float imageH; // Image Height\n\n PID* pidx; // PID objects\n\n PID* pidy;\n\n\n\n\n\n\tpublic:\n\n\t\t// Public class attributes and methods\n\n\t\tController(ros::NodeHandle ao_nh) : po_nh(ao_nh)\n\n\t\t{\n\n\t\t\t// PID controllers objects\n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 6, "score": 71525.04279903036 }, { "content": "/**\n\n * @file pid.h\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief PID controller header files\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "drone_controller/include/drone_controller/pid.h", "rank": 7, "score": 56703.05361104437 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n\n\n#ifndef PID_H\n\n#define PID_H\n\n\n", "file_path": "drone_controller/include/drone_controller/pid.h", "rank": 8, "score": 56701.0718885463 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n#include \"mavros_msgs/PositionTarget.h\" // Mavros topic to control vel and pos\n\n#include \"object_detector/States.h\" // Custom msgs of type States\n\n#include \"drone_controller/Error.h\" // Custom msgs of type Error\n\n#include <mavros_msgs/CommandTOL.h> // Service for landing\n\n\n\n\n\n#define FACTOR 0.003125 // Vx and Vy proportional gain\n\n#define FACTORTH 0.0055 // Theta proportional gain\n\n#define FACTORZ 0.05 // Descend Factor\n\n#define MAXV 1 // Max Vx and Vy speed\n\n#define MINV -1 // Min Vx and Vy speed\n\n#define MAXR 0.5 // Max Yaw rate\n\n#define MINR -0.5 // Min Yaw rate\n\n\n\n\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 9, "score": 55676.356743269076 }, { "content": " // Publish the service of landing\n\n ROS_INFO(\"Landing\"); \n\n // Print final Error\n\n printf(\"Error at Vx, Vy, Theta and Z are (%f,%f,%f,%f) \\n\", ErX, ErY, ErTheta, ErZ);\n\n pub1.publish(er);\n\n ros::shutdown(); // Shutdowm the node\n\n }\n\n }\n\n\n\n // Update vehicle's position\n\n zini = zpos; \n\n\n\n // Calculate proportional gain for each axis\n\n vy = ErX * FACTOR; \n\n vx = ErY * FACTOR; \n\n vthe = ErTheta * FACTORTH;\n\n\n\n // Limit output \n\n max_output(MAXV, MINV, vx); // Limit max Vx output\n\n max_output(MAXV, MINV, vy); // Limit max Vy output\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 10, "score": 55663.42429428311 }, { "content": " max_output(MAXR, MINR, vthe); // Limit max Vtheta output\n\n\n\n // Position target object to publish\n\n mavros_msgs::PositionTarget pos;\n\n\n\n //FRAME_LOCAL_NED to move WRT to body_ned frame\n\n pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED; \n\n\n\n pos.header.stamp = ros::Time::now(); // Time header stamp\n\n pos.header.frame_id = \"base_link\"; // \"base_link\" frame to compute odom\n\n pos.type_mask = 1987; // Mask for Vx, Vy, Z pos and Yaw rate\n\n pos.position.z = zpos;\n\n pos.velocity.x = vx;\n\n pos.velocity.y = vy;\n\n pos.yaw_rate = vthe;\n\n\n\n printf(\"Proportional Vx, Vy, Vthe and Zpos values at (%f,%f,%f,%f) \\n\", vx, vy, vthe, zpos);\n\n pub.publish(pos);\n\n\n\n printf(\"Error at Vx, Vy, Theta and Z are (%f,%f,%f,%f) \\n\", ErX, ErY, ErTheta, ErZ);\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 11, "score": 55654.37196236448 }, { "content": " pub1.publish(er);\n\n }\n\n\n\n /**\n\n * Limit the max output of the controller\n\n *\n\n *\n\n * @param max_v max output value\n\n * @param min_v min output value\n\n * @param out controller output\n\n */\n\n void max_output(const float& max_v, const float& min_v, float& out) \n\n {\n\n if (out > max_v)\n\n {\n\n out = max_v;\n\n } \n\n else if (out < min_v)\n\n {\n\n out = min_v;\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 12, "score": 55648.76884854716 }, { "content": " if(ErZ < 3)\n\n {\n\n zpos = zini - FACTORZ; // Descend Z based on the factor \n\n }\n\n else{\n\n zpos = zini; // If there is more than 3 pixels of error, hold pos\n\n }\n\n\n\n // Drone service for automatic langind when it reaches an specific altitude\n\n if(zpos <= 0.9)\n\n { \n\n mavros_msgs::CommandTOL land_cmd; // Set all the descend parameters to Zero\n\n land_cmd.request.yaw = 0;\n\n land_cmd.request.latitude = 0;\n\n land_cmd.request.longitude = 0;\n\n land_cmd.request.altitude = 0;\n\n\n\n // When it lands, everything goes to zero\n\n if (!(land_client.call(land_cmd) && land_cmd.response.success))\n\n { \n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 13, "score": 55643.70237857524 }, { "content": " // Error Calculation between image and template's center\n\n float ErX = imageW - msg.Xc; // Error in X of the image\n\n float ErY = imageH - msg.Yc; //Error in Y of the image\n\n float ErTheta = msg.Theta; // Error in Theta of the image\n\n float ErZ = abs(msg.W - msg.H); //Error in W and H of the images\n\n\n\n // Publish the error\n\n drone_controller::Error er;\n\n er.errorX = ErX;\n\n er.errorY = ErY;\n\n er.errorT = ErTheta;\n\n er.errorS = ErZ;\n\n\n\n // Variables to be published (Initialized in 0)\n\n float vx = 0;\n\n float vy = 0;\n\n float vthe = 0;\n\n float zpos = 0;\t\n\n\n\n // If the erroe between width and height is less than 3 pixels\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 14, "score": 55643.700864003884 }, { "content": " pub = po_nh.advertise<mavros_msgs::PositionTarget>(\"/mavros/setpoint_raw/local\",10) ; \n\n // Publisher type drone_controller::Error, it publishes in /error topic\n\n pub1 = po_nh.advertise<drone_controller::Error>(\"/error\",10) ;\n\n // Subscriber to /predicted_states topic from object_detector/Corners\n\n sub = po_nh.subscribe(\"/predicted_states\", 10, &Controller::controllerCallBack, this); \n\n // Landing client\n\n land_client = po_nh.serviceClient<mavros_msgs::CommandTOL>(\"mavros/cmd/land\");\n\n lastTime = ros::Time::now(); // ROS time initialization throw ros time\n\n imageW = 640/2; // Setpoint in X\n\n imageH = 480/2; // Setpoint in Y\n\n zini = 4.0; // Initial alttitude\n\n }\n\n\n\n // Subscriber callback\n\n void controllerCallBack(const object_detector::States& msg) \n\n {\n\n // Time since last call\n\n // double timeBetweenMarkers = (ros::Time::now() - lastTime).toSec(); //The average publish time is of 10ms\n\n // lastTime = ros::Time::now();\n\n\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 15, "score": 55640.909704277816 }, { "content": "/**\n\n * @file proportional_controller.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief Proportional controller to land the vehicle on the landing pad\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 16, "score": 55639.17493046559 }, { "content": " }\n\n }\n\n};\n\n\n\n\n\nint main(int argc, char** argv)\n\n{ \n\n\n\n ros::init(argc, argv, \"p_controller\"); \n\n ros::NodeHandle n;\n\n Controller cont(n);\n\n ros::spin();\n\n\n\n return 0;\n\n}\n\n\n\n\n", "file_path": "drone_controller/src/proportional_controller.cpp", "rank": 17, "score": 55634.64926685991 }, { "content": " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n\n\n#include <ros/ros.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n#include \"mavros_msgs/PositionTarget.h\" // Mavros topic to control vel and pos\n\n#include \"object_detector/States.h\" // Custom msgs of type States\n\n#include \"drone_controller/Error.h\" // Custom msgs of type Error\n\n\n\n#define FACTORX 0.00234375 // Vx proportional gain\n\n#define FACTORY 0.003125 // Vy proportional gain\n\n#define MAXV 0.75 // Max Vx and Vy speed\n\n#define MINV -0.75 // Min Vx and Vy speed\n\n\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 20, "score": 48683.048183039704 }, { "content": " er.errorX = ErX;\n\n er.errorY = ErY;\n\n er.errorT = 0;\n\n er.errorS = 0;\n\n\n\n // Variables to be published (Initialized in 0)\n\n float vx = 0;\n\n float vy = 0;\n\n\n\n // Calculate proportional gain for x and y\n\n vy = ErX * FACTORX; \n\n vx = ErY * FACTORY; \n\n\n\n max_output(MAXV, MINV, vx); // Limit max Vx output\n\n max_output(MAXV, MINV, vy); // Limit max Vy output\n\n\n\n // Position target object to publish\n\n mavros_msgs::PositionTarget pos;\n\n\n\n //FRAME_LOCAL_NED to move WRT to body_ned frame\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 21, "score": 48679.145318970666 }, { "content": " pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED; \n\n\n\n pos.header.stamp = ros::Time::now(); // Time header stamp\n\n pos.header.frame_id = \"base_link\"; // \"base_link\" frame to compute odom\n\n pos.type_mask = 1987; // Mask for Vx, Vy, Z pos and Yaw rate\n\n pos.position.z = 2.0;\n\n pos.velocity.x = vx;\n\n pos.velocity.y = vy;\n\n pos.yaw_rate = 0;\n\n\n\n printf(\"Proportional Vx, Vy at (%f,%f) \\n\", vx, vy);\n\n pub.publish(pos);\n\n\n\n printf(\"Error at Vx and Vy (%f,%f) \\n\", ErX, ErY);\n\n pub1.publish(er);\n\n }\n\n\n\n /**\n\n * Limit the max output of the controller\n\n *\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 22, "score": 48674.16025167681 }, { "content": " *\n\n * @param max_v max output value\n\n * @param min_v min output value\n\n * @param out controller output\n\n */\n\n void max_output(const float& max_v, const float& min_v, float& out) \n\n {\n\n if (out > max_v)\n\n {\n\n out = max_v;\n\n } \n\n else if (out < min_v)\n\n {\n\n out = min_v;\n\n }\n\n }\n\n};\n\n\n\n\n\nint main(int argc, char** argv)\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 25, "score": 48666.074478422845 }, { "content": " pub1 = po_nh.advertise<drone_controller::Error>(\"/error\",10) ;\n\n // Subscriber to /predicted_states topic from object_detector/Corners\n\n sub = po_nh.subscribe(\"/predicted_states\", 10, &Controller::controllerCallBack, this);\n\n lastTime = ros::Time::now(); // ROS time initialization throw ros time\n\n imageW = 640/2; // Setpoint in X\n\n imageH = 480/2; // Setpoint in Y\n\n }\n\n\n\n void controllerCallBack(const object_detector::States msg) //Callback para el subscriber\n\n {\n\n // Time since last call\n\n // double timeBetweenMarkers = (ros::Time::now() - lastTime).toSec(); //The average publish time is of 10ms\n\n // lastTime = ros::Time::now();\n\n\n\n // Error Calculation between image and template's center\n\n float ErX = imageW - msg.Xc; // Error in X of the image\n\n float ErY = imageH - msg.Yc; //Error in Y of the image\n\n\n\n // Publish the error\n\n drone_controller::Error er;\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 27, "score": 48660.76971619526 }, { "content": "/**\n\n * @file proportional_traslation.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief Proportional controller to move the vehicle towards the center of the \n\n * landing platform\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 28, "score": 48659.17881451959 }, { "content": "{ \n\n\n\n ros::init(argc, argv, \"p_traslation\"); \n\n ros::NodeHandle n;\n\n Controller cont(n);\n\n ros::spin();\n\n\n\n return 0;\n\n}\n\n\n", "file_path": "drone_controller/src/proportional_traslation.cpp", "rank": 31, "score": 48654.811139152815 }, { "content": "class States\n\n{\n\n\n\n\tprivate: \n\n\t\t// Private class attributes\n\n\t\tros::NodeHandle po_nh;\n\n\t\tros::Subscriber sub;\n\n\t\tros::Publisher pub;\n\n\n\n\n\n\tpublic:\n\n\t\t// Public class attributes and methods\n\n\t\tStates(ros::NodeHandle ao_nh) : po_nh( ao_nh )\n\n\t\t{\n\n\t\t\t// Publisher type object_detector::States, it publishes in /states topic\n\n\t\t\tpub = po_nh.advertise<object_detector::States>( \"/states\", 10) ; \n\n\t\t\t// Subscriber to /corners topic from object_detector/Corners\n\n\t\t\tsub = po_nh.subscribe(\"/corners\", 10, &States::centCalculator, this); \n\n\t\t}\n\n\n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 32, "score": 40061.21624896393 }, { "content": "class Kalman\n\n{\n\n private:\n\n // Private class attributes\n\n ros::NodeHandle po_nh;\n\n ros::Subscriber sub;\n\n ros::Publisher pub;\n\n\n\n MatrixXd T; // Posteriori estimate covariance matrix\n\n MatrixXd Q; // Covariance of the process noise\n\n MatrixXd R; // Covariance of the observation noise\n\n MatrixXd A; // State transition matrix\n\n MatrixXd H; // Observation model\n\n MatrixXd X; // State vector\n\n MatrixXd Z; // Innovation vectot\n\n MatrixXd S1; // Covariance of the innovation\n\n MatrixXd Kg; // Kalman gain\n\n float dt; // Delta of time\n\n int first_iter; // variable to check the first iteration of the algorithm\n\n\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 33, "score": 40061.21624896393 }, { "content": "class Drawer \n\n{\n\n private:\n\n ros::NodeHandle nh_; \n\n image_transport::ImageTransport it_; \n\n image_transport::Subscriber image_sub_;\n\n image_transport::Publisher image_pub_; \n\n ros::Subscriber sub;\n\n float data[5];\n\n \n\n public: \n\n Drawer() : it_(nh_), data()\n\n {\n\n // Subscriber to /image_raw topic\n\n image_sub_ = it_.subscribe(\"/quad_f450_camera/camera_link/raw_image\", 10, \n\n &Drawer::imageCb, this);\n\n // Subscriber to /predicted_states topic from object_detector/States\n\n sub = nh_.subscribe(\"/predicted_states\", 10, &Drawer::estimationsDetectedCallback, this); \n\n // Publisher type sensor_msgs, it publishes in /rectangle_draw/raw_image topic\n\n image_pub_ = it_.advertise(\"/rectangle_draw/raw_image\", 10); \n", "file_path": "object_detector/src/plot_estimation.cpp", "rank": 34, "score": 40061.21624896393 }, { "content": "class Detections\n\n{\n\n\n\n\tprivate: \n\n\t \t// Private class attributes\n\n\t\tros::NodeHandle po_nh;\n\n\t\tros::Subscriber sub;\n\n\t\tros::Publisher pub;\n\n\n\n\tpublic:\n\n\t\t// Public class attributes and methods\n\n\t\tDetections(ros::NodeHandle ao_nh) : po_nh( ao_nh )\n\n\t\t{\n\n\t\t\t// Publisher type object_detector::corners, it publishes in /corners topic\n\n\t\t\tpub = po_nh.advertise<object_detector::Corners>( \"/corners\", 10 ) ; \n\n\t\t\t// Subscriber to /objects topic from find_object_2d/ObjectsStamped\n\n\t\t\tsub = po_nh.subscribe(\"/objects\", 10, &Detections::cornersDetectedCallback, this); \n\n\t\t}\n\n\n\n\t\t// Subscriber callback\n", "file_path": "object_detector/src/corners_detector.cpp", "rank": 35, "score": 40061.21624896393 }, { "content": " // Compute controller output for each axis\n\n\t\t\tVy = (float) pidx->calculate(imageW, msg.Xc, timeBetweenMarkers); // Setpoint, Process Variable, Sample time for Vx\n\n\t\t\tVx = (float) pidy->calculate(imageH, msg.Yc, timeBetweenMarkers); \n\n\t\t\tVthe = (float) pidth->calculate(0, msg.Theta, timeBetweenMarkers);\n\n\n\n\t\t\t// Position target object to publish\n\n mavros_msgs::PositionTarget pos;\n\n\n\n\t\t\t//FRAME_LOCAL_NED to move WRT to body_ned frame\n\n pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED; \n\n\n\n\t\t\tpos.header.stamp = ros::Time::now(); // Time header stamp\n\n\t\t\tpos.header.frame_id = \"base_link\"; // \"base_link\" frame to compute odom\n\n\t\t\tpos.type_mask = 1987; // Mask for Vx, Vy, Z pos and Yaw rate\n\n\t\t\tpos.position.z = zpos;\n\n\t\t\tpos.velocity.x = Vx;\n\n\t\t\tpos.velocity.y = Vy;\n\n\t\t\tpos.yaw_rate = Vthe;\n\n\n\n\t\t\tprintf(\"PID Vx, Vy and Zpos values at (%f,%f, %f) \\n\", Vx, Vy, zpos);\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 36, "score": 29608.2572948443 }, { "content": " printf(\"PID Vx and Vy values at (%f,%f) \\n\", Vx, Vy);\n\n pub.publish(pos);\n\n\n\n\n\n printf(\"Error at Vx, Vy and Theta are (%f,%f,%f) \\n\", ErX, ErY, ErTheta);\n\n pub1.publish(er);\n\n }\n\n};\n\n\n\nint main(int argc, char** argv)\n\n{ \n\n\n\n ros::init(argc, argv, \"controller_node\"); //Nombre del nodo que uso para suscribirme y publicar la info\n\n ros::NodeHandle n;\n\n Controller cont(n);\n\n\n\n\n\n ros::spin();\n\n\n\n return 0;\n\n}\n\n\n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 37, "score": 29607.965451862387 }, { "content": "\n\n // Compute controller output for each axis\n\n Vy = (float) pidx->calculate(imageW, msg.Xc, timeBetweenMarkers); // Setpoint, Process Variable, Sample time for Vx\n\n Vx = (float) pidy->calculate(imageH, msg.Yc, timeBetweenMarkers); \n\n Vthe = (float) pidth->calculate(0, msg.Theta, timeBetweenMarkers);\n\n\n\n // Position target object to publish\n\n mavros_msgs::PositionTarget pos;\n\n\n\n //FRAME_LOCAL_NED to move WRT to body_ned frame\n\n pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED;\n\n\n\n pos.header.stamp = ros::Time::now(); // Time header stamp\n\n pos.header.frame_id = \"base_link\"; // \"base_link\" frame to compute odom\n\n pos.type_mask = 1987; // Mask for Vx, Vy, Z pos and Yaw rate\n\n pos.position.z = 2.0f;\n\n pos.velocity.x = Vx;\n\n pos.velocity.y = Vy;\n\n pos.yaw_rate = Vthe;\n\n\n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 38, "score": 29607.941189107005 }, { "content": "\t\t\tpub.publish(pos);\n\n\n\n\t\t\tprintf(\"Error at Vx, Vy, Theta and Z are (%f,%f,%f,%f) \\n\", ErX, ErY, ErTheta, ErZ);\n\n\t\t\tpub1.publish(er);\n\n\t\t}\n\n\n\n};\n\n\n\n\n\nint main(int argc, char** argv)\n\n{ \n\n ros::init(argc, argv, \"controller_node\"); \n\n ros::NodeHandle n;\n\n Controller cont(n);\n\n ros::spin();\n\n\n\n return 0;\n\n}\n\n\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 39, "score": 29607.012343581115 }, { "content": " mavros_msgs::PositionTarget pos;\n\n\n\n\t\t\t//FRAME_LOCAL_NED to move WRT to body_ned frame\n\n pos.coordinate_frame = mavros_msgs::PositionTarget::FRAME_BODY_NED;\n\n\n\n\t\t\tpos.header.stamp = ros::Time::now(); // Time header stamp\n\n\t\t\tpos.header.frame_id = \"base_link\"; // \"base_link\" frame to compute odom\n\n\t\t\tpos.type_mask = 1987; // Mask for Vx, Vy, Z pos and Yaw rate\n\n\t\t\tpos.position.z = 2.0f;\n\n\t\t\tpos.velocity.x = Vx;\n\n\t\t\tpos.velocity.y = Vy;\n\n\t\t\tpos.yaw_rate = 0;\n\n\n\n\t\t\tprintf(\"PID Vx and Vy values at (%f,%f) \\n\", Vx, Vy);\n\n\t\t\tpub.publish(pos);\n\n\n\n\t\t\tprintf(\"Error at Vx and Vy are (%f,%f) \\n\", ErX, ErY);\n\n\t\t\tpub1.publish(er);\n\n\t\t}\n\n};\n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 40, "score": 29606.999980370263 }, { "content": "\t\t\tpidx = new PID(0.75, -0.75, 0.00234375, 0.00046875, 0.0); // max, min, kp, kd, ki\n\n\t\t\tpidy = new PID(0.75, -0.75, 0.003125, 0.000625, 0.0);\n\n\t\t\t// Publisher type mavros_msgs::PositionTarget, it publishes in /mavros/setpoint_raw/local topic\n\n pub = po_nh.advertise<mavros_msgs::PositionTarget>(\"/mavros/setpoint_raw/local\",10) ; \n\n // Publisher type drone_controller::Error, it publishes in /error topic\n\n pub1 = po_nh.advertise<drone_controller::Error>(\"/error\",10) ;\n\n // Subscriber to /predicted_states topic from object_detector/Corners\n\n sub = po_nh.subscribe(\"/predicted_states\", 10, &Controller::controllerCallBack, this); \n\n\t\t\tlastTime = ros::Time::now(); // ROS time initialization throw ros time\n\n imageW = 640/2; // Setpoint in X\n\n imageH = 480/2; // Setpoint in Y\n\n\t\t}\n\n\n\n\t\tvoid controllerCallBack(const object_detector::States& msg) //Callback para el subscriber\n\n\t\t{\n\n\t\t\t// Error Calculation between image and template's center\n\n float ErX = imageW - msg.Xc; // Error in X of the image\n\n float ErY = imageH - msg.Yc; //Error in Y of the image\n\n\n\n // Publish the error\n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 41, "score": 29604.05099661713 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n#include \"mavros_msgs/PositionTarget.h\"\n\n#include \"object_detector/States.h\" // Custom msgs of type States\n\n#include \"drone_controller/Error.h\" // Custom msgs of type Error\n\n#include \"drone_controller/pid.h\"\n\n#include <mavros_msgs/CommandTOL.h> // Service for landing\n\n\n\n#define FACTORZ 0.025 // Descend Factor\n\n\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 42, "score": 29603.755310552875 }, { "content": "\t\t{\n\n\t\t\t// PID controllers objects\n\n\t\t\tpidx = new PID(0.75, -0.75, 0.005, 0.0008, 0.00005); // max, min, kp, kd, ki\n\n\t\t\tpidy = new PID(0.75, -0.75, 0.006, 0.00085, 0.00006);\n\n\t\t\tpidth = new PID(0.35, -0.35, 0.004, 0.0005, 0.00001);\n\n\t\t\t// Publisher type mavros_msgs::PositionTarget, it publishes in /mavros/setpoint_raw/local topic\n\n pub = po_nh.advertise<mavros_msgs::PositionTarget>(\"/mavros/setpoint_raw/local\",10) ; \n\n // Publisher type drone_controller::Error, it publishes in /error topic\n\n pub1 = po_nh.advertise<drone_controller::Error>(\"/error\",10) ;\n\n // Subscriber to /predicted_states topic from object_detector/Corners\n\n sub = po_nh.subscribe(\"/predicted_states\", 10, &Controller::controllerCallBack, this); \n\n // Landing client\n\n land_client = po_nh.serviceClient<mavros_msgs::CommandTOL>(\"mavros/cmd/land\");\n\n\t\t\tlastTime = ros::Time::now(); // ROS time initialization throw ros time\n\n imageW = 640/2; // Setpoint in X\n\n imageH = 480/2; // Setpoint in Y\n\n zini = 3.5; // Initial alttitude\n\n\t\t}\n\n\n\n\t\tvoid controllerCallBack(const object_detector::States& msg) //Callback para el subscriber\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 43, "score": 29603.68676282671 }, { "content": "\t\t{\n\n // Error Calculation between image and template's center\n\n float ErX = imageW - msg.Xc; // Error in X of the image\n\n float ErY = imageH - msg.Yc; //Error in Y of the image\n\n float ErTheta = msg.Theta; // Error in Theta of the image\n\n float ErZ = abs(msg.W - msg.H); //Error in W and H of the images\n\n\n\n // Publish the error\n\n drone_controller::Error er;\n\n er.errorX = ErX;\n\n er.errorY = ErY;\n\n er.errorT = ErTheta;\n\n er.errorS = ErZ;\n\n\n\n // Variables to be published (Initialized in 0)\n\n float Vx = 0;\n\n float Vy = 0;\n\n float Vthe = 0;\n\n float zpos = 0;\t\n\n\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 44, "score": 29603.67023283033 }, { "content": " // Error Calculation between image and template's center\n\n float ErX = imageW - msg.Xc; // Error in X of the image\n\n float ErY = imageH - msg.Yc; //Error in Y of the image\n\n float ErTheta = msg.Theta; // Error in Theta of the image\n\n\n\n // Publish the error\n\n drone_controller::Error er;\n\n er.errorX = ErX;\n\n er.errorY = ErY;\n\n er.errorT = ErTheta;\n\n er.errorS = 0;\n\n\n\n //Velocities\n\n float Vx = 0;\n\n float Vy = 0;\n\n float Vthe = 0;\n\n\n\n // Time since last call\n\n double timeBetweenMarkers = (ros::Time::now() - lastTime).toSec();\n\n lastTime = ros::Time::now();\n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 45, "score": 29603.486067599824 }, { "content": "\t\t\t\tland_cmd.request.yaw = 0;\n\n\t\t\t\tland_cmd.request.latitude = 0;\n\n\t\t\t\tland_cmd.request.longitude = 0;\n\n\t\t\t\tland_cmd.request.altitude = 0;\n\n\n\n\t\t\t\t//When it lands, everything goes to zero\n\n\t\t\t\tif (!(land_client.call(land_cmd) && land_cmd.response.success))\n\n\t\t\t\t{\n\n\t\t\t\t\t// Publish the service of landing\n\n\t\t\t\t\tROS_INFO(\"Landing\");\n\n\t\t\t\t\t// Print final Error\n\n\t\t\t\t\tprintf(\"Error at Vx, Vy, Theta and Z are (%f,%f,%f,%f) \\n\", er.errorX, er.errorY, er.errorT, er.errorS);\n\n\t\t\t\t\tpub1.publish(er);\n\n\t\t\t\t\tros::shutdown(); // Shutdowm the node\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\t// Update vehicle's position\n\n zini = zpos; \n\n\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 46, "score": 29603.313579778518 }, { "content": " drone_controller::Error er;\n\n er.errorX = ErX;\n\n er.errorY = ErY;\n\n er.errorT = 0;\n\n er.errorS = 0;\n\n\n\n // Variables to be published (Initialized in 0)\n\n float Vx = 0;\n\n float Vy = 0;\n\n float Vthe = 0;\n\n\n\n // Time since last call\n\n\t\t\tdouble timeBetweenMarkers = (ros::Time::now() - lastTime).toSec();\n\n\t\t\tlastTime = ros::Time::now();\n\n\n\n\t\t\t// Compute controller output for each axis\n\n\t\t\tVy = (float) pidx->calculate(imageW, msg.Xc, timeBetweenMarkers); // Setpoint, Process Variable, Sample time for Vx\n\n\t\t\tVx = (float) pidy->calculate(imageH, msg.Yc, timeBetweenMarkers); \n\n\n\n\t\t\t// Position target object to publish\n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 47, "score": 29602.82518603689 }, { "content": " pidx = new PID(0.75, -0.75, 0.00234375, 0.00046875, 0.0); // max, min, kp, kd, ki\n\n pidy = new PID(0.75, -0.75, 0.003125, 0.000625, 0.0);\n\n pidth = new PID(0.5, -0.5, 0.0055, 0.0011, 0.0);\n\n // Publisher type mavros_msgs::PositionTarget, it publishes in /mavros/setpoint_raw/local topic\n\n pub = po_nh.advertise<mavros_msgs::PositionTarget>(\"/mavros/setpoint_raw/local\",10) ; \n\n // Publisher type drone_controller::Error, it publishes in /error topic\n\n pub1 = po_nh.advertise<drone_controller::Error>(\"/error\",10) ;\n\n // Subscriber to /predicted_states topic from object_detector/Corners\n\n sub = po_nh.subscribe(\"/predicted_states\", 10, &Controller::controllerCallBack, this); \n\n lastTime = ros::Time::now(); // ROS time initialization throw ros time\n\n imageW = 640/2; // Setpoint in X\n\n imageH = 480/2; // Setpoint in Y\n\n }\n\n\n\n void controllerCallBack(const object_detector::States& msg) //Callback para el subscriber\n\n {\n\n // Time since last call\n\n // double timeBetweenMarkers = (ros::Time::now() - lastTime).toSec(); //The average publish time is of 10ms\n\n // lastTime = ros::Time::now();\n\n\n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 48, "score": 29601.860852851358 }, { "content": "\t\t\t// Time since last call\n\n\t\t\tdouble timeBetweenMarkers = (ros::Time::now() - lastTime).toSec();\n\n\t\t\tlastTime = ros::Time::now();\n\n\n\n\t\t\t// If the erroe between width and height is less than 4 pixels and height \n\n\t\t\t// is greater than 0.3\n\n\t\t\tif(ErZ < 4.0 && zini > 0.5) \n\n\t\t\t{\n\n\t\t\t\tzpos = zini - FACTORZ; // Descend Z based on the factor \n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tzpos = zini; // If there is more than 3 pixels of error, hold pos\n\n\t\t\t}\n\n\n\n\t\t\t// Drone service for automatic langind when it reaches an specific altitude\n\n\t\t\t// and centroid conditions\n\n\t\t\tif(zpos <= 0.5 && abs(imageW - msg.Xc) < 20 && abs(imageH - msg.Yc) < 20 )\n\n\t\t\t{\n\n\t\t\t\tmavros_msgs::CommandTOL land_cmd; // Set all the descend parameters to Zero\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 49, "score": 29601.29514818275 }, { "content": " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n\n\n#include <ros/ros.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n#include \"mavros_msgs/PositionTarget.h\"\n\n#include \"object_detector/States.h\" // Custom msgs of type States\n\n#include \"drone_controller/Error.h\" // Custom msgs of type Error\n\n#include \"drone_controller/pid.h\"\n\n\n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 50, "score": 29597.5865784517 }, { "content": " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n#include \"mavros_msgs/PositionTarget.h\"\n\n#include \"object_detector/States.h\" // Custom msgs of type States\n\n#include \"drone_controller/Error.h\" // Custom msgs of type Error\n\n#include \"drone_controller/pid.h\"\n\n\n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 51, "score": 29597.5865784517 }, { "content": "/**\n\n * @file pid_controller_tras.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief PID controller to move the vehicle towards the center of the \n\n * landing platform\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 52, "score": 29596.27148881828 }, { "content": "/**\n\n * @file pid_controller_rotate.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief PID controller to move the vehicle towards the center of the \n\n * landing platform and orientate it WRT x axis.\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n", "file_path": "drone_controller/src/pid_controller_rotate.cpp", "rank": 53, "score": 29596.208414129742 }, { "content": "/**\n\n * @file pid_controller_final.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief PID controller to land the vehicle on the landing pad\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "drone_controller/src/pid_controller_final.cpp", "rank": 54, "score": 29596.187731294565 }, { "content": "\n\nint main(int argc, char** argv)\n\n{ \n\n\tros::init(argc, argv, \"controller_node\");\n\n\tros::NodeHandle n;\n\n\tController cont(n);\n\n\tros::spin();\n\n\n\n\treturn 0;\n\n}\n\n\n", "file_path": "drone_controller/src/pid_controller_tras.cpp", "rank": 55, "score": 29594.382264949843 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <iostream>\n\n#include <cmath>\n\n#include \"drone_controller/pid.h\"\n\n\n\nusing namespace std;\n\n\n\n// Constructor\n\nPID::PID( double cmax, double cmin, double ckp, double ckd, double cki ) :\n\n max(cmax), min(cmin), kp(ckp), kd(ckd), ki(cki), pre_error(0), integral(0), pre_integral(0) {}\n\n\n\n// Destructor\n\nPID::~PID() {}\n", "file_path": "drone_controller/src/pid.cpp", "rank": 56, "score": 24472.48149656848 }, { "content": " pre_integral = integral;\n\n\n\n // Limit the max and min output\n\n if( output > max )\n\n {\n\n output = max; \n\n }\n\n\n\n else if( output < min )\n\n {\n\n output = min;\n\n }\n\n\n\n return output;\n\n}\n\n\n\n\n", "file_path": "drone_controller/src/pid.cpp", "rank": 57, "score": 24471.087133201534 }, { "content": "/**\n\n * @file pid.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief PID controller implementation\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "drone_controller/src/pid.cpp", "rank": 58, "score": 24467.753406142954 }, { "content": "\n\n//Calculation of PID values Setpoint is image_size/2\n\ndouble PID::calculate( double setpoint, double pv, double cdt )\n\n{\n\n \n\n // Calculate error\n\n double error = setpoint - pv;\n\n // Proportional term\n\n double Pout = kp * error;\n\n // Integral term\n\n integral = pre_integral + 0.5 * (pre_error + error) * 0.1; // cdt is equals to 0.1 to avoid overflow\n\n double Iout = ki * integral; // Integral output\n\n // Derivative term\n\n double derivative = (error - pre_error) / 0.1; // cdt is equals to 0.1 to avoid overflow\n\n double Dout = kp * kd * derivative; // Derivative output\n\n // Calculate total output\n\n double output = Pout + Iout + Dout;\n\n\n\n // Save error to previous error and previous integral value\n\n pre_error = error;\n", "file_path": "drone_controller/src/pid.cpp", "rank": 59, "score": 24465.196793691513 }, { "content": " $ roslaunch object_detector simu.launch\n\n\n\nThis will start the detection module of the system and track the landing platform as shown by the image below.\n\n \n\n <div align=\"center\">\n\n<img src=\"./images/kf.png\" width=\"330\">\n\n</div>\n\n\n\nTo land the vehicle use the **drone_controller** package. The process variable of the controller is the output of the detection pipeline. Do not use this package without the detector. \n\n\n\n $ rosrun drone_controller pid_controller_final \n\n\n", "file_path": "Usage.md", "rank": 60, "score": 7.9194246456996655 }, { "content": " ros::NodeHandle nh;\n\n\n\n ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>\n\n (\"mavros/state\", 10, state_cb);\n\n ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>\n\n (\"mavros/setpoint_position/local\", 10);\n\n ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>\n\n (\"mavros/cmd/arming\");\n\n ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>\n\n (\"mavros/set_mode\");\n\n\n\n //the setpoint publishing rate MUST be faster than 2Hz\n\n ros::Rate rate(20.0);\n\n\n\n // wait for FCU connection\n\n while(ros::ok() && !current_state.connected){\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n", "file_path": "mavros_off_board/src/set_offb.cpp", "rank": 61, "score": 6.953371554722525 }, { "content": " ros::NodeHandle nh;\n\n\n\n ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>\n\n (\"mavros/state\", 10, state_cb);\n\n ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>\n\n (\"mavros/setpoint_position/local\", 10);\n\n ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>\n\n (\"mavros/cmd/arming\");\n\n ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>\n\n (\"mavros/set_mode\");\n\n\n\n //the setpoint publishing rate MUST be faster than 2Hz\n\n ros::Rate rate(20.0);\n\n\n\n // wait for FCU connection\n\n while(ros::ok() && !current_state.connected){\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n", "file_path": "mavros_off_board/src/offb_node.cpp", "rank": 62, "score": 6.953371554722525 }, { "content": "\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n\n ROS_INFO(\"tring to land\");\n\n while (!(land_client.call(land_cmd) &&\n\n land_cmd.response.success)){\n\n //local_pos_pub.publish(pose);\n\n ROS_INFO(\"tring to land\");\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n return 0;\n\n}\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 63, "score": 6.394862348891358 }, { "content": "\t\t * @return norm euclidian dist of points\n\n\t\t */\n\n\t\tfloat computeEucDist(const float x_1, const float y_1, const float x_2, const float y_2) \n\n\t\t{\n\n\t\t\tfloat vector_x = x_2 - x_1;\n\n\t\t\tfloat vector_y = y_2 - y_1;\n\n\t\t\treturn sqrt(abs(vector_x * vector_x) + abs(vector_y * vector_y));\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Calculate the angle WRT X\n\n\t\t *\n\n\t\t *\n\n\t\t * @param x_1 coordiante x of first point\n\n\t\t * @param x_2 coordiante x of first point\n\n\t\t * @param x_3 coordiante x of first point\n\n\t\t * @param x_4 coordiante x of first point\n\n\t\t * @return th angle WRT X\n\n\t\t */\n\n\t\tfloat computeTheta(const float x_1, const float y_1, const float x_2, const float y_2) \n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 64, "score": 6.334631762543351 }, { "content": " public:\n\n // Public class attributes and methods\n\n Kalman(ros::NodeHandle ao_nh) : po_nh( ao_nh ), first_iter(0), dt(1), T(10,10), Q(10,10), R(5,5), \n\n A(10,10), H(5,10), X(10,1), Z(5,1), S1(5,5), Kg(5,5)\n\n {\n\n // Publisher type object_detector::States, it publishes in /predicted_states topic\n\n pub = po_nh.advertise<object_detector::States>( \"/predicted_states\", 10 ) ;\n\n // Subscriber to /states topic from object_detector/States\n\n sub = po_nh.subscribe(\"/states\", 10, &Kalman::predictionsDetectedCallback, this); \n\n // Delta of time for the transition matrix\n\n this->dt = 0.1;\n\n this->first_iter = 0;\n\n\n\n\n\n // Posteriori estimate covariance matrix initialization\n\n this->T << 2,0,0,0,0,0,0,0,0,0, 0,2,0,0,0,0,0,0,0,0, \n\n 0,0,5,0,0,0,0,0,0,0, 0,0,0,5,0,0,0,0,0,0, \n\n 0,0,0,0,5.625,0,0,0,0,0, 0,0,0,0,0,1e-3,0,0,0,0, \n\n 0,0,0,0,0,0,1e-3,0,0,0, 0,0,0,0,0,0,0,1e-3,0,0, \n\n 0,0,0,0,0,0,0,0,1e-3,0, 0,0,0,0,0,0,0,0,0,1e-3;\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 65, "score": 6.208478963683003 }, { "content": "int main(int argc, char **argv)\n\n{\n\n ros::init(argc, argv, \"offb_node\");\n\n ros::NodeHandle nh;\n\n\n\n ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>\n\n (\"mavros/state\", 10, state_cb);\n\n ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>\n\n (\"mavros/setpoint_position/local\", 10);\n\n ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>\n\n (\"mavros/cmd/arming\");\n\n ros::ServiceClient land_client = nh.serviceClient<mavros_msgs::CommandTOL>\n\n (\"mavros/cmd/land\");\n\n ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>\n\n (\"mavros/set_mode\");\n\n\n\n //the setpoint publishing rate MUST be faster than 2Hz\n\n ros::Rate rate(20.0);\n\n\n\n // wait for FCU connection\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 66, "score": 6.189542257628918 }, { "content": "\t\t\t\t\t\t\t\t\t\tmsg.BottomLeftX, msg.BottomLeftY);\n\n\n\n\t\t\t// Centroid of the template in the image\n\n\t\t\tst.Xc = msg.CenterX;\n\n\t\t\tst.Yc = msg.CenterY;\n\n\t\t\t// Computation of width and height as an average of the bottom and top magnitudes\n\n\t\t\tst.W = (v_bot + v_top) / 2; \n\n\t\t\tst.H = (v_right + v_left) / 2;\n\n\t\t\tst.Theta = theta;\n\n\n\n\t\t\t// Correction of theta when the angle is bigger than 90 degrees to avoid bad orientation for the controller\n\n\t\t\tif(theta > 90) \n\n\t\t\t{\n\n\t\t\t\tint cont = theta / 90;\n\n\t\t\t\tst.Theta = theta - cont * 90;\n\n\t\t\t}\n\n\t\t\telse if(theta < 90)\n\n\t\t\t{\n\n\t\t\t\tint cont = -1 * theta / 90;\n\n\t\t\t\tst.Theta = theta + cont * 90;\n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 67, "score": 5.94578320938032 }, { "content": " local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n ROS_INFO(\"second way point finished!\");\n\n\n\n // go to the third waypoint\n\n pose.pose.position.x = 1;\n\n pose.pose.position.y = 1;\n\n pose.pose.position.z = 0.75;\n\n //send setpoints for 10 seconds\n\n ROS_INFO(\"going to third way point\");\n\n for(int i = 0; ros::ok() && i < 10*20; ++i){\n\n\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n ROS_INFO(\"third way point finished!\");\n\n \n", "file_path": "mavros_off_board/src/path.cpp", "rank": 68, "score": 5.844732704874161 }, { "content": "\t\t// Subscriber callback\n\n\t\tvoid centCalculator(const object_detector::Corners& msg) //Callback para el subscriber \"CentCalculator\"\n\n\t\t{\t\n\n\t\t\t// Creation of a States object to publish the info\n\n\t\t\tobject_detector::States st;\n\n\n\n\t\t\t// Theta angle calculation\n\n\t\t\tfloat theta = computeTheta(msg.BottomLeftX, msg.BottomLeftY,\n\n\t\t\t\t\t\t\t\t\t\tmsg.BottomRightX, msg.BottomRightY);\n\n\t\t\t// Bottom vector magnitude\n\n\t\t\tfloat v_bot = computeEucDist(msg.BottomLeftX, msg.BottomLeftY,\n\n\t\t\t\t\t\t\t\t\t\tmsg.BottomRightX, msg.BottomRightY);\n\n\t\t\t// Right vector magnitude\n\n\t\t\tfloat v_right = computeEucDist(msg.BottomRightX, msg.BottomRightY,\n\n\t\t\t\t\t\t\t\t\t\tmsg.TopRightX, msg.TopRightY);\n\n\t\t\t// Top vector magnitude\n\n\t\t\tfloat v_top = computeEucDist(msg.TopLeftX, msg.TopLeftY,\n\n\t\t\t\t\t\t\t\t\t\tmsg.TopRightX, msg.TopRightY);\n\n\t\t\t// Left vector magnitude\n\n\t\t\tfloat v_left = computeEucDist(msg.TopLeftX, msg.TopLeftY,\n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 69, "score": 5.785325027210665 }, { "content": " image_pub_.publish(cv_ptr->toImageMsg());\n\n }\n\n\n\n void rectangle_draw(cv::Mat img)\n\n {\n\n // Assign the observations to measurements vector \n\n cv::Mat measurement = cv::Mat(5, 1, CV_32FC1, &this->data);\n\n\n\n // Assign the centroid of the platform to a point object\n\n cv::Point pt = cv::Point(measurement.at<float>(0), measurement.at<float>(1));\n\n\n\n // Create a rotated rectangle object\n\n cv::RotatedRect rRect = cv::RotatedRect(pt, cv::Size2f(measurement.at<float>(2),\n\n measurement.at<float>(3)), measurement.at<float>(4));\n\n\n\n // Points with the corner coordinates of the object\n\n cv::Point2f vertices[4];\n\n\n\n // Take the four corners from the rRect object and assing those to vertices\n\n rRect.points(vertices);\n", "file_path": "object_detector/src/plot_estimation.cpp", "rank": 70, "score": 5.512237848256694 }, { "content": " // Uncomment these lines to print the results on console\n\n /* printf(\"The Centroid predicted with KF are (%f,%f)\\n The Width is (%f)\\n The Height is (%f)\\n Theta is (%f)\\n\", \n\n\n\n \tpredictions.Xc, predictions.Yc,\n\n \tpredictions.W, predictions.H,\n\n \tpredictions.Theta);\n\n */\n\n \n\n pub.publish(predictions);\n\n }\n\n};\n\n\n\n\n\nint main(int argc, char** argv)\n\n{ \n\n ros::init(argc, argv, \"KF_predictor\"); \n\n ros::NodeHandle n;\n\n Kalman kf(n);\n\n ros::spin();\n\n\n\n return 0;\n\n} \n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 71, "score": 5.391127588724919 }, { "content": "/**\n\n * @file offb_node.cpp\n\n * @brief Offboard control example node, written with MAVROS version 0.19.x, PX4 Pro Flight\n\n * Stack and tested in Gazebo SITL\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/PoseStamped.h>\n\n#include <mavros_msgs/CommandBool.h>\n\n#include <mavros_msgs/SetMode.h>\n\n#include <mavros_msgs/State.h>\n\n\n\nmavros_msgs::State current_state;\n\nvoid state_cb(const mavros_msgs::State::ConstPtr& msg){\n\n current_state = *msg;\n\n}\n\n\n\nint main(int argc, char **argv)\n\n{\n\n ros::init(argc, argv, \"offb_node\");\n", "file_path": "mavros_off_board/src/offb_node.cpp", "rank": 72, "score": 5.360351574087792 }, { "content": "/**\n\n * @file set_offb.cpp\n\n * @brief Offboard control example node, written with MAVROS version 0.19.x, PX4 Pro Flight\n\n * Stack and tested in Gazebo SITL\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/PoseStamped.h> \n\n#include <mavros_msgs/CommandBool.h>\n\n#include <mavros_msgs/SetMode.h>\n\n#include <mavros_msgs/State.h>\n\n\n\nmavros_msgs::State current_state;\n\nvoid state_cb(const mavros_msgs::State::ConstPtr& msg){\n\n current_state = *msg;\n\n}\n\n\n\nint main(int argc, char **argv)\n\n{\n\n ros::init(argc, argv, \"offb_node\");\n", "file_path": "mavros_off_board/src/set_offb.cpp", "rank": 73, "score": 5.360351574087792 }, { "content": " 3. drone_controller\n\n\n\nIn the package *mavros_off_board* are the launch files, world file, description files (urdf, xacro, sdf) and basic scripts to control the aircraft. The package *object_detector* is the detection and tracking (Kalman Filter) pipeline of the system, this module allows the tracking of a landing template. Finally, *drone_controller* has the proportional and PID controllers developed to land the vehicle based on the estimations made with the *object_detector* package.\n\n\n\n<div align=\"center\">\n\n<img src=\"./images/uav.png\" width=\"330\">\n\n</div>\n\n\n", "file_path": "README.md", "rank": 74, "score": 5.314030648768544 }, { "content": "\t\t\t}\n\n\n\n\t\t\t// Uncomment these lines to print the results on console\n\n\t\t\t/*printf(\"Centroid in pix position (%f,%f)\\n Object Width (%f)\\n Object Height (%f)\\n Theta (%f)\\n\", \n\n\t\t\t\t\t\t\t\n\n\t\t\t\t\tst.Xc, st.Yc,\n\n\t\t\t\t\tst.W, st.H,\n\n\t\t\t\t\tst.Theta);\n\n\t\t\t*/\n\n\t\t\tpub.publish(st);\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Calculate the euclidian distance between two points\n\n\t\t *\n\n\t\t *\n\n\t\t * @param x_1 coordiante x of first point\n\n\t\t * @param x_2 coordiante x of first point\n\n\t\t * @param x_3 coordiante x of first point\n\n\t\t * @param x_4 coordiante x of first point\n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 75, "score": 5.26876497632996 }, { "content": " while(ros::ok() && current_state.connected){\n\n ros::spinOnce();\n\n rate.sleep();\n\n ROS_INFO(\"connecting to FCT...\");\n\n }\n\n\n\n geometry_msgs::PoseStamped pose;\n\n pose.pose.position.x = 0;\n\n pose.pose.position.y = 0;\n\n pose.pose.position.z = 0.75;\n\n\n\n //send a few setpoints before starting\n\n for(int i = 100; ros::ok() && i > 0; --i){\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n\n mavros_msgs::SetMode offb_set_mode;\n\n offb_set_mode.request.custom_mode = \"OFFBOARD\";\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 76, "score": 5.048049249761807 }, { "content": " geometry_msgs::PoseStamped pose;\n\n pose.pose.position.x = 0;\n\n pose.pose.position.y = 0;\n\n pose.pose.position.z = 2;\n\n\n\n //send a few setpoints before starting, esta parte en la que permite el dron entre en OFFBOARD mode\n\n for(int i = 100; ros::ok() && i > 0; --i){\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n\n\n\n return 0;\n\n}\n", "file_path": "mavros_off_board/src/set_offb.cpp", "rank": 77, "score": 4.769963581615315 }, { "content": " // Window name\n\n cv::namedWindow(OPENCV_WINDOW);\n\n }\n\n\n\n // Class destructor\n\n ~Drawer()\n\n {\n\n cv::destroyWindow(OPENCV_WINDOW); //destruyo el objeto namedWindow\n\n }\n\n\n\n // Subscriber callback to assign the values of the states to an array\n\n void estimationsDetectedCallback(const object_detector::States& msg) \n\n { \n\n this->data[0] = msg.Xc;\n\n this->data[1] = msg.Yc;\n\n this->data[2] = msg.W;\n\n this->data[3] = msg.H;\n\n this->data[4] = msg.Theta;\n\n }\n\n\n", "file_path": "object_detector/src/plot_estimation.cpp", "rank": 78, "score": 4.664563443315378 }, { "content": " }\n\n last_request = ros::Time::now();\n\n } else {\n\n if( !current_state.armed &&\n\n (ros::Time::now() - last_request > ros::Duration(5.0))){\n\n if( arming_client.call(arm_cmd) &&\n\n arm_cmd.response.success){\n\n ROS_INFO(\"Vehicle armed\");\n\n }\n\n last_request = ros::Time::now();\n\n }\n\n }\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n\n // go to the first waypoint\n\n pose.pose.position.x = 0;\n\n pose.pose.position.y = 0;\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 79, "score": 4.441709030745132 }, { "content": " pose.pose.position.z = 0.75;\n\n\n\n ROS_INFO(\"going to the first way point\");\n\n for(int i = 0; ros::ok() && i < 10*20; ++i){\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n ROS_INFO(\"first way point finished!\");\n\n\n\n\n\n // go to the second waypoint\n\n pose.pose.position.x = 0;\n\n pose.pose.position.y = 1;\n\n pose.pose.position.z = 0.75;\n\n\n\n //send setpoints for 10 seconds\n\n ROS_INFO(\"going to second way point\");\n\n for(int i = 0; ros::ok() && i < 10*20; ++i){\n\n\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 80, "score": 4.441709030745132 }, { "content": " // go to the forth waypoint\n\n pose.pose.position.x = 1;\n\n pose.pose.position.y = 0;\n\n pose.pose.position.z = 0.75;\n\n //send setpoints for 10 seconds\n\n ROS_INFO(\"going to forth way point\");\n\n for(int i = 0; ros::ok() && i < 10*20; ++i){\n\n\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n ROS_INFO(\"forth way point finished!\");\n\n \n\n pose.pose.position.x = 0;\n\n pose.pose.position.y = 0;\n\n pose.pose.position.z = 0.75;\n\n ROS_INFO(\"going back to the first point!\");\n\n //send setpoints for 10 seconds\n\n for(int i = 0; ros::ok() && i < 10*20; ++i){\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 81, "score": 4.182655060745933 }, { "content": " geometry_msgs::PoseStamped pose;\n\n pose.pose.position.x = 1.8;\n\n pose.pose.position.y = 2.0;\n\n pose.pose.position.z = 3.5;\n\n\n\n //send a few setpoints before starting\n\n for(int i = 100; ros::ok() && i > 0; --i){\n\n local_pos_pub.publish(pose);\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n\n mavros_msgs::SetMode offb_set_mode;\n\n offb_set_mode.request.custom_mode = \"OFFBOARD\";\n\n\n\n mavros_msgs::CommandBool arm_cmd;\n\n arm_cmd.request.value = true;\n\n\n\n ros::Time last_request = ros::Time::now();\n\n\n", "file_path": "mavros_off_board/src/offb_node.cpp", "rank": 82, "score": 4.1557245622319225 }, { "content": " while(ros::ok()){\n\n if( current_state.mode != \"OFFBOARD\" &&\n\n (ros::Time::now() - last_request > ros::Duration(5.0))){\n\n if( set_mode_client.call(offb_set_mode) &&\n\n offb_set_mode.response.mode_sent){\n\n ROS_INFO(\"Offboard enabled\");\n\n }\n\n last_request = ros::Time::now();\n\n } else {\n\n if( !current_state.armed &&\n\n (ros::Time::now() - last_request > ros::Duration(5.0))){\n\n if( arming_client.call(arm_cmd) &&\n\n arm_cmd.response.success){\n\n ROS_INFO(\"Vehicle armed\");\n\n }\n\n last_request = ros::Time::now();\n\n }\n\n }\n\n\n\n local_pos_pub.publish(pose);\n\n\n\n ros::spinOnce();\n\n rate.sleep();\n\n }\n\n\n\n return 0;\n\n}\n", "file_path": "mavros_off_board/src/offb_node.cpp", "rank": 83, "score": 3.880863396632487 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <image_transport/image_transport.h>\n\n#include <cv_bridge/cv_bridge.h>\n\n#include <sensor_msgs/image_encodings.h>\n\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <opencv2/highgui/highgui.hpp>\n\n#include \"object_detector/States.h\" // Custom msg of type States\n\n#include <find_object_2d/ObjectsStamped.h>\n\n#include <std_msgs/Float32MultiArray.h>\n\n\n\nstatic const std::string OPENCV_WINDOW = \"Estimation\";\n\n\n", "file_path": "object_detector/src/plot_estimation.cpp", "rank": 84, "score": 3.8648114980897326 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <vector>\n\n#include <find_object_2d/ObjectsStamped.h> // find_object_2d objectStamped msj\n\n#include <std_msgs/Float32MultiArray.h> \n\n#include \"object_detector/Corners.h\" // Custom msj with the corners and centroid of the object\n\n#include <QTransform> // Library to do the perspective transforms\n\n\n\n// Struct to sort the list of points with respect to X\n", "file_path": "object_detector/src/corners_detector.cpp", "rank": 85, "score": 3.744978734120452 }, { "content": "/**\n\n * @file path.cpp\n\n * @brief offboard example node, written with mavros version 0.14.2, px4 flight\n\n * stack and tested in Gazebo SITL\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/PoseStamped.h>\n\n#include <mavros_msgs/CommandBool.h>\n\n#include <mavros_msgs/CommandTOL.h>\n\n#include <mavros_msgs/SetMode.h>\n\n#include <mavros_msgs/State.h>\n\n\n\n#define FLIGHT_ALTITUDE 0.75f\n\n\n\nmavros_msgs::State current_state;\n\nvoid state_cb(const mavros_msgs::State::ConstPtr& msg){\n\n current_state = *msg;\n\n}\n\n\n", "file_path": "mavros_off_board/src/path.cpp", "rank": 86, "score": 3.68864074592934 }, { "content": " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include <find_object_2d/ObjectsStamped.h>\n\n#include \"object_detector/Corners.h\" // Custom msg of type Corners\n\n#include \"object_detector/States.h\" // Custom msgs of type States\n\n\n\n# define M_PI 3.14159265358979323846 /* pi */\n\n\n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 87, "score": 3.604411073660314 }, { "content": " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n\n\n#include <ros/ros.h>\n\n#include \"object_detector/States.h\" // Custom msg of type States\n\n#include <Eigen/Dense>\n\n\n\n# define M_PI 3.14159265358979323846 /* pi */\n\n\n\nusing namespace Eigen;\n\n\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 88, "score": 3.5528128929411995 }, { "content": "\t\t{\n\n\t\t\tfloat vector_x = x_2 - x_1;\n\n\t\t\tfloat vector_y = y_2 - y_1;\n\n\t\t\treturn atan2(vector_y, vector_x) * 180 / M_PI;\n\n\t\t}\n\n};\n\n\n\n\n\nint main(int argc, char** argv)\n\n{ \n\n ros::init(argc, argv, \"data_calculation\"); // Node name\n\n ros::NodeHandle n;\n\n States compt(n);\n\n ros::spin();\n\n\n\n return 0;\n\n}\n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 89, "score": 3.324940548053341 }, { "content": "\n\n# Autonomous landing of a UAV\n\n\n\nROS packages developed for the autonomous landing of a UAV on a stationary platform.\n\n\n\n<div align=\"center\">\n\n<img src=\"./images/land_gif.gif\" width=\"480\" />\n\n</div>\n\n\n\n## Description\n\n\n\nThe autonomous landing system has been tested in Simulation with Gazebo and with a modified DJI F450 with an onboard computer. The workflow of the system is a simulated environment is as follows. The system is launched in Gazebo and communicated with the Firmware of PX4. Then, the vehicle takeoff from the ground and moves to a position where the landing platform is visible. The detection module starts working and with a feature-based detector and a Kalman Filter, the landing pad is tracking thoroughly. Once the first estimation of the landing platform is made, the landing controller begins to work and moves the vehicle towards the center of the platform while it is descending. Finally, the vehicle lands and ends its mission.\n\n\n\n<div align=\"center\">\n\n<img src=\"./images/world.png\" width=\"330\">\n\n</div>\n\n\n\nThis system can be used in more complex tasks where the landing phase wants to be automated. Precision agriculture, Patrolling and building inspection are just few examples where a system like this might be used to land the vehicle.\n\n\n\nThe following diagram illustrates the general workflow of the system. First the homography matrix is computed between the current image frame and the predefined template, using a feature-based detector. Then, the homography matrix is used to compute the corners and the centroid of the object. These points are then passed to a Kalman filter estimation module. Finally, the Kalman filter estimations are used to track the template in the image frame, and passed as input for a set of three PID-based controllers that perform the safe landing of the vehicle\n\n\n\n<div align=\"center\">\n\n<img src=\"./images/pipeline.png\">\n\n</div>\n\n\n\nThere are three main packages that compose this project, these are:\n\n\n\n 1. mavros_off_board\n\n 2. object_detector\n", "file_path": "README.md", "rank": 90, "score": 3.301165828885351 }, { "content": " this->X(2,0) = msg.W; // State Width\n\n this->X(3,0) = msg.H; // State Height\n\n this->X(4,0) = msg.Theta; // State Theta\n\n this->X(5,0) = 0; // State Xc'\n\n this->X(6,0) = 0; // State Yc'\n\n this->X(7,0) = 0; // State Width'\n\n this->X(8,0) = 0; // State Height'\n\n this->X(9,0) = 0; // State Theta'\n\n this->first_iter = 1;\n\n }\n\n\n\n // Prediction step\n\n this->X = this->A*this->X; \n\n this->T = ((this->A*this->T)*this->A.transpose())+this->Q;\n\n\n\n // Update step, assign the observations to the measurement vector \n\n measurement(0,0) = msg.Xc;\n\n measurement(1,0) = msg.Yc;\n\n measurement(2,0) = msg.W;\n\n measurement(3,0) = msg.H;\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 91, "score": 3.2683421993177335 }, { "content": "\t\tvoid cornersDetectedCallback(const std_msgs::Float32MultiArrayConstPtr& msg) \n\n\t\t{\n\n\t\t\t// Creation of a Corners object to publish the info\n\n\t\t\tobject_detector::Corners coordinates; \n\n\t\t\t// data saving in temporal variables\n\n\t\t\tconst std::vector<float> & data = msg->data; \n\n\t\t\tif(data.size())\n\n\t\t\t{\n\n\t\t\t\tfor(unsigned int i=0; i<data.size(); i+=12) // For to extract data given by the find object 2d topic\n\n\t\t\t\t{\n\n\t\t\t\t\t// get data\n\n\t\t\t\t\tint id = (int)data[i];\n\n\t\t\t\t\tfloat objectWidth = data[i+1];\n\n\t\t\t\t\tfloat objectHeight = data[i+2];\n\n\n\n\t\t\t\t\t// Find corners Qt \n\n\t\t\t\t\t// QTrasform initialization with the homography matrix\n\n\t\t\t\t\tQTransform qtHomography(data[i+3], data[i+4], data[i+5],\n\n\t\t\t\t\t\tdata[i+6], data[i+7], data[i+8],\n\n\t\t\t\t\t\tdata[i+9], data[i+10], data[i+11]);\n", "file_path": "object_detector/src/corners_detector.cpp", "rank": 92, "score": 3.142758489695419 }, { "content": " measurement(4,0) = msg.Theta;\n\n\n\n // If there is a valid measurement (the detector found the coordinates)\n\n if((measurement(0)>0)&&(measurement(1)>0)&&(measurement(2)>0)&&(measurement(3)>0)) \n\n {\n\n // Update step\n\n this->Z = measurement - this->H*this->X; \n\n this->S1 = ((this->H*this->T)*this->H.transpose())+R; \n\n this->Kg = (this->T*this->H.transpose())*this->S1.inverse(); \n\n this->X = this->X + this->Kg*this->Z; \n\n this->T = (MatrixXd::Identity(10,10)-(this->Kg*this->H))*this->T; \n\n }\n\n\n\n // Assign the predictions to the publisher object\n\n predictions.Xc = this->X(0,0);\n\n predictions.Yc = this->X(1,0);\n\n predictions.W = this->X(2,0);\n\n predictions.H = this->X(3,0);\n\n predictions.Theta = this->X(4,0);\n\n\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 93, "score": 2.869125638942524 }, { "content": "/**\n\n * @file cent_calculator.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief This node computes the centroid, height, widhth and angle WRT to x\n\n * of a template\n\n * @version 0.1\n\n * @date 04-30-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n", "file_path": "object_detector/src/cent_calculator.cpp", "rank": 94, "score": 2.654772279117387 }, { "content": "/**\n\n * @file plot_estimation.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief Plot in an image the estimation of the template\n\n * @version 0.1\n\n * @date 05-01-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "object_detector/src/plot_estimation.cpp", "rank": 95, "score": 2.6329098287544093 }, { "content": "/**\n\n * @file corners_detector.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief Algorithm to detect the corners of a template in an image\n\n * @version 0.1\n\n * @date 04-29-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "object_detector/src/corners_detector.cpp", "rank": 96, "score": 2.622113080288477 }, { "content": "/**\n\n * @file kalman_filter.cpp\n\n * @author Miguel Saavedra (miguel.saaruiz@[email protected])\n\n * @brief Linear kalman filter implementation for states estimation\n\n * @version 0.1\n\n * @date 04-30-2020\n\n * \n\n * Copyright (c) 2020 Miguel Saavedra\n\n * \n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the \"Software\"), to deal\n\n * in the Software without restriction, including without limitation the rights\n\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n * \n\n * The above copyright notice and this permission notice shall be included in all\n\n * copies or substantial portions of the Software.\n\n * \n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 97, "score": 2.6114045184454033 }, { "content": "\n\n // State vector initialization\n\n this->X = MatrixXd::Zero(10,1); \n\n // Innovation vectot initialization\n\n this->Z = MatrixXd::Zero(5,1); \n\n // Covariance of the innovation initialization\n\n this->S1 = MatrixXd::Zero(5,5); \n\n // Kalman gain initialization\n\n this->Kg = MatrixXd::Zero(5,5); \n\n\n\n // State transition matrix initialization\n\n this->A << 1,0,0,0,0,dt,0,0,0,0, 0,1,0,0,0,0,dt,0,0,0, \n\n 0,0,1,0,0,0,0,dt,0,0, 0,0,0,1,0,0,0,0,dt,0, \n\n 0,0,0,0,1,0,0,0,0,dt, 0,0,0,0,0,1,0,0,0,0, \n\n 0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,1,0,0, \n\n 0,0,0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,1;\n\n \n\n /* Transition model \n\n * Xc [1 0 0 0 0 dt 0 0 0 0]\n\n * Yc [0 1 0 0 0 0 dt 0 0 0]\n", "file_path": "object_detector/src/kalman_filter.cpp", "rank": 98, "score": 2.4542249774793437 }, { "content": "\t\t\t\t\n\n\t\t\t}\n\n\t\t\t// Publish the coordinates\n\n\t\t\tpub.publish(coordinates);\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * Assign the corners of the publishing object\n\n\t\t *\n\n\t\t * Assign the proper corner to each element of the \n\n\t\t * corners publishing object\n\n\t\t *\n\n\t\t * @param p vector of points.\n\n\t\t * @param c publishing object with the sorted corners\n\n\t\t */\n\n\t\tvoid assignCorners(const std::vector<QPointF>& p, object_detector::Corners& c) \n\n\t\t{\n\n\t\t\t// Assign the bottom left and top left corners\n\n\t\t\tif(p[0].y() > p[1].y()) \n\n\t\t\t\t{\n", "file_path": "object_detector/src/corners_detector.cpp", "rank": 99, "score": 2.441463729533 } ]
C++
cppcache/src/ThinClientLocatorHelper.cpp
rhoughton-pivot/geode-native
ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd
#include "ThinClientLocatorHelper.hpp" #include <algorithm> #include <set> #include <boost/thread/lock_types.hpp> #include <geode/DataInput.hpp> #include <geode/DataOutput.hpp> #include <geode/SystemProperties.hpp> #include "CacheImpl.hpp" #include "ClientConnectionRequest.hpp" #include "ClientConnectionResponse.hpp" #include "ClientReplacementRequest.hpp" #include "LocatorListRequest.hpp" #include "LocatorListResponse.hpp" #include "QueueConnectionRequest.hpp" #include "QueueConnectionResponse.hpp" #include "TcpConn.hpp" #include "TcpSslConn.hpp" #include "TcrConnectionManager.hpp" #include "ThinClientPoolDM.hpp" #include "Version.hpp" namespace apache { namespace geode { namespace client { const size_t BUFF_SIZE = 3000; const size_t DEFAULT_CONNECTION_RETRIES = 3; ThinClientLocatorHelper::ThinClientLocatorHelper( const std::vector<std::string>& locators, const ThinClientPoolDM* poolDM) : locators_(locators.begin(), locators.end()), m_poolDM(poolDM), m_sniProxyHost(""), m_sniProxyPort(0) {} ThinClientLocatorHelper::ThinClientLocatorHelper( const std::vector<std::string>& locators, const std::string& sniProxyHost, int sniProxyPort, const ThinClientPoolDM* poolDM) : locators_(locators.begin(), locators.end()), m_poolDM(poolDM), m_sniProxyHost(sniProxyHost), m_sniProxyPort(sniProxyPort) {} size_t ThinClientLocatorHelper::getConnRetries() const { auto retries = m_poolDM->getRetryAttempts(); return retries <= 0 ? DEFAULT_CONNECTION_RETRIES : retries; } std::vector<ServerLocation> ThinClientLocatorHelper::getLocators() const { decltype(locators_) locators; { boost::shared_lock<decltype(mutex_)> guard{mutex_}; if (locators_.empty()) { return {}; } locators = locators_; } RandGen randGen; std::random_shuffle(locators.begin(), locators.end(), randGen); return locators; } std::unique_ptr<Connector> ThinClientLocatorHelper::createConnection( const ServerLocation& location) const { auto& sys_prop = m_poolDM->getConnectionManager() .getCacheImpl() ->getDistributedSystem() .getSystemProperties(); const auto port = location.getPort(); auto timeout = sys_prop.connectTimeout(); const auto& hostname = location.getServerName(); auto buffer_size = m_poolDM->getSocketBufferSize(); if (sys_prop.sslEnabled()) { if (m_sniProxyHost.empty()) { return std::unique_ptr<Connector>(new TcpSslConn( hostname, static_cast<uint16_t>(port), timeout, buffer_size, sys_prop.sslTrustStore(), sys_prop.sslKeyStore(), sys_prop.sslKeystorePassword())); } else { return std::unique_ptr<Connector>(new TcpSslConn( hostname, static_cast<uint16_t>(port), m_sniProxyHost, m_sniProxyPort, timeout, buffer_size, sys_prop.sslTrustStore(), sys_prop.sslKeyStore(), sys_prop.sslKeystorePassword())); } } else { return std::unique_ptr<Connector>(new TcpConn( hostname, static_cast<uint16_t>(port), timeout, buffer_size)); } } static constexpr int32_t kGossipVersion = 1002; std::shared_ptr<Serializable> ThinClientLocatorHelper::sendRequest( const ServerLocation& location, const std::shared_ptr<Serializable>& request) const { auto& sys_prop = m_poolDM->getConnectionManager() .getCacheImpl() ->getDistributedSystem() .getSystemProperties(); try { auto conn = createConnection(location); auto data = m_poolDM->getConnectionManager().getCacheImpl()->createDataOutput(); data.writeInt(kGossipVersion); data.writeInt(Version::current().getOrdinal()); data.writeObject(request); auto sentLength = conn->send( reinterpret_cast<char*>(const_cast<uint8_t*>(data.getBuffer())), data.getBufferLength(), m_poolDM->getReadTimeout()); if (sentLength <= 0) { return nullptr; } char buff[BUFF_SIZE]; const auto receivedLength = conn->receive(buff, m_poolDM->getReadTimeout()); if (!receivedLength) { return nullptr; } auto di = m_poolDM->getConnectionManager().getCacheImpl()->createDataInput( reinterpret_cast<uint8_t*>(buff), receivedLength); if (di.read() == REPLY_SSL_ENABLED && !sys_prop.sslEnabled()) { LOGERROR("SSL is enabled on locator, enable SSL in client as well"); throw AuthenticationRequiredException( "SSL is enabled on locator, enable SSL in client as well"); } di.rewindCursor(1); return di.readObject(); } catch (const AuthenticationRequiredException& excp) { throw excp; } catch (const Exception& excp) { LOGFINE("Exception while querying locator: %s: %s", excp.getName().c_str(), excp.what()); } catch (...) { LOGFINE("Exception while querying locator"); } return nullptr; } GfErrType ThinClientLocatorHelper::getAllServers( std::vector<std::shared_ptr<ServerLocation> >& servers, const std::string& serverGrp) const { for (const auto& loc : getLocators()) { LOGDEBUG("getAllServers getting servers from server = %s ", loc.getServerName().c_str()); auto request = std::make_shared<GetAllServersRequest>(serverGrp); auto response = std::dynamic_pointer_cast<GetAllServersResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } servers = response->getServers(); return GF_NOERR; } return GF_NOERR; } GfErrType ThinClientLocatorHelper::getEndpointForNewCallBackConn( ClientProxyMembershipID& memId, std::list<ServerLocation>& outEndpoint, std::string&, int redundancy, const std::set<ServerLocation>& exclEndPts, const std::string& serverGrp) const { auto locators = getLocators(); auto locatorsSize = locators.size(); auto maxAttempts = getConnRetries(); LOGFINER( "ThinClientLocatorHelper::getEndpointForNewCallBackConn maxAttempts = " "%zu", maxAttempts); for (auto attempt = 0ULL; attempt < maxAttempts;) { const auto& loc = locators[attempt++ % locatorsSize]; LOGFINER("Querying locator at [%s:%d] for queue server from group [%s]", loc.getServerName().c_str(), loc.getPort(), serverGrp.c_str()); auto request = std::make_shared<QueueConnectionRequest>( memId, exclEndPts, redundancy, false, serverGrp); auto response = std::dynamic_pointer_cast<QueueConnectionResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } outEndpoint = response->getServers(); return GF_NOERR; } throw NoAvailableLocatorsException("Unable to query any locators"); } GfErrType ThinClientLocatorHelper::getEndpointForNewFwdConn( ServerLocation& outEndpoint, std::string&, const std::set<ServerLocation>& exclEndPts, const std::string& serverGrp, const TcrConnection* currentServer) const { bool locatorFound = false; auto locators = getLocators(); auto locatorsSize = locators.size(); auto maxAttempts = getConnRetries(); LOGFINER( "ThinClientLocatorHelper::getEndpointForNewFwdConn maxAttempts = %zu", maxAttempts); for (auto attempt = 0ULL; attempt < maxAttempts;) { const auto& loc = locators[attempt++ % locatorsSize]; LOGFINE("Querying locator at [%s:%d] for server from group [%s]", loc.getServerName().c_str(), loc.getPort(), serverGrp.c_str()); std::shared_ptr<Serializable> request; if (currentServer == nullptr) { LOGDEBUG("Creating ClientConnectionRequest"); request = std::make_shared<ClientConnectionRequest>(exclEndPts, serverGrp); } else { LOGDEBUG("Creating ClientReplacementRequest for connection: %s", currentServer->getEndpointObject()->name().c_str()); request = std::make_shared<ClientReplacementRequest>( currentServer->getEndpointObject()->name(), exclEndPts, serverGrp); } auto response = std::dynamic_pointer_cast<ClientConnectionResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } response->printInfo(); if (!response->serverFound()) { LOGFINE("Server not found"); locatorFound = true; continue; } outEndpoint = response->getServerLocation(); LOGFINE("Server found at [%s:%d]", outEndpoint.getServerName().c_str(), outEndpoint.getPort()); return GF_NOERR; } if (locatorFound) { throw NotConnectedException("No servers found"); } else { throw NoAvailableLocatorsException("Unable to query any locators"); } } GfErrType ThinClientLocatorHelper::updateLocators( const std::string& serverGrp) { auto locators = getLocators(); for (const auto& loc : locators) { LOGFINER("Querying locator list at: [%s:%d] for update from group [%s]", loc.getServerName().c_str(), loc.getPort(), serverGrp.c_str()); auto request = std::make_shared<LocatorListRequest>(serverGrp); auto response = std::dynamic_pointer_cast<LocatorListResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } auto new_locators = response->getLocators(); for (const auto& old_loc : locators) { auto iter = std::find(new_locators.begin(), new_locators.end(), old_loc); if (iter == new_locators.end()) { new_locators.push_back(old_loc); } } { boost::unique_lock<decltype(mutex_)> lock(mutex_); locators_.swap(new_locators); } return GF_NOERR; } return GF_NOTCON; } } } }
#include "ThinClientLocatorHelper.hpp" #include <algorithm> #include <set> #include <boost/thread/lock_types.hpp> #include <geode/DataInput.hpp> #include <geode/DataOutput.hpp> #include <geode/SystemProperties.hpp> #include "CacheImpl.hpp" #include "ClientConnectionRequest.hpp" #include "ClientConnectionResponse.hpp" #include "ClientReplacementRequest.hpp" #include "LocatorListRequest.hpp" #include "LocatorListResponse.hpp" #include "QueueConnectionRequest.hpp" #include "QueueConnectionResponse.hpp" #include "TcpConn.hpp" #include "TcpSslConn.hpp" #include "TcrConnectionManager.hpp" #include "ThinClientPoolDM.hpp" #include "Version.hpp" namespace apache { namespace geode { namespace client { const size_t BUFF_SIZE = 3000; const size_t DEFAULT_CONNECTION_RETRIES = 3; ThinClientLocatorHelper::ThinClientLocatorHelper( const std::vector<std::string>& locators, const ThinClientPoolDM* poolDM) : locators_(locators.begin(), locators.end()), m_poolDM(poolDM), m_sniProxyHost(""), m_sniProxyPort(0) {} ThinClientLocatorHelper::ThinClientLocatorHelper( const std::vector<std::string>& locators, const std::string& sniProxyHost, int sniProxyPort, const ThinClientPoolDM* poolDM) : locators_(locators.begin(), locators.end()), m_poolDM(poolDM), m_sniProxyHost(sniProxyHost), m_sniProxyPort(sniProxyPort) {} size_t ThinClientLocatorHelper::getConnRetries() const { auto retries = m_poolDM->getRetryAttempts(); return retries <= 0 ? DEFAULT_CONNECTION_RETRIES : retries; } std::vector<ServerLocation> ThinClientLocatorHelper::getLocators() const { decltype(locators_) locators; { boost::shared_lock<decltype(mutex_)> guard{mutex_}; if (locators_.empty()) { return {}; } locators = locators_; } RandGen randGen; std::random_shuffle(locators.begin(), locators.end(), randGen); return locators; } std::unique_ptr<Connector> ThinClientLocatorHelper::createConnection( const ServerLocation& location) const { auto& sys_prop = m_poolDM->getConnectionManager() .getCacheImpl() ->getDistributedSystem() .getSystemProperties(); const auto port = location.getPort(); auto timeout = sys_prop.connectTimeout(); const auto& hostname = location.getServerName(); auto buffer_size = m_poolDM->getSocketBufferSize(); if (sys_prop.sslEnabled()) { if (m_sniProxyHost.empty()) { return std::unique_ptr<Connector>(new TcpSslConn( hostname, static_cast<uint16_t>(port), timeout, buffer_size, sys_prop.sslTrustStore(), sys_prop.sslKeyStore(), sys_prop.sslKeystorePassword())); } else { return
; } } else { return std::unique_ptr<Connector>(new TcpConn( hostname, static_cast<uint16_t>(port), timeout, buffer_size)); } } static constexpr int32_t kGossipVersion = 1002; std::shared_ptr<Serializable> ThinClientLocatorHelper::sendRequest( const ServerLocation& location, const std::shared_ptr<Serializable>& request) const { auto& sys_prop = m_poolDM->getConnectionManager() .getCacheImpl() ->getDistributedSystem() .getSystemProperties(); try { auto conn = createConnection(location); auto data = m_poolDM->getConnectionManager().getCacheImpl()->createDataOutput(); data.writeInt(kGossipVersion); data.writeInt(Version::current().getOrdinal()); data.writeObject(request); auto sentLength = conn->send( reinterpret_cast<char*>(const_cast<uint8_t*>(data.getBuffer())), data.getBufferLength(), m_poolDM->getReadTimeout()); if (sentLength <= 0) { return nullptr; } char buff[BUFF_SIZE]; const auto receivedLength = conn->receive(buff, m_poolDM->getReadTimeout()); if (!receivedLength) { return nullptr; } auto di = m_poolDM->getConnectionManager().getCacheImpl()->createDataInput( reinterpret_cast<uint8_t*>(buff), receivedLength); if (di.read() == REPLY_SSL_ENABLED && !sys_prop.sslEnabled()) { LOGERROR("SSL is enabled on locator, enable SSL in client as well"); throw AuthenticationRequiredException( "SSL is enabled on locator, enable SSL in client as well"); } di.rewindCursor(1); return di.readObject(); } catch (const AuthenticationRequiredException& excp) { throw excp; } catch (const Exception& excp) { LOGFINE("Exception while querying locator: %s: %s", excp.getName().c_str(), excp.what()); } catch (...) { LOGFINE("Exception while querying locator"); } return nullptr; } GfErrType ThinClientLocatorHelper::getAllServers( std::vector<std::shared_ptr<ServerLocation> >& servers, const std::string& serverGrp) const { for (const auto& loc : getLocators()) { LOGDEBUG("getAllServers getting servers from server = %s ", loc.getServerName().c_str()); auto request = std::make_shared<GetAllServersRequest>(serverGrp); auto response = std::dynamic_pointer_cast<GetAllServersResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } servers = response->getServers(); return GF_NOERR; } return GF_NOERR; } GfErrType ThinClientLocatorHelper::getEndpointForNewCallBackConn( ClientProxyMembershipID& memId, std::list<ServerLocation>& outEndpoint, std::string&, int redundancy, const std::set<ServerLocation>& exclEndPts, const std::string& serverGrp) const { auto locators = getLocators(); auto locatorsSize = locators.size(); auto maxAttempts = getConnRetries(); LOGFINER( "ThinClientLocatorHelper::getEndpointForNewCallBackConn maxAttempts = " "%zu", maxAttempts); for (auto attempt = 0ULL; attempt < maxAttempts;) { const auto& loc = locators[attempt++ % locatorsSize]; LOGFINER("Querying locator at [%s:%d] for queue server from group [%s]", loc.getServerName().c_str(), loc.getPort(), serverGrp.c_str()); auto request = std::make_shared<QueueConnectionRequest>( memId, exclEndPts, redundancy, false, serverGrp); auto response = std::dynamic_pointer_cast<QueueConnectionResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } outEndpoint = response->getServers(); return GF_NOERR; } throw NoAvailableLocatorsException("Unable to query any locators"); } GfErrType ThinClientLocatorHelper::getEndpointForNewFwdConn( ServerLocation& outEndpoint, std::string&, const std::set<ServerLocation>& exclEndPts, const std::string& serverGrp, const TcrConnection* currentServer) const { bool locatorFound = false; auto locators = getLocators(); auto locatorsSize = locators.size(); auto maxAttempts = getConnRetries(); LOGFINER( "ThinClientLocatorHelper::getEndpointForNewFwdConn maxAttempts = %zu", maxAttempts); for (auto attempt = 0ULL; attempt < maxAttempts;) { const auto& loc = locators[attempt++ % locatorsSize]; LOGFINE("Querying locator at [%s:%d] for server from group [%s]", loc.getServerName().c_str(), loc.getPort(), serverGrp.c_str()); std::shared_ptr<Serializable> request; if (currentServer == nullptr) { LOGDEBUG("Creating ClientConnectionRequest"); request = std::make_shared<ClientConnectionRequest>(exclEndPts, serverGrp); } else { LOGDEBUG("Creating ClientReplacementRequest for connection: %s", currentServer->getEndpointObject()->name().c_str()); request = std::make_shared<ClientReplacementRequest>( currentServer->getEndpointObject()->name(), exclEndPts, serverGrp); } auto response = std::dynamic_pointer_cast<ClientConnectionResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } response->printInfo(); if (!response->serverFound()) { LOGFINE("Server not found"); locatorFound = true; continue; } outEndpoint = response->getServerLocation(); LOGFINE("Server found at [%s:%d]", outEndpoint.getServerName().c_str(), outEndpoint.getPort()); return GF_NOERR; } if (locatorFound) { throw NotConnectedException("No servers found"); } else { throw NoAvailableLocatorsException("Unable to query any locators"); } } GfErrType ThinClientLocatorHelper::updateLocators( const std::string& serverGrp) { auto locators = getLocators(); for (const auto& loc : locators) { LOGFINER("Querying locator list at: [%s:%d] for update from group [%s]", loc.getServerName().c_str(), loc.getPort(), serverGrp.c_str()); auto request = std::make_shared<LocatorListRequest>(serverGrp); auto response = std::dynamic_pointer_cast<LocatorListResponse>( sendRequest(loc, request)); if (response == nullptr) { continue; } auto new_locators = response->getLocators(); for (const auto& old_loc : locators) { auto iter = std::find(new_locators.begin(), new_locators.end(), old_loc); if (iter == new_locators.end()) { new_locators.push_back(old_loc); } } { boost::unique_lock<decltype(mutex_)> lock(mutex_); locators_.swap(new_locators); } return GF_NOERR; } return GF_NOTCON; } } } }
std::unique_ptr<Connector>(new TcpSslConn( hostname, static_cast<uint16_t>(port), m_sniProxyHost, m_sniProxyPort, timeout, buffer_size, sys_prop.sslTrustStore(), sys_prop.sslKeyStore(), sys_prop.sslKeystorePassword()))
call_expression
[ { "content": "struct hash<apache::geode::client::ServerLocation> {\n\n typedef apache::geode::client::ServerLocation argument_type;\n\n typedef size_t result_type;\n\n size_t operator()(const apache::geode::client::ServerLocation& val) const {\n\n return val.hashcode();\n\n }\n\n};\n\n\n\n} // namespace std\n\n\n\n#endif // GEODE_SERVERLOCATION_H_\n", "file_path": "cppcache/src/ServerLocation.hpp", "rank": 0, "score": 263097.4041627996 }, { "content": "struct hash<apache::geode::client::CacheableString>\n\n : hash<apache::geode::client::CacheableKey> {};\n\n\n\n} // namespace std\n\n\n\n#endif // GEODE_CACHEABLESTRING_H_\n", "file_path": "cppcache/include/geode/CacheableString.hpp", "rank": 1, "score": 257906.1983114849 }, { "content": "struct hash<apache::geode::client::CacheableKey> {\n\n typedef apache::geode::client::CacheableKey argument_type;\n\n typedef size_t result_type;\n\n result_type operator()(const argument_type& val) const {\n\n return val.hashcode();\n\n }\n\n};\n\n\n\n} // namespace std\n\n\n\n#endif // GEODE_CACHEABLEKEY_H_\n", "file_path": "cppcache/include/geode/CacheableKey.hpp", "rank": 2, "score": 257906.19831148494 }, { "content": "struct hash<apache::geode::client::BucketServerLocation> {\n\n typedef apache::geode::client::BucketServerLocation argument_type;\n\n typedef size_t result_type;\n\n size_t operator()(\n\n const apache::geode::client::BucketServerLocation& val) const {\n\n return val.hashcode();\n\n }\n\n};\n\n\n\n} // namespace std\n\n\n\n#endif // GEODE_BUCKETSERVERLOCATION_H_\n", "file_path": "cppcache/src/BucketServerLocation.hpp", "rank": 3, "score": 253954.552991339 }, { "content": "class APACHE_GEODE_EXPORT StructSet : public CqResults {\n\n public:\n\n ~StructSet() noexcept override = default;\n\n\n\n /**\n\n * Get the index number of the specified field name in the StructSet.\n\n *\n\n * @param fieldname the field name for which the index is required.\n\n * @returns the index number of the specified field name.\n\n * @throws std::invalid_argument if the field name is not found.\n\n */\n\n virtual int32_t getFieldIndex(const std::string& fieldname) = 0;\n\n\n\n /**\n\n * Get the field name of the StructSet from the specified index number.\n\n *\n\n * @param index the index number of the field name to get.\n\n * @returns the field name from the specified index number or nullptr if not\n\n * found.\n\n * @throws std::out_of_range if index is not found\n\n */\n\n virtual const std::string& getFieldName(int32_t index) = 0;\n\n};\n\n\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_STRUCTSET_H_\n", "file_path": "cppcache/include/geode/StructSet.hpp", "rank": 4, "score": 237296.49732817002 }, { "content": "class APACHE_GEODE_EXPORT ResultSet : public SelectResults {\n\n public:\n\n ~ResultSet() noexcept override = default;\n\n};\n\n\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_RESULTSET_H_\n", "file_path": "cppcache/include/geode/ResultSet.hpp", "rank": 5, "score": 237296.49732817002 }, { "content": "class APACHE_GEODE_EXPORT CacheableHashSet\n\n : public internal::CacheableContainerPrimitive<\n\n HashSetOfCacheableKey, internal::DSCode::CacheableHashSet,\n\n CacheableHashSet> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n HashSetOfCacheableKey, internal::DSCode::CacheableHashSet,\n\n CacheableHashSet>;\n\n\n\n/**\n\n * A mutable <code>Cacheable</code> array list wrapper that can serve as\n\n * a distributable object for caching.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 6, "score": 229953.21461327438 }, { "content": "class APACHE_GEODE_EXPORT TimeoutException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~TimeoutException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::TimeoutException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when the cache writer aborts the operation.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 7, "score": 225481.68716527254 }, { "content": "class APACHE_GEODE_EXPORT CacheableLinkedHashSet\n\n : public internal::CacheableContainerPrimitive<\n\n HashSetOfCacheableKey, internal::DSCode::CacheableLinkedHashSet,\n\n CacheableLinkedHashSet> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n HashSetOfCacheableKey, internal::DSCode::CacheableLinkedHashSet,\n\n CacheableLinkedHashSet>;\n\n\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_CACHEABLEBUILTINS_H_\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 8, "score": 225438.58411841164 }, { "content": "class APACHE_GEODE_EXPORT NoAvailableLocatorsException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~NoAvailableLocatorsException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::NoAvailableLocatorsException\";\n\n }\n\n};\n\n/**\n\n *@brief Thrown if all connections in the pool are in use.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 9, "score": 221131.70082418746 }, { "content": "class APACHE_GEODE_EXPORT DuplicateDurableClientException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~DuplicateDurableClientException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::DuplicateDurableClientException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when the cache listener throws an exception.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 10, "score": 215199.69629261878 }, { "content": "class ThinClientPoolDM;\n", "file_path": "cppcache/include/geode/PoolManager.hpp", "rank": 11, "score": 211652.4724506307 }, { "content": "struct hash<apache::geode::client::PdxType> {\n\n typedef apache::geode::client::PdxType argument_type;\n\n typedef size_t result_type;\n\n result_type operator()(const argument_type& val) const {\n\n std::hash<std::string> strHash;\n\n auto result = strHash(val.getPdxClassName());\n\n\n\n for (auto entry : val.getFieldNameVsPdxType()) {\n\n auto pdxPtr = entry.second;\n\n result = result ^ (strHash(pdxPtr->getClassName()) << 1);\n\n result = result ^ (strHash(pdxPtr->getFieldName()) << 1);\n\n }\n\n\n\n return result;\n\n }\n\n};\n\n\n\n} // namespace std\n\n\n\n#endif // GEODE_PDXTYPE_H_\n", "file_path": "cppcache/src/PdxType.hpp", "rank": 12, "score": 192331.53599279275 }, { "content": "struct hash<apache::geode::client::EventSource> {\n\n typedef apache::geode::client::EventSource argument_type;\n\n typedef size_t result_type;\n\n size_t operator()(const apache::geode::client::EventSource &val) const {\n\n return std::hash<std::string>{}(\n\n std::string(val.getSrcId(), val.getSrcIdLen()));\n\n }\n\n};\n\n\n\n} // namespace std\n\n#endif // GEODE_EVENTSOURCE_H_\n", "file_path": "cppcache/src/EventSource.hpp", "rank": 13, "score": 192331.53599279275 }, { "content": "class APACHE_GEODE_EXPORT Struct\n\n : public internal::DataSerializableFixedId_t<internal::DSFid::Struct> {\n\n public:\n\n typedef std::vector<std::shared_ptr<Serializable>>::iterator iterator;\n\n\n\n /**\n\n * Constructor - meant only for internal use.\n\n */\n\n Struct(StructSet* ssPtr,\n\n std::vector<std::shared_ptr<Serializable>>& fieldValues);\n\n\n\n Struct() = default;\n\n\n\n ~Struct() noexcept override = default;\n\n\n\n /**\n\n * Factory function for registration of <code>Struct</code>.\n\n */\n\n static std::shared_ptr<Serializable> createDeserializable();\n\n\n", "file_path": "cppcache/include/geode/Struct.hpp", "rank": 14, "score": 186961.13008538258 }, { "content": "class APACHE_GEODE_EXPORT Query {\n\n public:\n\n virtual ~Query() noexcept = default;\n\n\n\n /**\n\n * Executes the OQL Query on the cache server and returns the results.\n\n *\n\n * @param timeout The time to wait for query response, optional.\n\n *\n\n * @throws IllegalArgumentException If timeout exceeds 2147483647ms.\n\n * @throws QueryException if some query error occurred at the server.\n\n * @throws IllegalStateException if some error occurred.\n\n * @throws NotConnectedException if no java cache server is available. For\n\n * pools\n\n * configured with locators, if no locators are available, the cause of\n\n * NotConnectedException\n\n * is set to NoAvailableLocatorsException.\n\n * @returns A smart pointer to the SelectResults which can either be a\n\n * ResultSet or a StructSet.\n\n */\n", "file_path": "cppcache/include/geode/Query.hpp", "rank": 15, "score": 186961.1300853826 }, { "content": "class APACHE_GEODE_EXPORT Serializable {\n\n public:\n\n /**\n\n *@brief return the size in bytes of the instance being serialized.\n\n * This is used to determine whether the cache is using up more\n\n * physical memory than it has been configured to use. The method can\n\n * return zero if the user does not require the ability to control\n\n * cache memory utilization.\n\n * Note that you must implement this only if you use the HeapLRU feature.\n\n */\n\n virtual size_t objectSize() const;\n\n\n\n /**\n\n * Display this object as 'string', which depends on the implementation in\n\n * the subclasses. The default implementation renders the classname.\n\n */\n\n virtual std::string toString() const;\n\n\n\n /** Factory method that creates the Serializable object that matches the type\n\n * of value.\n", "file_path": "cppcache/include/geode/Serializable.hpp", "rank": 16, "score": 186961.13008538258 }, { "content": "class APACHE_GEODE_EXPORT Properties\n\n : public internal::DataSerializablePrimitive {\n\n public:\n", "file_path": "cppcache/include/geode/Properties.hpp", "rank": 17, "score": 186961.1300853826 }, { "content": "class APACHE_GEODE_EXPORT Delta {\n\n public:\n\n /**\n\n * <code>hasDelta( )</code> is invoked by Geode during <code>Region::put(\n\n * std::shared_ptr<CacheableKey>, std::shared_ptr<Cacheable> )</code> to\n\n * determine if the object contains a delta. If <code>hasDelta( )</code>\n\n * returns true, the delta in the object is serialized by invoking\n\n * <code>Delta::toDelta( DataOutput& )</code>. If <code>hasDelta( )</code>\n\n * returns false, the object is serialized by invoking\n\n * <code>Cacheable::toData( DataOutput& )</code>.\n\n */\n\n virtual bool hasDelta() const = 0;\n\n\n\n /**\n\n * Writes out delta information to out in a user-defined format. This is\n\n * invoked on an application object after Geode determines the presence\n\n * of delta in it by calling <code>hasDelta()</code> on the object.\n\n *\n\n * @throws IOException\n\n */\n", "file_path": "cppcache/include/geode/Delta.hpp", "rank": 18, "score": 186961.1300853826 }, { "content": "class APACHE_GEODE_EXPORT Execution {\n\n public:\n\n Execution();\n\n ~Execution() noexcept;\n\n Execution(Execution&& move) noexcept;\n\n Execution& operator=(Execution&& move) noexcept;\n\n\n\n /**\n\n * Specifies a data filter of routing objects for selecting the Geode\n\n * members\n\n * to execute the function.\n\n * <p>\n\n * If the filter set is empty the function is executed on all members\n\n * that have the FunctionService::onRegion(Region).</p>\n\n * @param routingObj Set defining the data filter to be used for executing the\n\n * function\n\n * @return an Execution with the filter\n\n * @throws IllegalArgumentException if filter passed is nullptr.\n\n * @throws UnsupportedOperationException if not called after\n\n * FunctionService::onRegion(Region).\n", "file_path": "cppcache/include/geode/Execution.hpp", "rank": 19, "score": 186961.1300853826 }, { "content": "struct hash<apache::geode::client::internal::DSFid>\n\n : public std::unary_function<apache::geode::client::internal::DSFid,\n\n size_t> {\n\n size_t operator()(apache::geode::client::internal::DSFid val) const {\n\n return std::hash<int32_t>{}(static_cast<int32_t>(val));\n\n }\n\n};\n\n\n\n} // namespace std\n\n\n\nnamespace apache {\n\nnamespace geode {\n\nnamespace client {\n\n\n\nusing internal::DataSerializableInternal;\n\nusing internal::DataSerializablePrimitive;\n\n\n", "file_path": "cppcache/src/SerializationRegistry.hpp", "rank": 20, "score": 186317.54240391447 }, { "content": "struct hash<apache::geode::client::internal::DSCode>\n\n : public std::unary_function<apache::geode::client::internal::DSCode,\n\n size_t> {\n\n size_t operator()(apache::geode::client::internal::DSCode val) const {\n\n return std::hash<int32_t>{}(static_cast<int32_t>(val));\n\n }\n\n};\n\n\n\ntemplate <>\n", "file_path": "cppcache/src/SerializationRegistry.hpp", "rank": 21, "score": 186317.54240391447 }, { "content": "#define GEODE_RESULTSET_H_\n\n\n\n#include \"SelectResults.hpp\"\n\n#include \"internal/geode_globals.hpp\"\n\n\n\nnamespace apache {\n\nnamespace geode {\n\nnamespace client {\n\n\n\n/**\n\n * @class ResultSet ResultSet.hpp\n\n * A ResultSet may be obtained after executing a Query which is obtained from a\n\n * QueryService which in turn is obtained from a Cache.\n\n */\n", "file_path": "cppcache/include/geode/ResultSet.hpp", "rank": 22, "score": 185442.1672564332 }, { "content": "#define GEODE_STRUCTSET_H_\n\n\n\n#include \"CqResults.hpp\"\n\n#include \"Struct.hpp\"\n\n#include \"internal/geode_globals.hpp\"\n\n\n\n/**\n\n * @file\n\n */\n\n\n\nnamespace apache {\n\nnamespace geode {\n\nnamespace client {\n\n\n\n/**\n\n * @class StructSet StructSet.hpp\n\n *\n\n * A StructSet may be obtained after executing a Query which is obtained from a\n\n * QueryService which in turn is obtained from a Cache.\n\n * It is the parent of a Struct which contains the field values.\n\n */\n", "file_path": "cppcache/include/geode/StructSet.hpp", "rank": 23, "score": 185441.52067265383 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one or more\n\n * contributor license agreements. See the NOTICE file distributed with\n\n * this work for additional information regarding copyright ownership.\n\n * The ASF licenses this file to You under the Apache License, Version 2.0\n\n * (the \"License\"); you may not use this file except in compliance with\n\n * the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#pragma once\n\n\n\n#ifndef GEODE_RESULTSET_H_\n", "file_path": "cppcache/include/geode/ResultSet.hpp", "rank": 24, "score": 185411.63781789542 }, { "content": "/*\n\n * Licensed to the Apache Software Foundation (ASF) under one or more\n\n * contributor license agreements. See the NOTICE file distributed with\n\n * this work for additional information regarding copyright ownership.\n\n * The ASF licenses this file to You under the Apache License, Version 2.0\n\n * (the \"License\"); you may not use this file except in compliance with\n\n * the License. You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#pragma once\n\n\n\n#ifndef GEODE_STRUCTSET_H_\n", "file_path": "cppcache/include/geode/StructSet.hpp", "rank": 25, "score": 185411.63781789542 }, { "content": "class APACHE_GEODE_EXPORT Cache : public GeodeCache {\n\n public:\n\n /**\n\n * Returns the {@link RegionFactory} to create the region.\n\n * Before creating the Region, one can set region attributes using this\n\n * instance.\n\n *\n\n * @param regionShortcut\n\n * To create the region specific type, @see RegionShortcut\n\n */\n\n virtual RegionFactory createRegionFactory(RegionShortcut regionShortcut);\n\n\n\n /**\n\n * Initializes the cache from an xml file\n\n *\n\n * @param cacheXml\n\n * Valid cache.xml file\n\n */\n\n void initializeDeclarativeCache(const std::string& cacheXml) override;\n\n\n", "file_path": "cppcache/include/geode/Cache.hpp", "rank": 26, "score": 183563.39081482074 }, { "content": "class TXId : public apache::geode::client::TransactionId {\n\n public:\n\n TXId();\n\n\n\n TXId& operator=(const TXId&);\n\n\n\n ~TXId() noexcept override;\n\n\n\n int32_t getId();\n\n\n\n // This method is only for testing and should not be used for any\n\n // other purpose. See TXIdTest.cpp for more details.\n\n static void setInitalTransactionIDValue(int32_t);\n\n\n\n private:\n\n int32_t m_TXId;\n\n static std::atomic<int32_t> m_transactionId;\n\n TXId(const TXId&);\n\n};\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_TXID_H_\n", "file_path": "cppcache/src/TXId.hpp", "rank": 27, "score": 182836.89994074972 }, { "content": "class GfshExecuteException : public apache::geode::client::Exception {\n\n int returnCode_;\n\n\n\n public:\n\n GfshExecuteException(std::string message, int returnCode);\n\n ~GfshExecuteException() override;\n\n std::string getName() const override;\n\n int getGfshReturnCode();\n\n};\n\n\n", "file_path": "cppcache/integration/framework/GfshExecute.h", "rank": 28, "score": 182836.89994074972 }, { "content": "class APACHE_GEODE_EXPORT GeodeCache : public RegionService {\n\n public:\n\n ~GeodeCache() override = 0;\n\n\n\n /** Returns the name of this cache.\n\n * @return the string name of this cache\n\n */\n\n virtual const std::string& getName() const = 0;\n\n\n\n /** Initialize the cache by the contents of an xml file\n\n * @param cacheXml\n\n * The xml file\n\n * @throws OutOfMemoryException\n\n * @throws CacheXmlException\n\n * Something went wrong while parsing the XML\n\n * @throws IllegalStateException\n\n * If xml file is well-flrmed but not valid\n\n * @throws RegionExistsException if a region is already in\n\n * this cache\n\n * @throws CacheClosedException if the cache is closed\n", "file_path": "cppcache/include/geode/GeodeCache.hpp", "rank": 29, "score": 181986.4403308846 }, { "content": "class StructSet;\n\n\n\n/**\n\n * @class Struct Struct.hpp\n\n * A Struct has a StructSet as its parent. It contains the field values\n\n * returned after executing a Query obtained from a QueryService which in turn\n\n * is obtained from a Cache.\n\n */\n", "file_path": "cppcache/include/geode/Struct.hpp", "rank": 30, "score": 180723.64700711812 }, { "content": "class APACHE_GEODE_EXPORT DataInput {\n\n public:\n\n /**\n\n * Read a signed byte from the <code>DataInput</code>.\n\n *\n\n * @@return signed byte read from stream\n\n */\n\n inline int8_t read() {\n\n _GEODE_CHECK_BUFFER_SIZE(1);\n\n return readNoCheck();\n\n }\n\n\n\n /**\n\n * Read a boolean value from the <code>DataInput</code>.\n\n */\n\n inline bool readBoolean() {\n\n _GEODE_CHECK_BUFFER_SIZE(1);\n\n return *(m_buf++) == 1 ? true : false;\n\n }\n\n\n", "file_path": "cppcache/include/geode/DataInput.hpp", "rank": 31, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT ResultCollector {\n\n /**\n\n * @brief public methods\n\n */\n\n public:\n\n ResultCollector() = default;\n\n virtual ~ResultCollector() noexcept = default;\n\n\n\n /**\n\n * Returns the result of function execution, potentially blocking until all\n\n * the results are available.\n\n * If geode sendException is called then {@link ResultCollector.getResult}\n\n * will not\n\n * throw exception but will have exception {@link\n\n * UserFunctionExecutionException} as a part of results received.\n\n * @param timeout if result is not ready within this time,\n\n * exception will be thrown\n\n * @return the result\n\n * @throws FunctionException if result retrieval fails\n\n * @see UserFunctionExecutionException\n", "file_path": "cppcache/include/geode/ResultCollector.hpp", "rank": 32, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheableVector\n\n : public internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>,\n\n internal::DSCode::CacheableVector, CacheableVector> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>, internal::DSCode::CacheableVector,\n\n CacheableVector>;\n\n\n\n/**\n\n * A mutable <code>CacheableKey</code> to <code>Serializable</code>\n\n * hash map that can serve as a distributable object for caching.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 33, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT AuthInitialize {\n\n public:\n\n virtual ~AuthInitialize() noexcept = default;\n\n\n\n /**@brief initialize with the given set of security properties\n\n * and return the credentials for the client as properties.\n\n * @param securityprops the set of security properties provided to the\n\n * <code>DistributedSystem.connect</code> method\n\n * @param server it is the ID of the current endpoint.\n\n * The format expected is \"host:port\".\n\n * @returns the credentials to be used for the given <code>server</code>\n\n * @remarks This method can modify the given set of properties. For\n\n * example it may invoke external agents or even interact with the user.\n\n */\n\n virtual std::shared_ptr<Properties> getCredentials(\n\n const std::shared_ptr<Properties>& securityprops,\n\n const std::string& server) = 0;\n\n\n\n /**@brief Invoked before the cache goes down. */\n\n virtual void close() = 0;\n\n};\n\n\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_AUTHINITIALIZE_H_\n", "file_path": "cppcache/include/geode/AuthInitialize.hpp", "rank": 34, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT RegionService {\n\n public:\n\n virtual ~RegionService() = 0;\n\n\n\n /**\n\n * Indicates if this cache has been closed.\n\n * After a new cache object is created, this method returns false;\n\n * After the close is called on this cache object, this method\n\n * returns true.\n\n *\n\n * @return true, if this cache is closed; false, otherwise\n\n */\n\n virtual bool isClosed() const = 0;\n\n\n\n /**\n\n * Terminates this object cache and releases all the local resources.\n\n * After this cache is closed, any further\n\n * method call on this cache or any region object will throw\n\n * <code>CacheClosedException</code>, unless otherwise noted.\n\n * If RegionService is created from {@link Cache#createAuthenticatedView\" },\n", "file_path": "cppcache/include/geode/RegionService.hpp", "rank": 35, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PdxWriter {\n\n public:\n\n /**\n\n * @brief constructors\n\n */\n\n PdxWriter() = default;\n\n\n\n PdxWriter(PdxWriter&& move) = default;\n\n\n\n /**\n\n * @brief destructor\n\n */\n\n virtual ~PdxWriter() = default;\n\n\n\n /**\n\n * Writes the named field with the given value to the serialized form\n\n * The fields type is <code>char16_t</code>\n\n * <p>C++ char16_t is mapped to Java char</p>\n\n * @param fieldName The name of the field to write\n\n * @param value The value of the field to write\n", "file_path": "cppcache/include/geode/PdxWriter.hpp", "rank": 36, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CqEvent {\n\n public:\n\n CqEvent() {}\n\n\n\n virtual ~CqEvent() {}\n\n /**\n\n * Get the CqQuery object of this event.\n\n * @see CqQuery\n\n * @return CqQuery object.\n\n */\n\n virtual std::shared_ptr<CqQuery> getCq() const = 0;\n\n\n\n /**\n\n * Get the operation on the base region that triggered this event.\n\n * @return Operation operation on the base region (on which CQ is created).\n\n */\n\n virtual CqOperation getBaseOperation() const = 0;\n\n\n\n /**\n\n * Get the operation on the query results. Supported operations\n", "file_path": "cppcache/include/geode/CqEvent.hpp", "rank": 37, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT EntryEvent {\n\n protected:\n\n std::shared_ptr<Region> m_region; /**< Region */\n\n std::shared_ptr<CacheableKey> m_key; /**< Cacheable key */\n\n std::shared_ptr<Cacheable> m_oldValue; /**< Old value */\n\n std::shared_ptr<Cacheable> m_newValue; /**< New value */\n\n std::shared_ptr<Serializable>\n\n m_callbackArgument; /**< Callback argument for this event, if any. */\n\n bool m_remoteOrigin; /**< True if from a remote (non-local) process */\n\n\n\n public:\n\n /** Constructor, given all values. */\n\n EntryEvent(const std::shared_ptr<Region>& region,\n\n const std::shared_ptr<CacheableKey>& key,\n\n const std::shared_ptr<Cacheable>& oldValue,\n\n const std::shared_ptr<Cacheable>& newValue,\n\n const std::shared_ptr<Serializable>& aCallbackArgument,\n\n const bool remoteOrigin);\n\n\n\n /** Destructor. */\n", "file_path": "cppcache/include/geode/EntryEvent.hpp", "rank": 38, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheableString\n\n : public internal::DataSerializablePrimitive,\n\n public CacheableKey {\n\n protected:\n\n std::string m_str;\n\n DSCode m_type;\n\n mutable int m_hashcode;\n\n\n\n public:\n\n inline explicit CacheableString(DSCode type = DSCode::CacheableASCIIString)\n\n : m_str(), m_type(type), m_hashcode(0) {}\n\n\n\n inline explicit CacheableString(const std::string& value)\n\n : CacheableString(std::string(value)) {}\n\n\n\n inline explicit CacheableString(std::string&& value)\n\n : m_str(std::move(value)), m_hashcode(0) {\n\n bool ascii = isAscii(m_str);\n\n\n\n m_type = m_str.length() > std::numeric_limits<uint16_t>::max()\n", "file_path": "cppcache/include/geode/CacheableString.hpp", "rank": 39, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PoolFactory {\n\n public:\n\n /**\n\n * The default amount of time which we will wait for a free connection if max\n\n * connections is set and all of the connections are in use.\n\n * <p>Current value: <code>10s</code>.\n\n */\n\n static const std::chrono::milliseconds DEFAULT_FREE_CONNECTION_TIMEOUT;\n\n\n\n /**\n\n * The default interval in which the pool will check to see if\n\n * a connection to a given server should be moved to a different\n\n * server to improve the load balance.\n\n * <p>Current value: <code>5min</code>\n\n */\n\n static const std::chrono::milliseconds DEFAULT_LOAD_CONDITIONING_INTERVAL;\n\n\n\n /**\n\n * The default size in bytes of the socket buffer on each connection\n\n * established.\n", "file_path": "cppcache/include/geode/PoolFactory.hpp", "rank": 40, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT FunctionService {\n\n public:\n\n /**\n\n * Returns a {@link Execution} object that can be used to execute a data\n\n * dependent function on the specified Region.<br>\n\n * When invoked from a Geode client, the method returns an Execution\n\n * instance that sends a message to one of the connected servers as specified\n\n * by the {@link Pool} for the region. Depending on the filters setup on the\n\n * {@link Execution}, the function is executed on all Geode members that\n\n * define the data region, or a subset of members.\n\n * {@link Execution::withFilter(filter)}).\n\n *\n\n * @param region\n\n * If Pool is multiusersecure mode then one need to pass nstance of Region\n\n * from RegionService.\n\n *\n\n * @return Execution\n\n * @throws NullPointerException\n\n * if the region passed in is nullptr\n\n */\n", "file_path": "cppcache/include/geode/FunctionService.hpp", "rank": 41, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheWriter {\n\n public:\n\n /**\n\n * Called before an entry is updated. The entry update is initiated by a\n\n * <code>put</code>\n\n * or a <code>get</code> that causes the loader to update an existing entry.\n\n * The entry previously existed in the cache where the operation was\n\n * initiated, although the old value may have been nullptr. The entry being\n\n * updated may or may not exist in the local cache where the CacheWriter is\n\n * installed.\n\n *\n\n * @param event EntryEvent denotes the event object associated with updating\n\n * the entry\n\n *\n\n *\n\n * @see Region::put\n\n * @see Region::get\n\n */\n\n virtual bool beforeUpdate(const EntryEvent& event);\n\n\n", "file_path": "cppcache/include/geode/CacheWriter.hpp", "rank": 42, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT SystemProperties {\n\n public:\n\n /**\n\n * Constructor. Will set the default values first, and then overwrite with\n\n * the values found in the given Properties object (if any), and\n\n * then from the values in the given file (if it exists).\n\n *\n\n * If useMemType is true, use the given member type; if false, always set\n\n * member type to SERVER.\n\n */\n\n explicit SystemProperties(const std::shared_ptr<Properties>& propertiesPtr,\n\n const std::string& configFile = \"\");\n\n\n\n SystemProperties(const SystemProperties& rhs) = delete;\n\n void operator=(const SystemProperties& rhs) = delete;\n\n\n\n /**\n\n * Destructor.\n\n */\n\n ~SystemProperties();\n", "file_path": "cppcache/include/geode/SystemProperties.hpp", "rank": 43, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheFactory {\n\n public:\n\n /**\n\n * To create the instance of {@link CacheFactory}\n\n */\n\n CacheFactory() noexcept;\n\n\n\n /**\n\n * To create the instance of {@link CacheFactory}\n\n * @param properties\n\n * Properties which are applicable at client level.\n\n */\n\n explicit CacheFactory(const std::shared_ptr<Properties>& properties) noexcept;\n\n\n\n ~CacheFactory() = default;\n\n\n\n /**\n\n * To create the instance of {@link Cache}.\n\n */\n\n Cache create() const;\n", "file_path": "cppcache/include/geode/CacheFactory.hpp", "rank": 44, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CqAttributes {\n\n public:\n\n virtual ~CqAttributes() noexcept = default;\n\n\n\n /**\n\n * CqListeners type\n\n */\n\n typedef std::vector<std::shared_ptr<CqListener>> listener_container_type;\n\n\n\n /**\n\n * Get the CqListeners set with the CQ.\n\n * Returns all the Listeners associated with this CQ.\n\n * @see CqListener\n\n * @returns listener_container_type\n\n */\n\n virtual listener_container_type getCqListeners() = 0;\n\n};\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_CQATTRIBUTES_H_\n", "file_path": "cppcache/include/geode/CqAttributes.hpp", "rank": 45, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheableEnum\n\n : public internal::DataSerializablePrimitive,\n\n public CacheableKey {\n\n private:\n\n std::string m_enumClassName;\n\n std::string m_enumName;\n\n int32_t m_ordinal;\n\n int32_t m_hashcode;\n\n\n\n public:\n\n inline CacheableEnum()\n\n : m_enumClassName(nullptr),\n\n m_enumName(nullptr),\n\n m_ordinal(-1),\n\n m_hashcode(0) {}\n\n inline CacheableEnum(std::string enumClassName, std::string enumName,\n\n int32_t ordinal)\n\n : m_enumClassName(std::move(enumClassName)),\n\n m_enumName(std::move(enumName)),\n\n m_ordinal(ordinal),\n", "file_path": "cppcache/include/geode/CacheableEnum.hpp", "rank": 46, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT TransactionId {\n\n public:\n\n TransactionId();\n\n virtual ~TransactionId();\n\n};\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_TRANSACTIONID_H_\n", "file_path": "cppcache/include/geode/TransactionId.hpp", "rank": 47, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT RegionEntry {\n\n public:\n\n /**\n\n * @brief constructors\n\n * created by region\n\n */\n\n RegionEntry(const std::shared_ptr<Region>& region,\n\n const std::shared_ptr<CacheableKey>& key,\n\n const std::shared_ptr<Cacheable>& value);\n\n virtual ~RegionEntry() noexcept;\n\n\n\n /** Returns the key for this entry.\n\n *\n\n * @return the key for this entry\n\n */\n\n std::shared_ptr<CacheableKey> getKey();\n\n\n\n /** Returns the value of this entry in the local cache. Does not invoke\n\n * a <code>CacheLoader</code>,\n\n *\n", "file_path": "cppcache/include/geode/RegionEntry.hpp", "rank": 48, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PdxSerializer {\n\n public:\n\n PdxSerializer() {}\n\n\n\n virtual ~PdxSerializer() {}\n\n\n\n /**\n\n * Deserialize this object.\n\n *\n\n * @param className the class name whose object needs to be de-serialized\n\n * @param pdxReader the PdxReader stream to use for reading the object data\n\n */\n\n virtual std::shared_ptr<void> fromData(const std::string& className,\n\n PdxReader& pdxReader) = 0;\n\n\n\n /**\n\n * Serializes this object in Geode PDX format.\n\n * @param userObject the object which needs to be serialized\n\n * @param pdxWriter the PdxWriter object to use for serializing the object\n\n */\n", "file_path": "cppcache/include/geode/PdxSerializer.hpp", "rank": 49, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT RegionFactory {\n\n public:\n\n RegionFactory() = delete;\n\n ~RegionFactory() = default;\n\n RegionFactory(const RegionFactory& nocopy) = delete;\n\n RegionFactory(RegionFactory&& move) = default;\n\n\n\n /**\n\n * Create a {@link Region} of the given <code>name</code>.\n\n * @param name\n\n * the name of the Region.\n\n * @throws RegionExistsException if a region is already in\n\n * this cache\n\n * @throws CacheClosedException if the cache is closed\n\n */\n\n std::shared_ptr<Region> create(std::string name);\n\n\n\n /** Sets the cache loader for the next <code>RegionAttributes</code> created.\n\n * @param cacheLoader the cache loader or nullptr if no loader\n\n * @return a reference to <code>this</code>\n", "file_path": "cppcache/include/geode/RegionFactory.hpp", "rank": 50, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CqQuery {\n\n public:\n\n /**\n\n * Get the query string provided when a new Query was created from a\n\n * QueryService.\n\n * @returns The query string.\n\n */\n\n virtual const std::string& getQueryString() const = 0;\n\n\n\n /**\n\n * Get teh query object generated for this CQs query.\n\n * @return Query object for the query string\n\n */\n\n virtual std::shared_ptr<Query> getQuery() const = 0;\n\n\n\n /**\n\n * Get the name of the CQ.\n\n * @return the name of the CQ.\n\n */\n\n virtual const std::string& getName() const = 0;\n", "file_path": "cppcache/include/geode/CqQuery.hpp", "rank": 51, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CqListener {\n\n public:\n\n virtual ~CqListener() noexcept = default;\n\n\n\n CqListener();\n\n CqListener(const CacheListener& other) = delete;\n\n\n\n void operator=(const CqListener& other) = delete;\n\n\n\n /**\n\n * This method is invoked when an event is occurred on the region\n\n * that satisfied the query condition of this CQ.\n\n * This event does not contain an error.\n\n */\n\n virtual void onEvent(const CqEvent& aCqEvent);\n\n\n\n /**\n\n * This method is invoked when there is an error during CQ processing.\n\n * The error can appear while applying query condition on the event.\n\n * e.g if the event doesn't has attributes as specified in the CQ query.\n", "file_path": "cppcache/include/geode/CqListener.hpp", "rank": 52, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CqStatistics {\n\n public:\n\n /**\n\n * Get number of Insert events qualified by this CQ.\n\n * @return number of inserts.\n\n */\n\n virtual uint32_t numInserts() const = 0;\n\n\n\n /**\n\n * Get number of Delete events qualified by this CQ.\n\n * @return number of deletes.\n\n */\n\n virtual uint32_t numDeletes() const = 0;\n\n\n\n /**\n\n * Get number of Update events qualified by this CQ.\n\n * @return number of updates.\n\n */\n\n virtual uint32_t numUpdates() const = 0;\n\n\n", "file_path": "cppcache/include/geode/CqStatistics.hpp", "rank": 53, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT QueryService {\n\n public:\n\n typedef std::vector<std::shared_ptr<CqQuery>> query_container_type;\n\n\n\n /**\n\n * Get a new Query with the specified query string.\n\n *\n\n * @param querystr The query string with which to create a new Query.\n\n * @returns A smart pointer to the Query.\n\n */\n\n virtual std::shared_ptr<Query> newQuery(std::string querystr) = 0;\n\n\n\n /**\n\n * Constructs a new named continuous query, represented by an instance of\n\n * CqQuery. The CqQuery is not executed, however, until the execute method\n\n * is invoked on the CqQuery. The name of the query will be used\n\n * to identify this query in statistics archival.\n\n *\n\n * @param name the String name for this query\n\n * @param querystr the OQL query\n", "file_path": "cppcache/include/geode/QueryService.hpp", "rank": 54, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheableStack\n\n : public internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>,\n\n internal::DSCode::CacheableStack, CacheableStack> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n HashMapOfCacheable, internal::DSCode::CacheableStack, CacheableStack>;\n\n\n\n/**\n\n * A mutable <code>CacheableKey</code> to <code>Serializable</code>\n\n * hash map that can serve as a distributable object for caching.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 55, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT ExpirationAttributes {\n\n /**\n\n * @brief public methods\n\n */\n\n public:\n\n /**\n\n *@brief constructors\n\n */\n\n\n\n /** Constructs a default <code>ExpirationAttributes</code>, which indicates no\n\n * expiration\n\n * will take place.\n\n */\n\n ExpirationAttributes();\n\n\n\n /** Constructs an <code>ExpirationAttributes</code> with the specified\n\n * expiration time and\n\n * expiration action.\n\n * @param expirationTime Duration live before it expires\n\n * @param expirationAction the action to take when the value expires\n", "file_path": "cppcache/include/geode/ExpirationAttributes.hpp", "rank": 56, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT RegionEvent {\n\n protected:\n\n const std::shared_ptr<Region> m_region; /**< Region for this event. */\n\n const std::shared_ptr<Serializable>\n\n m_callbackArgument; /**< Callback argument for this event, if any. */\n\n const bool m_remoteOrigin; /**< True if from a remote process. */\n\n\n\n public:\n\n /** Constructor. */\n\n RegionEvent();\n\n /** Constructor, given the values. */\n\n RegionEvent(const std::shared_ptr<Region>& region,\n\n const std::shared_ptr<Serializable>& aCallbackArgument,\n\n const bool remoteOrigin);\n\n\n\n /** Destructor. */\n\n ~RegionEvent();\n\n\n\n /** Return the region this event occurred in. */\n\n inline std::shared_ptr<Region> getRegion() const { return m_region; }\n", "file_path": "cppcache/include/geode/RegionEvent.hpp", "rank": 57, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PdxReader {\n\n public:\n\n /**\n\n * @brief constructors\n\n */\n\n PdxReader() {}\n\n\n\n /**\n\n * @brief destructor\n\n */\n\n virtual ~PdxReader() {}\n\n\n\n /**\n\n * Read a wide char value from the <code>PdxReader</code>.\n\n * <p>C++ char16_t is mapped to Java char</p>\n\n * @param fieldName name of the field to read.\n\n * @return value of type wchar_t.\n\n * @throws IllegalStateException if PdxReader doesn't have the named field.\n\n *\n\n * @see PdxReader#hasField\n", "file_path": "cppcache/include/geode/PdxReader.hpp", "rank": 58, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT DataOutput {\n\n public:\n\n /**\n\n * Write an unsigned byte to the <code>DataOutput</code>.\n\n *\n\n * @param value the unsigned byte to be written\n\n */\n\n inline void write(uint8_t value) {\n\n ensureCapacity(1);\n\n writeNoCheck(value);\n\n }\n\n\n\n /**\n\n * Write a signed byte to the <code>DataOutput</code>.\n\n *\n\n * @param value the signed byte to be written\n\n */\n\n inline void write(int8_t value) { write(static_cast<uint8_t>(value)); }\n\n\n\n /**\n", "file_path": "cppcache/include/geode/DataOutput.hpp", "rank": 59, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheStatistics {\n\n private:\n\n using time_point = std::chrono::steady_clock::time_point;\n\n\n\n public:\n\n CacheStatistics();\n\n CacheStatistics(const CacheStatistics&) = delete;\n\n virtual ~CacheStatistics();\n\n\n\n /**\n\n * For an entry, returns the time that the entry's value was last modified.\n\n * For a region, returns the last time any of the region's entries' values or\n\n * the values in subregions' entries were modified. The\n\n * modification may have been initiated locally, or it may have been an update\n\n * distributed from another cache. It may also have been a new value provided\n\n * by a loader. The modification time on a region is propagated upward to\n\n * parent regions, transitively, to the root region.\n\n * <p>\n\n * Entry and subregion creation will update the modification time on a\n\n * region, but <code>destroy</code>, <code>destroyRegion</code>,\n", "file_path": "cppcache/include/geode/CacheStatistics.hpp", "rank": 60, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PartitionResolver {\n\n /**\n\n * @brief public methods\n\n */\n\n\n\n public:\n\n /**\n\n * @brief destructor\n\n */\n\n virtual ~PartitionResolver();\n\n\n\n /**\n\n * Returns the name of the PartitionResolver\n\n * @return String name\n\n */\n\n virtual const std::string& getName();\n\n\n\n /**\n\n * @param opDetails the detail of the entry event\n\n * @throws RuntimeException - any exception thrown will terminate the\n", "file_path": "cppcache/include/geode/PartitionResolver.hpp", "rank": 61, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT TypeRegistry {\n\n public:\n\n explicit TypeRegistry(CacheImpl* cache);\n\n\n\n /**\n\n * @brief register an instance factory method for a given type.\n\n * During registration the factory will be invoked to extract the typeId\n\n * to associate with this function.\n\n * @throws IllegalStateException if the typeId has already been\n\n * registered, or there is an error in registering the type; check errno\n\n * for more information in the latter case.\n\n */\n\n void registerType(TypeFactoryMethod creationFunction, int32_t id);\n\n\n\n /**\n\n * @brief register an Pdx instance factory method for a given type.\n\n * @throws IllegalStateException if the typeName has already been registered,\n\n * or there is an error in registering the type; check errno for\n\n * more information in the latter case.\n\n */\n", "file_path": "cppcache/include/geode/TypeRegistry.hpp", "rank": 62, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT SelectResults {\n\n public:\n\n virtual ~SelectResults() noexcept = default;\n\n\n\n /**\n\n * Get the size of the SelectResults.\n\n *\n\n * @returns the number of items in the SelectResults.\n\n */\n\n virtual size_t size() const = 0;\n\n\n\n /**\n\n * Index operator to directly access an item in the SelectResults.\n\n *\n\n * @param index the index number of the required item.\n\n * @throws IllegalArgumentException if the index is out of bounds.\n\n * @returns A smart pointer to the item indexed.\n\n */\n\n virtual const std::shared_ptr<Serializable> operator[](\n\n size_t index) const = 0;\n", "file_path": "cppcache/include/geode/SelectResults.hpp", "rank": 63, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheListener {\n\n /**\n\n * @brief public methods\n\n */\n\n public:\n\n /**\n\n * @brief destructor\n\n */\n\n virtual ~CacheListener();\n\n\n\n /** Handles the event of a new key being added to a region. The entry\n\n * did not previously exist in this region in the local cache (even with a\n\n * nullptr value).\n\n *\n\n * @param event denotes the event object associated with the entry creation\n\n * This function does not throw any exception.\n\n * @see Region::create\n\n * @see Region::put\n\n * @see Region::get\n\n */\n", "file_path": "cppcache/include/geode/CacheListener.hpp", "rank": 64, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PoolManager {\n\n public:\n\n /**\n\n * Creates a new {@link PoolFactory pool factory},\n\n * which is used to configure and create new {@link Pool}s.\n\n * @return the new pool factory\n\n */\n\n PoolFactory createFactory() const;\n\n\n\n /**\n\n * Returns a map containing all the pools in this manager.\n\n * The keys are pool names\n\n * and the values are {@link Pool} instances.\n\n * <p> The map contains the pools that this manager knows of at the time of\n\n * this call.\n\n * The map is free to be changed without affecting this manager.\n\n * @return a Map that is a snapshot of all the pools currently known to this\n\n * manager.\n\n */\n\n const HashMapOfPools& getAll() const;\n", "file_path": "cppcache/include/geode/PoolManager.hpp", "rank": 65, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT RegionAttributes\n\n : public internal::DataSerializableInternal {\n\n /**\n\n * @brief public static methods\n\n */\n\n public:\n\n /** Gets the cache loader for the region.\n\n * @return a pointer that points to the region's ,\n\n * <code>CacheLoader</code> , nullptr if there is no CacheLoader for this\n\n * region.\n\n */\n\n std::shared_ptr<CacheLoader> getCacheLoader() const;\n\n\n\n /** Gets the cache writer for the region.\n\n * @return a pointer that points to the region's ,\n\n * <code>CacheWriter</code> , nullptr if there is no CacheWriter for this\n\n * region\n\n */\n\n std::shared_ptr<CacheWriter> getCacheWriter() const;\n\n\n", "file_path": "cppcache/include/geode/RegionAttributes.hpp", "rank": 66, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT PersistenceManager {\n\n public:\n\n /**\n\n * Returns the current persistence manager.\n\n * @return persistence manager\n\n */\n\n static std::shared_ptr<PersistenceManager> getPersistenceManager();\n\n\n\n /**\n\n * Writes a key, value pair of region to the disk. The actual file or database\n\n * related write operations should be implemented\n\n * in this method by the class implementing this method.\n\n * @param key the key to write.\n\n * @param value the value to write\n\n * @param persistenceInfo related persistence information.\n\n * @throws RegionDestroyedException is the region is already destroyed.\n\n * @throws OutofMemoryException if the disk is full\n\n * @throws DiskFailureException if the write fails due to disk fail.\n\n */\n\n virtual void write(const std::shared_ptr<CacheableKey>& key,\n", "file_path": "cppcache/include/geode/PersistenceManager.hpp", "rank": 67, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheableDate\n\n : public internal::DataSerializablePrimitive,\n\n public CacheableKey {\n\n private:\n\n /**\n\n * Milliseconds since January 1, 1970, 00:00:00 GMT to be consistent with Java\n\n * Date.\n\n */\n\n int64_t m_timevalue;\n\n\n\n public:\n\n typedef std::chrono::system_clock clock;\n\n typedef std::chrono::time_point<clock> time_point;\n\n typedef std::chrono::milliseconds duration;\n\n\n\n /** Constructor, used for deserialization. */\n\n explicit CacheableDate(const time_t value = 0);\n\n\n\n /**\n\n * Construct from std::chrono::time_point<std::chrono::system_clock>.\n", "file_path": "cppcache/include/geode/CacheableDate.hpp", "rank": 68, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT AttributesMutator {\n\n private:\n\n std::shared_ptr<Region> m_region;\n\n\n\n public:\n\n /** Internal constructor. Use Region::getAttributesMutator() to acquire the\n\n * mutator for a region. */\n\n explicit AttributesMutator(const std::shared_ptr<Region>& region);\n\n\n\n virtual ~AttributesMutator();\n\n\n\n /** Sets the idleTimeout duration for region entries.\n\n * @param idleTimeout the idleTimeout for entries in this region.\n\n * @return the previous value.\n\n * @throw IllegalStateException if the new idleTimeout changes entry\n\n * expiration from\n\n * disabled to enabled or enabled to disabled.\n\n */\n\n std::chrono::seconds setEntryIdleTimeout(std::chrono::seconds idleTimeout);\n\n\n", "file_path": "cppcache/include/geode/AttributesMutator.hpp", "rank": 69, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheableUndefined\n\n : public internal::DataSerializableFixedId_t<\n\n internal::DSFid::CacheableUndefined> {\n\n public:\n\n inline CacheableUndefined() = default;\n\n virtual ~CacheableUndefined() noexcept override = default;\n\n CacheableUndefined& operator=(const CacheableUndefined& other) = delete;\n\n CacheableUndefined(const CacheableUndefined& other) = delete;\n\n\n\n void toData(DataOutput&) const override;\n\n\n\n void fromData(DataInput&) override;\n\n\n\n /**\n\n * @brief creation function for undefined query result\n\n */\n\n inline static std::shared_ptr<Serializable> createDeserializable() {\n\n return std::make_shared<CacheableUndefined>();\n\n }\n\n\n", "file_path": "cppcache/include/geode/CacheableUndefined.hpp", "rank": 70, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT CacheLoader {\n\n public:\n\n virtual ~CacheLoader() = default;\n\n CacheLoader(const CacheLoader& other) = delete;\n\n void operator=(const CacheLoader& other) = delete;\n\n\n\n /**Loads a value. Application writers should implement this\n\n * method to customize the loading of a value. This method is called\n\n * by the caching service when the requested value is not in the cache.\n\n * Any exception thrown by this method is propagated back to and thrown\n\n * by the invocation of {@link Region::get} that triggered this load.\n\n * @param rp a Region Pointer for which this is called.\n\n * @param key the key for the cacheable\n\n * @param helper any related user data, or nullptr\n\n * @return the value supplied for this key, or nullptr if no value can be\n\n * supplied.\n\n *\n\n *@see Region::get .\n\n */\n\n virtual std::shared_ptr<Cacheable> load(\n", "file_path": "cppcache/include/geode/CacheLoader.hpp", "rank": 71, "score": 179571.42175313426 }, { "content": "class APACHE_GEODE_EXPORT GeodeIOException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~GeodeIOException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::GeodeIOException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when geode configuration file is incorrect.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 72, "score": 177359.2680439263 }, { "content": "class APACHE_GEODE_EXPORT GeodeConfigException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~GeodeConfigException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::GeodeConfigException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when a null argument is provided to a method\n\n * where it is expected to be non-null.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 73, "score": 177359.2680439263 }, { "content": "class APACHE_GEODE_EXPORT CacheableLinkedList\n\n : public internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>,\n\n internal::DSCode::CacheableLinkedList, CacheableLinkedList> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>,\n\n internal::DSCode::CacheableLinkedList, CacheableLinkedList>;\n\n\n\n/**\n\n * A mutable <code>Cacheable</code> stack wrapper that can serve as\n\n * a distributable object for caching.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 74, "score": 176099.81515961196 }, { "content": "class APACHE_GEODE_EXPORT CacheableHashMap\n\n : public internal::CacheableContainerPrimitive<\n\n HashMapOfCacheable, internal::DSCode::CacheableHashMap,\n\n CacheableHashMap> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n HashMapOfCacheable, internal::DSCode::CacheableHashMap, CacheableHashMap>;\n\n\n\n/**\n\n * A mutable <code>CacheableKey</code> hash set wrapper that can serve as\n\n * a distributable object for caching.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 75, "score": 176099.81515961196 }, { "content": "class APACHE_GEODE_EXPORT Exception : public std::exception {\n\n public:\n\n explicit Exception(const std::string& message);\n\n explicit Exception(std::string&& message);\n\n explicit Exception(const char* message);\n\n Exception(const Exception&) = default;\n\n Exception& operator=(const Exception&) = default;\n\n Exception(Exception&&) noexcept = default;\n\n Exception& operator=(Exception&&) = default;\n\n ~Exception() noexcept override;\n\n\n\n /**\n\n * Get a stacktrace string from the location the exception was created.\n\n */\n\n virtual std::string getStackTrace() const;\n\n\n\n /**\n\n * Return the name of this exception type.\n\n * */\n\n virtual std::string getName() const;\n", "file_path": "cppcache/include/geode/Exception.hpp", "rank": 76, "score": 176099.81515961196 }, { "content": "class APACHE_GEODE_EXPORT CacheableHashTable\n\n : public internal::CacheableContainerPrimitive<\n\n HashMapOfCacheable, internal::DSCode::CacheableHashTable,\n\n CacheableHashTable> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n HashMapOfCacheable, internal::DSCode::CacheableHashTable,\n\n CacheableHashTable>;\n\n\n\n/**\n\n * A mutable <code>CacheableKey</code> to <code>Serializable</code>\n\n * hash map that can serve as a distributable object for caching. This is\n\n * provided for compability with java side, though is functionally identical\n\n * to <code>CacheableHashMap</code> i.e. does not provide the semantics of\n\n * java <code>IdentityHashMap</code>.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 77, "score": 176099.81515961196 }, { "content": "class APACHE_GEODE_EXPORT CacheableArrayList\n\n : public internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>,\n\n internal::DSCode::CacheableArrayList, CacheableArrayList> {\n\n public:\n\n using CacheableContainerPrimitive::CacheableContainerPrimitive;\n\n};\n\n\n\ntemplate class internal::CacheableContainerPrimitive<\n\n std::vector<std::shared_ptr<Cacheable>>,\n\n internal::DSCode::CacheableArrayList, CacheableArrayList>;\n\n\n\n/**\n\n * A mutable <code>Cacheable</code> array list wrapper that can serve as\n\n * a distributable object for caching.\n\n */\n", "file_path": "cppcache/include/geode/CacheableBuiltins.hpp", "rank": 78, "score": 176099.81515961196 }, { "content": "struct _is_duration<const volatile std::chrono::duration<Rep, Period>>\n\n : std::true_type {};\n\n\n\n/**\n\n * Converts std::chrono:duration from given unit to other where other duration\n\n * is no less than the given duration.\n\n *\n\n * For internal use only.\n\n */\n\ntemplate <class ToDuration, class Rep, class Period>\n\ninline\n\n typename std::enable_if<_is_duration<ToDuration>::value, ToDuration>::type\n\n _ceil(const std::chrono::duration<Rep, Period>& duration) {\n\n ToDuration other = std::chrono::duration_cast<ToDuration>(duration);\n\n if (other < duration) {\n\n return other + ToDuration{1};\n\n }\n\n return other;\n\n}\n\n\n", "file_path": "cppcache/include/geode/internal/chrono/duration.hpp", "rank": 79, "score": 174115.38600519588 }, { "content": "class SimpleAuthInitialize : public apache::geode::client::AuthInitialize {\n\n public:\n\n std::shared_ptr<apache::geode::client::Properties> getCredentials(\n\n const std::shared_ptr<apache::geode::client::Properties>& securityprops,\n\n const std::string& /*server*/) override;\n\n\n\n void close() override;\n\n\n\n SimpleAuthInitialize();\n\n\n\n SimpleAuthInitialize(std::string username, std::string password);\n\n\n\n ~SimpleAuthInitialize() override = default;\n\n\n\n int32_t getGetCredentialsCallCount();\n\n\n\n private:\n\n std::string username_;\n\n std::string password_;\n\n int32_t countOfGetCredentialsCalls_;\n\n};\n\n\n\n#endif // SIMPLEAUTHINITIALIZE_H_\n", "file_path": "cppcache/integration/test/SimpleAuthInitialize.hpp", "rank": 80, "score": 173253.53733681756 }, { "content": "class ExampleAuthInitialize : public apache::geode::client::AuthInitialize {\n\n std::shared_ptr<apache::geode::client::Properties> getCredentials(\n\n const std::shared_ptr<apache::geode::client::Properties>& securityprops,\n\n const std::string& server) override;\n\n\n\n void close() override;\n\n\n\n public:\n\n ExampleAuthInitialize();\n\n ~ExampleAuthInitialize() noexcept = default;\n\n};", "file_path": "examples/cpp/authinitialize/exampleAuthInitialize.hpp", "rank": 81, "score": 173253.53733681756 }, { "content": "class SimpleCqListener : public apache::geode::client::CqListener {\n\n public:\n\n SimpleCqListener(std::shared_ptr<boost::latch> createLatch,\n\n std::shared_ptr<boost::latch> updateLatch,\n\n std::shared_ptr<boost::latch> destroyLatch);\n\n void onEvent(const apache::geode::client::CqEvent& cqEvent) override;\n\n void onError(const apache::geode::client::CqEvent& cqEvent) override;\n\n void close() override;\n\n\n\n private:\n\n std::shared_ptr<boost::latch> createLatch_;\n\n std::shared_ptr<boost::latch> updateLatch_;\n\n std::shared_ptr<boost::latch> destroyLatch_;\n\n};\n\n\n\n#endif // SIMPLE_CQ_LISTENER_H\n", "file_path": "cppcache/integration/test/SimpleCqListener.hpp", "rank": 82, "score": 173253.53733681756 }, { "content": "class APACHE_GEODE_EXPORT UnknownException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~UnknownException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::UnknownException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when a cast operation fails.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 83, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT RollbackException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~RollbackException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::RollbackException\";\n\n }\n\n};\n\n/**\n\n * @brief Thrown when a commit fails due to a write conflict.\n\n * @see CacheTransactionManager#commit\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 84, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT CacheableObjectArray\n\n : public internal::DataSerializablePrimitive,\n\n public std::vector<std::shared_ptr<Cacheable>> {\n\n public:\n\n /** Constructor, used for deserialization. */\n\n inline CacheableObjectArray() : std::vector<std::shared_ptr<Cacheable>>() {}\n\n\n\n /** Create a vector with n elements allocated. */\n\n inline explicit CacheableObjectArray(int32_t n)\n\n : std::vector<std::shared_ptr<Cacheable>>(n) {}\n\n\n\n ~CacheableObjectArray() noexcept override = default;\n\n\n\n CacheableObjectArray& operator=(const CacheableObjectArray& other) = delete;\n\n CacheableObjectArray(const CacheableObjectArray& other) = delete;\n\n\n\n void toData(DataOutput& output) const override;\n\n\n\n virtual void fromData(DataInput& input) override;\n\n\n", "file_path": "cppcache/include/geode/CacheableObjectArray.hpp", "rank": 85, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT AssertionException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~AssertionException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::AssertionException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when an argument to a method is illegal.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 86, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT NotConnectedException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~NotConnectedException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::NotConnectedException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when there is an error in the cache proxy.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 87, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT QueryException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~QueryException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::QueryException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when an unknown message is received from the server.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 88, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT CqServiceStatistics {\n\n public:\n\n virtual ~CqServiceStatistics() noexcept = default;\n\n\n\n /**\n\n * Get the number of CQs currently active.\n\n * Active CQs are those which are executing (in running state).\n\n * @return number of CQs\n\n */\n\n virtual uint32_t numCqsActive() const = 0;\n\n\n\n /**\n\n * Get the total number of CQs created. This is a cumulative number.\n\n * @return number of CQs created.\n\n */\n\n virtual uint32_t numCqsCreated() const = 0;\n\n\n\n /**\n\n * Get the total number of closed CQs. This is a cumulative number.\n\n * @return number of CQs closed.\n", "file_path": "cppcache/include/geode/CqServiceStatistics.hpp", "rank": 89, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT OutOfMemoryException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~OutOfMemoryException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::OutOfMemoryException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when an attempt is made to release a lock not\n\n * owned by the thread.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 90, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT NotAuthorizedException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~NotAuthorizedException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::NotAuthorizedException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when authentication fails.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 91, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT CqAttributesMutator {\n\n public:\n\n /** Constructs a <code>CqAttributesMutator</code> with the given {@link\n\n * CqAttributes}.\n\n */\n\n explicit CqAttributesMutator(const std::shared_ptr<CqAttributes>& impl);\n\n\n\n /**\n\n * Adds a CQ listener to the end of the list of CQ listeners on this CqQuery.\n\n * @param aListener the user defined CQ listener to add to the CqQuery.\n\n * @throws IllegalArgumentException if <code>aListener</code> is nullptr\n\n */\n\n void addCqListener(const std::shared_ptr<CqListener>& aListener);\n\n\n\n /**\n\n * Removes given CQ listener from the list of CQ listeners on this CqQuery.\n\n * Does nothing if the specified listener has not been added.\n\n * If the specified listener has been added then will\n\n * be called on it; otherwise does nothing.\n\n * @param aListener the CQ listener to remove from the CqQuery.\n", "file_path": "cppcache/include/geode/CqAttributesMutator.hpp", "rank": 92, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT NoSystemException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~NoSystemException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::NoSystemException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when an attempt is made to connect to\n\n * DistributedSystem second time.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 93, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT PdxUnreadFields {\n\n public:\n\n PdxUnreadFields() = default;\n\n virtual ~PdxUnreadFields() = default;\n\n};\n\n} // namespace client\n\n} // namespace geode\n\n} // namespace apache\n\n\n\n#endif // GEODE_PDXUNREADFIELDS_H_\n", "file_path": "cppcache/include/geode/PdxUnreadFields.hpp", "rank": 94, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT MessageException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~MessageException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::MessageException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when a non authorized operation is done.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 95, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT TransactionException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~TransactionException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::TransactionException\";\n\n }\n\n};\n\n/**\n\n * @brief The RollbackException exception indicates that either the transaction\n\n * has been rolled back or an operation cannot complete because the\n\n * transaction is marked for rollback only.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 96, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT NotOwnerException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~NotOwnerException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::NotOwnerException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when a region is created in an incorrect scope.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 97, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT OutOfRangeException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~OutOfRangeException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::OutOfRangeException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when query exception occurs at the server.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 98, "score": 172764.93089918632 }, { "content": "class APACHE_GEODE_EXPORT InterruptedException : public Exception {\n\n public:\n\n using Exception::Exception;\n\n ~InterruptedException() noexcept override {}\n\n std::string getName() const override {\n\n return \"apache::geode::client::InterruptedException\";\n\n }\n\n};\n\n\n\n/**\n\n *@brief Thrown when an operation unsupported by the\n\n * current configuration is attempted.\n\n **/\n", "file_path": "cppcache/include/geode/ExceptionTypes.hpp", "rank": 99, "score": 172764.93089918632 } ]
C++
content/renderer/history_controller.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
#include "content/renderer/history_controller.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_view_impl.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" using blink::WebFrame; using blink::WebHistoryCommitType; using blink::WebHistoryItem; using blink::WebURLRequest; namespace content { HistoryController::HistoryController(RenderViewImpl* render_view) : render_view_(render_view) { } HistoryController::~HistoryController() { } void HistoryController::GoToEntry(scoped_ptr<HistoryEntry> target_entry, WebURLRequest::CachePolicy cache_policy) { HistoryFrameLoadVector same_document_loads; HistoryFrameLoadVector different_document_loads; provisional_entry_ = target_entry.Pass(); WebFrame* main_frame = render_view_->GetMainRenderFrame()->GetWebFrame(); if (current_entry_) { RecursiveGoToEntry( main_frame, same_document_loads, different_document_loads); } if (same_document_loads.empty() && different_document_loads.empty()) { different_document_loads.push_back( std::make_pair(main_frame, provisional_entry_->root())); } for (size_t i = 0; i < same_document_loads.size(); ++i) { WebFrame* frame = same_document_loads[i].first; if (!RenderFrameImpl::FromWebFrame(frame)) continue; frame->loadHistoryItem(same_document_loads[i].second, blink::WebHistorySameDocumentLoad, cache_policy); } for (size_t i = 0; i < different_document_loads.size(); ++i) { WebFrame* frame = different_document_loads[i].first; if (!RenderFrameImpl::FromWebFrame(frame)) continue; frame->loadHistoryItem(different_document_loads[i].second, blink::WebHistoryDifferentDocumentLoad, cache_policy); } } void HistoryController::RecursiveGoToEntry( WebFrame* frame, HistoryFrameLoadVector& same_document_loads, HistoryFrameLoadVector& different_document_loads) { DCHECK(provisional_entry_); DCHECK(current_entry_); RenderFrameImpl* render_frame = RenderFrameImpl::FromWebFrame(frame); const WebHistoryItem& new_item = provisional_entry_->GetItemForFrame(render_frame); const WebHistoryItem& old_item = current_entry_->GetItemForFrame(render_frame); if (new_item.isNull()) return; if (old_item.isNull() || new_item.itemSequenceNumber() != old_item.itemSequenceNumber()) { if (!old_item.isNull() && new_item.documentSequenceNumber() == old_item.documentSequenceNumber()) same_document_loads.push_back(std::make_pair(frame, new_item)); else different_document_loads.push_back(std::make_pair(frame, new_item)); return; } for (WebFrame* child = frame->firstChild(); child; child = child->nextSibling()) { RecursiveGoToEntry(child, same_document_loads, different_document_loads); } } void HistoryController::UpdateForInitialLoadInChildFrame( RenderFrameImpl* frame, const WebHistoryItem& item) { DCHECK_NE(frame->GetWebFrame()->top(), frame->GetWebFrame()); if (!current_entry_) return; if (HistoryEntry::HistoryNode* existing_node = current_entry_->GetHistoryNodeForFrame(frame)) { existing_node->set_item(item); return; } RenderFrameImpl* parent = RenderFrameImpl::FromWebFrame(frame->GetWebFrame()->parent()); if (HistoryEntry::HistoryNode* parent_history_node = current_entry_->GetHistoryNodeForFrame(parent)) { parent_history_node->AddChild(item, frame->GetRoutingID()); } } void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { if (commit_type == blink::WebBackForwardCommit) { if (!provisional_entry_) return; current_entry_.reset(provisional_entry_.release()); } else if (commit_type == blink::WebStandardCommit) { CreateNewBackForwardItem(frame, item, navigation_within_page); } else if (commit_type == blink::WebInitialCommitInChildFrame) { UpdateForInitialLoadInChildFrame(frame, item); } } HistoryEntry* HistoryController::GetCurrentEntry() { return current_entry_.get(); } WebHistoryItem HistoryController::GetItemForNewChildFrame( RenderFrameImpl* frame) const { if (!current_entry_) return WebHistoryItem(); return current_entry_->GetItemForFrame(frame); } void HistoryController::RemoveChildrenForRedirect(RenderFrameImpl* frame) { if (!provisional_entry_) return; if (HistoryEntry::HistoryNode* node = provisional_entry_->GetHistoryNodeForFrame(frame)) node->RemoveChildren(); } void HistoryController::CreateNewBackForwardItem( RenderFrameImpl* target_frame, const WebHistoryItem& new_item, bool clone_children_of_target) { if (!current_entry_) { current_entry_.reset( new HistoryEntry(new_item, target_frame->GetRoutingID())); } else { current_entry_.reset(current_entry_->CloneAndReplace( new_item, clone_children_of_target, target_frame, render_view_)); } } }
#include "content/renderer/history_controller.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_view_impl.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" using blink::WebFrame; using blink::WebHistoryCommitType; using blink::WebHistoryItem; using blink::WebURLRequest; namespace content { HistoryController::HistoryController(RenderViewImpl* render_view) : render_view_(render_view
new_item.isNull()) return; if (old_item.isNull() || new_item.itemSequenceNumber() != old_item.itemSequenceNumber()) { if (!old_item.isNull() && new_item.documentSequenceNumber() == old_item.documentSequenceNumber()) same_document_loads.push_back(std::make_pair(frame, new_item)); else different_document_loads.push_back(std::make_pair(frame, new_item)); return; } for (WebFrame* child = frame->firstChild(); child; child = child->nextSibling()) { RecursiveGoToEntry(child, same_document_loads, different_document_loads); } } void HistoryController::UpdateForInitialLoadInChildFrame( RenderFrameImpl* frame, const WebHistoryItem& item) { DCHECK_NE(frame->GetWebFrame()->top(), frame->GetWebFrame()); if (!current_entry_) return; if (HistoryEntry::HistoryNode* existing_node = current_entry_->GetHistoryNodeForFrame(frame)) { existing_node->set_item(item); return; } RenderFrameImpl* parent = RenderFrameImpl::FromWebFrame(frame->GetWebFrame()->parent()); if (HistoryEntry::HistoryNode* parent_history_node = current_entry_->GetHistoryNodeForFrame(parent)) { parent_history_node->AddChild(item, frame->GetRoutingID()); } } void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { if (commit_type == blink::WebBackForwardCommit) { if (!provisional_entry_) return; current_entry_.reset(provisional_entry_.release()); } else if (commit_type == blink::WebStandardCommit) { CreateNewBackForwardItem(frame, item, navigation_within_page); } else if (commit_type == blink::WebInitialCommitInChildFrame) { UpdateForInitialLoadInChildFrame(frame, item); } } HistoryEntry* HistoryController::GetCurrentEntry() { return current_entry_.get(); } WebHistoryItem HistoryController::GetItemForNewChildFrame( RenderFrameImpl* frame) const { if (!current_entry_) return WebHistoryItem(); return current_entry_->GetItemForFrame(frame); } void HistoryController::RemoveChildrenForRedirect(RenderFrameImpl* frame) { if (!provisional_entry_) return; if (HistoryEntry::HistoryNode* node = provisional_entry_->GetHistoryNodeForFrame(frame)) node->RemoveChildren(); } void HistoryController::CreateNewBackForwardItem( RenderFrameImpl* target_frame, const WebHistoryItem& new_item, bool clone_children_of_target) { if (!current_entry_) { current_entry_.reset( new HistoryEntry(new_item, target_frame->GetRoutingID())); } else { current_entry_.reset(current_entry_->CloneAndReplace( new_item, clone_children_of_target, target_frame, render_view_)); } } }
) { } HistoryController::~HistoryController() { } void HistoryController::GoToEntry(scoped_ptr<HistoryEntry> target_entry, WebURLRequest::CachePolicy cache_policy) { HistoryFrameLoadVector same_document_loads; HistoryFrameLoadVector different_document_loads; provisional_entry_ = target_entry.Pass(); WebFrame* main_frame = render_view_->GetMainRenderFrame()->GetWebFrame(); if (current_entry_) { RecursiveGoToEntry( main_frame, same_document_loads, different_document_loads); } if (same_document_loads.empty() && different_document_loads.empty()) { different_document_loads.push_back( std::make_pair(main_frame, provisional_entry_->root())); } for (size_t i = 0; i < same_document_loads.size(); ++i) { WebFrame* frame = same_document_loads[i].first; if (!RenderFrameImpl::FromWebFrame(frame)) continue; frame->loadHistoryItem(same_document_loads[i].second, blink::WebHistorySameDocumentLoad, cache_policy); } for (size_t i = 0; i < different_document_loads.size(); ++i) { WebFrame* frame = different_document_loads[i].first; if (!RenderFrameImpl::FromWebFrame(frame)) continue; frame->loadHistoryItem(different_document_loads[i].second, blink::WebHistoryDifferentDocumentLoad, cache_policy); } } void HistoryController::RecursiveGoToEntry( WebFrame* frame, HistoryFrameLoadVector& same_document_loads, HistoryFrameLoadVector& different_document_loads) { DCHECK(provisional_entry_); DCHECK(current_entry_); RenderFrameImpl* render_frame = RenderFrameImpl::FromWebFrame(frame); const WebHistoryItem& new_item = provisional_entry_->GetItemForFrame(render_frame); const WebHistoryItem& old_item = current_entry_->GetItemForFrame(render_frame); if (
random
[]
C++
agent/src/beerocks/monitor/beerocks_monitor_main.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
#include "monitor_thread.h" #include <bcl/beerocks_logging.h> #include <bcl/beerocks_os_utils.h> #include <bcl/beerocks_version.h> #include <easylogging++.h> BEEROCKS_INIT_BEEROCKS_VERSION static bool g_running = true; static int s_signal = 0; static std::string monitor_iface; static beerocks::logging *s_pLogger = nullptr; static void handle_signal() { if (!s_signal) return; switch (s_signal) { case SIGTERM: case SIGINT: LOG(INFO) << "Caught signal '" << strsignal(s_signal) << "' Exiting..."; g_running = false; break; case SIGUSR1: { LOG(INFO) << "LOG Roll Signal!"; if (!s_pLogger) { LOG(ERROR) << "Invalid logger pointer!"; return; } s_pLogger->apply_settings(); LOG(INFO) << "--- Start of file after roll ---"; break; } default: LOG(WARNING) << "Unhandled Signal: '" << strsignal(s_signal) << "' Ignoring..."; break; } s_signal = 0; } static void init_signals() { auto signal_handler = [](int signum) { s_signal = signum; }; struct sigaction sigterm_action; sigterm_action.sa_handler = signal_handler; sigemptyset(&sigterm_action.sa_mask); sigterm_action.sa_flags = 0; sigaction(SIGTERM, &sigterm_action, NULL); struct sigaction sigint_action; sigint_action.sa_handler = signal_handler; sigemptyset(&sigint_action.sa_mask); sigint_action.sa_flags = 0; sigaction(SIGINT, &sigint_action, NULL); struct sigaction sigusr1_action; sigusr1_action.sa_handler = signal_handler; sigemptyset(&sigusr1_action.sa_mask); sigusr1_action.sa_flags = 0; sigaction(SIGUSR1, &sigusr1_action, NULL); } static bool parse_arguments(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "i:")) != -1) { switch (opt) { case 'i': { monitor_iface.assign(optarg); break; } case '?': { if (isprint(optopt)) { LOG(ERROR) << "Unknown option -" << optopt << "!"; return false; } else { LOG(ERROR) << "Unknown character " << optopt << "!"; return false; } break; } } } return true; } int main(int argc, char *argv[]) { init_signals(); int openFds = sysconf(_SC_OPEN_MAX); for (int fd = 0; fd < openFds; fd++) { if ((fd != STDOUT_FILENO) && (fd != STDIN_FILENO) && (fd != STDERR_FILENO)) { close(fd); } } std::string module_description; if (beerocks::version::handle_version_query(argc, argv, module_description)) { return 0; } if (!parse_arguments(argc, argv)) { std::cout << "Usage: " << argv[0] << " -i <monitor iface>" << std::endl; return 0; } std::string slave_config_file_path = "./" + std::string(BEEROCKS_AGENT) + ".conf"; beerocks::config_file::sConfigSlave beerocks_slave_conf; if (!beerocks::config_file::read_slave_config_file(slave_config_file_path, beerocks_slave_conf)) { slave_config_file_path = BEEROCKS_CONF_PATH + std::string(BEEROCKS_AGENT) + ".conf"; if (!beerocks::config_file::read_slave_config_file(slave_config_file_path, beerocks_slave_conf)) { std::cout << "config file '" << slave_config_file_path << "' args error." << std::endl; return 1; } } std::string base_monitor_name = std::string(BEEROCKS_MONITOR) + "_" + monitor_iface; beerocks::logging logger(beerocks_slave_conf.sLog, base_monitor_name); s_pLogger = &logger; logger.apply_settings(); LOG(INFO) << std::endl << "Running " << base_monitor_name << " Version " << BEEROCKS_VERSION << " Build date " << BEEROCKS_BUILD_DATE << std::endl << std::endl; beerocks::version::log_version(argc, argv); if (logger.get_log_files_enabled()) { beerocks::os_utils::redirect_console_std(beerocks_slave_conf.sLog.files_path + base_monitor_name + "_std.log"); } beerocks::os_utils::kill_pid(beerocks_slave_conf.temp_path, base_monitor_name); beerocks::os_utils::write_pid_file(beerocks_slave_conf.temp_path, base_monitor_name); std::string pid_file_path = beerocks_slave_conf.temp_path + "pid/" + base_monitor_name; std::string slave_uds = beerocks_slave_conf.temp_path + std::string(BEEROCKS_SLAVE_UDS) + "_" + monitor_iface; son::monitor_thread monitor(slave_uds, monitor_iface, beerocks_slave_conf, logger); if (monitor.init()) { auto touch_time_stamp_timeout = std::chrono::steady_clock::now(); while (g_running) { if (s_signal) { handle_signal(); continue; } if (std::chrono::steady_clock::now() > touch_time_stamp_timeout) { beerocks::os_utils::touch_pid_file(pid_file_path); touch_time_stamp_timeout = std::chrono::steady_clock::now() + std::chrono::seconds(beerocks::TOUCH_PID_TIMEOUT_SECONDS); } if (!monitor.work()) { break; } } monitor.stop(); } else { LOG(ERROR) << "monitor.init(), iface=" << monitor_iface << " slave_uds=" << slave_uds; } s_pLogger = nullptr; return 0; }
#include "monitor_thread.h" #include <bcl/beerocks_logging.h> #include <bcl/beerocks_os_utils.h> #include <bcl/beerocks_version.h> #include <easylogging++.h> BEEROCKS_INIT_BEEROCKS_VERSION static bool g_running = true; static int s_signal = 0; static std::string monitor_iface; static beerocks::logging *s_pLogger = nullptr; static void handle_signal() { if (!s_signal) return; switch (s_signal) { case SIGTERM: case SIGINT: LOG(INFO) << "Caught signal '" << strsignal(s_signal) << "' Exiting..."; g_running = false; break; case SIGUSR1: { LOG(INFO) << "LOG Roll Signal!"; if (!s_pLogger) { LOG(ERROR) << "Invalid logger pointer!"; return; } s_pLogger->apply_settings(); LOG(INFO) << "--- Start of file after roll ---"; break; } default: LOG(WARNING) << "Unhandled Signal: '" << strsignal(s_signal) << "' Ignoring..."; break; } s_signal = 0; } static void init_signals() { auto signal_handler = [](int signum) { s_signal = signum; }; struct sigaction sigterm_action; sigterm_action.sa_handler = signal_handler; sigemptyset(&sigterm_action.sa_mask); sigterm_action.sa_flags = 0; sigaction(SIGTERM, &sigterm_action, NULL); struct sigaction sigint_action; sigint_action.sa_handler = signal_handler; sigemptyset(&sigint_action.sa_mask); sigint_action.sa_flags = 0; sigaction(SIGINT, &sigint_action, NULL); struct sigaction sigusr1_action; sigusr1_action.sa_handler = signal_handler; sigemptyset(&sigusr1_action.sa_mask); sigusr1_action.sa_flags = 0; sigaction(SIGUSR1, &sigusr1_action, NULL); } static bool parse_arguments(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "i:")) != -1) { switch (opt) { case 'i': { monitor_iface.assign(optarg); break; } case '?': { if (isprint(optopt)) { LOG(ERROR) << "Unknown option -" << optopt << "!"; return false; } else { LOG(ERROR) << "Unknown character " << optopt << "!"; return false; } break; } } } return true; } int main(int argc, char *argv[]) { init_signals(); int openFds = sysconf(_SC_OPEN_MAX); for (int fd = 0; fd < openFds; fd++) { if ((fd != STDOUT_FILENO) && (fd != STDIN_FILENO) && (fd != STDERR_FILENO)) { close(fd); } } std::string module_description; if (beerocks::version::handle_version_query(argc, argv, module_description)) { return 0; }
std::string slave_config_file_path = "./" + std::string(BEEROCKS_AGENT) + ".conf"; beerocks::config_file::sConfigSlave beerocks_slave_conf; if (!beerocks::config_file::read_slave_config_file(slave_config_file_path, beerocks_slave_conf)) { slave_config_file_path = BEEROCKS_CONF_PATH + std::string(BEEROCKS_AGENT) + ".conf"; if (!beerocks::config_file::read_slave_config_file(slave_config_file_path, beerocks_slave_conf)) { std::cout << "config file '" << slave_config_file_path << "' args error." << std::endl; return 1; } } std::string base_monitor_name = std::string(BEEROCKS_MONITOR) + "_" + monitor_iface; beerocks::logging logger(beerocks_slave_conf.sLog, base_monitor_name); s_pLogger = &logger; logger.apply_settings(); LOG(INFO) << std::endl << "Running " << base_monitor_name << " Version " << BEEROCKS_VERSION << " Build date " << BEEROCKS_BUILD_DATE << std::endl << std::endl; beerocks::version::log_version(argc, argv); if (logger.get_log_files_enabled()) { beerocks::os_utils::redirect_console_std(beerocks_slave_conf.sLog.files_path + base_monitor_name + "_std.log"); } beerocks::os_utils::kill_pid(beerocks_slave_conf.temp_path, base_monitor_name); beerocks::os_utils::write_pid_file(beerocks_slave_conf.temp_path, base_monitor_name); std::string pid_file_path = beerocks_slave_conf.temp_path + "pid/" + base_monitor_name; std::string slave_uds = beerocks_slave_conf.temp_path + std::string(BEEROCKS_SLAVE_UDS) + "_" + monitor_iface; son::monitor_thread monitor(slave_uds, monitor_iface, beerocks_slave_conf, logger); if (monitor.init()) { auto touch_time_stamp_timeout = std::chrono::steady_clock::now(); while (g_running) { if (s_signal) { handle_signal(); continue; } if (std::chrono::steady_clock::now() > touch_time_stamp_timeout) { beerocks::os_utils::touch_pid_file(pid_file_path); touch_time_stamp_timeout = std::chrono::steady_clock::now() + std::chrono::seconds(beerocks::TOUCH_PID_TIMEOUT_SECONDS); } if (!monitor.work()) { break; } } monitor.stop(); } else { LOG(ERROR) << "monitor.init(), iface=" << monitor_iface << " slave_uds=" << slave_uds; } s_pLogger = nullptr; return 0; }
if (!parse_arguments(argc, argv)) { std::cout << "Usage: " << argv[0] << " -i <monitor iface>" << std::endl; return 0; }
if_condition
[ { "content": "struct json_object;\n\nnamespace mapf {\n", "file_path": "framework/common/include/mapf/common/logger.h", "rank": 0, "score": 203256.10839559737 }, { "content": "class Logger {\n\npublic:\n", "file_path": "framework/common/include/mapf/common/logger.h", "rank": 1, "score": 164508.12492931454 }, { "content": "class cACTION_APMANAGER_HOSTAP_CHANNEL_SWITCH_ACS_START : public BaseClass\n\n{\n\n public:\n\n cACTION_APMANAGER_HOSTAP_CHANNEL_SWITCH_ACS_START(uint8_t* buff, size_t buff_len, bool parse = false);\n\n explicit cACTION_APMANAGER_HOSTAP_CHANNEL_SWITCH_ACS_START(std::shared_ptr<BaseClass> base, bool parse = false);\n\n ~cACTION_APMANAGER_HOSTAP_CHANNEL_SWITCH_ACS_START();\n\n\n\n static eActionOp_APMANAGER get_action_op(){\n\n return (eActionOp_APMANAGER)(ACTION_APMANAGER_HOSTAP_CHANNEL_SWITCH_ACS_START);\n\n }\n\n sApChannelSwitch& cs_params();\n\n int8_t& tx_limit();\n\n uint8_t& tx_limit_valid();\n\n void class_swap() override;\n\n bool finalize() override;\n\n static size_t get_initial_size();\n\n\n\n private:\n\n bool init();\n\n eActionOp_APMANAGER* m_action_op = nullptr;\n\n sApChannelSwitch* m_cs_params = nullptr;\n\n int8_t* m_tx_limit = nullptr;\n\n uint8_t* m_tx_limit_valid = nullptr;\n\n};\n\n\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_apmanager.h", "rank": 2, "score": 163674.60696818744 }, { "content": "class cACTION_CONTROL_HOSTAP_CHANNEL_SWITCH_ACS_START : public BaseClass\n\n{\n\n public:\n\n cACTION_CONTROL_HOSTAP_CHANNEL_SWITCH_ACS_START(uint8_t* buff, size_t buff_len, bool parse = false);\n\n explicit cACTION_CONTROL_HOSTAP_CHANNEL_SWITCH_ACS_START(std::shared_ptr<BaseClass> base, bool parse = false);\n\n ~cACTION_CONTROL_HOSTAP_CHANNEL_SWITCH_ACS_START();\n\n\n\n static eActionOp_CONTROL get_action_op(){\n\n return (eActionOp_CONTROL)(ACTION_CONTROL_HOSTAP_CHANNEL_SWITCH_ACS_START);\n\n }\n\n sApChannelSwitch& cs_params();\n\n void class_swap() override;\n\n bool finalize() override;\n\n static size_t get_initial_size();\n\n\n\n private:\n\n bool init();\n\n eActionOp_CONTROL* m_action_op = nullptr;\n\n sApChannelSwitch* m_cs_params = nullptr;\n\n};\n\n\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_control.h", "rank": 3, "score": 163674.60696818744 }, { "content": " uint8_t use_optional_wide_band_ch_switch;\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 4, "score": 160719.59890901655 }, { "content": "class RollMonitor : public el::LogDispatchCallback {\n\npublic:\n\n void enable(bool enable)\n\n {\n\n m_enabled = enable;\n\n if (!m_enabled) {\n\n m_fsLogFileStream = nullptr;\n\n m_szRollLogFileSize = 0;\n\n }\n\n }\n\n\n\n void handle(const el::LogDispatchData *logData)\n\n {\n\n\n\n //////////////////////////////\n\n // DO NOT USE LOGGING HERE! //\n\n //////////////////////////////\n\n\n\n if (!m_enabled) {\n\n return;\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 5, "score": 158532.0831734428 }, { "content": "class NetLogger : public el::LogDispatchCallback {\n\npublic:\n\n void enable(const std::string &server, uint16_t port, std::string module_name)\n\n {\n\n m_server = server;\n\n m_port = port;\n\n m_module_name = module_name;\n\n this->setEnabled(true);\n\n }\n\n\n\nprotected:\n\n void handle(const el::LogDispatchData *logdata) noexcept override\n\n {\n\n std::string msg = m_module_name + \": \" +\n\n logdata->logMessage()->logger()->logBuilder()->build(\n\n logdata->logMessage(),\n\n logdata->dispatchAction() == el::base::DispatchAction::NormalLog);\n\n SocketClient logmaster(m_server, m_port);\n\n logmaster.writeString(msg);\n\n }\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 6, "score": 158507.83529951045 }, { "content": "///////////////////////////////////////\n\n// AUTO GENERATED FILE - DO NOT EDIT //\n\n///////////////////////////////////////\n\n\n\n/* SPDX-License-Identifier: BSD-2-Clause-Patent\n\n *\n\n * Copyright (c) 2016-2019 Intel Corporation\n\n *\n\n * This code is subject to the terms of the BSD+Patent license.\n\n * See LICENSE file for more details.\n\n */\n\n\n\n#ifndef _TLVF_IEEE_1905_1_TLVUNKNOWN_H_\n\n#define _TLVF_IEEE_1905_1_TLVUNKNOWN_H_\n\n\n\n#include <cstddef>\n\n#include <stdint.h>\n\n#include <tlvf/swap.h>\n\n#include <string.h>\n\n#include <memory>\n\n#include <tlvf/BaseClass.h>\n\n#include <tlvf/ClassList.h>\n\n#include <tuple>\n\n\n\nnamespace ieee1905_1 {\n\n\n\n\n", "file_path": "framework/tlvf/AutoGenerated/include/tlvf/ieee_1905_1/tlvUnknown.h", "rank": 7, "score": 156391.07904684354 }, { "content": "class tlvUnknown : public BaseClass\n\n{\n\n public:\n\n tlvUnknown(uint8_t* buff, size_t buff_len, bool parse = false);\n\n explicit tlvUnknown(std::shared_ptr<BaseClass> base, bool parse = false);\n\n ~tlvUnknown();\n\n\n\n uint8_t& type();\n\n const uint16_t& length();\n\n size_t data_length() { return m_data_idx__ * sizeof(uint8_t); }\n\n uint8_t* data(size_t idx = 0);\n\n bool alloc_data(size_t count = 1);\n\n void class_swap() override;\n\n bool finalize() override;\n\n static size_t get_initial_size();\n\n\n\n private:\n\n bool init();\n\n uint8_t* m_type = nullptr;\n\n uint16_t* m_length = nullptr;\n\n uint8_t* m_data = nullptr;\n\n size_t m_data_idx__ = 0;\n\n int m_lock_order_counter__ = 0;\n\n};\n\n\n\n}; // close namespace: ieee1905_1\n\n\n\n#endif //_TLVF/IEEE_1905_1_TLVUNKNOWN_H_\n", "file_path": "framework/tlvf/AutoGenerated/include/tlvf/ieee_1905_1/tlvUnknown.h", "rank": 8, "score": 154777.67710776711 }, { "content": "struct msglib_pollitems;\n\n\n", "file_path": "framework/common/include/mapf/common/poller.h", "rank": 9, "score": 148448.52003373127 }, { "content": "struct dh_st;\n\n}\n\n\n\nnamespace mapf {\n\n\n\n/**\n\n * @brief Wrapper functions for performing encryption\n\n */\n\nnamespace encryption {\n\n\n", "file_path": "framework/common/include/mapf/common/encryption.h", "rank": 10, "score": 148448.52003373127 }, { "content": "struct msglib_socket;\n\n\n", "file_path": "framework/common/include/mapf/broker/broker.h", "rank": 11, "score": 148448.52003373127 }, { "content": "struct msglib_socket;\n", "file_path": "framework/common/include/mapf/common/socket.h", "rank": 12, "score": 148448.52003373127 }, { "content": " bool start(const void *args = nullptr)\n\n {\n\n if (m_started) {\n\n LOG(WARNING) << \"FSM already started\";\n\n return true;\n\n }\n\n\n\n // Make sure that the initial state is configured\n\n auto iter = m_config.states().find(m_init_state);\n\n if (iter == m_config.states().end()) {\n\n LOG(FATAL) << \"Invalid initial state '\" << m_init_state << \"'\";\n\n return false;\n\n }\n\n\n\n auto state_handler = iter->second;\n\n m_started = true;\n\n\n\n // Enter the initial state\n\n return state_handler->enter(args);\n", "file_path": "common/beerocks/bcl/include/bcl/beerocks_state_machine.h", "rank": 13, "score": 143028.61270936977 }, { "content": "class File : base::StaticClass {\n\n public:\n\n /// @brief Creates new out file stream for specified filename.\n\n /// @return Pointer to newly created fstream or nullptr\n\n static base::type::fstream_t* newFileStream(const std::string& filename);\n\n\n\n /// @brief Gets size of file provided in stream\n\n static std::size_t getSizeOfFile(base::type::fstream_t* fs);\n\n\n\n /// @brief Determines whether or not provided path exist in current file system\n\n static bool pathExists(const char* path, bool considerFile = false);\n\n\n\n /// @brief Creates specified path on file system\n\n /// @param path Path to create.\n\n static bool createPath(const std::string& path);\n\n /// @brief Extracts path of filename with leading slash\n\n static std::string extractPathFromFilename(const std::string& fullPath,\n\n const char* seperator = base::consts::kFilePathSeperator);\n\n /// @brief builds stripped filename and puts it in buff\n\n static void buildStrippedFilename(const char* filename, char buff[],\n\n std::size_t limit = base::consts::kSourceFilenameMaxLength);\n\n /// @brief builds base filename and puts it in buff\n\n static void buildBaseFilename(const std::string& fullPath, char buff[],\n\n std::size_t limit = base::consts::kSourceFilenameMaxLength,\n\n const char* seperator = base::consts::kFilePathSeperator);\n\n};\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 14, "score": 139998.03581332494 }, { "content": " void struct_swap(){\n", "file_path": "framework/tlvf/AutoGenerated/include/tlvf/ieee_1905_1/s802_11SpecificInformation.h", "rank": 15, "score": 131522.182269335 }, { "content": "class cACTION_CLI_RESPONSE_INT : public BaseClass\n\n{\n\n public:\n\n cACTION_CLI_RESPONSE_INT(uint8_t* buff, size_t buff_len, bool parse = false);\n\n explicit cACTION_CLI_RESPONSE_INT(std::shared_ptr<BaseClass> base, bool parse = false);\n\n ~cACTION_CLI_RESPONSE_INT();\n\n\n\n static eActionOp_CLI get_action_op(){\n\n return (eActionOp_CLI)(ACTION_CLI_RESPONSE_INT);\n\n }\n\n uint8_t& isOK();\n\n int8_t& currentValue();\n\n void class_swap() override;\n\n bool finalize() override;\n\n static size_t get_initial_size();\n\n\n\n private:\n\n bool init();\n\n eActionOp_CLI* m_action_op = nullptr;\n\n uint8_t* m_isOK = nullptr;\n\n int8_t* m_currentValue = nullptr;\n\n};\n\n\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_cli.h", "rank": 16, "score": 129043.28429108064 }, { "content": " uint8_t switch_reason;\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 17, "score": 129037.252097344 }, { "content": " uint8_t isStaticSmps;\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 18, "score": 129037.252097344 }, { "content": " uint64_t start_time;\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 19, "score": 129034.54237037226 }, { "content": " uint8_t log_level;\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 20, "score": 129003.59510021287 }, { "content": " void struct_init(){\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 21, "score": 128967.5244070334 }, { "content": " void struct_swap(){\n", "file_path": "common/beerocks/tlvf/AutoGenerated/include/beerocks/tlvf/beerocks_message_common.h", "rank": 22, "score": 128967.5244070334 }, { "content": " sigint_action.sa_flags = 0;\n\n sigaction(SIGINT, &sigint_action, NULL);\n\n\n\n struct sigaction sigusr1_action;\n\n sigusr1_action.sa_handler = signal_handler;\n\n sigemptyset(&sigusr1_action.sa_mask);\n\n sigusr1_action.sa_flags = 0;\n\n sigaction(SIGUSR1, &sigusr1_action, NULL);\n\n}\n\n\n\nstatic bool parse_arguments(int argc, char *argv[])\n\n{\n\n int opt;\n\n while ((opt = getopt(argc, argv, \"k\")) != -1) {\n\n switch (opt) {\n\n case 'k': {\n\n s_kill_master = true;\n\n break;\n\n }\n\n case '?': {\n", "file_path": "controller/src/beerocks/master/beerocks_master_main.cpp", "rank": 24, "score": 86.61425982186309 }, { "content": " case SIGINT:\n\n LOG(INFO) << \"Caught signal '\" << strsignal(s_signal) << \"' Exiting...\";\n\n g_running = false;\n\n break;\n\n\n\n // Roll log file\n\n case SIGUSR1: {\n\n LOG(INFO) << \"LOG Roll Signal!\";\n\n if (!s_pLogger) {\n\n LOG(ERROR) << \"Invalid logger pointer!\";\n\n return;\n\n }\n\n\n\n s_pLogger->apply_settings();\n\n LOG(INFO) << \"--- Start of file after roll ---\";\n\n break;\n\n }\n\n\n\n default:\n\n LOG(WARNING) << \"Unhandled Signal: '\" << strsignal(s_signal) << \"' Ignoring...\";\n", "file_path": "controller/src/beerocks/master/beerocks_master_main.cpp", "rank": 25, "score": 82.15976767274412 }, { "content": " sigaction(SIGINT, &sigint_action, NULL);\n\n\n\n struct sigaction sigusr1_action;\n\n sigusr1_action.sa_handler = signal_handler;\n\n sigemptyset(&sigusr1_action.sa_mask);\n\n sigusr1_action.sa_flags = 0;\n\n sigaction(SIGUSR1, &sigusr1_action, NULL);\n\n}\n\n\n\nstatic bool parse_arguments(int argc, char *argv[])\n\n{\n\n int opt;\n\n while ((opt = getopt(argc, argv, \"i:q:\")) != -1) {\n\n switch (opt) {\n\n case 'i': {\n\n g_son_slave_iface.assign(optarg);\n\n break;\n\n }\n\n case 'q': // quary platfrom: is_master, is_gateway, is_onboarding\n\n {\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 27, "score": 80.56291502840858 }, { "content": " LOG(INFO) << \"Caught signal '\" << strsignal(s_signal) << \"' Exiting...\";\n\n g_running = false;\n\n break;\n\n\n\n // Roll log file\n\n case SIGUSR1: {\n\n LOG(INFO) << \"LOG Roll Signal!\";\n\n if (!s_pLogger) {\n\n LOG(ERROR) << \"Invalid logger pointer!\";\n\n return;\n\n }\n\n\n\n s_pLogger->apply_settings();\n\n LOG(INFO) << \"--- Start of file after roll ---\";\n\n break;\n\n }\n\n\n\n default:\n\n LOG(WARNING) << \"Unhandled Signal: '\" << strsignal(s_signal) << \"' Ignoring...\";\n\n break;\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 28, "score": 77.14763232620595 }, { "content": "// It should only be there in one place in each executable module\n\nBEEROCKS_INIT_BEEROCKS_VERSION\n\n\n\nstatic bool g_running = true;\n\nstatic int s_signal = 0;\n\nstatic std::string g_son_slave_iface;\n\n\n\n// Pointer to logger instance\n\nstatic beerocks::logging *s_pLogger = nullptr;\n\n\n\nstatic void handle_signal()\n\n{\n\n if (!s_signal)\n\n return;\n\n\n\n switch (s_signal) {\n\n\n\n // Terminate\n\n case SIGTERM:\n\n case SIGINT:\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 29, "score": 74.2838620637913 }, { "content": "// Do not use this macro anywhere else in ire process\n\n// It should only be there in one place in each executable module\n\nBEEROCKS_INIT_BEEROCKS_VERSION\n\n\n\nstatic bool g_running = true;\n\nstatic bool s_kill_master = false;\n\nstatic int s_signal = 0;\n\n\n\n// Pointer to logger instance\n\nstatic beerocks::logging *s_pLogger = nullptr;\n\n\n\nstatic void handle_signal()\n\n{\n\n if (!s_signal)\n\n return;\n\n\n\n switch (s_signal) {\n\n\n\n // Terminate\n\n case SIGTERM:\n", "file_path": "controller/src/beerocks/master/beerocks_master_main.cpp", "rank": 31, "score": 68.60057348216698 }, { "content": " break;\n\n }\n\n\n\n s_signal = 0;\n\n}\n\n\n\nstatic void init_signals()\n\n{\n\n // Signal handler function\n\n auto signal_handler = [](int signum) { s_signal = signum; };\n\n\n\n struct sigaction sigterm_action;\n\n sigterm_action.sa_handler = signal_handler;\n\n sigemptyset(&sigterm_action.sa_mask);\n\n sigterm_action.sa_flags = 0;\n\n sigaction(SIGTERM, &sigterm_action, NULL);\n\n\n\n struct sigaction sigint_action;\n\n sigint_action.sa_handler = signal_handler;\n\n sigemptyset(&sigint_action.sa_mask);\n", "file_path": "controller/src/beerocks/master/beerocks_master_main.cpp", "rank": 33, "score": 60.455050747278776 }, { "content": "{\n\n std::cout << \"-d/--delay <us>: Init delay (wait before start test)\\n\"\n\n \"-i/--iterations <num>: Iterations for each test case\\n\"\n\n \"-a/--attempts <num>: Max attempts for slow joiner WA\\n\"\n\n \"-t/--test <name>: Test to run (all | string | frame | message | mult | factory)\\n\"\n\n \"-v/--verbose: Enable verbose printing\\n\"\n\n \"-h/--help: Show help\\n\";\n\n exit(1);\n\n}\n\n\n\nvoid ProcessArgs(int argc, char **argv)\n\n{\n\n const char *const short_opts = \"i:a:t:d:vh\";\n\n const option long_opts[] = {{\"iterations\", 1, nullptr, 'i'}, {\"delay\", 1, nullptr, 'd'},\n\n {\"attempts\", 1, nullptr, 'a'}, {\"test\", 1, nullptr, 't'},\n\n {\"verbose\", 0, nullptr, 'v'}, {\"help\", 0, nullptr, 'h'},\n\n {nullptr, 0, nullptr, 0}};\n\n\n\n while (true) {\n\n const auto opt = getopt_long(argc, argv, short_opts, long_opts, nullptr);\n", "file_path": "framework/common/test/socket_test.cpp", "rank": 34, "score": 60.17071383369089 }, { "content": " return mapf::Logger::Instance().logger_name();\n\n}\n\n\n\nstatic inline std::string const bool_to_string(bool b)\n\n{\n\n return b ? std::string(\"TRUE\") : std::string(\"FALSE\");\n\n}\n\n\n\n#ifdef USE_INOTIFY\n\nstatic void *watch_log_file(void *args)\n\n{\n\n const char *logger_name = (const char *)args;\n\n int fd = -1, length = -1, i = 0, ret = 0;\n\n int event_buf_len = (sizeof(struct inotify_event) + 16) * 1024;\n\n char buffer[event_buf_len];\n\n struct inotify_event *fileEvent;\n\n\n\n fd = inotify_init();\n\n if (fd < 0) {\n\n return nullptr;\n", "file_path": "framework/common/logger.cpp", "rank": 35, "score": 58.29399466263153 }, { "content": " return true;\n\n}\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n\n\n mapf::Logger::Instance().LoggerInit(\"transport_test\");\n\n\n\n int c;\n\n int interfaces = 0;\n\n while ((c = getopt(argc, argv, \"b:i:u:x\")) != -1) {\n\n switch (c) {\n\n case 'b':\n\n ieee1905_bridge_if_index = if_nametoindex(optarg);\n\n if (ieee1905_bridge_if_index == 0) {\n\n fprintf(stderr, \"unknown interface %s\\n\", optarg);\n\n return false;\n\n }\n\n break;\n\n case 'i':\n", "file_path": "framework/transport/ieee1905_transport/test/ieee1905_transport_test.cpp", "rank": 36, "score": 57.05196615876523 }, { "content": " sigterm_action.sa_flags = 0;\n\n sigaction(SIGTERM, &sigterm_action, NULL);\n\n\n\n struct sigaction sigint_action;\n\n sigint_action.sa_handler = sigint_handler;\n\n sigemptyset(&sigint_action.sa_mask);\n\n sigint_action.sa_flags = 0;\n\n sigaction(SIGINT, &sigint_action, NULL);\n\n}\n\n\n\n#ifdef HAVE_READLINE\n\nstatic void *xmalloc(int alloc_size)\n\n{\n\n void *m = malloc(alloc_size);\n\n if (m == nullptr) {\n\n LOG(FATAL) << \"Error: Out of memory. Exiting\";\n\n sigterm_handler(0);\n\n return nullptr;\n\n }\n\n return m;\n", "file_path": "controller/src/beerocks/cli/beerocks_cli_main.cpp", "rank": 37, "score": 55.94512793047902 }, { "content": " }\n\n\n\n s_signal = 0;\n\n}\n\n\n\nstatic void init_signals()\n\n{\n\n // Signal handler function\n\n auto signal_handler = [](int signum) { s_signal = signum; };\n\n\n\n struct sigaction sigterm_action;\n\n sigterm_action.sa_handler = signal_handler;\n\n sigemptyset(&sigterm_action.sa_mask);\n\n sigterm_action.sa_flags = 0;\n\n sigaction(SIGTERM, &sigterm_action, NULL);\n\n\n\n struct sigaction sigint_action;\n\n sigint_action.sa_handler = signal_handler;\n\n sigemptyset(&sigint_action.sa_mask);\n\n sigint_action.sa_flags = 0;\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 38, "score": 55.84012175759434 }, { "content": "\n\nvoid Logger::LoggerInit() { LoggerInit(DEFAULT_LOGGER_NAME); }\n\n\n\n//for initial configuration and for default configuring all loggers\n\nvoid Logger::LoggerInit(const char *logger_name)\n\n{\n\n if (std::string(logger_name).compare(DEFAULT_LOGGER_NAME) != 0) //string are not equal\n\n logger_name_ = logger_name;\n\n else\n\n logger_name_ = std::string(__progname);\n\n\n\n LoggerConfig(logger_name);\n\n static bool init_performed = false;\n\n if (!init_performed) {\n\n el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier(\"%proc\", get_name));\n\n#ifdef USE_INOTIFY\n\n init_performed = true;\n\n pthread_t watchThread;\n\n int rc = pthread_create(&watchThread, NULL, watch_log_file, (void *)logger_name);\n\n if (rc)\n", "file_path": "framework/common/logger.cpp", "rank": 39, "score": 52.140233453354654 }, { "content": " friend class el::base::DefaultLogDispatchCallback;\n\n friend class el::LogBuilder;\n\n friend class el::base::MessageBuilder;\n\n friend class el::base::Writer;\n\n friend class el::base::PerformanceTracker;\n\n friend class el::base::LogDispatcher;\n\n\n\n void setApplicationArguments(int argc, char** argv);\n\n\n\n inline void setApplicationArguments(int argc, const char** argv) {\n\n setApplicationArguments(argc, const_cast<char**>(argv));\n\n }\n\n};\n\nextern ELPP_EXPORT base::type::StoragePointer elStorage;\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 40, "score": 52.03168666271625 }, { "content": " const std::string& value);\n\n /// @brief Sets default configurations. This configuration is used for future (and conditionally for existing) loggers\n\n static void setDefaultConfigurations(const Configurations& configurations,\n\n bool reconfigureExistingLoggers = false);\n\n /// @brief Returns current default\n\n static const Configurations* defaultConfigurations(void);\n\n /// @brief Returns log stream reference pointer if needed by user\n\n static const base::LogStreamsReferenceMapPtr logStreamsReference(void);\n\n /// @brief Default typed configuration based on existing defaultConf\n\n static base::TypedConfigurations defaultTypedConfigurations(void);\n\n /// @brief Populates all logger IDs in current repository.\n\n /// @param [out] targetList List of fill up.\n\n static std::vector<std::string>* populateAllLoggerIds(std::vector<std::string>* targetList);\n\n /// @brief Sets configurations from global configuration file.\n\n static void configureFromGlobal(const char* globalConfigurationFilePath);\n\n /// @brief Configures loggers using command line arg. Ensure you have already set command line args,\n\n /// @return False if invalid argument or argument with no value provided, true if attempted to configure logger.\n\n /// If true is returned that does not mean it has been configured successfully, it only means that it\n\n /// has attempted to configure logger using configuration file provided in argument\n\n static bool configureFromArg(const char* argKey);\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 41, "score": 51.615300190356635 }, { "content": " logger->releaseLock();\n\n return s;\n\n }\n\n /// @brief Returns command line arguments (pointer) provided to easylogging++\n\n static inline const el::base::utils::CommandLineArgs* commandLineArgs(void) {\n\n return ELPP->commandLineArgs();\n\n }\n\n /// @brief Reserve space for custom format specifiers for performance\n\n /// @see std::vector::reserve\n\n static inline void reserveCustomFormatSpecifiers(std::size_t size) {\n\n ELPP->m_customFormatSpecifiers.reserve(size);\n\n }\n\n /// @brief Installs user defined format specifier and handler\n\n static inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {\n\n ELPP->installCustomFormatSpecifier(customFormatSpecifier);\n\n }\n\n /// @brief Uninstalls user defined format specifier and handler\n\n static inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) {\n\n return ELPP->uninstallCustomFormatSpecifier(formatSpecifier);\n\n }\n\n /// @brief Returns true if custom format specifier is installed\n\n static inline bool hasCustomFormatSpecifier(const char* formatSpecifier) {\n\n return ELPP->hasCustomFormatSpecifier(formatSpecifier);\n\n }\n\n static inline void validateFileRolling(Logger* logger, Level level) {\n\n if (ELPP == nullptr || logger == nullptr) return;\n\n logger->m_typedConfigurations->validateFileRolling(level, ELPP->preRollOutCallback());\n\n }\n\n};\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 42, "score": 50.81339746427096 }, { "content": " std::cout << \" h - show this help menu\" << std::endl;\n\n}\n\nint main(int argc, char *argv[])\n\n{\n\n mapf::Logger::Instance().LoggerInit(\"local_bus\");\n\n std::string conf = std::string(MAPF_ROOT) + \"/share/local_bus.conf\";\n\n std::string endpoint, frontend, backend;\n\n int opt;\n\n\n\n while ((opt = getopt(argc, argv, \"c:f:b:h\")) != EOF) {\n\n switch (opt) {\n\n case 'c':\n\n conf = optarg;\n\n std::cout << \"conf path: \" << conf << std::endl;\n\n break;\n\n case 'f':\n\n frontend = optarg;\n\n break;\n\n case 'b':\n\n backend = optarg;\n", "file_path": "framework/common/local_bus.cpp", "rank": 43, "score": 50.102582190887084 }, { "content": " if (!foundReason) {\n\n ss << \"Application has crashed due to unknown signal [\" << sig << \"]\";\n\n }\n\n return ss.str();\n\n}\n\n/// @brief Logs reason of crash from sig\n\nstatic void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {\n\n if (sig == SIGINT && ELPP->hasFlag(el::LoggingFlag::IgnoreSigInt)) {\n\n return;\n\n }\n\n std::stringstream ss;\n\n ss << \"CRASH HANDLED; \";\n\n ss << crashReason(sig);\n\n#if ELPP_STACKTRACE\n\n if (stackTraceIfAvailable) {\n\n ss << std::endl << \" ======= Backtrace: =========\" << std::endl << base::debug::StackTrace();\n\n }\n\n#else\n\n ELPP_UNUSED(stackTraceIfAvailable);\n\n#endif // ELPP_STACKTRACE\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 44, "score": 50.06277193405993 }, { "content": " std::string request;\n\n request.assign(optarg);\n\n std::cout << std::endl\n\n << request << \"=\" << beerocks::platform_manager::extern_query_db(request)\n\n << std::endl;\n\n exit(0);\n\n }\n\n case '?': {\n\n if (isprint(optopt)) {\n\n LOG(ERROR) << \"Unknown option -\" << optopt << \"!\";\n\n return false;\n\n } else {\n\n LOG(ERROR) << \"Unknown character \" << optopt << \"!\";\n\n return false;\n\n }\n\n break;\n\n }\n\n }\n\n }\n\n return true;\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 45, "score": 48.63916439039309 }, { "content": "\n\n static void handle_logging_rollover(const char *, std::size_t);\n\n\n\nprivate:\n\n static const std::string format;\n\n static const std::string syslogFormat;\n\n\n\n std::string m_module_name;\n\n\n\n size_t m_logfile_size;\n\n bool m_log_files_enabled = true;\n\n std::string m_log_files_path;\n\n std::string m_log_filename;\n\n bool m_log_files_auto_roll = true;\n\n log_levels m_levels;\n\n log_levels m_syslog_levels;\n\n bool m_stdout_enabled = true;\n\n bool m_syslog_enabled = false;\n\n\n\n settings_t m_settings_map;\n\n};\n\n\n\n} // namespace beerocks\n\n\n\n#endif // _BEEROCKS_LOGGING_H_\n", "file_path": "common/beerocks/bcl/include/bcl/beerocks_logging.h", "rank": 46, "score": 47.94996451894501 }, { "content": " if (isprint(optopt)) {\n\n LOG(ERROR) << \"Unknown option -\" << optopt << \"!\";\n\n return false;\n\n } else {\n\n LOG(ERROR) << \"Unknown character \" << optopt << \"!\";\n\n return false;\n\n }\n\n break;\n\n }\n\n }\n\n }\n\n return true;\n\n}\n\n\n\nstatic void fill_master_config(son::db::sDbMasterConfig &master_conf,\n\n beerocks::config_file::sConfigMaster &main_master_conf)\n\n{\n\n master_conf.vendor = main_master_conf.vendor;\n\n master_conf.model = main_master_conf.model;\n\n master_conf.ucc_listener_port =\n", "file_path": "controller/src/beerocks/master/beerocks_master_main.cpp", "rank": 47, "score": 47.83173038546799 }, { "content": "\n\n Writer& construct(Logger* logger, bool needLock = true);\n\n Writer& construct(int count, const char* loggerIds, ...);\n\n protected:\n\n LogMessage* m_msg;\n\n Level m_level;\n\n const char* m_file;\n\n const base::type::LineNumber m_line;\n\n const char* m_func;\n\n base::type::VerboseLevel m_verboseLevel;\n\n Logger* m_logger;\n\n bool m_proceed;\n\n base::MessageBuilder m_messageBuilder;\n\n base::DispatchAction m_dispatchAction;\n\n std::vector<std::string> m_loggerIds;\n\n friend class el::Helpers;\n\n\n\n void initializeLogger(const std::string& loggerId, bool lookup = true, bool needLock = true);\n\n void processDispatch();\n\n void triggerDispatch(void);\n\n};\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 48, "score": 47.068709680511446 }, { "content": "static const base::type::VerboseLevel kMaxVerboseLevel = 9;\n\nstatic const char* kUnknownUser = \"user\";\n\nstatic const char* kUnknownHost = \"unknown-host\";\n\n\n\n\n\n//---------------- DEFAULT LOG FILE -----------------------\n\n\n\n#if defined(ELPP_NO_DEFAULT_LOG_FILE)\n\n# if ELPP_OS_UNIX\n\nstatic const char* kDefaultLogFile = \"/dev/null\";\n\n# elif ELPP_OS_WINDOWS\n\nstatic const char* kDefaultLogFile = \"nul\";\n\n# endif // ELPP_OS_UNIX\n\n#elif defined(ELPP_DEFAULT_LOG_FILE)\n\nstatic const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE;\n\n#else\n\nstatic const char* kDefaultLogFile = \"myeasylog.log\";\n\n#endif // defined(ELPP_NO_DEFAULT_LOG_FILE)\n\n\n\n\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 49, "score": 47.0211863549232 }, { "content": " ELPP->setThreadName(name);\n\n }\n\n static inline std::string getThreadName() {\n\n return ELPP->getThreadName(base::threading::getCurrentThreadId());\n\n }\n\n#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)\n\n /// @brief Overrides default crash handler and installs custom handler.\n\n /// @param crashHandler A functor with no return type that takes single int argument.\n\n /// Handler is a typedef with specification: void (*Handler)(int)\n\n static inline void setCrashHandler(const el::base::debug::CrashHandler::Handler& crashHandler) {\n\n el::elCrashHandler.setHandler(crashHandler);\n\n }\n\n /// @brief Abort due to crash with signal in parameter\n\n /// @param sig Crash signal\n\n static void crashAbort(int sig, const char* sourceFile = \"\", unsigned int long line = 0);\n\n /// @brief Logs reason of crash as per sig\n\n /// @param sig Crash signal\n\n /// @param stackTraceIfAvailable Includes stack trace if available\n\n /// @param level Logging level\n\n /// @param logger Logger to use for logging\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 50, "score": 45.90081275771177 }, { "content": " /// @return boolean that is true if the file exists and false otherwise.\n\n ///\n\n static bool file_exists(const std::string &fname);\n\n\n\n static std::string system_call(std::string cmd, int log_lvl = 0, bool detached = false);\n\n\n\n static void kill_pid(std::string path, std::string file_name);\n\n\n\n static bool is_pid_running(std::string path, std::string file_name, int *pid_out = nullptr);\n\n\n\n static bool write_pid_file(std::string path, std::string file_name);\n\n\n\n static bool touch_pid_file(std::string file_path);\n\n\n\n static int redirect_console_std(std::string log_file_name);\n\n\n\n static void close_file(int fd);\n\n};\n\n} // namespace beerocks\n\n\n\n#endif //_BEEROCKS_OS_UTILS_H_\n", "file_path": "common/beerocks/bcl/include/bcl/beerocks_os_utils.h", "rank": 51, "score": 45.744206444189416 }, { "content": "#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)\n\nstatic const char* kDefaultLogFileParam = \"--default-log-file\";\n\n#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)\n\n#if defined(ELPP_LOGGING_FLAGS_FROM_ARG)\n\nstatic const char* kLoggingFlagsParam = \"--logging-flags\";\n\n#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)\n\nstatic const char* kValidLoggerIdSymbols =\n\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._\";\n\nstatic const char* kConfigurationComment = \"##\";\n\nstatic const char* kConfigurationLevel = \"*\";\n\nstatic const char* kConfigurationLoggerId = \"--\";\n\n}\n\n// el::base::utils\n\nnamespace utils {\n\n\n\n/// @brief Aborts application due with user-defined status\n\nstatic void abort(int status, const std::string& reason) {\n\n // Both status and reason params are there for debugging with tools like gdb etc\n\n ELPP_UNUSED(status);\n\n ELPP_UNUSED(reason);\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 52, "score": 45.501628189436516 }, { "content": "\n\n private:\n\n std::string level_ = \"DEBUG\", file_path_ = \"logs.log\";\n\n bool write_to_syslog_ = false, write_to_console_ = true, write_to_file_ = false;\n\n size_t max_file_size_ = 1024, log_flush_threshold_ = 100;\n\n const char *kMessageFormat = \"%datetime{%H:%m:%s} [%proc] [%level] %fbase[%line]: %msg\";\n\n void SetValuesFromJson(struct json_object *jlogger, std::string logger_name);\n\n };\n\n\n\npublic:\n\n static Logger &Instance()\n\n {\n\n static Logger instance;\n\n return instance;\n\n }\n\n void LoggerInit();\n\n void LoggerInit(const char *logger_name);\n\n void LoggerConfig();\n\n void LoggerConfig(const char *logger_name);\n\n void LoggerConfig(Logger::Config &cfg);\n", "file_path": "framework/common/include/mapf/common/logger.h", "rank": 53, "score": 44.45981820069549 }, { "content": "}\n\n\n\nstatic char *dupstr(const std::string &s)\n\n{\n\n auto r_len = s.size() + 1;\n\n char *r = (char *)xmalloc(r_len);\n\n if (r == nullptr) {\n\n LOG(FATAL) << \"Error: Out of memory. Exiting\";\n\n sigterm_handler(0);\n\n return nullptr;\n\n }\n\n beerocks::string_utils::copy_string(r, s.c_str(), r_len);\n\n return r;\n\n}\n\n\n\nstatic char *command_generator(const char *text, int state)\n\n{\n\n static int list_index;\n\n\n\n std::string text_str(text);\n", "file_path": "controller/src/beerocks/cli/beerocks_cli_main.cpp", "rank": 54, "score": 44.09696093783762 }, { "content": "static void cli_tcp_proxy(std::string temp_path)\n\n{\n\n std::string master_uds = temp_path + std::string(BEEROCKS_MASTER_UDS);\n\n beerocks::cli_proxy cli_proxy_thread(master_uds);\n\n\n\n if (!cli_proxy_thread.start()) {\n\n LOG(ERROR) << \"cli_proxy.start() failed \";\n\n g_running = false;\n\n }\n\n\n\n while (g_running) {\n\n UTILS_SLEEP_MSEC(1000);\n\n }\n\n std::cout << \"beerocks_cli exit...\" << std::endl;\n\n cli_proxy_thread.stop();\n\n}\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n init_signals();\n", "file_path": "controller/src/beerocks/cli/beerocks_cli_main.cpp", "rank": 55, "score": 43.933732607234056 }, { "content": " ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str();\n\n}\n\n\n\nstatic inline void crashAbort(int sig) {\n\n base::utils::abort(sig, std::string());\n\n}\n\n\n\n/// @brief Default application crash handler\n\n///\n\n/// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program.\n\nstatic inline void defaultCrashHandler(int sig) {\n\n base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId);\n\n base::debug::crashAbort(sig);\n\n}\n\n\n\n// CrashHandler\n\n\n\nCrashHandler::CrashHandler(bool useDefault) {\n\n if (useDefault) {\n\n setHandler(defaultCrashHandler);\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 56, "score": 43.341021883279915 }, { "content": " static void logCrashReason(int sig, bool stackTraceIfAvailable = false,\n\n Level level = Level::Fatal, const char* logger = base::consts::kDefaultLoggerId);\n\n#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)\n\n /// @brief Installs pre rollout callback, this callback is triggered when log file is about to be rolled out\n\n /// (can be useful for backing up)\n\n static inline void installPreRollOutCallback(const PreRollOutCallback& callback) {\n\n ELPP->setPreRollOutCallback(callback);\n\n }\n\n /// @brief Uninstalls pre rollout callback\n\n static inline void uninstallPreRollOutCallback(void) {\n\n ELPP->unsetPreRollOutCallback();\n\n }\n\n /// @brief Installs post log dispatch callback, this callback is triggered when log is dispatched\n\n template <typename T>\n\n static inline bool installLogDispatchCallback(const std::string& id) {\n\n return ELPP->installLogDispatchCallback<T>(id);\n\n }\n\n /// @brief Uninstalls log dispatch callback\n\n template <typename T>\n\n static inline void uninstallLogDispatchCallback(const std::string& id) {\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 57, "score": 43.230560653017214 }, { "content": "\n\n LOG(DEBUG) << \"backhaul_mgr.stop()\";\n\n backhaul_mgr.stop();\n\n\n\n LOG(DEBUG) << \"platform_mgr.stop()\";\n\n platform_mgr.stop();\n\n }\n\n\n\n LOG(DEBUG) << \"Bye Bye!\";\n\n s_pLogger = nullptr;\n\n\n\n return 0;\n\n}\n\n\n\nstatic int run_son_slave(int slave_num, beerocks::config_file::sConfigSlave &beerocks_slave_conf,\n\n const std::string &hostap_iface, int argc, char *argv[])\n\n{\n\n std::string base_slave_name = std::string(BEEROCKS_AGENT) + \"_\" + hostap_iface;\n\n\n\n //init logger\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 58, "score": 43.21030546662832 }, { "content": "#include <libbridge.h>\n\n}\n\n\n\n#include <mapf/common/logger.h>\n\n\n\nnamespace beerocks {\n\nnamespace bpl {\n\n\n\nint arp_mon_start(BPL_ARP_MON_CTX *ctx, const char *iface)\n\n{\n\n if (!ctx || !iface) {\n\n LOG(ERROR) << \"Invalid arguments: ctx = \" << ctx << \", iface = \" << iface;\n\n\n\n return -1;\n\n }\n\n\n\n // Clear context pointer\n\n *ctx = nullptr;\n\n\n\n arp_monitor *pArpMon = new arp_monitor();\n", "file_path": "framework/platform/bpl/uci/arp/bpl_arp.cpp", "rank": 59, "score": 43.150194065091746 }, { "content": " /// existing Configurations to base all the values and then set rest of configuration via configuration text.\n\n /// @return True if successfully parsed, false otherwise.\n\n static bool parseFromText(const std::string& configurationsString, Configurations* sender,\n\n Configurations* base = nullptr);\n\n\n\n private:\n\n friend class el::Loggers;\n\n static void ignoreComments(std::string* line);\n\n static bool isLevel(const std::string& line);\n\n static bool isComment(const std::string& line);\n\n static inline bool isConfig(const std::string& line);\n\n static bool parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel,\n\n Configurations* conf);\n\n };\n\n\n\n private:\n\n std::string m_configurationFile;\n\n bool m_isFromFile;\n\n friend class el::Loggers;\n\n\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 60, "score": 43.14587046271819 }, { "content": "\n\n// Helpers\n\n\n\n#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)\n\n\n\nvoid Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) {\n\n std::stringstream ss;\n\n ss << base::debug::crashReason(sig).c_str();\n\n ss << \" - [Called el::Helpers::crashAbort(\" << sig << \")]\";\n\n if (sourceFile != nullptr && strlen(sourceFile) > 0) {\n\n ss << \" - Source: \" << sourceFile;\n\n if (line > 0)\n\n ss << \":\" << line;\n\n else\n\n ss << \" (line number not specified)\";\n\n }\n\n base::utils::abort(sig, ss.str());\n\n}\n\n\n\nvoid Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 61, "score": 42.84089515077573 }, { "content": " return true;\n\n}\n\n\n\nbool main_thread::init_dhcp_monitor()\n\n{\n\n static auto dhcp_monitor_cb_wrapper = [&](std::string op, std::string mac, std::string ip,\n\n std::string hostname) {\n\n send_dhcp_notification(op, mac, ip, hostname);\n\n };\n\n\n\n if (!m_pDHCPMonSocket) {\n\n\n\n int dhcp_mon_fd = bpl::dhcp_mon_start(\n\n [](const char *op, const char *mac, const char *ip, const char *hostname) {\n\n dhcp_monitor_cb_wrapper(op, mac, ip, hostname);\n\n });\n\n if (dhcp_mon_fd < 0) {\n\n if (dhcp_mon_fd == -int(bpl::eErrorCode::OPERATION_NOT_SUPPORTED)) {\n\n LOG(INFO) << \"Skip starting DHCP monitor (not supported)\";\n\n return (true);\n", "file_path": "agent/src/beerocks/slave/platform_manager/platform_manager_thread.cpp", "rank": 63, "score": 42.40747550658182 }, { "content": " }\n\n error_time_stamp_timeout = std::chrono::steady_clock::now();\n\n }\n\n UTILS_SLEEP_MSEC(100);\n\n }\n\n\n\n s_pLogger = nullptr;\n\n\n\n return 0;\n\n}\n\n\n\nstatic int run_beerocks_slave(beerocks::config_file::sConfigSlave &beerocks_slave_conf,\n\n const std::unordered_map<int, std::string> &interfaces_map, int argc,\n\n char *argv[])\n\n{\n\n std::string base_slave_name = std::string(BEEROCKS_AGENT);\n\n std::ofstream versionfile;\n\n\n\n //init logger\n\n beerocks::logging slave_logger(beerocks_slave_conf.sLog, base_slave_name);\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 64, "score": 42.406157958000875 }, { "content": " }\n\n std::string cmd = file_name + \" -i \" + hostap_iface;\n\n LOG(DEBUG) << \"son_slave_watchdog(): sending SYSTEM_CALL with cmd = \" << cmd\n\n << std::endl;\n\n beerocks::SYSTEM_CALL(cmd, 2, true);\n\n }\n\n }\n\n}\n\n\n\nstatic int system_hang_test(beerocks::config_file::sConfigSlave &beerocks_slave_conf, int argc,\n\n char *argv[])\n\n{\n\n std::string name = std::string(\"system_hang_test\");\n\n std::ofstream versionfile;\n\n\n\n //init logger\n\n beerocks::logging logger(beerocks_slave_conf.sLog, name);\n\n s_pLogger = &logger;\n\n logger.apply_settings();\n\n LOG(INFO) << std::endl\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 65, "score": 42.251066022861316 }, { "content": " g_test != \"mult\" && g_test != \"factory\") {\n\n std::cout << \"Invalid test name: \" << g_test << std::endl;\n\n PrintHelp();\n\n }\n\n std::cout << \"Test: \" << g_test << std::endl;\n\n break;\n\n case 'v':\n\n g_cfg.verbose = true;\n\n std::cout << \"Verbose\\n\";\n\n break;\n\n case 'h': // -h or --help\n\n case '?': // Unrecognized option\n\n default:\n\n PrintHelp();\n\n break;\n\n }\n\n }\n\n}\n\n\n\nvoid sighandler(int signum)\n", "file_path": "framework/common/test/socket_test.cpp", "rank": 66, "score": 42.17386832201652 }, { "content": "// Invoked when sigint is invoked\n\nstatic void sigint_handler(int signum)\n\n{\n\n if (g_loop_cmd_exec) {\n\n g_loop_cmd_exec = false;\n\n clear_screen();\n\n set_cursor(1, 1);\n\n std::cout << \"Stopped...\" << std::endl << std::endl;\n\n } else {\n\n fclose(stdin);\n\n g_running = false;\n\n }\n\n}\n\n\n\n// Initialize the calls to handle Ctrl+C and Ctrl+x\n\nstatic void init_signals()\n\n{\n\n struct sigaction sigterm_action;\n\n sigterm_action.sa_handler = sigterm_handler;\n\n sigemptyset(&sigterm_action.sa_mask);\n", "file_path": "controller/src/beerocks/cli/beerocks_cli_main.cpp", "rank": 67, "score": 42.133507677046296 }, { "content": " }\n\n\n\n std::string rollover_name(std::string(log_name) + std::string(\".rollover\"));\n\n\n\n remove(rollover_name.c_str());\n\n rename(log_name, rollover_name.c_str());\n\n}\n\n\n\nvoid logging::apply_settings()\n\n{\n\n // Disable The instance of RollMonitor to start fresh\n\n if (m_log_files_auto_roll) {\n\n auto roll_monitor = el::Helpers::logDispatchCallback<RollMonitor>(\"RollMonitor\");\n\n if (roll_monitor) {\n\n roll_monitor->enable(false);\n\n }\n\n }\n\n\n\n el::Configurations defaultConf;\n\n defaultConf.setToDefault();\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 68, "score": 41.95530809147686 }, { "content": "\n\nbool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) {\n\n base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());\n\n std::vector<CustomFormatSpecifier>::iterator it = std::find(m_customFormatSpecifiers.begin(),\n\n m_customFormatSpecifiers.end(), formatSpecifier);\n\n if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) {\n\n m_customFormatSpecifiers.erase(it);\n\n return true;\n\n }\n\n return false;\n\n}\n\n\n\nvoid Storage::setApplicationArguments(int argc, char** argv) {\n\n m_commandLineArgs.setArgs(argc, argv);\n\n m_vRegistry->setFromArgs(commandLineArgs());\n\n // default log file\n\n#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)\n\n if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) {\n\n Configurations c;\n\n c.setGlobally(ConfigurationType::Filename,\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 69, "score": 41.50718903014919 }, { "content": "bool Str::cStringEq(const char* s1, const char* s2) {\n\n if (s1 == nullptr && s2 == nullptr) return true;\n\n if (s1 == nullptr || s2 == nullptr) return false;\n\n return strcmp(s1, s2) == 0;\n\n}\n\n\n\nbool Str::cStringCaseEq(const char* s1, const char* s2) {\n\n if (s1 == nullptr && s2 == nullptr) return true;\n\n if (s1 == nullptr || s2 == nullptr) return false;\n\n\n\n // With thanks to cygwin for this code\n\n int d = 0;\n\n\n\n while (true) {\n\n const int c1 = toupper(*s1++);\n\n const int c2 = toupper(*s2++);\n\n\n\n if (((d = c1 - c2) != 0) || (c2 == '\\0')) {\n\n break;\n\n }\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 70, "score": 41.1470457207326 }, { "content": " {\n\n SIGFPE, \"SIGFPE\", \"Erroneous arithmetic operation\",\n\n \"Arithemetic operation issue such as division by zero or operation resulting in overflow.\"\n\n },\n\n {\n\n SIGILL, \"SIGILL\", \"Illegal instruction\",\n\n \"Generally due to a corruption in the code or to an attempt to execute data.\"\n\n },\n\n {\n\n SIGSEGV, \"SIGSEGV\", \"Invalid access to memory\",\n\n \"Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory.\"\n\n },\n\n {\n\n SIGINT, \"SIGINT\", \"Interactive attention signal\",\n\n \"Interruption generated (generally) by user or operating system.\"\n\n },\n\n};\n\nstatic const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]);\n\n} // namespace consts\n\n} // namespace base\n\ntypedef std::function<void(const char*, std::size_t)> PreRollOutCallback;\n\nnamespace base {\n\nstatic inline void defaultPreRollOutCallback(const char*, std::size_t) {}\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 71, "score": 40.83586281694186 }, { "content": "\n\nint start_broker()\n\n{\n\n pid_t pid = fork();\n\n mapf_assert(pid >= 0);\n\n\n\n if (pid == 0) {\n\n signal(SIGTERM, sighandler);\n\n MAPF_INFO(\"broker starting\");\n\n mapf::Broker broker;\n\n broker.Bind(mapf::BrokerSocket::FRONTEND, kPubAddr);\n\n broker.Bind(mapf::BrokerSocket::BACKEND, kSubAddr);\n\n broker.Run();\n\n }\n\n return pid;\n\n}\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n mapf::Logger::Instance().LoggerInit(\"poller_test\");\n", "file_path": "framework/common/test/poller_test.cpp", "rank": 72, "score": 40.6370640053468 }, { "content": " }\n\n }\n\n\n\n // Enable roll monitor\n\n if (m_log_files_auto_roll) {\n\n auto roll_monitor = el::Helpers::logDispatchCallback<RollMonitor>(\"RollMonitor\");\n\n if (roll_monitor) {\n\n roll_monitor->enable(true);\n\n } else {\n\n el::Helpers::installLogDispatchCallback<RollMonitor>(\"RollMonitor\");\n\n }\n\n }\n\n}\n\n\n\nbool logging::load_settings(const std::string &config_file_path)\n\n{\n\n std::ifstream in_conf_file(config_file_path);\n\n std::string line;\n\n\n\n const std::string SETTING = \"setting\";\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 73, "score": 40.55219268938208 }, { "content": "};\n\nnamespace base {\n\n/// @brief Namespace containing constants used internally.\n\nnamespace consts {\n\nstatic const char kFormatSpecifierCharValue = 'v';\n\nstatic const char kFormatSpecifierChar = '%';\n\nstatic const unsigned int kMaxLogPerCounter = 100000;\n\nstatic const unsigned int kMaxLogPerContainer = 100;\n\nstatic const unsigned int kDefaultSubsecondPrecision = 3;\n\n\n\n#ifdef ELPP_DEFAULT_LOGGER\n\nstatic const char* kDefaultLoggerId = ELPP_DEFAULT_LOGGER;\n\n#else\n\nstatic const char* kDefaultLoggerId = \"default\";\n\n#endif\n\n\n\n#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)\n\n#ifdef ELPP_DEFAULT_PERFORMANCE_LOGGER\n\nstatic const char* kPerformanceLoggerId = ELPP_DEFAULT_PERFORMANCE_LOGGER;\n\n#else\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 74, "score": 40.2494167302318 }, { "content": " }\n\n cs_waiting_for_event = eEvent::INVALID_EVENT;\n\n FSM_MOVE_STATE(GOTO_IDLE);\n\n}\n\n\n\nvoid channel_selection_task::handle_event(int event_type, void *obj)\n\n{\n\n //TASK_LOG(DEBUG) << \"event_type \" << event_type << \" was received\";\n\n if (obj == nullptr) {\n\n TASK_LOG(ERROR) << \"obj == nullptr\";\n\n return;\n\n }\n\n auto event_hostap_mac = network_utils::mac_to_string(((sMacAddr *)obj)->oct);\n\n if (hostap_mac == event_hostap_mac) {\n\n bool handle_event = false;\n\n switch (eEvent(event_type)) {\n\n case eEvent::ACS_RESPONSE_EVENT: {\n\n if (FSM_IS_IN_STATE(WAIT_FOR_ACS_RESPONSE)) {\n\n handle_event = true;\n\n acs_response_event = (sAcsResponse_event *)obj;\n", "file_path": "controller/src/beerocks/master/tasks/channel_selection_task.cpp", "rank": 75, "score": 40.2123053918255 }, { "content": " }\n\n\n\n // Disable the callback - it will be reenabled after the roll\n\n enable(false);\n\n } else {\n\n std::cout << \"failed to roll logs\" << std::endl;\n\n }\n\n }\n\n }\n\n\n\nprivate:\n\n el::base::type::fstream_t *m_fsLogFileStream = nullptr;\n\n std::size_t m_szRollLogFileSize = 0;\n\n bool m_enabled = true;\n\n};\n\n\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 76, "score": 40.153687069002764 }, { "content": "\n\n//////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////// Implementation ///////////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////\n\n\n\nbool base_wlan_hal_dummy::dummy_obj_read_int(const std::string &key, parsed_obj_map_t &obj,\n\n int64_t &value, bool ignore_unknown)\n\n{\n\n auto val_iter = obj.find(key);\n\n if (val_iter == obj.end()) {\n\n LOG(ERROR) << \"param :\" << key << \" is not exist\";\n\n return false;\n\n }\n\n\n\n static const std::string unknown_string = \"UNKNOWN\";\n\n\n\n if (ignore_unknown && !unknown_string.compare(val_iter->second)) {\n\n value = 0;\n\n return true;\n\n }\n", "file_path": "common/beerocks/bwl/dummy/base_wlan_hal_dummy.cpp", "rank": 77, "score": 39.92537315163341 }, { "content": " return true;\n\n}\n\n\n\nvoid Logger::flush(void) {\n\n ELPP_INTERNAL_INFO(3, \"Flushing logger [\" << m_id << \"] all levels\");\n\n base::threading::ScopedLock scopedLock(lock());\n\n base::type::EnumType lIndex = LevelHelper::kMinValid;\n\n LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {\n\n flush(LevelHelper::castFromInt(lIndex), nullptr);\n\n return false;\n\n });\n\n}\n\n\n\nvoid Logger::flush(Level level, el::base::FileStreamPtr fs) {\n\n // Use shared_ptr to prevent file closing in the middle of operation\n\n if (fs == nullptr && m_typedConfigurations->toFile(level)) {\n\n fs = m_typedConfigurations->sharedFileStream(level);\n\n }\n\n if (fs != nullptr) {\n\n fs->flush();\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 78, "score": 39.53800004635886 }, { "content": "//////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////// Local Module Functions ///////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////\n\n\n\n#ifdef BEEROCKS_DEBUG\n\n\n\nstatic void config_logger(const std::string log_file = std::string())\n\n{\n\n el::Configurations defaultConf;\n\n\n\n defaultConf.setToDefault();\n\n defaultConf.setGlobally(el::ConfigurationType::Format,\n\n \"%level %datetime{%H:%m:%s} %fbase %line --> %msg\");\n\n\n\n if (log_file.empty()) {\n\n defaultConf.setGlobally(el::ConfigurationType::ToFile, \"false\");\n\n defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, \"true\");\n\n } else {\n\n defaultConf.setGlobally(el::ConfigurationType::ToFile, \"true\");\n\n defaultConf.setGlobally(el::ConfigurationType::Filename, log_file.c_str());\n", "file_path": "controller/src/beerocks/bml/internal/bml_internal.cpp", "rank": 79, "score": 39.52651471929966 }, { "content": " return true;\n\n}\n\n\n\nbool slave_thread::handle_cmdu_backhaul_manager_message(\n\n Socket *sd, std::shared_ptr<beerocks_header> beerocks_header)\n\n{\n\n if (backhaul_manager_socket == nullptr) {\n\n LOG(ERROR) << \"backhaul_socket == nullptr\";\n\n return true;\n\n } else if (backhaul_manager_socket != sd) {\n\n LOG(ERROR) << \"Unknown socket, ACTION_BACKHAUL action_op: \"\n\n << int(beerocks_header->action_op());\n\n return true;\n\n }\n\n\n\n switch (beerocks_header->action_op()) {\n\n case beerocks_message::ACTION_BACKHAUL_REGISTER_RESPONSE: {\n\n LOG(DEBUG) << \"ACTION_BACKHAUL_REGISTER_RESPONSE\";\n\n if (slave_state == STATE_WAIT_FOR_BACKHAUL_MANAGER_REGISTER_RESPONSE) {\n\n auto response =\n", "file_path": "agent/src/beerocks/slave/son_slave_thread.cpp", "rank": 80, "score": 39.52240528396786 }, { "content": "\n\nint main(int argc, char *argv[])\n\n{\n\n int slave_num;\n\n\n\n init_signals();\n\n\n\n // Check for version query first, handle and exit if requested.\n\n std::string module_description;\n\n if (beerocks::version::handle_version_query(argc, argv, module_description)) {\n\n return 0;\n\n }\n\n\n\n //get command line options\n\n if (!parse_arguments(argc, argv)) {\n\n std::cout << \"Usage: \" << argv[0] << std::endl;\n\n return 0;\n\n }\n\n\n\n // read slave config file\n", "file_path": "agent/src/beerocks/slave/beerocks_slave_main.cpp", "rank": 81, "score": 39.025468113096736 }, { "content": " }\n\n\n\n if (cache_settings) {\n\n save_settings(get_cache_path());\n\n }\n\n\n\n eval_settings();\n\n}\n\n\n\nlogging::logging(const beerocks::config_file::SConfigLog &settings, std::string module_name,\n\n bool cache_settings)\n\n : m_module_name(module_name), m_logfile_size(LOGGING_DEFAULT_MAX_SIZE),\n\n m_levels(LOG_LEVELS_GLOBAL_DEFAULT), m_syslog_levels(LOG_LEVELS_SYSLOG_DEFAULT)\n\n{\n\n m_settings_map.insert(\n\n {\"log_files_enabled\", settings.files_enabled.empty() ? \"true\" : settings.files_enabled});\n\n m_settings_map.insert({\"log_files_path\", settings.files_path});\n\n m_settings_map.insert({\"log_files_auto_roll\",\n\n settings.files_auto_roll.empty() ? \"true\" : settings.files_auto_roll});\n\n m_settings_map.insert({\"log_global_levels\", settings.global_levels});\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 82, "score": 38.67962361995194 }, { "content": " friend class el::base::DefaultLogDispatchCallback;\n\n friend class el::base::MessageBuilder;\n\n friend class el::base::Writer;\n\n friend class el::base::PErrorWriter;\n\n friend class el::base::Storage;\n\n friend class el::base::PerformanceTracker;\n\n friend class el::base::LogDispatcher;\n\n\n\n Logger(void);\n\n\n\n#if ELPP_VARIADIC_TEMPLATES_SUPPORTED\n\n template <typename T, typename... Args>\n\n void log_(Level, int, const char*, const T&, const Args&...);\n\n\n\n template <typename T>\n\n inline void log_(Level, int, const T&);\n\n\n\n template <typename T, typename... Args>\n\n void log(Level, const char*, const T&, const Args&...);\n\n\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 83, "score": 38.679574648610114 }, { "content": " ///\n\n /// @return boolean true if the string contains only whitespace characters\n\n ///\n\n static bool is_empty(const std::string &);\n\n\n\n ///\n\n /// @brief get a head and tail trimmed substring from provided string\n\n ///\n\n /// @return string representation of the boolean value [\"true\" | \"false\"]\n\n ///\n\n static std::string bool_str(bool val);\n\n\n\n static void copy_string(char *dst, const char *src, size_t dst_len);\n\n\n\n static std::vector<std::string> str_split(const std::string &s, char delim);\n\n\n\n#ifndef __GNUC__\n\n#define __builtin_FILE() __FILE__\n\n#define __builtin_LINE() __LINE__\n\n#endif\n", "file_path": "common/beerocks/bcl/include/bcl/beerocks_string_utils.h", "rank": 84, "score": 38.35832081053142 }, { "content": "\n\n auto logger = el::Loggers::getLogger(\"default\");\n\n if (!logger) {\n\n LOG(ERROR) << \"invalid logger!\";\n\n return;\n\n }\n\n auto typedConfigurations = logger->typedConfigurations();\n\n if (!typedConfigurations) {\n\n LOG(ERROR) << \"invalid typedConfigurations!\";\n\n return;\n\n }\n\n\n\n // Create symbolic links to the current log file\n\n if (m_log_files_enabled) {\n\n auto logFilePath = typedConfigurations->filename(el::Level::Info);\n\n auto logFileName = logFilePath.substr(logFilePath.find_last_of(\"/\") + 1);\n\n auto symLinkName = get_log_files_path() + \"/\" + m_module_name + \".log\";\n\n unlink(symLinkName.c_str());\n\n if (symlink(logFileName.c_str(), symLinkName.c_str()) != 0) {\n\n LOG(ERROR) << \"Failed creating symbolic link. errno: \" << strerror(errno);\n", "file_path": "common/beerocks/bcl/source/beerocks_logging.cpp", "rank": 85, "score": 38.35305451786652 }, { "content": " /// @brief Returns value of arguments\n\n /// @see hasParamWithValue(const char*)\n\n const char* getParamValue(const char* paramKey) const;\n\n /// @brief Return true if arguments has a param (not having a value) i,e without '='\n\n bool hasParam(const char* paramKey) const;\n\n /// @brief Returns true if no params available. This exclude argv[0]\n\n bool empty(void) const;\n\n /// @brief Returns total number of arguments. This exclude argv[0]\n\n std::size_t size(void) const;\n\n friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c);\n\n\n\n private:\n\n int m_argc;\n\n char** m_argv;\n\n std::unordered_map<std::string, std::string> m_paramsWithValue;\n\n std::vector<std::string> m_params;\n\n};\n\n/// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr type.\n\n///\n\n/// @detail Most of the functions are virtual final methods but anything implementing this abstract class should implement\n\n/// unregisterAll() and deepCopy(const AbstractRegistry<T_Ptr, Container>&) and write registerNew() method according to container\n\n/// and few more methods; get() to find element, unregister() to unregister single entry.\n\n/// Please note that this is thread-unsafe and should also implement thread-safety mechanisms in implementation.\n\ntemplate <typename T_Ptr, typename Container>\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 86, "score": 38.196492874335405 }, { "content": " broker.Run();\n\n }\n\n\n\n return pid;\n\n}\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n mapf::Logger::Instance().LoggerInit(\"socket_test\");\n\n ProcessArgs(argc, argv);\n\n\n\n signal(SIGABRT, sighandler);\n\n pid_t pid = start_broker(g_cfg);\n\n\n\n mapf::Context &ctx = mapf::Context::Instance();\n\n\n\n if (g_test == \"all\" || g_test == \"string\") {\n\n MAPF_INFO(\"Socket test string start\");\n\n SocketTestString test_string(ctx, &g_cfg);\n\n test_string.Run();\n", "file_path": "framework/common/test/socket_test.cpp", "rank": 87, "score": 38.00708847096709 }, { "content": " el::base::type::StoragePointer *log_storage =\n\n static_cast<el::base::type::StoragePointer *>(log_ctx);\n\n\n\n el::Helpers::setStorage(*log_storage);\n\n s_fExtLogContext = true;\n\n\n\n return (BML_RET_OK);\n\n}\n\n\n\nint bml_internal::set_restricted_channels(const uint8_t *restricted_channels, const std::string mac,\n\n uint8_t is_global, uint8_t size)\n\n{\n\n // // If the socket is not valid, attempt to re-establish the connection\n\n // if (m_sockPlatform == nullptr && !connect_to_platform()) {\n\n // return (-BML_RET_CONNECT_FAIL);\n\n // }\n\n LOG(DEBUG) << \"bml_internal::set_restricted_channels entry\";\n\n // Validate restricted_channels\n\n if (restricted_channels == nullptr) {\n\n LOG(ERROR) << \"Invalid restricted_channels ptr\";\n", "file_path": "controller/src/beerocks/bml/internal/bml_internal.cpp", "rank": 88, "score": 37.98103037569071 }, { "content": " return true;\n\n}\n\n\n\nint os_utils::redirect_console_std(std::string log_file_name)\n\n{\n\n int fd_log_file_std = open(log_file_name.c_str(), O_CREAT | O_APPEND | O_RDWR, 0644);\n\n if (fd_log_file_std > 0) {\n\n std::ostringstream msg;\n\n msg << std::endl << \"Start Log\" << std::endl << std::endl;\n\n if (write(fd_log_file_std, msg.str().c_str(), msg.str().size()) < 0) {\n\n LOG(ERROR) << \"Failed writing to file\";\n\n }\n\n // dup2() - If the newfd was previously open,\n\n // it is silently closed before being reused\n\n dup2(fd_log_file_std, STDOUT_FILENO);\n\n dup2(fd_log_file_std, STDERR_FILENO);\n\n }\n\n close_file(fd_log_file_std);\n\n return fd_log_file_std;\n\n}\n\n\n\nvoid os_utils::close_file(int fd)\n\n{\n\n if (fd) {\n\n close(fd);\n\n }\n\n}\n", "file_path": "common/beerocks/bcl/source/beerocks_os_utils.cpp", "rank": 89, "score": 37.79667293072817 }, { "content": " // sending empty or irrelevant events...\n\n default:\n\n LOG(WARNING) << \"Unhandled event received: \" << opcode;\n\n return true;\n\n break;\n\n }\n\n\n\n return true;\n\n}\n\n\n\nbool sta_wlan_hal_dwpal::process_dwpal_nl_event(struct nl_msg *msg)\n\n{\n\n LOG(ERROR) << __func__ << \"isn't implemented by this derived and shouldn't be called\";\n\n return false;\n\n}\n\n\n\n// Add a new network and return the ID\n\nint sta_wlan_hal_dwpal::add_network()\n\n{\n\n char *reply = nullptr;\n", "file_path": "common/beerocks/bwl/dwpal/sta_wlan_hal_dwpal.cpp", "rank": 90, "score": 37.78710160188634 }, { "content": " return -BML_RET_INVALID_CONFIGURATION;\n\n }\n\n }\n\n\n\n return BML_RET_OK;\n\n}\n\n\n\nvoid rdkb_wlan_task::send_bml_response(int event, Socket *sd, int32_t ret)\n\n{\n\n switch (event) {\n\n case STEERING_EVENT_UNREGISTER:\n\n case STEERING_EVENT_REGISTER: {\n\n auto response = message_com::create_vs_message<\n\n beerocks_message::cACTION_BML_STEERING_EVENT_REGISTER_UNREGISTER_RESPONSE>(cmdu_tx);\n\n\n\n if (response == nullptr) {\n\n LOG(ERROR) << \"Failed building ACTION_BML_STEERING_EVENT_REGISTER_UNREGISTER_RESPONSE \"\n\n \"message!\";\n\n break;\n\n }\n", "file_path": "controller/src/beerocks/master/tasks/rdkb/rdkb_wlan_task.cpp", "rank": 91, "score": 37.77281575117829 }, { "content": "/* SPDX-License-Identifier: BSD-2-Clause-Patent\n\n *\n\n * Copyright (c) 2016-2019 Intel Corporation\n\n *\n\n * This code is subject to the terms of the BSD+Patent license.\n\n * See LICENSE file for more details.\n\n */\n\n\n\n#include <iostream>\n\n#include <mapf/broker/broker.h>\n\n#include <mapf/local_bus.h>\n\n#include <mapf/topology_discovery_agent/topology_discovery_agent.h>\n\n#include <signal.h>\n\n\n\nstatic void signal_handler(int signum)\n\n{\n\n MAPF_INFO(\"PID #\" << getpid() << \": Interrupt Signal (\" << signum << \") received.\");\n\n exit(signum);\n\n}\n\n\n", "file_path": "framework/discovery_agent/topology_discovery_agent_main.cpp", "rank": 92, "score": 37.63384825038087 }, { "content": "inline void Logger::verbose(int vlevel, const char* s, const T& value, const Args&... args) {\n\n acquireLock(); // released in Writer!\n\n log_(el::Level::Verbose, vlevel, s, value, args...);\n\n}\n\ntemplate <typename T>\n\ninline void Logger::verbose(int vlevel, const T& log) {\n\n acquireLock(); // released in Writer!\n\n log_(el::Level::Verbose, vlevel, log);\n\n}\n\n# else\n\ntemplate <typename T, typename... Args>\n\ninline void Logger::verbose(int, const char*, const T&, const Args&...) {\n\n return;\n\n}\n\ntemplate <typename T>\n\ninline void Logger::verbose(int, const T&) {\n\n return;\n\n}\n\n# endif // ELPP_VERBOSE_LOG\n\n# define LOGGER_LEVEL_WRITERS(FUNCTION_NAME, LOG_LEVEL)\\\n", "file_path": "framework/external/easylogging/easylogging++.h", "rank": 93, "score": 37.14822191416908 }, { "content": " return BML_RET_OP_FAILED;\n\n }\n\n auto release_waiting_thread = [&]() -> void {\n\n m_prmGetVapListCreds->set_value(response->result() == 0);\n\n m_prmGetVapListCreds = nullptr;\n\n };\n\n\n\n if (m_vaps == nullptr || m_pvaps_list_size == nullptr) {\n\n LOG(ERROR) << \"The pointer to the user data buffer is null!\";\n\n release_waiting_thread();\n\n break;\n\n }\n\n if (response->result() != 0) {\n\n LOG(ERROR) << \"GET_VAP_LIST_CREDENTIALS_REQUEST failed with error: \"\n\n << response->result();\n\n release_waiting_thread();\n\n break;\n\n }\n\n auto vap_list_size = response->vap_list_size();\n\n LOG(INFO) << \"Received \" << (int)vap_list_size << \" VAPs from the controller\";\n", "file_path": "controller/src/beerocks/bml/internal/bml_internal.cpp", "rank": 94, "score": 37.12540958273662 }, { "content": "\n\n switch (mode) {\n\n case AntMode::ANT_2X2: {\n\n cmd += \"2 2\";\n\n } break;\n\n case AntMode::ANT_4X4: {\n\n cmd += \"4 4\";\n\n } break;\n\n default: {\n\n LOG(ERROR) << \"Invalid antenna mode: \" << int(mode);\n\n return false;\n\n }\n\n }\n\n\n\n LOG(DEBUG) << \"Send cmd: \" << cmd;\n\n // Execute the command\n\n beerocks::os_utils::system_call(cmd, 2);\n\n\n\n return true;\n\n}\n", "file_path": "common/beerocks/bwl/dwpal/ap_wlan_hal_dwpal.cpp", "rank": 95, "score": 37.09921531023746 }, { "content": "\n\n int opt;\n\n enum {\n\n CLI_PROXY,\n\n CLI_ANALYZER,\n\n CLI_NON_INTERACTIVE,\n\n CLI_INTERACTIVE,\n\n } cli_role = CLI_INTERACTIVE;\n\n\n\n std::string analyzer_ip;\n\n std::string ip;\n\n std::string command_string;\n\n\n\n while ((opt = getopt(argc, argv, \"pi:c:a:\")) != -1) {\n\n switch (opt) {\n\n case 'p': {\n\n cli_role = CLI_PROXY;\n\n break;\n\n }\n\n case 'i': {\n", "file_path": "controller/src/beerocks/cli/beerocks_cli_main.cpp", "rank": 96, "score": 37.0312094393103 }, { "content": " for (auto& item : configStringToTypeMap) {\n\n if (base::utils::Str::cStringCaseEq(configStr, item.configString)) {\n\n return item.configType;\n\n }\n\n }\n\n return ConfigurationType::Unknown;\n\n}\n\n\n\nvoid ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {\n\n base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid;\n\n do {\n\n if (fn()) {\n\n break;\n\n }\n\n *startIndex = static_cast<base::type::EnumType>(*startIndex << 1);\n\n } while (*startIndex <= cIndexMax);\n\n}\n\n\n\n// Configuration\n\n\n", "file_path": "framework/external/easylogging/easylogging++.cc", "rank": 97, "score": 36.74483988706086 }, { "content": "int main(int argc, char *argv[])\n\n{\n\n signal(SIGTERM, signal_handler);\n\n\n\n mapf::DiscAgent da;\n\n\n\n // run forever\n\n da.Run();\n\n}\n", "file_path": "framework/discovery_agent/topology_discovery_agent_main.cpp", "rank": 98, "score": 36.61529769036882 }, { "content": "\n\n int rc = poller->CheckEvent(s->getSocketFd());\n\n if (rc & MAPF_POLLIN) {\n\n return true;\n\n } else if (rc & MAPF_POLLERR) {\n\n THREAD_LOG(DEBUG) << \"Received POLLER\";\n\n return true;\n\n } else if (rc == 0) {\n\n return false;\n\n } else {\n\n THREAD_LOG(ERROR) << \"check event error on local bus sub socket, rc=\" << rc;\n\n return false;\n\n }\n\n}\n\n\n\nbool transport_socket_thread::handle_cmdu_message_bus()\n\n{\n\n auto msg = bus->subscriber().Receive();\n\n if (msg == nullptr) {\n\n THREAD_LOG(ERROR) << \"Received msg is null\";\n", "file_path": "common/beerocks/btl/btl_local_bus.cpp", "rank": 99, "score": 36.60473960814262 } ]
C++
LinkedLists/lab2-1.cpp
eva-rubio/Data-Structures-and-Algorithms
97467f89a9a0dc928fd1f19301067dd565114470
#include<iostream> using namespace std; struct node { int num; node * next; }; void print(node * first); void prependNode(int userNum, node * & first); void deleteFirst(node * & first); void findMax(node * & first); int main() { node * first; node * last; char more_nodes = 'y'; int choice; int userNum; first = new node; cout << "What's the first number: "; cin >> first -> num; first -> next = NULL; last = first; while(more_nodes == 'y') { last -> next = new node; last = last -> next; cout << "What value do you want to put in the new box: "; cin >> last -> num; last -> next = NULL; print(first); cout << "Do you have more numbers to enter?"; cin >> more_nodes; } do { cout << "1. Print the list\n" << "2. Print the biggest number in the list\n" << "3. Prepend (add) a node to the beginning of the list\n" << "4. Delete the first node\n" << "5. Quit\n\n" << "What do you want to do: "; cin >> choice; if (choice == 1) { print(first); } else if (choice == 2) { findMax(first); } else if (choice == 3) { cout << "Please introduce the number to prepend to the list: " << endl; cin >> userNum; prependNode(userNum, first); } else if (choice == 4) { deleteFirst(first); } } while (choice != 5); return 0; } void print(node * first) { node * temp; temp = first; while(temp != NULL) { cout << temp -> num << endl; temp = temp -> next; } } void prependNode(int userNum, node * & first){ node * nodeToAdd; nodeToAdd = new node; nodeToAdd -> num = userNum; if (first != NULL){ nodeToAdd -> next = first; first = nodeToAdd; }else{ nodeToAdd -> next = NULL; first = nodeToAdd; print(first); } print(first); } void deleteFirst(node * & first){ if(first != NULL){ node * temp; temp = first; first = first -> next; delete temp; print(first); }else{ cout << "The list is already empty, cant delete anything!"; } } void findMax(node * & first){ int biggest = -1; while (first != NULL) { if (biggest < first->num) biggest = first->num; first = first->next; } cout << "The largest value in the list is: " << biggest << endl; }
#include<iostream> using namespace std; struct node { int num; node * next; }; void print(node * first); void prependNode(int userNum, node * & first); void deleteFirst(node * & first); void findMax(node * & first); int main() { node * first; node * last; char more_nodes = 'y'; int choice; int userNum; first = new node; cout << "What's the first number: "; cin >> first -> num; first -> next = NULL; last = first; while(more_nodes == 'y') { last -> next = new node; last = last -> next; cout << "What value do you want to put in the new box: "; cin >> last -> num; last -> next = NULL; print(first); cout << "Do you have more numbers to enter?"; cin >> more_nodes; } do { cout << "1. Print the list\n" << "2. Print the biggest number in the list\n" << "3. Prepend (add) a node to the beginning of the list\n" << "4. Delete the first node\n" << "5. Quit\n\n" << "What do you want to do: "; cin >> choice; if (choice == 1) { print(first); } else if (choice == 2) { findMax(first); } else if (choice == 3) { cout << "Please introduce the number to prepend to the list: " << endl; cin >> userNum; prependNode(userNum, first); } else if (choice == 4) { deleteFirst(first); } } while (choice != 5); return 0; } void print(node * first) { node * temp; temp = first; while(temp != NULL) { cout << temp -> num << endl; temp = temp -> next; } } void prependNode(int userNum, node * & first){ node * nodeToAdd; nodeToAdd = new node; nodeToAdd -> num = userNum; if (first != NULL){ nodeToAdd -> next = first; first = nodeToAdd; }else{ nodeToAdd -> next = NULL; first = nodeToAdd; print(first); } print(first); } void deleteFirst(node * & first){
} void findMax(node * & first){ int biggest = -1; while (first != NULL) { if (biggest < first->num) biggest = first->num; first = first->next; } cout << "The largest value in the list is: " << biggest << endl; }
if(first != NULL){ node * temp; temp = first; first = first -> next; delete temp; print(first); }else{ cout << "The list is already empty, cant delete anything!"; }
if_condition
[ { "content": "struct node {\n\n\tint numID;\t\t\t// A single integer field (called numID)\n\n\tstring name;\t\t// A single string field (called name)\n\n\tnode * next;\t\t// A pointer to the next node in the list\n\n};\n\n\n\nvoid print(node * first);\n\nvoid prepend(int userNum, string userName, node * & first);\n\nvoid append(int userNum, string userName, node * & first);\n\nvoid remove(int userNum, node * & first);\n\nvoid swap(node * & one, node * & two);\t\n\nvoid sort(node * first);\t\t\t\n\n\n\nint main() {\n\n// Variable definitions\n\n\tnode * first;\t\t\t\t// Pointer to the first node in the list\n\n\tnode * last;\t\t\t\t// Pointer to the last node in the list\n\n\tint size;\t\t\t\t\t// How many students are in the file\n\n\tint choice;\t\t\t\t\t// Menu choice\n\n\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 0, "score": 71441.0530514359 }, { "content": "struct node{\n\n\tstring name;\n\n\tint IDnum;\n\n\tnode * next;\t\t// the next node in each row of the table\n\n};\n\n\n", "file_path": "Hashing/evahash.cpp", "rank": 1, "score": 56380.17775058054 }, { "content": "struct node{\n\n\tint num;\n\n\tnode * parent;\n\n\tnode * left;\n\n\tnode * right;\n\n};\n\n\n\nvoid print(node * temp);\n\nvoid insert(node * & root, node * temp, int value);\n\nvoid search(node * temp, int value);\n\nvoid remove(node * temp, int value);\n\n\n\nint main()\n\n{\n\n\tnode * root = NULL;\n\n\tint choice;\n\n\tint value;\n\n\t\n\n\tdo\n\n\t{\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 2, "score": 48876.761556207624 }, { "content": "\n\n\n\n\n\ndo {\n\n\tcout << \"1. Print the list\\n\"\n\n\t<< \"2. Prepend (add) a node to the beginning of the list\\n\"\n\n\t<< \"3. Append (add) a node to the end of the list\\n\"\n\n\t<< \"4. Delete a node by ID\\n\"\n\n\t<< \"5. Sort the list by ID\\n\"\n\n\t<< \"6. Quit\\n\\n\"\n\n\t<< \"What do you want to do: \";\n\n\tcin >> choice;\n\n\tcout << endl;\n\n\n\n\tif (choice == 1) {\n\n\t\tprint(first);\n\n\t}\n\n\t\t//\t\tPREPEND\n\n\telse if (choice == 2) {\n\n\t\tcout << \"Please introduce student's ID to PREPEND to the list: \" << endl;\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 4, "score": 19209.58245464359 }, { "content": "\t// This loop adds one new node, loads data into it, and updates pointers\t\n\n\t\twhile(more_nodes == 'y')\t\t\n\n\t\t{\n\n\t\t\tlast -> next = new node;\t// Get a new node tacked onto the end of the list\n\n\t\t\tlast = last -> next;\t\t// Toggle last to point to this new node (since it's the new \"last\")\n\n\t\t\tcout << \"introduce new student's ID: \";\n\n\t\t\tcin >> last -> numID;\t\t\t// Put the data from the user into the new node (which is the last one in this case)\n\n\t\t\tcout << \"introduce new student's NAME: \";\n\n\t\t\tcin >> last -> name;\n\n\t\t\tlast -> next = NULL;\t\t// Point the new node to NULL\n\n\t\t\t\n\n\t\t\tprint(first);\n\n\n\n\t\t\tcout << \"Do you have more numbers to enter?\";\n\n\t\t\tcin >> more_nodes;\n\n\t\t}\n\n\n\n//_____________________________________________________________________________________________________________________________________________________________\t\n\n//_____________________________________________________________________________________________________________________________________________________________\t\n\n//\t\t\t\tShould be uncommentted when imputing the file\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 5, "score": 19209.174844375993 }, { "content": "\t\ttemp = first;\n\n\n\n\t\twhile (temp->next != NULL) {\n\n\t\t\ttemp = temp->next;\n\n\t\t}\n\n temp->next = nodeToAdd;\t\t// add nodeToAdd at the end\n\n }\n\n\n\n print(first);\n\n\n\n\n\n\n\n}\n\n\n\n/**\n\n * Allows the user to enter any student numID, and deletes that student's node from list.\n\n * Adjust pointers if node is deleted.\n\n * If not found, print message.\n\n *\n\n * @param userNum\t\tThe ID of the student node that will be deleted from list.\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 9, "score": 19205.281404626472 }, { "content": "\t{\n\n\t\tcout << \" --- ID: \" << temp -> numID << \" Name: \" << temp -> name << endl;\t\t// PRINT OUT THE NAME AND ID\n\n\t\ttemp = temp -> next;\t\t\t\t// Move temp to the next node\n\n\t}\n\n\tcout << endl;\n\n}\n\n\n\n/**\n\n * Allows user to enter a new student name and ID to a node at the START of the list.\n\n *\n\n * @param userNum\t\tThe ID of the student node that will be created and added to list.\n\n * @param userName \t\tThe name of the student node that will be created and added to list.\n\n * @param first \t\tThe current first node of list.\n\n \n\n */\n\nvoid prepend(int userNum, string userName, node * & first) {\n\n\t//creates new node with user input\n\n\tnode * nodeToAdd;\n\n\tnodeToAdd = new node;\n\n\tnodeToAdd -> numID = userNum;\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 10, "score": 19204.663248110362 }, { "content": " * @param first\t\t \tThe current first node of list.\n\n \n\n */\n\nvoid append(int userNum, string userName, node * & first) {\n\n\t//creates new node with user input\n\n\tnode * nodeToAdd;\n\n\tnodeToAdd = new node;\n\n\tnodeToAdd -> numID = userNum;\n\n\tnodeToAdd -> name = userName;\n\n\tnodeToAdd -> next = NULL;\n\n\n\n\t\n\n\t// if list is empty\n\n\tif (first == NULL) { \n\n\t\tfirst = nodeToAdd;\n\n\t}\n\n \t//if list if NOT empty\n\n\telse {\n\n\t\t// crezate temp to scroll through list to find last node\n\n\t\tnode * temp;\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 13, "score": 19203.780031004066 }, { "content": "\tint inputID;\n\n\tstring inputName;\n\n//_____________________________________________________________________________________________________________________________________________________________\t\n\n//_____________________________________________________________________________________________________________________________________________________________\t\n\n//\t\t\t\t\t-- Descomentar esta zona para input manualmente los student nodes. -- \n\n//\t\t\t\t\t\t\t\t\tTo manually enter data into nodes:\n\n\n\n\n\n\tchar more_nodes = 'y';\t// Control to know if the user wants to enter more\n\n\n\n\t\t// Creates the first node\n\n\t\tfirst = new node;\t\t\t// Create the first node\n\n\t\tcout << \"What's the first student ID: \";\n\n\t\tcin >> first -> numID;\t\t// Put data in it\n\n\t\tcout << \"What's the first student's NAME: \";\n\n\t\tcin >> first -> name;\t\t// Put data in it\n\n\t\tfirst -> next = NULL;\t\t// Point it to NULL (since it's the end)\n\n\t\tlast = first;\t\t\t\t// Point last to it (since it's the end)\n\n\n\n\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 15, "score": 19203.440847264457 }, { "content": " * @param first\t\t \tThe current first node of list.\n\n \n\n */\n\n\n\nvoid remove(int userNum, node * & first) {\n\n\t// create temp to scroll through list\n\n\tnode * temp;\n\n\ttemp = first;\n\n\t// Previous node to the one to delete\n\n\tnode * prev;\n\n\tprev = first;\n\n\n\n\t// if list only has one mode, and that mode is the desired one, cout message. (weird case, raro raro por si acaso)\n\n\tif (temp->next == NULL && temp->numID == userNum)\n\n\t{\n\n\t\tcout << endl << \"ERROR. Student ID: \"<< userNum <<\" found but cannot be deleted as it is the only element on \" << endl; \n\n\t\tcout << \"the list and it cannot be made empty.\" << endl << endl;\n\n\t\treturn;\n\n\t}\n\n\t\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 17, "score": 19200.779968473238 }, { "content": "\t// check if ID is in FIRST node (while list has more than 1 elem)\n\n\tif (temp != NULL && temp->numID == userNum)\n\n\t{\n\n \t//update first pointer to point to correct node (el segundo en este caso se convierte en primero)\n\n\t\tfirst = temp->next; \n\n delete(temp); //deletes de ndoe recyclin the memory \n\n return;\n\n }\n\n\n\n // loop rest of list\n\n\n\n // prev = temp; not sure if before or inside while\n\n // si no es el numero avanzamos en la loop\n\n while (temp != NULL && temp->numID != userNum) {\n\n \tprev = temp;\n\n \ttemp = temp->next;\n\n }\n\n\n\n //makingsure the ID is actually in the list\n\n if (temp == NULL) {\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 18, "score": 19200.37660303101 }, { "content": "\telse if (choice == 5) {\n\n\t\tsort(first);\t\t\t\n\n\t}\n\n\n\n\tcout << \" -- Here's your updated list: -- \" << endl << endl;\t\t\n\n\tprint(first);\n\n\n\n\t\t//\t\tQUIT\n\n} while (choice != 6);\n\n\n\nreturn 0;\n\n}\n\n\n\n\n\nvoid print(node * first) {\n\n\t// Print out the linked list by having a temporary pointer scroll through the entire list\n\n\tnode * temp;\t\t\t\t// Make a temporary (dummy) pointer\n\n\ttemp = first;\t\t\t\t// Point it to the first node in the list\n\n\n\n\twhile(temp != NULL)\t\t\t// Continue until temp reaches NULL (the end)\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 19, "score": 19200.366233345332 }, { "content": "\tnodeToAdd -> name = userName;\n\n\tnodeToAdd -> next = NULL;\n\n\n\n\t// if list is empty\n\n\tif (first == NULL) { \n\n\t\tfirst = nodeToAdd;\n\n\t}\n\n \t//if list if NOT empty\n\n\telse {\n\n\t\tnodeToAdd->next = first;\n\n\t\tfirst = nodeToAdd;\n\n\t}\n\n\n\n}\n\n\n\n/**\n\n * Allows user to enter a new student name and ID to a node at the END of the list.\n\n *\n\n * @param userNum\t\tThe ID of the student node that will be created and added to list.\n\n * @param userName \t\tThe name of the student node that will be created and added to list.\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 20, "score": 19199.30861474196 }, { "content": "\t\tcin >> inputID;\n\n\t\tcout << \"Please introduce student's NAME to PREPEND to the list: \" << endl;\n\n\t\tcin >> inputName;\n\n\t\tprepend(inputID, inputName ,first);\n\n\t}\t\t\n\n\t\t//\t\tAPPEND\n\n\telse if (choice == 3) {\n\n\t\tcout << \"Please introduce student's ID to APPEND to the list: \" << endl;\n\n\t\tcin >> inputID;\n\n\t\tcout << \"Please introduce student's NAME to APPEND to the list: \" << endl;\n\n\t\tcin >> inputName;\n\n\t\tappend(inputID, inputName ,first);\n\n\t}\t\t\n\n\t\t//\t\tDELETE\n\n\telse if (choice == 4) {\n\n\t\tcout << \"Please introduce student's ID to DELETE from the list: \" << endl;\n\n\t\tcin >> inputID;\n\n\t\tremove(inputID, first);\t\t\n\n\t}\n\n\t\t//\t\tSORT\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 21, "score": 19198.80088447573 }, { "content": "\t//temp = first;\n\n\tnode * otherTemp;\n\n\n\n\n\n\t//check to see if list is empty\n\n\t// (doesnt happen cause list cannot be made empty (delete methd))\n\n\tif (temp == NULL) {\n\n\t\tcout << \"The list is empty, cannot be sorted.\" << endl;\n\n\t\treturn;\n\n\t}\n\n\tdo {\n\n swapping = 0;\t// reseteamos el valor cada vez que entramos en el loop\n\n temp = first;\t// para que la lista se sortee del todo y no un elemento por vez que loop runs\n\n\n\n while (temp->next != NULL) {\n\n \tif (temp->numID > temp->next->numID) { \n\n \t\tswap(temp, temp->next);\n\n swapping++;\t\t\t// se incrementa solo si se ha realizado un swap\n\n }\n\n temp = temp->next;\t// advance in list\n\n }\n\n otherTemp = temp;\t//veamos si lo necesito, not sure\n\n }\n\n while (swapping);\n\n\n\n\n\n}\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 22, "score": 19197.63964549823 }, { "content": " \tcout << endl << \"404 ERROR. Student ID: \"<< userNum << \" not found.\" << endl << endl;\n\n \treturn;\n\n } \n\n\n\n // update pointers so that prev jumps over the node to delete\n\n prev->next = temp->next;\n\n \t//delete temp once the rerouting was done\n\n delete(temp); \n\n\n\n \n\n}\n\n\n\n/**\n\n * Swaps the two given nodes.\n\n *\n\n * @param one A node to sawap.\n\n * @param two A node to swap.\n\n \n\n */\n\nvoid swap(node * & one, node * & two){\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 23, "score": 19197.142271097397 }, { "content": "\t\t} else {\n\n\n\n while(myTemp->next != NULL){ \n\n\n\n \tmyTemp = myTemp->next;\n\n \tmyTemp->next = myNode;\n\n }\n\n }\n\n //last node\n\n //myTemp->next = myNode;\n\n // myTemp->next->next = NULL;\n\n\n\n}\n\n\n\ninfile.close();\n\n*/\n\n//_____________________________________________________________________________________________________________________________________________________________\t\n\n\n\n\n\n\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 24, "score": 19196.95934721428 }, { "content": "\tint howMany;\n\n\tinfile >> howMany;\n\n\t//grabs 2 and stores them separately each line\n\n\n\n// we are loading data into the node recently created'first'\n\n\twhile(!infile.eof()){\n\n\n\n\t\tnode * myNode;\n\n\t\tmyNode = new node;\n\n\t\tinfile >> myNode->numID;\n\n\t\tinfile >> myNode->name;\n\n\n\n\t\tnode *myTemp = first;\n\n\n\n\t\t//siempre va a estar null first al principio\n\n\t\tif (myTemp == NULL) {\n\n\t\t\t//if first node null se iguala a mynode\n\n\t\t\tmyTemp = myNode; \n\n\t\t\tmyTemp->next = NULL;\n\n\t\t\t\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 25, "score": 19196.199451929962 }, { "content": "\n\n\tint tempID = one->numID;\n\n\tstring tempName = one->name;\n\n\n\n\tone->numID = two->numID;\n\n\tone->name = two->name;\n\n\ttwo->numID = tempID;\n\n\ttwo->name = tempName;\n\n\n\n}\n\n\n\n/**\n\n * Sorts linked list by numID with the Bubble Sort Algorithm.\n\n *\n\n * @param first The first node of the list to sort.\n\n \n\n */\n\nvoid sort(node * first) {\n\n\tint swapping = 0;\n\n\tnode * temp;\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 26, "score": 19195.57467360746 }, { "content": "\n\n// Create the first node\n\n//\tfirst = new node;\t\t\t// Create the first node\n\n//\tlast = first;\t\t\t\t// Point last to it (since it's the end) \n\n//_____________________________________________________________________________________________________________________________________________________________\t\n\n/*\n\n\n\n// OPEN THE FILE AND LOAD DATA INTO THE first NODE\n\n\n\n// LOOP THROUGH THE FILE AND LOAD THE REMAINING DATA INTO THE LIST\n\n\n\n\t// Holds the instances of ifstream.\n\n\tifstream infile; \n\n //Opens the file\n\n\tinfile.open(\"class_list.txt\");\n\n\n\n //grab info from file and save it in howMany(grabs first thing in the file)\n\n // number of students in file\n\n // la cosa esta \">>\" reads a line from txt file\n\n // Read the next word from the file and store it in currentWord: (fileIn >> currentWord)\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 27, "score": 19192.618272852294 }, { "content": "//============================================================================\n\n// File name : linkedlist.cpp\n\n// Author : Eva Rubio\n\n// Description : Program #2 - Linked Lists\n\n// Importing data from: class_list.txt\n\n// This program manages a database in a linked list.\n\n// I wasnt able to input the data from the file into the linked list, I tried everything (left some of my tries commented out).\n\n//The rest of the program works and compiles, so I decided to input the data manually instead of submitting something that did not compile. Sorry!\n\n//============================================================================\n\n\n\n#include <iostream>\n\n#include <fstream>\n\nusing namespace std;\n\n\n", "file_path": "LinkedLists/linkedlist.cpp", "rank": 28, "score": 19190.186229983145 }, { "content": "\t\t\ttemp = temp -> next;\n\n\t\t\tprint(temp, row);\n\n\t\t}\n\n\n\n\t}\n\n/**\n\n * Inserts a node in the hash table using the id num as key \n\n */\n\n\tvoid addNode() {\n\n\n\n\t\tint idNew;\n\n\t\tstring nameNew;\n\n\t\tnode * newNode = new node;\n\n\n\n\t\tnode * myTemp = new node; // que es una fila en realidad\n\n\n\n\t\tcout << \"Enter a new name to be inserted: \";\n\n\t\tcin >> nameNew;\n\n\t\tcout << \"Enter its ID number: \";\n\n\t\tcin >> idNew;\n", "file_path": "Hashing/evahash.cpp", "rank": 29, "score": 24.190731396347296 }, { "content": "\t\t{\n\n\t\t\tprint(root);\n\n\t\t\tcout << \"\\nWhat number do you want to search for: \";\n\n\t\t\tcin >> value;\n\n\t\t\tsearch(root, value);\n\n\t\t}\n\n\t\telse if (choice == 4)\n\n\t\t{\n\n\t\t\tcout << \"What number do you want to remove: \";\n\n\t\t\tcin >> value;\n\n\t\t\tremove(root, value);\n\n\t\t\tprint(root);\n\n\t\t}\n\n\t} while (choice != 5);\n\n\t\n\nreturn 0;\n\n}\n\n\n\n\n\nvoid insert(node * & root, node * temp, int value)\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 30, "score": 23.84000281209161 }, { "content": "\n\n\n\nint main()\n\n{\n\n\tint choice, key_ID;\n\n\tnode * temp;\n\n\tstring key_name;\n\n\thash_table chart;\t\t// Declares a hash table called chart\n\n\n\n\tdo\n\n\t{\n\n\t\tcout << \"\\n0. Print the row lengths\\n\"\n\n\t\t\t << \"1. Print the entire table\\n\"\n\n\t\t\t << \"2. Add a node\\n\"\n\n\t\t\t << \"3. Look up a node in the table by ID number\\n\"\n\n\t\t\t << \"4. Look up a node in the table by name\\n\"\n\n\t\t << \"5. Quit\\n\\n\"\n\n\t\t << \"What do you want to do: \";\n\n\t\tcin >> choice;\n\n\n", "file_path": "Hashing/evahash.cpp", "rank": 31, "score": 18.92905072272034 }, { "content": "\t\t\t{\n\n\t\t\t\ttemp = temp -> right;\n\n\t\t\t\tinsert(root, temp, value);\n\n\t\t\t}\n\n\n\n\t\t}\n\n\t}\n\n\t\t\n\n}\t\t\t\n\n\n\nvoid search(node * temp, int value)\n\n{\n\n\tif(temp == NULL)\n\n\t{\n\n\t\tcout << \"\\nYour number isn't in the tree\\n\";\n\n\t}\n\n\telse if(temp -> num == value)\n\n\t{\n\n\t\tcout << \"\\nYou found the number in the tree\\n\";\n\n\t}\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 32, "score": 18.924588118008977 }, { "content": "\t\tcout << \"\\n1. Print the tree\\n\"\n\n\t\t \t << \"2. Insert into the tree\\n\"\n\n\t\t\t << \"3. Search for a value in the tree\\n\"\n\n\t\t\t << \"4. Delete from the tree\\n\"\n\n\t\t << \"5. Quit\\n\\n\"\n\n\t\t << \"What do you want to do: \";\n\n\t\tcin >> choice;\n\n\n\n\t\tif (choice == 1)\n\n\t\t{\n\n\t\t\tprint(root);\n\n\t\t}\n\n\t\telse if (choice == 2)\n\n\t\t{\n\n\t\t\tcout << \"\\nWhat number do you want to insert: \";\n\n\t\t\tcin >> value;\n\n\t \tinsert(root, root, value);\n\n\t\t\tprint(root);\n\n\t\t}\n\n\t\telse if (choice == 3)\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 33, "score": 18.698015437367367 }, { "content": " *\n\n * @param temp Temporary node to go through table\n\n * @param row To keep track of where in the table we are\n\n */\n\n\tvoid print(node * temp, int row) {\n\n\t\t// last row of array: SIZE-1\n\n\t\t// always stopping case goes first. if it is the lAST NULL:\n\n\t\tif(temp == NULL && row == SIZE-1) {\n\n\t\t\tcout << \"\\n\\nPrinting Complete\\n\";\n\n\n\n\t\t//if its a REGULAR NULL - go to the next row\t\n\n\t\t} else if(temp == NULL) {\n\n\t\t\tcout << endl;\n\n\t\t\trow++;\n\n\t\t\ttemp = table[row];\n\n\t\t\tprint(temp, row);\n\n\n\n\t\t//if its a regular NUMBER - print and continue.\n\n\t\t} else {\n\n\t\t\tcout << temp -> name << \" : \" << temp -> IDnum << '\\t';\n", "file_path": "Hashing/evahash.cpp", "rank": 34, "score": 17.11426218939976 }, { "content": "\n\n\t\telse if (value < temp -> num) {\t// si debo seguir buscando, esto es recursivo\n\n\t\t\ttemp = temp -> left;\n\n\t\t}\n\n\t\telse if (value > temp -> num) {\n\n\t\t\ttemp = temp -> right;\n\n\t\t}\n\n\t}\n\n\n\n\n\n\n\n\n\n}\n\n\n\nvoid print(node * temp)\n\n{\n\n\tcout << endl << endl;\t\n\n\n\n\tfor(int j = 0; j < 5; j++)\n\n\t{\t\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 35, "score": 16.44802117906955 }, { "content": "\telse if(value < temp -> num)\n\n\t{\n\n\t\ttemp = temp -> left;\n\n\t\tsearch(temp, value);\n\n\t}\n\n\telse if(value > temp -> num)\n\n\t{\n\n\t\ttemp = temp -> right;\n\n\t\tsearch(temp, value);\n\n\t}\n\n\n\n}\n\n\n\n/**\n\n * Searches the table to find the node to delete, if found, rearanges pointers and deletes such node.\n\n *\n\n * @param temp \t\t\tThe node to delete \n\n * @param value \t\t \n\n*/\n\nvoid remove(node * temp, int value){\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 36, "score": 16.183379075331327 }, { "content": "\t\tif (choice == 0)\n\n\t\t{\n\n\t\t\tchart.rowLengths();\n\n\t\t}\n\n\t\telse if (choice == 1)\n\n\t\t{\n\n\t\t\tchart.print(chart.temp, 0);\n\n\t\t}\n\n\t\telse if (choice == 2)\n\n\t\t{\n\n\t \tchart.addNode();\n\n\t\t}\n\n\t\telse if (choice == 3)\n\n\t\t{\n\n\t\t\tcout << \"What ID number do you want to search for: \";\n\n\t\t\tcout << endl;\n\n\t\t\tcin >> key_ID;\n\n\t\t\ttemp = chart.table[chart.hashing(key_ID)];\n\n\t\t\t//chart.IDLookup(temp, key_ID);\n\n\t\t\tchart.buscar(temp, key_ID);\n", "file_path": "Hashing/evahash.cpp", "rank": 37, "score": 16.040996490946874 }, { "content": "{\n\n\tif(temp == NULL)\n\n\t{\n\n\t\ttemp = new node;\n\n\t\ttemp -> num = value;\n\n\t\ttemp -> parent = NULL;\n\n\t\ttemp -> left = NULL;\n\n\t\ttemp -> right = NULL;\n\n\t\troot = temp;\n\n\t}\n\n\telse\n\n\t{\n\n\t\tif(value <= temp -> num)\n\n\t\t{\n\n\t\t\tif(temp -> left == NULL)\n\n\t\t\t{\n\n\t\t\t\ttemp -> left = new node;\n\n\t\t\t\ttemp -> left -> num = value;\n\n\t\t\t\ttemp -> left -> left = NULL;\n\n\t\t\t\ttemp -> left -> right = NULL;\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 38, "score": 15.181257988342896 }, { "content": "\n\n\t\t} else if (choice == 2) {\n\n\t\t\tcout << \"Please introduce the Row number to be sorted: \" << endl;\n\n\t\t\tcin >> selection;\n\n\t\t\tgetRowSORTED(chart, selection);\n\n\n\n\t\t} else if (choice == 3) {\n\n\t\t\tcout << \"Please introduce the Row number to be searched: \" << endl;\n\n\t\t\tcin >> selection;\n\n\t\t\tcout << \"Please introduce value to search: \" << endl;\n\n\t\t\tcin >> toFind;\n\n\t\t\tbinarySearchRow(chart, selection, toFind);\n\n\n\n\t\t}\n\n\n\n\n\n\t} while (choice != 4);\n\n\n\n\n\n\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 39, "score": 14.193672125589396 }, { "content": "\t\t\t\ttemp -> right = NULL;\n\n\t\t\t\tdelete temp -> right;\n\n\t\t\t}\n\n\t\t\telse if (temp -> right == NULL && temp -> left != NULL) {\n\n\t\t\t\ttemp -> num = temp -> left -> num;\n\n\t\t\t\ttemp -> left = NULL;\n\n\t\t\t\tdelete temp -> left;\n\n\t\t\t}\n\n\n\n\t\t\telse if (temp -> left != NULL && temp -> right != NULL) { // cuando tiene DOS hijos--\n\n\n\n\t\t\t\tnode * otherTemp = new node;\n\n\t\t\t\totherTemp = temp -> left;\n\n\n\n\t\t\t\tif (otherTemp -> right == NULL) {\n\n\t\t\t\t\ttemp -> num = otherTemp -> num;\n\n\t\t\t\t\ttemp -> left = otherTemp->left;\n\n\t\t\t\t\tdelete otherTemp;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 40, "score": 13.79877685414388 }, { "content": "*/\n\n\tvoid buscar(node * temp, int key_ID){\n\n\t\tint theCorrectRow = hashing(key_ID); //to search faster and only in the row it should be in\n\n\t\tif (temp == NULL){\n\n\t\t\tcout << \"The ID number: \" << key_ID << \" is NOT in the chart.\\n\";\n\n\n\n\t\t} else if (temp != NULL && temp -> IDnum != key_ID){\n\n\t\t\tbuscar(temp->next, key_ID);\n\n\n\n\t\t}else {\n\n\t\t\tcout << endl;\n\n\t\t\tcout << \"ID number \" << key_ID << \" found! Corresponding Name: \" << temp->name << endl;\n\n\t\t}\n\n\n\n\t}\n\n/*\n\n * Searches through table to see if given 'name' is in it or not. \n\n *\n\n * @param temp \t\tThe a temp pointer (pointing to row 0's first node) \n\n * @param key_name \tThe name to be found in the table\n", "file_path": "Hashing/evahash.cpp", "rank": 41, "score": 13.405535980193417 }, { "content": "\tif (where == -1){\n\n\t\tcout << endl << \"Value not in chart. \" << endl;\n\n\t}else{\n\n\t\tcout << endl << \"Value at index : \" << where << endl;\n\n\t}\n\n}\n\n\n\n/**\n\n * Gets the desired Column of a 2d array and sorts it with the Bubble Sort algorithm.\n\n *\n\n * @param chart A 2d array.\n\n * @param userChoice The Column to get.\n\n */\n\nvoid getColumnBubbleSorted(int chart[SIZE][SIZE], int userChoice){\n\n\tint temp[SIZE];\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\ttemp[i] = chart[i][userChoice];\n\n\t}\n\n\t// prints the selected column of array\n\n\tcout << \"COLUMN \" << userChoice <<\" BEFORE SORTING: \" << endl;\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 42, "score": 13.349298968254105 }, { "content": "\t\t\t\ttemp -> left -> parent = temp;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\ttemp = temp -> left;\n\n\t\t\t\tinsert(root, temp, value);\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\telse if(value > temp -> num)\n\n\t\t{\n\n\t\t\tif(temp -> right == NULL)\n\n\t\t\t{\n\n\t\t\t\ttemp -> right = new node;\n\n\t\t\t\ttemp -> right -> num = value;\n\n\t\t\t\ttemp -> right -> left = NULL;\n\n\t\t\t\ttemp -> right -> right = NULL;\n\n\t\t\t\ttemp -> right -> parent = temp;\n\n\t\t\t}\n\n\t\t\telse\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 43, "score": 13.343187288669466 }, { "content": "\n\n\t\t\t\twhile (otherTemp -> right != NULL) {\n\n\t\t\t\t\totherTemp = otherTemp -> right;\n\n\t\t\t\t}\n\n\t\t\t\t\n\n\t\t\t\tcout << temp -> num;\n\n\t\t\t\tcout << otherTemp -> num;\n\n\t\t\t\ttemp -> num = otherTemp -> num;\n\n\n\n\t\t\t\tif (otherTemp -> left == NULL) {\n\n\t\t\t\t\totherTemp -> parent -> right = NULL;\n\n\t\t\t\t\tdelete otherTemp;\n\n\t\t\t\t}\n\n\t\t\t\tif (otherTemp -> left != NULL) {\n\n\t\t\t\t\totherTemp -> parent -> left = otherTemp -> left;\n\n\t\t\t\t\tdelete otherTemp;\n\n\t\t\t\t}\t\n\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\t}\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 44, "score": 12.670702151437785 }, { "content": "\t\tcout << '\\t';\n\n\t}\n\n\tcout << temp -> num << endl << endl;\n\n\t\n\n\tfor(int j = 1; j < 5; j++)\n\n\t{\t\n\n\t\tcout << '\\t';\n\n\t}\n\n\t\n\n\tif(temp -> left != NULL)\n\n\t\tcout << temp -> left -> num << \" \";\n\n\telse\n\n\t\tcout << \" \";\n\n\tif(temp -> right != NULL)\n\n\t\tcout << temp -> right -> num;\n\n \t\n\n\t\n\n\tcout << endl << endl;\n\n\n\n\tcout << \" \";\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 45, "score": 12.604745544264068 }, { "content": "\t//binarySearchRow(chart, 3, 12);\n\n\n\n\t///------- ^^^my tests^^^^\n\n\n\n\tdo {\n\n\t\tcout << \"0. Print the whole chart\\n\"\n\n\t\t<< \"1. Bubble sort a COLUMN of scores\\n\"\n\n\t\t<< \"2. Selection sort a ROW of scores\\n\"\n\n\t\t<< \"3. Binary search a ROW\\n\"\n\n\t\t<< \"4. Quit\\n\\n\"\n\n\t\t<< \"What do you want to do: \";\n\n\t\tcin >> choice;\n\n\n\n\t\tif (choice == 0) {\n\n\t\t\tprint2Darray(chart);\n\n\t\t\t\n\n\t\t} else if (choice == 1){\n\n\t\t\tcout << \"Please introduce the Column number to be BUBBLE sorted: \" << endl;\n\n\t\t\tcin >> selection;\n\n\t\t\tgetColumnBubbleSorted(chart, selection);\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 46, "score": 12.348381067008729 }, { "content": "\t\t// to know where it goes\n\n\t\trow = hashing(idNew);\n\n\t\t//el row(array) en el que vamos a store el new node\n\n\t\tmyTemp = table[row];\n\n\t\tnewNode -> name = nameNew;\n\n\t\tnewNode -> IDnum = idNew;\n\n\t\t//points the newNode next to point to the corresponding array(row) in the table\n\n\t\t// hace que el next point to el array que esta en la fila correspondiente\n\n\t\tnewNode -> next = myTemp;\n\n\n\n\t\t//Point the slot i table pointer to this newnode\n\n\t\ttable[row] = newNode;\n\n\t\tlength[row]++;\n\n\n\n\t}\n\n/**\n\n * Searches the table to find if the 'ID' given is in it or not.\n\n *\n\n * @param temp \t\t\tThe appropiate table pointer \n\n * @param key_ID \t\tThe ID to be found in the table\n", "file_path": "Hashing/evahash.cpp", "rank": 47, "score": 11.672379896255281 }, { "content": "\t\n\n\t//When encontrado o I'm at Null\n\n\twhile (temp != NULL) {\n\n\t\tif (temp -> num == value) {\n\n\t\t\t//encontradooooooo!\n\n\n\n\t\t\t\n\n\t\t\tif (temp -> left == NULL && temp -> right == NULL) {\t// when at the boottom, nadie debajo\n\n\t\t\t\tif (temp -> parent -> right == temp) {\n\n\t\t\t\t\ttemp -> parent -> right = NULL;\n\n\t\t\t\t\tdelete temp;\n\n\t\t\t\t}\n\n\t\t\t\tif (temp -> parent -> left == temp) {\n\n\t\t\t\t\ttemp -> parent -> left = NULL;\n\n\t\t\t\t\tdelete temp;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\telse if (temp -> left == NULL && temp -> right != NULL) { // solamente UNICO hijo\n\n\t\t\t\ttemp -> num = temp -> right -> num;\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 48, "score": 11.642196583825477 }, { "content": "#include <iostream>\n\n#include <ctime>\n\n#include <math.h>\n\n#include <cstdlib>\n\n\n\n// Author: Eva Rubio\n\n\n\nusing namespace std;\n\n\n\nconst int SIZE = 8;\n\n\n\nvoid print2Darray(int chart[SIZE][SIZE]); // This function will print the chart\n\nvoid getRowSORTED(int chart[SIZE][SIZE], int userChoice);\n\nvoid getRow(int chart[SIZE][SIZE], int userChoice);\n\nvoid getColumn(int chart[SIZE][SIZE], int userChoice);\n\nvoid getColumnBubbleSorted(int chart[SIZE][SIZE], int userChoice);\n\nvoid print1Darray(int *array, int size);\n\nvoid selectionSort(int *array);\n\nvoid bubbleSort(int *array);\n\nint binarySearch(int *array, int toFind);\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 49, "score": 11.603591148738191 }, { "content": "\n\n\tnode * templ = NULL;\n\n\tnode * tempr = NULL;\n\n\tnode * templl = NULL;\n\n\tnode * templr = NULL;\n\n\tnode * temprl = NULL;\n\n\tnode * temprr = NULL;\n\n\t\n\n\tif (temp -> left != NULL)\n\n\t{\n\n\t\ttempl = temp -> left;\n\n\t\tif(templ -> left != NULL)\n\n\t\t{\n\n\t\t\tcout << templ -> left -> num << \" \";\n\n\t\t\ttempll = templ -> left;\n\n\t\t}\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t\tif(templ -> right != NULL)\n\n\t\t{\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 50, "score": 11.1594287896181 }, { "content": " * @param userChoice The Row to get.\n\n */\n\nvoid getRow(int chart[SIZE][SIZE], int userChoice){\n\n\tint temp[SIZE];\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\ttemp[i] = chart[userChoice][i];\n\n\t}\n\n\tprint1Darray(temp, SIZE);\n\n}\n\n/**\n\n * Gets the desired Column of a 2d array and prints it.\n\n *\n\n * @param chart A 2d array.\n\n * @param userChoice The Column to get.\n\n */\n\nvoid getColumn(int chart[SIZE][SIZE], int userChoice){\n\n\tint temp[SIZE];\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\ttemp[i] = chart[i][userChoice];\n\n\t}\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 51, "score": 11.049874671964577 }, { "content": "\t// prints the selected column of array\n\n\tprint1Darray(temp, SIZE);\n\n}\n\n/**\n\n * Gets the desired Row of a 2d array and sorts its .\n\n *\n\n * @param chart A 2d array.\n\n * @param userChoice The Row to get and sort.\n\n */\n\nvoid getRowSORTED(int chart[SIZE][SIZE], int userChoice){\n\n\tint temp[SIZE];\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\ttemp[i] = chart[userChoice][i];\n\n\t}\n\n\tcout << \"ROW \" << userChoice <<\" BEFORE SORTING: \" << endl;\n\n\tprint1Darray(temp, SIZE);\n\n\t//cout << endl << \"getRowSORTED method will now call selectionSort: \" << endl;\n\n\tcout << endl << \" SORTED ROW 2:\" << endl;\n\n\tselectionSort(temp);\t\n\n}\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 52, "score": 10.97924917903552 }, { "content": "\t\t}\n\n\t\telse if (choice == 4)\n\n\t\t{\n\n\t\t\tcout << \"What name do you want to search for: \";\n\n\t\t\tcin >> key_name;\n\n\t\t\ttemp = chart.table[0];\n\n\t\t\tif(chart.nameLookup(temp,0,key_name) == true)\n\n\t\t\t{\n\n\t\t\t\tcout << key_name << \" is in your chart!\\n\";\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tcout << key_name << \" is NOT in the chart\\n\";\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t} while (choice != 5);\n\n\t\t\n\n\treturn 0;\n\n}\n\n\n\n\n", "file_path": "Hashing/evahash.cpp", "rank": 53, "score": 10.779824425727462 }, { "content": "void binarySearchRow(int chart[SIZE][SIZE], int userChoice, int toFind);\n\n\n\n\n\nint main(){\n\n\n\n\tint chart [SIZE][SIZE]; // This declares a 2d array of ints\n\n\tint choice;\n\n\tint selection; // For the user to select a row or colum to sort or search\n\n\tint toFind; //number to look for in binary search\n\n\n\n int array1[SIZE] = {6,7,8,0,1,9,3,2};\n\n //cout << endl << \"SORTS ROW of 1d test array: \" << endl;\n\n\t//selectionSort(array1);\n\n\t/**\n\n\tcout << \"UNSORTED: \" << endl;\n\n\tprint1Darray(array1, SIZE);\n\n\tcout << endl << \"SORTED: \" << endl;\n\n\tbubbleSort(array1);\n\n\tint where;\n\n\twhere = binarySearch(array1, 8);\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 54, "score": 10.14881353497214 }, { "content": "\n\n/**\n\n * Gets the desired Row of a 2d array, sorts it and searchs through the row \n\n * with the Binary Search algo.\n\n *\n\n * @param chart A 2d array.\n\n * @param userChoice The Row to get.\n\n */\n\nvoid binarySearchRow(int chart[SIZE][SIZE], int userChoice, int toFind){\n\n\tint temp[SIZE]; // to get one unique row in a 2d array\n\n\tint where;\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\ttemp[i] = chart[userChoice][i];\n\n\t}\n\n\tcout << \"ROW \" << userChoice <<\" BEFORE SORTING: \" << endl;\n\n\tprint1Darray(temp, SIZE);\n\n\tcout << endl << \"ROW \" << userChoice <<\" AFTER SORTING: \" << endl;\n\n\tbubbleSort(temp);\n\n\n\n\twhere = binarySearch(temp, toFind);\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 55, "score": 10.072386069592678 }, { "content": "\t\t}\t\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t}\t\n\n\n\n\tcout << endl << endl;\n\n\n\n\tcout << \" \";\n\n\n\nif (temp -> left != NULL)\n\n{\n\n\tif (templl != NULL)\n\n\t{\n\n\t\tif (templl -> left != NULL)\n\n\t\t\tcout << templl -> left -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t\tif (templl -> right != NULL)\n\n\t\t\tcout << templl -> right -> num << \" \";\n\n\t\telse\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 56, "score": 9.751185099736714 }, { "content": "\tcout << \" \";\n\n\n\nif (temp -> right != NULL)\n\n{\n\n\tif (temprl != NULL)\n\n\t{\n\n\t\tif (temprl -> left != NULL)\n\n\t\t\tcout << temprl -> left -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t\tif (temprl -> right != NULL)\n\n\t\t\tcout << temprl -> right -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t}\n\n\telse\n\n\t\tcout << \" \";\n\n\n\n\tif (temprr != NULL)\n\n\t{\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 57, "score": 9.717911625381344 }, { "content": "\t\n\n/**\n\n * function which associates a hash value to each data element (based on its key value)\n\n *\n\n * @param key_ID The key from the data element\n\n * @return \t\tThe designated location (hash value) for that data element in the table\n\n */\n\n\tint hashing(int key_ID) {\n\n\t\treturn key_ID % SIZE;\n\n\t}\n\n\n\n\tvoid rowLengths() {\n\n\t\tcout << \"Here are the lengths of each row:\\n\";\n\n\t\tfor (int i = 0; i < SIZE; i++)\n\n\t\t{\n\n\t\t\tcout << '|' << i << \"| \" << length[i] << endl;\n\n\t\t}\n\n\t}\n\n/**\n\n * Prints the table\n", "file_path": "Hashing/evahash.cpp", "rank": 58, "score": 9.580027772116726 }, { "content": "\t\t\tcout << templ -> right -> num << \" \";\n\n \t\t\ttemplr = templ -> right;\n\n\t\t}\t\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t}\t\n\n\tif (temp -> right != NULL)\n\n\t{\n\n\t\ttempr = temp -> right;\n\n\t\tif(tempr -> left != NULL)\n\n\t\t{\n\n\t\t\tcout << tempr -> left -> num << \" \";\n\n\t\t\ttemprl = tempr -> left;\n\n\t\t}\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t\tif(tempr -> right != NULL)\n\n\t\t{\n\n\t\t\tcout << tempr -> right -> num << \" \";\n\n \t\t\ttemprr = tempr -> right;\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 59, "score": 9.479058353909993 }, { "content": "\tcout << \"the location: \" << where << endl;\n\n*/\n\n\t// This code will load the chart with random numbers between 0-50\n\n\tint seed = time(0);\n\n\tsrand(seed);\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\tfor (int j = 0; j < SIZE; j++) {\n\n\t\t\tchart[i][j] = rand() % 50;\n\n\t\t}\n\n\t}\n\n\t\n\n\t//cout << \"Creates NEW Chart and prints it: \" << endl;\n\n\t//print2Darray(chart);\n\n\t//cout << \"Gets row 2 and prints it: \" << endl;\n\n\t//getRowSORTED(chart, 2);\n\n\t//cout << endl << \"Gets Column 3 and prints it: \" << endl;\n\n\t//getColumn(chart, 3);\n\n\t//cout << endl << \"Gets column 3 and sorts it: \" << endl;\n\n\t//getColumnBubbleSorted(chart, 3);\n\n\t//cout << endl << \"binary search row 3, looking for 12: \" << endl;\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 60, "score": 9.343962854259233 }, { "content": " * @return \t\t\ttrue or false\n\n */\n\n\tbool nameLookup(node * temp, int row, string key_name) {\n\n\t\t// end of table\n\n\t\tif(temp == NULL && row == SIZE-1) {\n\n\t\t\treturn false;\n\n\t\t\t//avanzar a la siguente row y preguntar otra vez\n\n\t\t} else if(temp == NULL && row != SIZE-1) {\n\n\t\t\trow++;\n\n\t\t\ttemp = table[row];\n\n\t\t\treturn nameLookup(temp, row, key_name);\n\n\n\n\t\t} else if(temp != NULL && temp->name != key_name){\t// dentro de la misma fila pero no es el primer valor\n\n\t\t\treturn nameLookup(temp->next, row ,key_name);\n\n\n\n\t\t} else {\n\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n\n};\n", "file_path": "Hashing/evahash.cpp", "rank": 61, "score": 9.292486820970865 }, { "content": "\tprint1Darray(temp, SIZE);\n\n\tcout << endl << \" SORTED COLUMN:\" << endl;\n\n\tbubbleSort(temp);\n\n}\n\n\n\n/**\n\n * Uses Selection Sort algorythm to sort the given 1d array and keeps track of swaps and comparisons. \n\n *\n\n * @param array The array\n\n */\n\nvoid selectionSort(int *array) {\n\n int small;\n\n int mytemp;\n\n int comparisons = 0;\n\n int swaps = 0;\n\n \n\n \n\n for (int k = 0; k < SIZE; k++){\n\n \n\n int small = k;\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 62, "score": 9.095760666592207 }, { "content": "\n\n\n\n\n\n\n\n\t\n\n\tcout << \"ENNNNNND \" << endl;\n\n\n\n\n\n\treturn 0;\n\n}\n\n/**\n\n * Prints 2D array.\n\n *\n\n * @param array An array.\n\n */\n\nvoid print2Darray(int chart[SIZE][SIZE]) {\n\n\tfor (int i = 0; i < SIZE; i++) {\n\n\t\tfor (int j = 0; j < SIZE; j++) {\n\n\t\t\tcout << chart[i][j] << '\\t';\n\n\t\t}\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 63, "score": 8.746838786513836 }, { "content": "\t\tcout << endl;\n\n\t}\n\n\tcout << endl;\n\n}\n\n/**\n\n * Prints 1D array.\n\n *\n\n * @param array An array.\n\n * @param size The size of the array.\n\n */\n\nvoid print1Darray(int array[], int size)\n\n{\n\n\tint i;\n\n\tfor(i = 0; i < size; i++)\n\n\t\tcout << array[i] << '\\t';\n\n}\n\n/**\n\n * Gets the desired Row of a 2d array and prints it.\n\n *\n\n * @param chart A 2d array.\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 64, "score": 8.744016933411539 }, { "content": "//============================================================================\n\n// File name : hash.cpp\n\n// Author : Eva Rubio\n\n// Description : Prog #3 - Hashing\n\n// This program implements a class for a hash table \n\n//============================================================================\n\n\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nconst int SIZE = 10;\n\n\n", "file_path": "Hashing/evahash.cpp", "rank": 65, "score": 8.170470707316495 }, { "content": "\t\t\tcout << \" \";\n\n\t}\n\n\telse\n\n\t\tcout << \" \";\n\n\n\n\tif (templr != NULL)\n\n\t{\n\n\t\tif (templr -> left != NULL)\n\n\t\t\tcout << templr -> left -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t\tif (templr -> right != NULL)\n\n\t\t\tcout << templr -> right -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\t\t\n\n\t}\n\n\telse\n\n\t\tcout << \" \";\n\n}\n\nelse\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 66, "score": 8.046121352334277 }, { "content": "\t\tif (temprr -> left != NULL)\n\n\t\t\tcout << temprr -> left -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\n\n\t\tif (temprr -> right != NULL)\n\n\t\t\tcout << temprr -> right -> num << \" \";\n\n\t\telse\n\n\t\t\tcout << \" \";\t\t\n\n\t}\n\n\telse\n\n\t\tcout << \" \";\n\n}\n\nelse\n\n\tcout << \" \";\n\n\n\n} ", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 67, "score": 7.89009718395125 }, { "content": "\n\n/**\n\n * Uses Bubble Sort algorythm to sort the given 1d array and keeps track of swaps and comparisons. \n\n *\n\n * @param array The array\n\n */\n\n\n\nvoid bubbleSort(int *array) {\n\n int swaps = 0;\n\n int comparisons = 0;\n\n int mytemp;\n\n\n\n for (int i = 0; i < SIZE; ++i){\n\n for (int j = 0; j < SIZE - 1; j++){\n\n comparisons++;\n\n //only swap if bigger number\n\n if (array[j] > array[j + 1]){\n\n swaps++;\n\n mytemp = array[j];\n\n array[j] = array[j + 1];\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 68, "score": 7.42673835638869 }, { "content": "//============================================================================\n\n// File name : BTS.cpp\n\n// Author : Eva Rubio\n\n// Description : LAB #6 - Binary Search Trees\n\n// This program implements a BST\n\n//============================================================================\n\n\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n", "file_path": "BinarySearchTrees/BTS- lab6.cpp", "rank": 69, "score": 6.450805402004812 }, { "content": " for (int current = k; current < SIZE; current++){\n\n \tcomparisons++;\n\n //checking which one is the smaller\n\n if (array[small] > array[current]){ \n\n small = current;\n\n }\n\n }\n\n\n\n //swaping the values, need to have mytemp to store it\n\n mytemp = array[k];\n\n array[k] = array[small];\n\n array[small] = mytemp;\n\n swaps++; \n\n cout << endl << \"Swaps done: \" << swaps << \" Numb of comparisons: \" << comparisons << endl;\n\n cout << endl << \"My sorted array: \" << endl;\n\n\n\n print1Darray(array, SIZE);\n\n }\n\n cout << endl;\n\n}\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 70, "score": 4.8886207328179045 }, { "content": " array[j + 1] = mytemp;\n\n }\n\n }\n\n //exists early if there are no swaps done.\n\n if( swaps == 0 ){\n\n break;\n\n }\n\n print1Darray(array, SIZE);\n\n cout << endl;\n\n }\n\n\n\n cout << endl << \"Swaps done: \" << swaps << \" Numb of comparisons: \" << comparisons << endl;\n\n}\n\n\n\n\n\n/**\n\n * Uses Binary Search algorythm to search the given 1d SORTED array and keeps track of swaps and comparisons. \n\n *\n\n * @param array The SORTED array\n\n * @param toFind The number to be searched for in the given array\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 71, "score": 4.828157825899681 }, { "content": " * @return The location, index, of toFind. Returns -1 otherwise.\n\n */\n\n\n\nint binarySearch(int *array, int toFind) {\n\n\tint low = 0;\n\n\tint middle = 0;\n\n\tint high = SIZE - 1;\n\n\n\n\twhile(high >= low){\n\n\t\tmiddle = (high + low)/2;\n\n\t\tif (array[middle] < toFind){\n\n\t\t\tlow = middle +1;\n\n\t\t}else if (array[middle] > toFind){\n\n\t\t\thigh = middle -1;\n\n\t\t}else{\n\n\t\t\treturn middle;\n\n\t\t}\n\n\n\n\t}\n\n\treturn -1; //if not found\n\n}\n\n\n", "file_path": "SearchingAndSortingAlgo/sortingAlgo.cpp", "rank": 72, "score": 4.635315027096164 } ]
C++
tumor2d/src/matrix.ipp
ICB-DCM/lookahead-study
b9849ce2b0cebbe55d6c9f7a248a5f4dff191007
#ifndef MATRIX_IPP #include <stdio.h> #include <stdlib.h> #include <math.h> #define SINGULAR 1e-16 template <class T> T **allocMatrix( int n, int m) { T **A = (T**) malloc( n*sizeof(T*)); for( int i=0; i<n; i++){ A[i] = (T*) malloc( m*sizeof(T)); for( int j=0; j<m; j++) A[i][j] = 0.; } return A; } template <class T> void freeMatrix( T** &A, int n) { for( int i=0; i<n; i++) free(A[i]); free(A); } template <class T> void vectorMatrixProduct( T* &v, T** &A, T* &u, int m, int n) { for( int j=0; j<n; j++){ u[j] = 0; for( int i=0; i<m; i++) u[j] += v[i] * A[i][j]; } } template <class T> void matrixVectorProduct( T** &A, T* &v, T* &u, int m, int n) { for( int i=0; i<m; i++){ u[i] = 0; for( int j=0; j<n; j++) u[i] += A[i][j] * v[j]; } } template <class T> T dotProduct( T* &v1, T* &v2, int n) { T dotProd = 0; for( int i=0; i<n; i++){ dotProd += v1[i] * v2[i]; } return dotProd; } template <class T> void decomposeGaussJordan( T** &A, T** &LR, int n) { for( int i=0; i<n; n++){ for( int j=i; j<n; j++){ for( int k=0; k<i-1; k++){ A[i][j] -= A[i][k] * A[k][j]; } } for( int j=i+1; j<n; j++){ for( int k=0; k<i-1; k++){ A[j][i] -= A[j][k] * A[k][i]; } A[j][i] /= A[i][i]; } } } template <class T> void decompCholeskyOwn( T** &A, T** &L, int n) { for( int i=0; i<n; i++) for( int j=0; j<=i; j++){ double Summe = A[i][j]; for( int k=0; k<=j-1; k++) Summe = Summe - L[i][k] * L[j][k]; if( i > j){ L[i][j] = Summe / L[j][j]; L[j][i] = 0.; } else if( Summe > 0) L[i][i] = sqrt( Summe); else fprintf( stderr, "Matrix not positive definite\n"); } } template <class T> void invertGaussJordan( T** &a, T** &ainv, int n) { int i, j; int s; int pzeile; int fehler = 0; double f; const double Epsilon = 0.01; double Maximum; FILE *fout = stdout; int pivot = 1; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { ainv[i][j] = 0.0; if (i == j) ainv[i][j] = 1.0; } } #if DEBUG MatOut (stdout, a, n, 2*n); #endif s = 0; do { Maximum = fabs(a[s][s]); if (pivot) { pzeile = s; for (i = s + 1; i < n; i++) if (fabs(a[i][s]) > Maximum) { Maximum = fabs(a[i][s]); pzeile = i; } } fehler = (Maximum < Epsilon); if (fehler) break; if (pivot) { if (pzeile != s) { double h; for (j = s; j < n; j++) { h = a[s][j]; a[s][j] = a[pzeile][j]; a[pzeile][j] = h; } for (j = 0; j < n; j++) { h = ainv[s][j]; ainv[s][j] = ainv[pzeile][j]; ainv[pzeile][j] = h; } } } f = a[s][s]; for (j = s; j < n; j++) a[s][j] = a[s][j] / f; for (j = 0; j < n; j++) ainv[s][j] = ainv[s][j] / f; for (i = 0; i < n; i++) { if (i != s) { f = -a[i][s]; for (j = s; j < n; j++) a[i][j] += f * a[s][j]; for (j = 0; j < n; j++) ainv[i][j] += f * ainv[s][j]; } } #if DEBUG fprintf(stdout, "Nach %1i-tem Eliminationschritt:\n", s+1); MatOut (stdout, a, n, 2*n); #endif s++; } while (s < n); if (fehler) { fprintf(fout, "Inverse: Matrix ist singulaer\n"); } } template <class T> void invertGaussJordan( T* &a, T* &ainv, int n) { int i, j; int s; int pzeile; int fehler = 0; double f; const double Epsilon = 0.01; double Maximum; FILE *fout = stdout; int pivot = 1; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { ainv[i*n+j] = 0.0; if (i == j) ainv[i*n+j] = 1.0; } } #if DEBUG MatOut (stdout, a, n, 2*n); #endif s = 0; do { Maximum = fabs(a[s*n+s]); if (pivot) { pzeile = s; for (i = s + 1; i < n; i++) if (fabs(a[i*n+s]) > Maximum) { Maximum = fabs(a[i*n+s]); pzeile = i; } } fehler = (Maximum < Epsilon); if (fehler) break; if (pivot) { if (pzeile != s) { double h; for (j = s; j < n; j++) { h = a[s*n+j]; a[s*n+j] = a[pzeile*n+j]; a[pzeile*n+j] = h; } for (j = 0; j < n; j++) { h = ainv[s*n+j]; ainv[s*n+j] = ainv[pzeile*n+j]; ainv[pzeile*n+j] = h; } } } f = a[s*n+s]; for (j = s; j < n; j++) a[s*n+j] = a[s*n+j] / f; for (j = 0; j < n; j++) ainv[s*n+j] = ainv[s*n+j] / f; for (i = 0; i < n; i++) { if (i != s) { f = -a[i*n+s]; for (j = s; j < n; j++) a[i*n+j] += f * a[s*n+j]; for (j = 0; j < n; j++) ainv[i*n+j] += f * ainv[s*n+j]; } } #if DEBUG fprintf(stdout, "Nach %1i-tem Eliminationschritt:\n", s+1); MatOut (stdout, a, n, 2*n); #endif s++; } while (s < n); if (fehler) { fprintf(fout, "Inverse: Matrix ist singulaer\n"); } } template <class T> void solveLinearSystemB( T **A, T *b, T *x, int dim, T **B) { int i, j; int k; for( i=0; i<dim; i++){ for( j=0; j<dim; j++){ B[i][j] = A[i][j]; } } for( k=0; k<dim; k++){ if(B[k][k]==0){ for( i=k+1; i<dim && B[i][k]==0; i++); if(i<dim && B[i][k]!=0){ T temp; for( j=k; j<dim; j++){ temp = B[i][j]; B[i][j] = B[k][j]; B[k][j] = temp; } temp = b[i]; b[i] = b[k]; b[k] = temp; } } if(B[k][k]!=0){ for( j=k+1; j<dim; j++) B[k][j]=B[k][j]/B[k][k]; b[k]=b[k]/B[k][k]; B[k][k]=1.; for( i=k+1; i<dim; i++){ for( j=k+1; j<dim; j++) B[i][j]=B[i][j]-B[i][k]*B[k][j]; b[i]=b[i]+b[k]*-B[i][k]; B[i][k]=0; } } } for( k=dim-1; k>=0; k--){ if( B[k][k]!=0) for( i=0; i<k; i++){ b[i]=b[i]+b[k]*-B[i][k]; B[i][k]=0; } } for( i=0; i<dim; i++) x[i] = b[i]; } template <class T> void solveLinearSystem( T **A, T *b, T *x, int dim) { T **B = allocMatrix<T>( dim, dim); if( B == NULL){ exit( 0); } solveLinearSystemB<T>( A, b, x, dim, B); freeMatrix( B, dim); } template <class T> void normalizeVector( T *x, int m){ T sum = 0; for( int j=0; j<m; j++) sum += x[j]; for( int j=0; j<m; j++) x[j] /= sum; } template <class T> T norm( T *x, int dim, int order = 0) { if( order == 0){ T max = 0; for( int i=0; i<dim; i++) max = fmax( fabs(x[i]), max); return max; }else{ T sum = 0; for( int i=0; i<dim; i++) sum += pow( x[i], order); return pow( sum, 1./order); } } template <class T> T norm_diff( T *x1, T *x2, int dim, int order = 0) { if( order == 0){ T max = 0; for( int i=0; i<dim; i++) max = fmax( fabs(x1[i]-x2[i]), max); return max; }else{ T sum = 0; for( int i=0; i<dim; i++) sum += pow( x1[i]-x2[i], order); return pow( sum, 1./order); } } template <class T> bool inbound( T *x, T *lb, T *ub, int d) { for( int i=0; i<d; i++) if( x[i] < lb[i] || x[i] > ub[i]) return false; return true; } template <class T> bool inbound( T *x, T lb, T ub, int d) { for( int i=0; i<d; i++) if( x[i] < lb || x[i] > ub) return false; return true; } template <class T> bool inbound( T *x, T lb, T ub, int d, char mode) { if( mode == 0){ for( int i=0; i<d; i++) if( x[i] < lb || x[i] > ub) return false; return true; } if( mode == 1){ for( int i=0; i<d; i++) if( x[i] >= lb && x[i] <= ub) return true; return false; } } #define MATRIX_IPP #endif
#ifndef MATRIX_IPP #include <stdio.h> #include <stdlib.h> #include <math.h> #define SINGULAR 1e-16 template <class T> T **allocMatrix( int n, int m) { T **A = (T**) malloc( n*sizeof(T*)); for( int i=0; i<n; i++){ A[i] = (T*) malloc( m*sizeof(T)); for( int j=0; j<m; j++) A[i][j] = 0.; } return A; } template <class T> void freeMatrix( T** &A, int n) { for( int i=0; i<n; i++) free(A[i]); free(A); } template <class T> void vectorMatrixProduct( T* &v, T** &A, T* &u, int m, int n) { for( int j=0; j<n; j++){ u[j] = 0; for( int i=0; i<m; i++) u[j] += v[i] * A[i][j]; } } template <class T> void matrixVectorProduct( T** &A, T* &v, T* &u, int m, int n) { for( int i=0; i<m; i++){ u[i] = 0; for( int j=0; j<n; j++) u[i] += A[i][j] * v[j]; } } template <class T> T dotProduct( T* &v1, T* &v2, int n) { T dotProd = 0; for( int i=0; i<n; i++){ dotProd += v1[i] * v2[i]; } return dotProd; } template <class T> void decomposeGaussJordan( T** &A, T** &LR, int n) { for( int i=0; i<n; n++){ for( int j=i; j<n; j++){ for( int k=0; k<i-1; k++){ A[i][j] -= A[i][k] * A[k][j]; } } for( int j=i+1; j<n; j++){ for( int k=0; k<i-1; k++){ A[j][i] -= A[j][k] * A[k][i]; } A[j][i] /= A[i][i]; } } } template <class T> void decompCholeskyOwn( T** &A, T** &L, int n) { for( int i=0; i<n; i++) for( int j=0; j<=i; j++){ double Summe = A[i][j]; for( int k=0; k<=j-1; k++) Summe = Summe - L[i][k] * L[j][k]; if( i > j){ L[i][j] = Summe / L[j][j]; L[j][i] = 0.; } else if( Summe > 0) L[i][i] = sqrt( Summe); else fprintf( stderr, "Matrix not positive definite\n"); } } template <class T> void invertGaussJordan( T** &a, T** &ainv, int n) { int i, j; int s; int pzeile; int fehler = 0; double f; const double Epsilon = 0.01; double Maximum; FILE *fout = stdout; int pivot = 1; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { ainv[i][j] = 0.0; if (i == j) ainv[i][j] = 1.0; } } #if DEBUG MatOut (stdout, a, n, 2*n); #endif s = 0; d
%1i-tem Eliminationschritt:\n", s+1); MatOut (stdout, a, n, 2*n); #endif s++; } while (s < n); if (fehler) { fprintf(fout, "Inverse: Matrix ist singulaer\n"); } } template <class T> void solveLinearSystemB( T **A, T *b, T *x, int dim, T **B) { int i, j; int k; for( i=0; i<dim; i++){ for( j=0; j<dim; j++){ B[i][j] = A[i][j]; } } for( k=0; k<dim; k++){ if(B[k][k]==0){ for( i=k+1; i<dim && B[i][k]==0; i++); if(i<dim && B[i][k]!=0){ T temp; for( j=k; j<dim; j++){ temp = B[i][j]; B[i][j] = B[k][j]; B[k][j] = temp; } temp = b[i]; b[i] = b[k]; b[k] = temp; } } if(B[k][k]!=0){ for( j=k+1; j<dim; j++) B[k][j]=B[k][j]/B[k][k]; b[k]=b[k]/B[k][k]; B[k][k]=1.; for( i=k+1; i<dim; i++){ for( j=k+1; j<dim; j++) B[i][j]=B[i][j]-B[i][k]*B[k][j]; b[i]=b[i]+b[k]*-B[i][k]; B[i][k]=0; } } } for( k=dim-1; k>=0; k--){ if( B[k][k]!=0) for( i=0; i<k; i++){ b[i]=b[i]+b[k]*-B[i][k]; B[i][k]=0; } } for( i=0; i<dim; i++) x[i] = b[i]; } template <class T> void solveLinearSystem( T **A, T *b, T *x, int dim) { T **B = allocMatrix<T>( dim, dim); if( B == NULL){ exit( 0); } solveLinearSystemB<T>( A, b, x, dim, B); freeMatrix( B, dim); } template <class T> void normalizeVector( T *x, int m){ T sum = 0; for( int j=0; j<m; j++) sum += x[j]; for( int j=0; j<m; j++) x[j] /= sum; } template <class T> T norm( T *x, int dim, int order = 0) { if( order == 0){ T max = 0; for( int i=0; i<dim; i++) max = fmax( fabs(x[i]), max); return max; }else{ T sum = 0; for( int i=0; i<dim; i++) sum += pow( x[i], order); return pow( sum, 1./order); } } template <class T> T norm_diff( T *x1, T *x2, int dim, int order = 0) { if( order == 0){ T max = 0; for( int i=0; i<dim; i++) max = fmax( fabs(x1[i]-x2[i]), max); return max; }else{ T sum = 0; for( int i=0; i<dim; i++) sum += pow( x1[i]-x2[i], order); return pow( sum, 1./order); } } template <class T> bool inbound( T *x, T *lb, T *ub, int d) { for( int i=0; i<d; i++) if( x[i] < lb[i] || x[i] > ub[i]) return false; return true; } template <class T> bool inbound( T *x, T lb, T ub, int d) { for( int i=0; i<d; i++) if( x[i] < lb || x[i] > ub) return false; return true; } template <class T> bool inbound( T *x, T lb, T ub, int d, char mode) { if( mode == 0){ for( int i=0; i<d; i++) if( x[i] < lb || x[i] > ub) return false; return true; } if( mode == 1){ for( int i=0; i<d; i++) if( x[i] >= lb && x[i] <= ub) return true; return false; } } #define MATRIX_IPP #endif
o { Maximum = fabs(a[s][s]); if (pivot) { pzeile = s; for (i = s + 1; i < n; i++) if (fabs(a[i][s]) > Maximum) { Maximum = fabs(a[i][s]); pzeile = i; } } fehler = (Maximum < Epsilon); if (fehler) break; if (pivot) { if (pzeile != s) { double h; for (j = s; j < n; j++) { h = a[s][j]; a[s][j] = a[pzeile][j]; a[pzeile][j] = h; } for (j = 0; j < n; j++) { h = ainv[s][j]; ainv[s][j] = ainv[pzeile][j]; ainv[pzeile][j] = h; } } } f = a[s][s]; for (j = s; j < n; j++) a[s][j] = a[s][j] / f; for (j = 0; j < n; j++) ainv[s][j] = ainv[s][j] / f; for (i = 0; i < n; i++) { if (i != s) { f = -a[i][s]; for (j = s; j < n; j++) a[i][j] += f * a[s][j]; for (j = 0; j < n; j++) ainv[i][j] += f * ainv[s][j]; } } #if DEBUG fprintf(stdout, "Nach %1i-tem Eliminationschritt:\n", s+1); MatOut (stdout, a, n, 2*n); #endif s++; } while (s < n); if (fehler) { fprintf(fout, "Inverse: Matrix ist singulaer\n"); } } template <class T> void invertGaussJordan( T* &a, T* &ainv, int n) { int i, j; int s; int pzeile; int fehler = 0; double f; const double Epsilon = 0.01; double Maximum; FILE *fout = stdout; int pivot = 1; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { ainv[i*n+j] = 0.0; if (i == j) ainv[i*n+j] = 1.0; } } #if DEBUG MatOut (stdout, a, n, 2*n); #endif s = 0; do { Maximum = fabs(a[s*n+s]); if (pivot) { pzeile = s; for (i = s + 1; i < n; i++) if (fabs(a[i*n+s]) > Maximum) { Maximum = fabs(a[i*n+s]); pzeile = i; } } fehler = (Maximum < Epsilon); if (fehler) break; if (pivot) { if (pzeile != s) { double h; for (j = s; j < n; j++) { h = a[s*n+j]; a[s*n+j] = a[pzeile*n+j]; a[pzeile*n+j] = h; } for (j = 0; j < n; j++) { h = ainv[s*n+j]; ainv[s*n+j] = ainv[pzeile*n+j]; ainv[pzeile*n+j] = h; } } } f = a[s*n+s]; for (j = s; j < n; j++) a[s*n+j] = a[s*n+j] / f; for (j = 0; j < n; j++) ainv[s*n+j] = ainv[s*n+j] / f; for (i = 0; i < n; i++) { if (i != s) { f = -a[i*n+s]; for (j = s; j < n; j++) a[i*n+j] += f * a[s*n+j]; for (j = 0; j < n; j++) ainv[i*n+j] += f * ainv[s*n+j]; } } #if DEBUG fprintf(stdout, "Nach
random
[ { "content": "extern SparseMatrix *J;\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 0, "score": 140394.67320057453 }, { "content": "extern float *v1;\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 1, "score": 140394.67320057453 }, { "content": "extern float *v2;\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 2, "score": 140394.67320057453 }, { "content": "class Epsilon(ABC):\n\n \"\"\"\n\n Abstract epsilon base class.\n\n\n\n This class encapsulates a strategy for setting a new epsilon for\n\n each new population.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n \"\"\"\n\n Constructor.\n\n \"\"\"\n\n pass\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n \"\"\"\n\n This method is called by the ABCSMC framework before the first usage\n\n of the epsilon and can be used to calibrate it to the statistics of the\n\n samples.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to initialize the epsilon for.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n Returns on demand the distances for initializing the epsilon.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles sampled in the previous iteration.\n\n max_nr_populations: int\n\n The maximum number of populations.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n def configure_sampler(self, sampler):\n\n \"\"\"\n\n This is called by the ABCSMC class and gives the epsilon\n\n the opportunity to configure the sampler.\n\n For example, it might request the sampler to\n\n also return rejected particles in order to adapt the\n\n epsilon to the statistics of the sample.\n\n The method is called by the ABCSMC framework before the first\n\n use of the epsilon (at the beginning of ABCSMC.run()), after\n\n initialize().\n\n\n\n The default is to do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n sampler: Sampler\n\n The sampler used in ABCSMC.\n\n \"\"\"\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Update epsilon value to be used as acceptance criterion for\n\n generation t.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The generation index to update / set epsilon for. Counting is\n\n zero-based. So the first population has t=0.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n The distances that should be used to update epsilon, as returned\n\n by Population.get_weighted_distances(). These are usually the\n\n distances of samples accepted in population t-1. The distances may\n\n differ from those used for acceptance in population t-1, if the\n\n distance function for population t has been updated.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles.\n\n acceptance_rate: float\n\n The current generation's acceptance rate.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n @abstractmethod\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Get epsilon value for generation t.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to get the epsilon threshold for.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon for population t.\n\n \"\"\"\n\n\n\n def requires_calibration(self) -> bool:\n\n \"\"\"\n\n Whether the class requires an initial calibration, based on\n\n samples from the prior. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def is_adaptive(self) -> bool:\n\n \"\"\"\n\n Whether the class is dynamically updated after each generation,\n\n based on the last generation's available data. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def get_config(self):\n\n \"\"\"\n\n Return configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n config: dict\n\n Dictionary describing the distance function.\n\n \"\"\"\n\n return {\"name\": self.__class__.__name__}\n\n\n\n def to_json(self):\n\n \"\"\"\n\n Return JSON encoded configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n json_str: str\n\n JSON encoded string describing the distance function.\n\n The default implementation is to try to convert the dictionary\n\n returned my ``get_config``.\n\n \"\"\"\n", "file_path": "pyABC/0.10.14/epsilon/base.py", "rank": 3, "score": 106199.24547312749 }, { "content": "class Epsilon(ABC):\n\n \"\"\"\n\n Abstract epsilon base class.\n\n\n\n This class encapsulates a strategy for setting a new epsilon for\n\n each new population.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n \"\"\"\n\n Constructor.\n\n \"\"\"\n\n pass\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n \"\"\"\n\n This method is called by the ABCSMC framework before the first usage\n\n of the epsilon and can be used to calibrate it to the statistics of the\n\n samples.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to initialize the epsilon for.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n Returns on demand the distances for initializing the epsilon.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles sampled in the previous iteration.\n\n max_nr_populations: int\n\n The maximum number of populations.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n def configure_sampler(self, sampler):\n\n \"\"\"\n\n This is called by the ABCSMC class and gives the epsilon\n\n the opportunity to configure the sampler.\n\n For example, it might request the sampler to\n\n also return rejected particles in order to adapt the\n\n epsilon to the statistics of the sample.\n\n The method is called by the ABCSMC framework before the first\n\n use of the epsilon (at the beginning of ABCSMC.run()), after\n\n initialize().\n\n\n\n The default is to do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n sampler: Sampler\n\n The sampler used in ABCSMC.\n\n \"\"\"\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Update epsilon value to be used as acceptance criterion for\n\n generation t.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The generation index to update / set epsilon for. Counting is\n\n zero-based. So the first population has t=0.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n The distances that should be used to update epsilon, as returned\n\n by Population.get_weighted_distances(). These are usually the\n\n distances of samples accepted in population t-1. The distances may\n\n differ from those used for acceptance in population t-1, if the\n\n distance function for population t has been updated.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles.\n\n acceptance_rate: float\n\n The current generation's acceptance rate.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n @abstractmethod\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Get epsilon value for generation t.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to get the epsilon threshold for.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon for population t.\n\n \"\"\"\n\n\n\n def requires_calibration(self) -> bool:\n\n \"\"\"\n\n Whether the class requires an initial calibration, based on\n\n samples from the prior. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def is_adaptive(self) -> bool:\n\n \"\"\"\n\n Whether the class is dynamically updated after each generation,\n\n based on the last generation's available data. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def get_config(self):\n\n \"\"\"\n\n Return configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n config: dict\n\n Dictionary describing the distance function.\n\n \"\"\"\n\n return {\"name\": self.__class__.__name__}\n\n\n\n def to_json(self):\n\n \"\"\"\n\n Return JSON encoded configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n json_str: str\n\n JSON encoded string describing the distance function.\n\n The default implementation is to try to convert the dictionary\n\n returned my ``get_config``.\n\n \"\"\"\n", "file_path": "pyABC/Modified/epsilon/base.py", "rank": 4, "score": 105330.65076313548 }, { "content": "\tfloat *v; // values\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 5, "score": 95186.5864195042 }, { "content": "#ifdef __WithGUI__\n\n#include <gui/window.h>\n\nclass Window;\n\n#endif\n\n\n\n\n\n\n\n#ifdef __MultiMade__\n\n#include <time.h>\n\n#endif\n\n\n\n#ifdef __myOMP__\n\n#include <omp.h>\n\n#endif\n\n\n\n#include <ctime>\n\n#include <math.h>\n\n#include <iostream>\n\n#include <fstream>\n\n#include <sstream>\n\n#include <string>\n\n#include \"Montecarlo.h\"\n", "file_path": "tumor2d/src/Substrate.h", "rank": 6, "score": 94638.88071255387 }, { "content": "class Timer\n\n\t{\n\n\tprivate:\n\n\tclock_t start_clock;\n\n\tclock_t mytimer;\n\n\t\n\n\tpublic:\n\n\tTimer(): mytimer(0),calls(0) {}\n\n\tint calls;\n\n\tvoid Start() {start_clock = clock(); calls++;}\n\n\tvoid End(){mytimer += (clock() - start_clock);}\n\n\t\n\n\tdouble Mean(){return ((double)(mytimer / CLOCKS_PER_SEC)/(double)calls) ;}\t\n\n\tdouble Total(){return ((double)(mytimer/ CLOCKS_PER_SEC)) ;}\t\n\n\t};\n", "file_path": "tumor2d/src/Substrate.h", "rank": 7, "score": 94633.45534133844 }, { "content": "class Agent{\n\npublic:\n\n\t//Glucose Uptake\n\n\tstatic double NICK_G_CRITICAL_GLU;\n\n\tstatic double NICK_G_CRITICAL_OXY;\n\n\tstatic double NICK_G_MIN;\n\n\tstatic double NICK_G_MAX;\n\n\n\n\n\n\t//Oxygen Uptake\n\n\tstatic double NICK_O_CRITICAL_OXY;\n\n\tstatic double NICK_O_CRITICAL_GLU;\n\n\tstatic double NICK_O_MIN;\n\n\tstatic double NICK_O_MAX;\n\n\n\n\tstatic bool USE_GRAVITY;\n\n\n\n\tstatic float WASTE_UPTAKE;\n\n\tstatic float WASTE_THRESHOLD_QUIESCENCE;\n\n\t//static float WASTE_THRESHOLD_QUIESCENCE_INTRACELLULAR;\n", "file_path": "tumor2d/src/Agent.h", "rank": 8, "score": 94633.45534133844 }, { "content": "class Angiogenesis\n\n\t{\n\n\tpublic:\n\n\tAngiogenesis();\n\n\t~Angiogenesis();\n\n\t\n\n\n\n\tvoid Initialize(AgentList *agentList);\n\n\tbool Update_Network(double dt, ActionTree *p_list, VoronoiDiagram* voronoiDiagram);\t\n\n\tvoid GiveMeTheBlood();\n\n\tvoid Update_Graph(Agent *agentmoved);\n\n\n\n\n\n\n\n\tAgentList* angioAgentList;\n\n//\tint VoronoiCell_Number;\n\n//\tVoronoiCell **VoronoiCell_List;\n\n\n\n\tVessel_Graph **Node;\n\n\tint nbrNodes; //the number of nodes\n", "file_path": "tumor2d/src/Angiogenesis.h", "rank": 9, "score": 94633.45534133844 }, { "content": "class Substrate\n\n\t{\n\n\tpublic:\n\n\n\n\t#ifndef __WithGUI__\n\n\tSubstrate(int* sizeofaxes, int type, VoronoiDiagram *voronoiDiagram, AgentList *agentList, double Init_Oxy, double Init_Glu, double Work_Parameter, const char *thedirname, char*, double customTimestep);\n\n\t#else\n\n\tbool gui_is_defined;\n\n\tWindow *gui;\n\n\tSubstrate(int* sizeofaxes, int type, VoronoiDiagram *voronoiDiagram, AgentList *agentList, double Init_Oxy, double Init_Glu, double Work_Parameter, const char *thedirname, char *boundaryCondition, double customTimestep, Window *thegui);\n\n\tvoid SwitchOnVisualization();\n\n\tvoid SwitchOffVisualization();\n\n\tbool pause;\n\n\t#endif\n\n\n\n\tAngiogenesis vasculature;\n\n\n\n\t~Substrate();\n\n\tvoid Initialization(int mode);\n\n\tvoid RebuildMatrix();\n", "file_path": "tumor2d/src/Substrate.h", "rank": 10, "score": 94633.45534133844 }, { "content": "class Interpolation\n\n{\n\npublic:\n\n\tstatic VoronoiDiagram *voronoiDiagram;\n\n\tstatic float getRectangleAreaAboveThreshold3D( int index, char mode, float threshold);\n\n\tstatic float getDiscritizedVolumeAboveThreshold1D( int index, char mode, float threshold);\n\n\tstatic float getDiscritizedVolumeAboveThreshold2D( int index, char mode, float threshold);\n\n\tstatic float getDiscritizedVolumeAboveThreshold3D( int index, char mode, float threshold);\n\n\tstatic float getDiscritizedVolumeAboveThreshold1DCubicSpline( int index, char mode, float threshold);\n\n};\n\n\n\n\n\ndouble getVolume( double *p0, double *p1, double *p2, double *p3);\n\nvoid cubicSplines1Dcubic( int N, double *X, double *Y, double *a, double *b, double *c, double *d);\n\nvoid cubicSplines1Dconstraint( int N, double *X, double *Y, double *a, double *b, double *c, double *d);\n\n#endif /* INTERPOLATION_H_ */\n", "file_path": "tumor2d/src/Interpolation.h", "rank": 11, "score": 94633.45534133844 }, { "content": "class Molecule\n\n\t{\n\n\tpublic:\n\n\t\n\n\tMolecule()\n\n\t\t{\n\n\t\tmodulo = 0;\n\n\t\t}\n\n\t~Molecule();\n\n\t\n\n\tstatic void SetDomain(int x_size,int y_size,int z_size, double thetimestep, VoronoiCell ****thedomain);\n\n\tstatic void SetAgents( AgentList *theAgentArray);\n\n\tstatic void ChangeTimeStep(double ts){dt = ts;}\n\n\tvoid SetMethod(int methode, int refill, string bordercondition);\n\n\tvoid SetMemory();\n\n\tvoid SetMatrix(double parameter);\n\n\tvoid SetValuePointer(int mx, int my, int mz,double *thevalueaddress); \n\n\n\n\tvoid (*GiveMe)(Molecule *Mo);\n\n\tdouble (*Rate)(VoronoiCell *thecell);\n", "file_path": "tumor2d/src/Molecule.h", "rank": 12, "score": 94633.45534133844 }, { "content": "class Vessel_Graph;\n", "file_path": "tumor2d/src/Angiogenesis.h", "rank": 13, "score": 93144.68306574418 }, { "content": "class DataRecord\n\n\t{\n\n\tpublic:\n\n\tDataRecord(){}\n\n\n\n\tvoid Init()\n\n\t\t{\n\n\t\tfor(int i = 0; i < MaxRecord; i++)\n\n\t\t\t{\n\n\t\t\ttime[i] = 0.;\n\n\t\t\tliving_cells[i] = 0;\n\n\t\t\tvessels[i] = 0;\n\n\t\t\tradius_of_gyration[i] = 0;\n\n\t\t\tcalls[i] = 0;\n\n\t\t\t}\n\n\t\t}\n\n\t\n\n\tstatic const int MaxRecord = 3000;\n\n\tstatic const double TimeFrequency;\n\n\n", "file_path": "tumor2d/src/Substrate.h", "rank": 14, "score": 93144.68306574418 }, { "content": "class Cell;\n", "file_path": "tumor2d/src/model.cpp", "rank": 15, "score": 93144.68306574418 }, { "content": "class Process {\n\npublic:\n\n\tint _type;\n\n\tdouble _rate;\n\n\tCell *_cell;\n\n\tProcess( Cell* cell, int type, double rate=0) : _type(type), _rate(rate), _cell(cell) {};\n\n};\n\n\n", "file_path": "tumor2d/src/model.cpp", "rank": 16, "score": 93144.68306574418 }, { "content": "class Cell {\n\npublic:\n\n\tint _index;\n\n\tint _type;\n\n\tint _pos;\n\n\tProcess *processes[4];\n\n\tCell( int pos, int type, model_input minp, int idx=0) : _index(idx), _type(type), _pos(pos) {\n\n\t\tprocesses[0] = new Process( this, DIVISION, minp.k_div);\n\n\t\tprocesses[1] = new Process( this, NECROSIS, minp.k_nec);\n\n\t\tprocesses[2] = new Process( this, REENTER, minp.k_re);\n\n\t\tprocesses[3] = new Process( this, LYSIS, minp.k_lys);\n\n\t};\n\n\t~Cell(){\n\n\t\tfree( processes[0]);\n\n\t\tfree( processes[1]);\n\n\t\tfree( processes[2]);\n\n\t\tfree( processes[3]);\n\n\t};\n\n\tstatic void add( Cell* cell, Cell* cells[], int n_cells, Cell* lattice[], int n_lattice){\n\n\n", "file_path": "tumor2d/src/model.cpp", "rank": 17, "score": 93144.68306574418 }, { "content": "class Vessel_Unit;\n\n\n\nextern bool DoWeKnowEachOther(Vessel_Graph *N, Vessel_Graph *M);\n\nextern bool ProbaToSprout(double dt);\n\nextern bool ProbaToCollapse(double dt);\n\nextern bool ProbaToRegress();\n\nextern bool SurroundingNode(Vessel_Graph * Vg);\n\nextern bool SurroundingSlice(Vessel_Unit * Vu);\n\n\n", "file_path": "tumor2d/src/Angiogenesis.h", "rank": 18, "score": 93144.68306574418 }, { "content": "void matrixVectorProduct( double **A, double *b, double *x, int dim);\n", "file_path": "tumor2d/src/Mathematix.h", "rank": 19, "score": 92967.74061963701 }, { "content": "//CLASSES\n\nclass Vessel_Graph\n\n\t{\n\n\tpublic:\n\n\tVessel_Graph();\n\n\t\n\n\tint index;\n\n\tdouble x,y,z;\n\n\t//VoronoiCell *p_voronoiCell;\n\n\tAgent *p_agent;\n\n\t//double growth_factor;\n\n\n\n\t//to compute the pressure with a trilinear function\n\n\tdouble d_max, d_min, d;\n\n\n\n\n\n\tdouble pressure;\n\n\tdouble viscosity;\n\n\tdouble radius;\n\n\tdouble outflow; //the total flow is zero so outflow = -inflow. We take the outflow positive.\n\n\tbool circulation;\n", "file_path": "tumor2d/src/Vessel_Graph.h", "rank": 20, "score": 91741.40167534167 }, { "content": "class Vessel_Unit\n\n\t{\n\n\tpublic:\n\n\tVessel_Unit()\n\n\t\t{\n\n\t\tradius = 1;\n\n\t\tvelocity = 1;\n\n\t\tviscosity = 1;\n\n\t\tflow = 1;\n\n\t\tflowproportion = 1;\n\n\t\tshear = 1;\n\n\t\tcirculation = true;\n\n\t\t}\n\n\t\t\n\n\tint index;\n\n\tbool circulation;\n\n\tVessel_Graph *node1;\n\n\tVessel_Graph *node2;//the nodes in the graph which are connected by this edge.\n\n\tdouble theta,phi,length;\n\n\t\n", "file_path": "tumor2d/src/Vessel_Unit.h", "rank": 21, "score": 91735.56461730003 }, { "content": "class Vessel_Graph;\n\n\n", "file_path": "tumor2d/src/Vessel_Unit.h", "rank": 22, "score": 91735.56461730003 }, { "content": "class Vessel_Unit;\n", "file_path": "tumor2d/src/Vessel_Graph.h", "rank": 23, "score": 91735.56461730003 }, { "content": "// voronoi diagram type\n\nclass VoronoiDiagram {\n\npublic:\n\n\t// methodes\n\n\tVoronoiDiagram( char* filename);\n\n\tVoronoiDiagram( char* filename, VoronoiDiagram * DummyDiagram);\n\n\n\n\tvoid setVoronoiGrid();\n\n\tvoid setDomain();\n\n\tvoid triangulate();\n\n\tvoid sortTetrahedra();\n\n\tvoid setConvexHullNeighborhood();\n\n\tvoid NEWsetExtendedNeighborhood( int radius);\n\n\tvoid setExtendedNeighborhoodAroundVoronoiCell( int radius, int explorationRadius, VoronoiCell *explorationCenter);\n\n\tvoid setExtendedNeighborhoodWithinSphere( int radius, double sphereRadius, double *sphereCenter);\n\n\tvoid setExtendedNeighborhood( double radius);\n\n\tvoid setExtendedNeighborhood( int cells);\n\n\t\n\n\tstatic VoronoiCell *searchClosestVoronoiCell( VoronoiCell *explorationCenter, double targetPosition[DIMENSIONS]);\n\n\tVoronoiCell *searchClosestFreeVoronoiCell( VoronoiCell *explorationCenter, int explorationRadius);\n\n\tVoronoiCell *searchClosestFreeVoronoiCell( VoronoiCell *explorationCenter, int maxDepth, int *symbolicExtendedNeighborhoodSize, int **symbolicExtendedNeighborhood);\n", "file_path": "tumor2d/src/VoronoiDiagramExtended.h", "rank": 24, "score": 90399.87397002289 }, { "content": "//typedef struct _VoronoiCell VoronoiCell;\n\nclass VoronoiCell;\n\ntypedef struct _Tetrahedron Tetrahedron;\n", "file_path": "tumor2d/src/VoronoiDiagramExtended.h", "rank": 25, "score": 90399.87397002289 }, { "content": "// voronoi cell type\n\nclass VoronoiCell {\n\npublic:\n\n\t// methodes\n\n\tVoronoiCell();\n\n\tVoronoiCell( double x, double y, double z);\n\n\t~VoronoiCell();\n\n\n\n\tvoid actualizeExtendedNeighborhood( VoronoiDiagram *voronoiDiagram, int base_index, int generations, int* nr_kr_neighbors_gen, int radius);\n\n\tvoid actualizeFreeNeighbors();\n\n\tvoid checkFreeNeighbors();\n\n\tint isFree();\n\n\tint getState();\n\n\tdouble getDistanceTo( double[DIMENSIONS]);\n\n\tdouble getDistanceTo( VoronoiCell* cell);\n\n\tdouble getDistanceSquareTo( VoronoiCell* cell);\n\n\tbool isDomainBorder( VoronoiDiagram *vd);\n\n\n\n\tint index;\n\n\n\n\t// spatial position\n", "file_path": "tumor2d/src/VoronoiDiagramExtended.h", "rank": 26, "score": 90399.87397002289 }, { "content": "//typedef struct _VoronoiDiagram VoronoiDiagram;\n\nclass VoronoiDiagram;\n\ntypedef struct _SphericalCoordinates SphericalCoordinates;\n\ntypedef struct _ActionTree ActionTree;\n\ntypedef struct _AgentList AgentList;\n\n\n", "file_path": "tumor2d/src/VoronoiDiagramExtended.h", "rank": 27, "score": 90399.87397002289 }, { "content": "void deleteDoubleMatrix( double ** matrix, int dimi);\n", "file_path": "tumor2d/src/Mathematix.h", "rank": 28, "score": 89982.3706931833 }, { "content": "double ** newDoubleMatrix( int dimi, int dimj);\n", "file_path": "tumor2d/src/Mathematix.h", "rank": 29, "score": 89982.3706931833 }, { "content": "class DiffusionReactionEquation{\n\npublic:\n\n\t// SCHEMES\n\n\tstatic const char EXPLICIT\t\t= 1;\n\n\tstatic const char IMPLICIT\t\t= 2;\n\n\tstatic const char STEADYSTATE\t= 3;\n\n\tstatic const char CRANKNICHOLSON= 4;\n\n\n\n\t// BOUNDARY CONDITION\n\n\tstatic const char NEUMANN\t\t= 1;\n\n\tstatic const char DIRICHLET\t\t= 2;\n\n\n\nprivate:\n\n\tVoronoiDiagram *lattice;\n\n\n\n\tfloat *temp;\n\n\tfloat *x;\n\n\tfloat *b;\n\n\tSparseMatrix *A;\n\n\tbool systemUpToDate;\n", "file_path": "tumor2d/src/DiffusionReactionEquation.hpp", "rank": 30, "score": 87926.95561170683 }, { "content": "void deleteLongDoubleMatrix( long double ** matrix, int dimi);\n", "file_path": "tumor2d/src/Mathematix.h", "rank": 31, "score": 87908.1390088952 }, { "content": "long double ** newLongDoubleMatrix( int dimi, int dimj);\n", "file_path": "tumor2d/src/Mathematix.h", "rank": 32, "score": 87908.1390088952 }, { "content": "import numpy as np\n\nimport pandas as pd\n\nimport logging\n\nfrom typing import Callable, List, Union\n\nfrom .base import Epsilon\n\nfrom ..weighted_statistics import weighted_quantile\n\n\n\n\n\nlogger = logging.getLogger(\"Epsilon\")\n\n\n\n\n\nclass ConstantEpsilon(Epsilon):\n\n \"\"\"\n\n Keep epsilon constant over all populations.\n\n This acceptance threshold scheduling strategy is most likely only\n\n interesting for debugging purposes.\n\n\n\n Parameters\n\n ----------\n\n\n\n constant_epsilon_value: float\n\n The epsilon value for all populations\n\n \"\"\"\n\n\n\n def __init__(self,\n\n constant_epsilon_value: float):\n\n super().__init__()\n\n self.constant_epsilon_value = constant_epsilon_value\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"constant_epsilon_value\"] = self.constant_epsilon_value\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n\n return self.constant_epsilon_value\n\n\n\n\n\nclass ListEpsilon(Epsilon):\n\n \"\"\"\n\n Return epsilon values from a predefined list. For every time point\n\n enquired later, an epsilon value must exist in the list.\n\n\n\n Parameters\n\n ----------\n\n\n\n values: List[float]\n\n List of epsilon values.\n\n ``values[t]`` is the value for population t.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n values: List[float]):\n\n super().__init__()\n\n self.epsilon_values = list(values)\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"epsilon_values\"] = self.epsilon_values\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n\n return self.epsilon_values[t]\n\n\n\n def __len__(self):\n\n return len(self.epsilon_values)\n\n\n\n\n\nclass QuantileEpsilon(Epsilon):\n\n \"\"\"\n\n Calculate epsilon as alpha-quantile of the distances from the last\n\n population.\n\n\n\n This strategy works even if the posterior is multi-modal.\n\n Note that the acceptance threshold calculation is based on the distance\n\n to the observation, not on the parameters which generated data with that\n\n distance.\n\n\n\n If completely different parameter sets produce equally good samples,\n\n the distances of their samples to the ground truth data should be\n\n comparable.\n\n\n\n The idea behind weighting is that the probability p_k of obtaining a\n\n distance eps_k in the next generation should be proportional to the\n\n weight w_k of respective particle k in the current generation. Both\n\n weighted and non-weighted median should lead to correct results.\n\n\n\n Parameters\n\n ----------\n\n\n\n initial_epsilon: Union[str, int]\n\n * If 'from_sample', then the initial quantile is calculated from\n\n a sample of the current population size from the prior distribution.\n\n * If a number is given, this number is used.\n\n\n\n alpha: float\n\n The alpha-quantile to be used, e.g. alpha=0.5 means median.\n\n\n\n quantile_multiplier: float\n\n Multiplies the quantile by that number. also applies it\n\n to the initial quantile if it is calculated from samples.\n\n However, it does **not** apply to the initial quantile if\n\n it is given as a number.\n\n\n\n weighted: bool\n\n Flag indicating whether the new epsilon should be computed using\n\n weighted (True, default) or non-weighted (False) distances.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n alpha: float = 0.5,\n\n quantile_multiplier: float = 1,\n\n weighted: bool = True):\n\n\n\n logger.debug(\n\n \"init quantile_epsilon initial_epsilon={}, quantile_multiplier={}\"\n\n .format(initial_epsilon, quantile_multiplier))\n\n\n\n super().__init__()\n\n self._initial_epsilon = initial_epsilon\n\n self.alpha = alpha\n\n self.quantile_multiplier = quantile_multiplier\n\n self.weighted = weighted\n\n self._look_up = {}\n\n\n\n if self.alpha > 1 or self.alpha <= 0:\n\n raise ValueError(\"It must be 0 < alpha <= 1\")\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config.update({\"initial_epsilon\": self._initial_epsilon,\n\n \"alpha\": self.alpha,\n\n \"quantile_multiplier\": self.quantile_multiplier,\n\n \"weighted\": self.weighted})\n\n\n\n return config\n\n\n\n def requires_calibration(self) -> bool:\n\n return self._initial_epsilon == 'from_sample'\n\n\n\n def is_adaptive(self) -> bool:\n\n return True\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n if not self.requires_calibration():\n\n # safety check in __call__\n\n return\n\n\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # initialize epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logging\n\n logger.info(\"initial epsilon is {}\".format(self._look_up[t]))\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Epsilon value for time t, set before via update() method.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon value for time t (throws error if not existent).\n\n \"\"\"\n\n\n\n # initialize if necessary\n\n if not self._look_up:\n\n self._set_initial_value(t)\n\n try:\n\n eps = self._look_up[t]\n\n except KeyError as e:\n\n raise KeyError(\"The epsilon value for time {} does not exist: {} \"\n\n .format(t, repr(e)))\n\n\n\n return eps\n\n\n\n def _set_initial_value(self, t: int):\n\n self._look_up = {t: self._initial_epsilon}\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Compute quantile of the (weighted) distances given in population,\n\n and use this to update epsilon.\n\n \"\"\"\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # update epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logger\n\n logger.debug(\"new eps, t={}, eps={}\".format(t, self._look_up[t]))\n\n\n\n def _update(self,\n\n t: int,\n\n weighted_distances: pd.DataFrame):\n\n \"\"\"\n\n Here the real update happens, based on the weighted distances.\n\n \"\"\"\n\n\n\n # extract distances\n\n distances = weighted_distances.distance.values\n\n\n\n # extract weights\n\n if self.weighted:\n\n weights = weighted_distances.w.values.astype(float)\n\n # The sum of the weighted distances is larger than 1 if more than\n\n # a single simulation per parameter is performed.\n\n # Re-normalize in this case.\n\n weights /= weights.sum()\n\n else:\n\n len_distances = len(distances)\n\n weights = np.ones(len_distances) / len_distances\n\n\n\n # compute weighted quantile\n\n quantile = weighted_quantile(\n\n points=distances, weights=weights, alpha=self.alpha)\n\n\n\n # append to look_up property\n\n self._look_up[t] = quantile * self.quantile_multiplier\n\n\n\n\n\nclass MedianEpsilon(QuantileEpsilon):\n\n \"\"\"\n\n Calculate epsilon as median of the distances from the last population.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n median_multiplier: float = 1,\n\n weighted: bool = True):\n\n super().__init__(initial_epsilon=initial_epsilon,\n\n alpha=0.5,\n\n quantile_multiplier=median_multiplier,\n\n weighted=weighted)\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 33, "score": 77982.05544643616 }, { "content": "import numpy as np\n\nimport pandas as pd\n\nimport logging\n\nfrom typing import Callable, List, Union\n\nfrom .base import Epsilon\n\nfrom ..weighted_statistics import weighted_quantile\n\n\n\n\n\nlogger = logging.getLogger(\"Epsilon\")\n\n\n\n\n\nclass ConstantEpsilon(Epsilon):\n\n \"\"\"\n\n Keep epsilon constant over all populations.\n\n This acceptance threshold scheduling strategy is most likely only\n\n interesting for debugging purposes.\n\n\n\n Parameters\n\n ----------\n\n\n\n constant_epsilon_value: float\n\n The epsilon value for all populations\n\n \"\"\"\n\n\n\n def __init__(self,\n\n constant_epsilon_value: float):\n\n super().__init__()\n\n self.constant_epsilon_value = constant_epsilon_value\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"constant_epsilon_value\"] = self.constant_epsilon_value\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n\n return self.constant_epsilon_value\n\n\n\n\n\nclass ListEpsilon(Epsilon):\n\n \"\"\"\n\n Return epsilon values from a predefined list. For every time point\n\n enquired later, an epsilon value must exist in the list.\n\n\n\n Parameters\n\n ----------\n\n\n\n values: List[float]\n\n List of epsilon values.\n\n ``values[t]`` is the value for population t.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n values: List[float]):\n\n super().__init__()\n\n self.epsilon_values = list(values)\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"epsilon_values\"] = self.epsilon_values\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n\n return self.epsilon_values[t]\n\n\n\n def __len__(self):\n\n return len(self.epsilon_values)\n\n\n\n\n\nclass QuantileEpsilon(Epsilon):\n\n \"\"\"\n\n Calculate epsilon as alpha-quantile of the distances from the last\n\n population.\n\n\n\n This strategy works even if the posterior is multi-modal.\n\n Note that the acceptance threshold calculation is based on the distance\n\n to the observation, not on the parameters which generated data with that\n\n distance.\n\n\n\n If completely different parameter sets produce equally good samples,\n\n the distances of their samples to the ground truth data should be\n\n comparable.\n\n\n\n The idea behind weighting is that the probability p_k of obtaining a\n\n distance eps_k in the next generation should be proportional to the\n\n weight w_k of respective particle k in the current generation. Both\n\n weighted and non-weighted median should lead to correct results.\n\n\n\n Parameters\n\n ----------\n\n\n\n initial_epsilon: Union[str, int]\n\n * If 'from_sample', then the initial quantile is calculated from\n\n a sample of the current population size from the prior distribution.\n\n * If a number is given, this number is used.\n\n\n\n alpha: float\n\n The alpha-quantile to be used, e.g. alpha=0.5 means median.\n\n\n\n quantile_multiplier: float\n\n Multiplies the quantile by that number. also applies it\n\n to the initial quantile if it is calculated from samples.\n\n However, it does **not** apply to the initial quantile if\n\n it is given as a number.\n\n\n\n weighted: bool\n\n Flag indicating whether the new epsilon should be computed using\n\n weighted (True, default) or non-weighted (False) distances.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n alpha: float = 0.5,\n\n quantile_multiplier: float = 1,\n\n weighted: bool = True):\n\n\n\n logger.debug(\n\n \"init quantile_epsilon initial_epsilon={}, quantile_multiplier={}\"\n\n .format(initial_epsilon, quantile_multiplier))\n\n\n\n super().__init__()\n\n self._initial_epsilon = initial_epsilon\n\n self.alpha = alpha\n\n self.quantile_multiplier = quantile_multiplier\n\n self.weighted = weighted\n\n self._look_up = {}\n\n\n\n if self.alpha > 1 or self.alpha <= 0:\n\n raise ValueError(\"It must be 0 < alpha <= 1\")\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config.update({\"initial_epsilon\": self._initial_epsilon,\n\n \"alpha\": self.alpha,\n\n \"quantile_multiplier\": self.quantile_multiplier,\n\n \"weighted\": self.weighted})\n\n\n\n return config\n\n\n\n def requires_calibration(self) -> bool:\n\n return self._initial_epsilon == 'from_sample'\n\n\n\n def is_adaptive(self) -> bool:\n\n return True\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n if not self.requires_calibration():\n\n # safety check in __call__\n\n return\n\n\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # initialize epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logging\n\n logger.info(\"initial epsilon is {}\".format(self._look_up[t]))\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Epsilon value for time t, set before via update() method.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon value for time t (throws error if not existent).\n\n \"\"\"\n\n\n\n # initialize if necessary\n\n if not self._look_up:\n\n self._set_initial_value(t)\n\n try:\n\n eps = self._look_up[t]\n\n except KeyError as e:\n\n raise KeyError(\"The epsilon value for time {} does not exist: {} \"\n\n .format(t, repr(e)))\n\n\n\n return eps\n\n\n\n def _set_initial_value(self, t: int):\n\n self._look_up = {t: self._initial_epsilon}\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Compute quantile of the (weighted) distances given in population,\n\n and use this to update epsilon.\n\n \"\"\"\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # update epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logger\n\n logger.debug(\"new eps, t={}, eps={}\".format(t, self._look_up[t]))\n\n\n\n def _update(self,\n\n t: int,\n\n weighted_distances: pd.DataFrame):\n\n \"\"\"\n\n Here the real update happens, based on the weighted distances.\n\n \"\"\"\n\n\n\n # extract distances\n\n distances = weighted_distances.distance.values\n\n\n\n # extract weights\n\n if self.weighted:\n\n weights = weighted_distances.w.values.astype(float)\n\n # The sum of the weighted distances is larger than 1 if more than\n\n # a single simulation per parameter is performed.\n\n # Re-normalize in this case.\n\n weights /= weights.sum()\n\n else:\n\n len_distances = len(distances)\n\n weights = np.ones(len_distances) / len_distances\n\n\n\n # compute weighted quantile\n\n quantile = weighted_quantile(\n\n points=distances, weights=weights, alpha=self.alpha)\n\n\n\n # append to look_up property\n\n self._look_up[t] = quantile * self.quantile_multiplier\n\n\n\n\n\nclass MedianEpsilon(QuantileEpsilon):\n\n \"\"\"\n\n Calculate epsilon as median of the distances from the last population.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n median_multiplier: float = 1,\n\n weighted: bool = True):\n\n super().__init__(initial_epsilon=initial_epsilon,\n\n alpha=0.5,\n\n quantile_multiplier=median_multiplier,\n\n weighted=weighted)\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 34, "score": 77086.63201508544 }, { "content": "import numpy as np\n\nimport pandas as pd\n\nimport json\n\nfrom abc import ABC, abstractmethod\n\nfrom typing import Callable, List\n\n\n\n\n\nclass Epsilon(ABC):\n\n \"\"\"\n\n Abstract epsilon base class.\n\n\n\n This class encapsulates a strategy for setting a new epsilon for\n\n each new population.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n \"\"\"\n\n Constructor.\n\n \"\"\"\n\n pass\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n \"\"\"\n\n This method is called by the ABCSMC framework before the first usage\n\n of the epsilon and can be used to calibrate it to the statistics of the\n\n samples.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to initialize the epsilon for.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n Returns on demand the distances for initializing the epsilon.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles sampled in the previous iteration.\n\n max_nr_populations: int\n\n The maximum number of populations.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n def configure_sampler(self, sampler):\n\n \"\"\"\n\n This is called by the ABCSMC class and gives the epsilon\n\n the opportunity to configure the sampler.\n\n For example, it might request the sampler to\n\n also return rejected particles in order to adapt the\n\n epsilon to the statistics of the sample.\n\n The method is called by the ABCSMC framework before the first\n\n use of the epsilon (at the beginning of ABCSMC.run()), after\n\n initialize().\n\n\n\n The default is to do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n sampler: Sampler\n\n The sampler used in ABCSMC.\n\n \"\"\"\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Update epsilon value to be used as acceptance criterion for\n\n generation t.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The generation index to update / set epsilon for. Counting is\n\n zero-based. So the first population has t=0.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n The distances that should be used to update epsilon, as returned\n\n by Population.get_weighted_distances(). These are usually the\n\n distances of samples accepted in population t-1. The distances may\n\n differ from those used for acceptance in population t-1, if the\n\n distance function for population t has been updated.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles.\n\n acceptance_rate: float\n\n The current generation's acceptance rate.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n @abstractmethod\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Get epsilon value for generation t.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to get the epsilon threshold for.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon for population t.\n\n \"\"\"\n\n\n\n def requires_calibration(self) -> bool:\n\n \"\"\"\n\n Whether the class requires an initial calibration, based on\n\n samples from the prior. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def is_adaptive(self) -> bool:\n\n \"\"\"\n\n Whether the class is dynamically updated after each generation,\n\n based on the last generation's available data. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def get_config(self):\n\n \"\"\"\n\n Return configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n config: dict\n\n Dictionary describing the distance function.\n\n \"\"\"\n\n return {\"name\": self.__class__.__name__}\n\n\n\n def to_json(self):\n\n \"\"\"\n\n Return JSON encoded configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n json_str: str\n\n JSON encoded string describing the distance function.\n\n The default implementation is to try to convert the dictionary\n\n returned my ``get_config``.\n\n \"\"\"\n\n return json.dumps(self.get_config())\n\n\n\n\n\nclass NoEpsilon(Epsilon):\n\n \"\"\"\n\n Implements a kind of null object as epsilon.\n\n\n\n This can be used as a dummy epsilon when the Acceptor integrates the\n\n acceptance threshold.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n super().__init__()\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n return np.nan\n", "file_path": "pyABC/0.10.14/epsilon/base.py", "rank": 35, "score": 65169.43159231241 }, { "content": "import numpy as np\n\nimport scipy as sp\n\nfrom scipy import optimize\n\nimport pandas as pd\n\nimport numbers\n\nfrom typing import Callable, List, Union\n\nimport logging\n\n\n\nfrom .base import Epsilon\n\nfrom ..distance import SCALE_LIN\n\nfrom ..storage import save_dict_to_json\n\n\n\nlogger = logging.getLogger(\"Epsilon\")\n\n\n\n\n\nclass TemperatureBase(Epsilon):\n\n \"\"\"\n\n A temperature scheme handles the decrease of the temperatures employed\n\n by a :class:`pyabc.acceptor.StochasticAcceptor` over time.\n\n\n\n This class is not functional on its own, its derivatives must be used.\n\n \"\"\"\n\n\n\n\n\nclass ListTemperature(TemperatureBase):\n\n \"\"\"\n\n Pass a list of temperature values to use successively.\n\n\n\n Parameters\n\n ----------\n\n values:\n\n The array of temperatures to use successively.\n\n For exact inference, finish with 1.\n\n \"\"\"\n\n\n\n def __init__(self, values: List[float]):\n\n super().__init__()\n\n self.values = values\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n return self.values[t]\n\n\n\n\n\nclass Temperature(TemperatureBase):\n\n \"\"\"\n\n This class implements a highly adaptive and configurable temperature\n\n scheme. Via the argument `schemes`, arbitrary temperature schemes can be\n\n passed to calculate the next generation's temperature, via `aggregate_fun`\n\n one can define how to combine multiple guesses, via `initial_temperature`\n\n the initial temperature can be set.\n\n\n\n Parameters\n\n ----------\n\n schemes:\n\n Temperature schemes returning proposed\n\n temperatures for the next time point, e.g.\n\n instances of :class:`pyabc.epsilon.TemperatureScheme`.\n\n aggregate_fun:\n\n The function to aggregate the schemes by, of the form\n\n ``Callable[List[float], float]``.\n\n Defaults to taking the minimum.\n\n initial_temperature:\n\n The initial temperature. If None provided, an AcceptanceRateScheme\n\n is used.\n\n enforce_exact_final_temperature:\n\n Whether to force the final temperature (if max_nr_populations < inf)\n\n to be 1.0, giving exact inference.\n\n log_file:\n\n A log file for storing data of the temperature that are currently not\n\n saved in the database. The data are saved in json format.\n\n\n\n Properties\n\n ----------\n\n max_nr_populations:\n\n The maximum number of iterations as passed to ABCSMC.\n\n May be inf, but not all schemes can handle that (and will complain).\n\n temperatures:\n\n Times as keys and temperatures as values.\n\n \"\"\"\n\n\n\n def __init__(\n\n self,\n\n schemes: Union[Callable, List[Callable]] = None,\n\n aggregate_fun: Callable[[List[float]], float] = None,\n\n initial_temperature: float = None,\n\n enforce_exact_final_temperature: bool = True,\n\n log_file: str = None):\n\n super().__init__()\n\n self.schemes = schemes\n\n\n\n if aggregate_fun is None:\n\n # use minimum over all proposed temperature values\n\n aggregate_fun = min\n\n self.aggregate_fun = aggregate_fun\n\n\n\n if initial_temperature is None:\n\n initial_temperature = AcceptanceRateScheme()\n\n self.initial_temperature = initial_temperature\n\n\n\n self.enforce_exact_final_temperature = enforce_exact_final_temperature\n\n self.log_file = log_file\n\n\n\n # to be filled later\n\n self.max_nr_populations = None\n\n self.temperatures = {}\n\n self.temperature_proposals = {}\n\n\n\n def requires_calibration(self) -> bool:\n\n return self.initial_temperature.requires_distances()\n\n\n\n def is_adaptive(self) -> bool:\n\n # this is a bit unstable as the schemes are initialized only later,\n\n # however is fine as long as compatible functions are used in\n\n # `initialize()`\n\n return (self.schemes is not None\n\n and any(s.requires_distances() for s in self.schemes))\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n self.max_nr_populations = max_nr_populations\n\n\n\n # set default schemes\n\n if self.schemes is None:\n\n # this combination proved rather stable\n\n acc_rate_scheme = AcceptanceRateScheme()\n\n decay_scheme = (\n\n ExpDecayFixedIterScheme() if np.isfinite(max_nr_populations)\n\n else ExpDecayFixedRatioScheme())\n\n self.schemes = [acc_rate_scheme, decay_scheme]\n\n\n\n # set initial temperature for time t\n\n self._update(t, get_weighted_distances, get_all_records,\n\n 1.0, acceptor_config)\n\n\n\n def configure_sampler(self, sampler):\n\n if isinstance(self.initial_temperature, TemperatureScheme):\n\n self.initial_temperature.configure_sampler(sampler)\n\n for scheme in self.schemes:\n\n scheme.configure_sampler(sampler)\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n # set temperature for time t\n\n self._update(t, get_weighted_distances,\n\n get_all_records, acceptance_rate,\n\n acceptor_config)\n\n\n\n def _update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config):\n\n \"\"\"\n\n Compute the temperature for time `t`.\n\n \"\"\"\n\n # scheme arguments\n\n kwargs = {\n\n 't': t,\n\n 'get_weighted_distances': get_weighted_distances,\n\n 'get_all_records': get_all_records,\n\n 'max_nr_populations': self.max_nr_populations,\n\n 'pdf_norm': acceptor_config['pdf_norm'],\n\n 'kernel_scale': acceptor_config['kernel_scale'],\n\n 'prev_temperature': self.temperatures.get(t-1, None),\n\n 'acceptance_rate': acceptance_rate,\n\n }\n\n\n\n if t >= self.max_nr_populations - 1 \\\n\n and self.enforce_exact_final_temperature:\n\n # t is last time\n\n temps = [1.0]\n\n elif not self.temperatures: # need an initial value\n\n if isinstance(self.initial_temperature, TemperatureScheme):\n\n # execute scheme\n\n temps = [self.initial_temperature(**kwargs)]\n\n elif isinstance(self.initial_temperature, numbers.Number):\n\n temps = [self.initial_temperature]\n\n else:\n\n raise ValueError(\n\n \"Initial temperature must be a float or a callable\")\n\n else:\n\n # evaluate schemes\n\n temps = []\n\n for scheme in self.schemes:\n\n temp = scheme(**kwargs)\n\n temps.append(temp)\n\n\n\n # compute next temperature based on proposals and fallback\n\n # should not be higher than before\n\n fallback = self.temperatures[t-1] \\\n\n if t-1 in self.temperatures else np.inf\n\n temperature = self.aggregate_fun(temps)\n\n # also a value lower than 1.0 does not make sense\n\n temperature = max(min(temperature, fallback), 1.0)\n\n\n\n if not np.isfinite(temperature):\n\n raise ValueError(\"Temperature must be finite.\")\n\n # record found value\n\n self.temperatures[t] = temperature\n\n\n\n # logging\n\n logger.debug(f\"Proposed temperatures for {t}: {temps}.\")\n\n self.temperature_proposals[t] = temps\n\n if self.log_file:\n\n save_dict_to_json(self.temperature_proposals, self.log_file)\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n return self.temperatures[t]\n\n\n\n\n\nclass TemperatureScheme:\n\n \"\"\"\n\n A TemperatureScheme suggests the next temperature value. It is used as\n\n one of potentially multiple schemes employed in the Temperature class.\n\n This class is abstract.\n\n \"\"\"\n\n\n\n def configure_sampler(self, sampler):\n\n \"\"\"\n\n Modify the sampler. As in, and redirected from,\n\n :func:`pyabc.epsilon.Temperature.configure_sampler`.\n\n \"\"\"\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n \"\"\"\n\n Suggest a temperature.\n\n\n\n Parameters\n\n ----------\n\n t:\n\n The time to compute for.\n\n get_weighted_distances:\n\n Callable to obtain the weights and kernel values to be used for\n\n the scheme.\n\n get_all_records:\n\n Callable returning a List[dict] of all recorded particles.\n\n max_nr_populations:\n\n The maximum number of populations that are supposed to be taken.\n\n pdf_norm:\n\n The normalization constant c that will be used in the acceptance\n\n step.\n\n kernel_scale:\n\n Scale on which the pdf values are (linear or logarithmic).\n\n prev_temperature:\n\n The temperature that was used last time (or None if not\n\n applicable).\n\n acceptance_rate:\n\n The recently obtained rate.\n\n \"\"\"\n\n pass\n\n\n\n def requires_distances(self) -> bool:\n\n \"\"\"\n\n Whether the scheme requires the last generation's accepted distances.\n\n Default: False\n\n \"\"\"\n\n return False\n\n\n\n\n\nclass AcceptanceRateScheme(TemperatureScheme):\n\n \"\"\"\n\n Try to keep the acceptance rate constant at a value of\n\n `target_rate`. Note that this scheme will fail to\n\n reduce the temperature sufficiently in later iterations, if the\n\n problem's inherent acceptance rate is lower, but it has been\n\n observed to give big feasible temperature leaps in early iterations.\n\n In particular, this scheme can be used to propose an initial temperature.\n\n\n\n Parameters\n\n ----------\n\n target_rate: float, optional\n\n The target acceptance rate to match.\n\n min_rate: float, optional\n\n The minimum rate below which not to apply the acceptance step scheme\n\n any more. Setting this to a value of e.g. 0.05 can make sense\n\n 1) because it may be unlikely that the acceptance rate scheme will\n\n propose a useful temperature at such low acceptance levels, and\n\n 2) to avoid uneccessary computations.\n\n \"\"\"\n\n\n\n def __init__(self, target_rate: float = 0.3, min_rate: float = None):\n\n self.target_rate = target_rate\n\n self.min_rate = min_rate\n\n\n\n def configure_sampler(self, sampler):\n\n sampler.sample_factory.record_rejected = True\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # check minimum rate\n\n if self.min_rate is not None and acceptance_rate < self.min_rate:\n\n return np.inf\n\n\n\n # execute function (expensive if in calibration)\n\n records = get_all_records()\n\n # convert to dataframe for easier extraction\n\n records = pd.DataFrame(records)\n\n\n\n # previous and current transition densities\n\n t_pd_prev = np.array(records['transition_pd_prev'], dtype=float)\n\n t_pd = np.array(records['transition_pd'], dtype=float)\n\n # acceptance kernel likelihoods\n\n pds = np.array(records['distance'], dtype=float)\n\n\n\n # compute importance weights\n\n weights = t_pd / t_pd_prev\n\n # len would suffice, but maybe rather not rely on things to be normed\n\n weights /= sum(weights)\n\n\n\n temperature = match_acceptance_rate(\n\n weights, pds, pdf_norm, kernel_scale, self.target_rate)\n\n\n\n return temperature\n\n\n\n\n\ndef match_acceptance_rate(\n\n weights, pds, pdf_norm, kernel_scale, target_rate):\n\n \"\"\"\n\n For large temperature, changes become effective on an exponential scale,\n\n thus we optimize the logarithm of the inverse temperature beta.\n\n\n\n For a temperature close to 1, subtler changes are neccesary, however here\n\n the logarhtm is nearly linear anyway.\n\n \"\"\"\n\n # objective function which we wish to find a root for\n\n def obj(b):\n\n beta = np.exp(b)\n\n\n\n # compute rescaled posterior densities\n\n if kernel_scale == SCALE_LIN:\n\n acc_probs = (pds / pdf_norm) ** beta\n\n else: # kernel_scale == SCALE_LOG\n\n acc_probs = np.exp((pds - pdf_norm) * beta)\n\n\n\n # to acceptance probabilities to be sure\n\n acc_probs = np.minimum(acc_probs, 1.0)\n\n\n\n # objective function\n\n val = np.sum(weights * acc_probs) - target_rate\n\n return val\n\n\n\n # TODO the lower boundary min_b is somewhat arbitrary\n\n min_b = -100\n\n if obj(0) > 0:\n\n # function is monotonically decreasing\n\n # smallest possible value already > 0\n\n b_opt = 0\n\n elif obj(min_b) < 0:\n\n # it is obj(-inf) > 0 always\n\n logger.info(\"AcceptanceRateScheme: Numerics limit temperature.\")\n\n b_opt = min_b\n\n else:\n\n # perform binary search\n\n b_opt = optimize.bisect(obj, min_b, 0, maxiter=100000)\n\n\n\n beta_opt = np.exp(b_opt)\n\n\n\n temperature = 1. / beta_opt\n\n return temperature\n\n\n\n\n\nclass ExpDecayFixedIterScheme(TemperatureScheme):\n\n \"\"\"\n\n The next temperature is set as\n\n\n\n .. math::\n\n T_j = T_{max}^{(n-j)/n}\n\n\n\n where n denotes the number of populations, and j=1,...,n the iteration.\n\n This translates to\n\n\n\n .. math::\n\n T_j = T_{j-1}^{(n-j)/(n-(j-1))}.\n\n\n\n This ensures that a temperature of 1.0 is reached after exactly the\n\n remaining number of steps.\n\n\n\n So, in both cases the sequence of temperatures follows an exponential\n\n decay, also known as a geometric progression, or a linear progression\n\n in log-space.\n\n\n\n Note that the formula is applied anew in each iteration.\n\n This is advantageous if also other schemes are used s.t. T_{j-1}\n\n is smaller than by the above.\n\n\n\n Parameters\n\n ----------\n\n\n\n alpha: float\n\n Factor by which to reduce the temperature, if `max_nr_populations`\n\n is infinite.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n pass\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a finite number of iterations\n\n if max_nr_populations == np.inf:\n\n raise ValueError(\n\n \"The ExpDecayFixedIterScheme requires a finite \"\n\n \"`max_nr_populations`.\")\n\n\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n\n\n # how many steps left?\n\n t_to_go = max_nr_populations - t\n\n\n\n # compute next temperature according to exponential decay\n\n temperature = temp_base ** ((t_to_go - 1) / t_to_go)\n\n\n\n return temperature\n\n\n\n\n\nclass ExpDecayFixedRatioScheme(TemperatureScheme):\n\n \"\"\"\n\n The next temperature is chosen as\n\n\n\n .. math::\n\n T_j = \\\\alpha \\\\cdot T_{j-1}.\n\n\n\n Like the :class:`pyabc.epsilon.ExpDecayFixedIterScheme`,\n\n this yields a geometric progression, however with a fixed ratio,\n\n irrespective of the number of iterations. If a finite number of\n\n iterations is specified in ABCSMC, there is no influence on the final\n\n jump to a temperature of 1.0.\n\n\n\n This is quite similar to the :class:`pyabc.epsilon.DalyScheme`, although\n\n simpler in implementation. The alpha value here corresponds to a value of\n\n 1 - alpha there.\n\n\n\n Parameters\n\n ----------\n\n alpha: float, optional\n\n The ratio of subsequent temperatures.\n\n min_rate: float, optional\n\n A minimum acceptance rate. If this rate has been violated in the\n\n previous iteration, the alpha value is increased.\n\n max_rate: float, optional\n\n Maximum rate to not be exceeded, otherwise the alpha value is\n\n decreased.\n\n \"\"\"\n\n def __init__(self, alpha: float = 0.5,\n\n min_rate: float = 1e-4, max_rate: float = 0.5):\n\n self.alpha = alpha\n\n self.min_rate = min_rate\n\n self.max_rate = max_rate\n\n self.alphas = {}\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # previous alpha\n\n alpha = self.alphas.get(t-1, self.alpha)\n\n\n\n # check if acceptance rate criterion violated\n\n if acceptance_rate > self.max_rate and t > 1:\n\n logger.debug(\"ExpDecayFixedRatioScheme: \"\n\n \"Reacting to high acceptance rate.\")\n\n alpha = max(alpha / 2, alpha - (1 - alpha) * 2)\n\n if acceptance_rate < self.min_rate:\n\n logger.debug(\"ExpDecayFixedRatioScheme: \"\n\n \"Reacting to low acceptance rate.\")\n\n # increase alpha\n\n alpha = alpha + (1 - alpha) / 2\n\n # record\n\n self.alphas[t] = alpha\n\n\n\n # reduce temperature\n\n temperature = self.alphas[t] * prev_temperature\n\n\n\n return temperature\n\n\n\n\n\nclass PolynomialDecayFixedIterScheme(TemperatureScheme):\n\n \"\"\"\n\n Compute next temperature as pre-last entry in\n\n\n\n >>> np.linspace(1, (temp_base)**(1 / temp_decay_exponent),\n\n >>> t_to_go + 1) ** temp_decay_exponent)\n\n\n\n Requires finite `max_nr_populations`.\n\n\n\n Note that this is similar to the\n\n :class:`pyabc.epsilon.ExpDecayFixedIterScheme`, which is\n\n indeed the limit for `exponent -> infinity`. For smaller\n\n exponent, the sequence makes larger steps for low temperatures. This\n\n can be useful in cases, where lower temperatures (which are usually\n\n more expensive) can be traversed in few larger steps, however also\n\n the opposite may be true, i.e. that more steps at low temperatures\n\n are advantageous.\n\n\n\n Parameters\n\n ----------\n\n exponent: float, optional\n\n The exponent to use in the scheme.\n\n \"\"\"\n\n\n\n def __init__(self, exponent: float = 3):\n\n self.exponent = exponent\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n\n\n # check if we can compute a decay step\n\n if max_nr_populations == np.inf:\n\n raise ValueError(\"Can only perform PolynomialDecayScheme step \"\n\n \"with a finite max_nr_populations.\")\n\n\n\n # how many steps left?\n\n t_to_go = max_nr_populations - t\n\n\n\n # compute sequence\n\n temps = np.linspace(1, (temp_base)**(1 / self.exponent),\n\n t_to_go+1) ** self.exponent\n\n\n\n logger.debug(f\"Temperatures proposed by polynomial decay method: \"\n\n f\"{temps}.\")\n\n\n\n # pre-last step is the next step\n\n temperature = temps[-2]\n\n return temperature\n\n\n\n\n\nclass DalyScheme(TemperatureScheme):\n\n \"\"\"\n\n This scheme is loosely based on [#daly2017]_, however note that it does\n\n not try to replicate it entirely. In particular, the implementation\n\n of pyABC does not allow the sampling to be stopped when encountering\n\n too low acceptance rates, such that this can only be done ex-posteriori\n\n here.\n\n\n\n Parameters\n\n ----------\n\n alpha: float, optional\n\n The ratio by which to decrease the temperature value. More\n\n specifically, the next temperature is given as\n\n `(1-alpha) * temperature`.\n\n min_rate: float, optional\n\n A minimum acceptance rate. If this rate has been violated in the\n\n previous iteration, the alpha value is decreased.\n\n\n\n\n\n .. [#daly2017] Daly Aidan C., Cooper Jonathan, Gavaghan David J.,\n\n and Holmes Chris. \"Comparing two sequential Monte Carlo samplers\n\n for exact and approximate Bayesian inference on biological\n\n models\". Journal of The Royal Society Interface, 2017.\n\n \"\"\"\n\n\n\n def __init__(self, alpha: float = 0.5, min_rate: float = 1e-4):\n\n self.alpha = alpha\n\n self.min_rate = min_rate\n\n self.k = {}\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n\n\n # addressing the std, not the var\n\n eps_base = np.sqrt(temp_base)\n\n\n\n if not self.k:\n\n # initial iteration\n\n self.k[t - 1] = eps_base\n\n\n\n k_base = self.k[t - 1]\n\n\n\n if acceptance_rate < self.min_rate:\n\n logger.debug(\"DalyScheme: Reacting to low acceptance rate.\")\n\n # reduce reduction\n\n k_base = self.alpha * k_base\n\n\n\n self.k[t] = min(k_base, self.alpha * eps_base)\n\n eps = eps_base - self.k[t]\n\n temperature = eps**2\n\n\n\n return temperature\n\n\n\n\n\nclass FrielPettittScheme(TemperatureScheme):\n\n \"\"\"\n\n Basically takes linear steps in log-space. See [#vyshemirsky2008]_.\n\n\n\n .. [#vyshemirsky2008] Vyshemirsky, Vladislav, and Mark A. Girolami.\n\n \"Bayesian ranking of biochemical system models.\"\n\n Bioinformatics 24.6 (2007): 833-839.\n\n \"\"\"\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # check if we can compute a decay step\n\n if max_nr_populations == np.inf:\n\n raise ValueError(\"Can only perform FrielPettittScheme step with a \"\n\n \"finite max_nr_populations.\")\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n beta_base = 1. / temp_base\n\n\n\n # time to go\n\n t_to_go = max_nr_populations - t\n\n\n\n beta = beta_base + ((1. - beta_base) * 1 / t_to_go) ** 2\n\n\n\n temperature = 1. / beta\n\n return temperature\n\n\n\n\n\nclass EssScheme(TemperatureScheme):\n\n \"\"\"\n\n Try to keep the effective sample size (ESS) constant.\n\n\n\n Parameters\n\n ----------\n\n target_relative_ess: float\n\n Targe relative effective sample size.\n\n \"\"\"\n\n\n\n def __init__(self, target_relative_ess: float = 0.8):\n\n self.target_relative_ess = target_relative_ess\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # execute function (expensive if in calibration)\n\n df = get_weighted_distances()\n\n\n\n weights = np.array(df['w'], dtype=float)\n\n pdfs = np.array(df['distance'], dtype=float)\n\n\n\n # compute rescaled posterior densities\n\n if kernel_scale == SCALE_LIN:\n\n values = pdfs / pdf_norm\n\n else: # kernel_scale == SCALE_LOG\n\n values = np.exp(pdfs - pdf_norm)\n\n\n\n # to probability mass function (i.e. normalize)\n\n weights /= np.sum(weights)\n\n\n\n target_ess = len(weights) * self.target_relative_ess\n\n\n\n if prev_temperature is None:\n\n beta_base = 0.0\n\n else:\n\n beta_base = 1. / prev_temperature\n\n\n\n # objective to minimize\n\n def obj(beta):\n\n return (_ess(values, weights, beta) - target_ess)**2\n\n\n\n bounds = sp.optimize.Bounds(lb=np.array([beta_base]),\n\n ub=np.array([1.]))\n\n # TODO make more efficient by providing gradients\n\n ret = sp.optimize.minimize(\n\n obj, x0=np.array([0.5 * (1 + beta_base)]),\n\n bounds=bounds)\n\n beta = ret.x\n\n\n\n temperature = 1. / beta\n\n return temperature\n\n\n\n def requires_distances(self) -> bool:\n\n return True\n\n\n\n\n\ndef _ess(pdfs, weights, beta):\n\n \"\"\"\n\n Effective sample size (ESS) of importance samples.\n\n \"\"\"\n\n num = np.sum(weights * pdfs**beta)**2\n\n den = np.sum((weights * pdfs**beta)**2)\n\n return num / den\n", "file_path": "pyABC/0.10.14/epsilon/temperature.py", "rank": 36, "score": 65169.43159231241 }, { "content": "import numpy as np\n\nimport pandas as pd\n\nimport json\n\nfrom abc import ABC, abstractmethod\n\nfrom typing import Callable, List\n\n\n\n\n\nclass Epsilon(ABC):\n\n \"\"\"\n\n Abstract epsilon base class.\n\n\n\n This class encapsulates a strategy for setting a new epsilon for\n\n each new population.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n \"\"\"\n\n Constructor.\n\n \"\"\"\n\n pass\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n \"\"\"\n\n This method is called by the ABCSMC framework before the first usage\n\n of the epsilon and can be used to calibrate it to the statistics of the\n\n samples.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to initialize the epsilon for.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n Returns on demand the distances for initializing the epsilon.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles sampled in the previous iteration.\n\n max_nr_populations: int\n\n The maximum number of populations.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n def configure_sampler(self, sampler):\n\n \"\"\"\n\n This is called by the ABCSMC class and gives the epsilon\n\n the opportunity to configure the sampler.\n\n For example, it might request the sampler to\n\n also return rejected particles in order to adapt the\n\n epsilon to the statistics of the sample.\n\n The method is called by the ABCSMC framework before the first\n\n use of the epsilon (at the beginning of ABCSMC.run()), after\n\n initialize().\n\n\n\n The default is to do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n sampler: Sampler\n\n The sampler used in ABCSMC.\n\n \"\"\"\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Update epsilon value to be used as acceptance criterion for\n\n generation t.\n\n\n\n Default: Do nothing.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The generation index to update / set epsilon for. Counting is\n\n zero-based. So the first population has t=0.\n\n get_weighted_distances: Callable[[], pd.DataFrame]\n\n The distances that should be used to update epsilon, as returned\n\n by Population.get_weighted_distances(). These are usually the\n\n distances of samples accepted in population t-1. The distances may\n\n differ from those used for acceptance in population t-1, if the\n\n distance function for population t has been updated.\n\n get_all_records: Callable[[], List[dict]]\n\n Returns on demand a list of information obtained from all\n\n particles.\n\n acceptance_rate: float\n\n The current generation's acceptance rate.\n\n acceptor_config: dict\n\n An object provided by the Acceptor class.\n\n \"\"\"\n\n pass\n\n\n\n @abstractmethod\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Get epsilon value for generation t.\n\n\n\n Parameters\n\n ----------\n\n\n\n t: int\n\n The time point to get the epsilon threshold for.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon for population t.\n\n \"\"\"\n\n\n\n def requires_calibration(self) -> bool:\n\n \"\"\"\n\n Whether the class requires an initial calibration, based on\n\n samples from the prior. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def is_adaptive(self) -> bool:\n\n \"\"\"\n\n Whether the class is dynamically updated after each generation,\n\n based on the last generation's available data. Default: False.\n\n \"\"\"\n\n return False\n\n\n\n def get_config(self):\n\n \"\"\"\n\n Return configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n config: dict\n\n Dictionary describing the distance function.\n\n \"\"\"\n\n return {\"name\": self.__class__.__name__}\n\n\n\n def to_json(self):\n\n \"\"\"\n\n Return JSON encoded configuration of the distance function.\n\n\n\n Returns\n\n -------\n\n\n\n json_str: str\n\n JSON encoded string describing the distance function.\n\n The default implementation is to try to convert the dictionary\n\n returned my ``get_config``.\n\n \"\"\"\n\n return json.dumps(self.get_config())\n\n\n\n\n\nclass NoEpsilon(Epsilon):\n\n \"\"\"\n\n Implements a kind of null object as epsilon.\n\n\n\n This can be used as a dummy epsilon when the Acceptor integrates the\n\n acceptance threshold.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n super().__init__()\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n return np.nan\n", "file_path": "pyABC/Modified/epsilon/base.py", "rank": 37, "score": 64082.56737505892 }, { "content": "import numpy as np\n\nimport scipy as sp\n\nfrom scipy import optimize\n\nimport pandas as pd\n\nimport numbers\n\nfrom typing import Callable, List, Union\n\nimport logging\n\n\n\nfrom .base import Epsilon\n\nfrom ..distance import SCALE_LIN\n\nfrom ..storage import save_dict_to_json\n\n\n\nlogger = logging.getLogger(\"Epsilon\")\n\n\n\n\n\nclass TemperatureBase(Epsilon):\n\n \"\"\"\n\n A temperature scheme handles the decrease of the temperatures employed\n\n by a :class:`pyabc.acceptor.StochasticAcceptor` over time.\n\n\n\n This class is not functional on its own, its derivatives must be used.\n\n \"\"\"\n\n\n\n\n\nclass ListTemperature(TemperatureBase):\n\n \"\"\"\n\n Pass a list of temperature values to use successively.\n\n\n\n Parameters\n\n ----------\n\n values:\n\n The array of temperatures to use successively.\n\n For exact inference, finish with 1.\n\n \"\"\"\n\n\n\n def __init__(self, values: List[float]):\n\n super().__init__()\n\n self.values = values\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n return self.values[t]\n\n\n\n\n\nclass Temperature(TemperatureBase):\n\n \"\"\"\n\n This class implements a highly adaptive and configurable temperature\n\n scheme. Via the argument `schemes`, arbitrary temperature schemes can be\n\n passed to calculate the next generation's temperature, via `aggregate_fun`\n\n one can define how to combine multiple guesses, via `initial_temperature`\n\n the initial temperature can be set.\n\n\n\n Parameters\n\n ----------\n\n schemes:\n\n Temperature schemes returning proposed\n\n temperatures for the next time point, e.g.\n\n instances of :class:`pyabc.epsilon.TemperatureScheme`.\n\n aggregate_fun:\n\n The function to aggregate the schemes by, of the form\n\n ``Callable[List[float], float]``.\n\n Defaults to taking the minimum.\n\n initial_temperature:\n\n The initial temperature. If None provided, an AcceptanceRateScheme\n\n is used.\n\n enforce_exact_final_temperature:\n\n Whether to force the final temperature (if max_nr_populations < inf)\n\n to be 1.0, giving exact inference.\n\n log_file:\n\n A log file for storing data of the temperature that are currently not\n\n saved in the database. The data are saved in json format.\n\n\n\n Properties\n\n ----------\n\n max_nr_populations:\n\n The maximum number of iterations as passed to ABCSMC.\n\n May be inf, but not all schemes can handle that (and will complain).\n\n temperatures:\n\n Times as keys and temperatures as values.\n\n \"\"\"\n\n\n\n def __init__(\n\n self,\n\n schemes: Union[Callable, List[Callable]] = None,\n\n aggregate_fun: Callable[[List[float]], float] = None,\n\n initial_temperature: float = None,\n\n enforce_exact_final_temperature: bool = True,\n\n log_file: str = None):\n\n super().__init__()\n\n self.schemes = schemes\n\n\n\n if aggregate_fun is None:\n\n # use minimum over all proposed temperature values\n\n aggregate_fun = min\n\n self.aggregate_fun = aggregate_fun\n\n\n\n if initial_temperature is None:\n\n initial_temperature = AcceptanceRateScheme()\n\n self.initial_temperature = initial_temperature\n\n\n\n self.enforce_exact_final_temperature = enforce_exact_final_temperature\n\n self.log_file = log_file\n\n\n\n # to be filled later\n\n self.max_nr_populations = None\n\n self.temperatures = {}\n\n self.temperature_proposals = {}\n\n\n\n def requires_calibration(self) -> bool:\n\n return self.initial_temperature.requires_distances()\n\n\n\n def is_adaptive(self) -> bool:\n\n # this is a bit unstable as the schemes are initialized only later,\n\n # however is fine as long as compatible functions are used in\n\n # `initialize()`\n\n return (self.schemes is not None\n\n and any(s.requires_distances() for s in self.schemes))\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n self.max_nr_populations = max_nr_populations\n\n\n\n # set default schemes\n\n if self.schemes is None:\n\n # this combination proved rather stable\n\n acc_rate_scheme = AcceptanceRateScheme()\n\n decay_scheme = (\n\n ExpDecayFixedIterScheme() if np.isfinite(max_nr_populations)\n\n else ExpDecayFixedRatioScheme())\n\n self.schemes = [acc_rate_scheme, decay_scheme]\n\n\n\n # set initial temperature for time t\n\n self._update(t, get_weighted_distances, get_all_records,\n\n 1.0, acceptor_config)\n\n\n\n def configure_sampler(self, sampler):\n\n if isinstance(self.initial_temperature, TemperatureScheme):\n\n self.initial_temperature.configure_sampler(sampler)\n\n for scheme in self.schemes:\n\n scheme.configure_sampler(sampler)\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n # set temperature for time t\n\n self._update(t, get_weighted_distances,\n\n get_all_records, acceptance_rate,\n\n acceptor_config)\n\n\n\n def _update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config):\n\n \"\"\"\n\n Compute the temperature for time `t`.\n\n \"\"\"\n\n # scheme arguments\n\n kwargs = {\n\n 't': t,\n\n 'get_weighted_distances': get_weighted_distances,\n\n 'get_all_records': get_all_records,\n\n 'max_nr_populations': self.max_nr_populations,\n\n 'pdf_norm': acceptor_config['pdf_norm'],\n\n 'kernel_scale': acceptor_config['kernel_scale'],\n\n 'prev_temperature': self.temperatures.get(t-1, None),\n\n 'acceptance_rate': acceptance_rate,\n\n }\n\n\n\n if t >= self.max_nr_populations - 1 \\\n\n and self.enforce_exact_final_temperature:\n\n # t is last time\n\n temps = [1.0]\n\n elif not self.temperatures: # need an initial value\n\n if isinstance(self.initial_temperature, TemperatureScheme):\n\n # execute scheme\n\n temps = [self.initial_temperature(**kwargs)]\n\n elif isinstance(self.initial_temperature, numbers.Number):\n\n temps = [self.initial_temperature]\n\n else:\n\n raise ValueError(\n\n \"Initial temperature must be a float or a callable\")\n\n else:\n\n # evaluate schemes\n\n temps = []\n\n for scheme in self.schemes:\n\n temp = scheme(**kwargs)\n\n temps.append(temp)\n\n\n\n # compute next temperature based on proposals and fallback\n\n # should not be higher than before\n\n fallback = self.temperatures[t-1] \\\n\n if t-1 in self.temperatures else np.inf\n\n temperature = self.aggregate_fun(temps)\n\n # also a value lower than 1.0 does not make sense\n\n temperature = max(min(temperature, fallback), 1.0)\n\n\n\n if not np.isfinite(temperature):\n\n raise ValueError(\"Temperature must be finite.\")\n\n # record found value\n\n self.temperatures[t] = temperature\n\n\n\n # logging\n\n logger.debug(f\"Proposed temperatures for {t}: {temps}.\")\n\n self.temperature_proposals[t] = temps\n\n if self.log_file:\n\n save_dict_to_json(self.temperature_proposals, self.log_file)\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n return self.temperatures[t]\n\n\n\n\n\nclass TemperatureScheme:\n\n \"\"\"\n\n A TemperatureScheme suggests the next temperature value. It is used as\n\n one of potentially multiple schemes employed in the Temperature class.\n\n This class is abstract.\n\n \"\"\"\n\n\n\n def configure_sampler(self, sampler):\n\n \"\"\"\n\n Modify the sampler. As in, and redirected from,\n\n :func:`pyabc.epsilon.Temperature.configure_sampler`.\n\n \"\"\"\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n \"\"\"\n\n Suggest a temperature.\n\n\n\n Parameters\n\n ----------\n\n t:\n\n The time to compute for.\n\n get_weighted_distances:\n\n Callable to obtain the weights and kernel values to be used for\n\n the scheme.\n\n get_all_records:\n\n Callable returning a List[dict] of all recorded particles.\n\n max_nr_populations:\n\n The maximum number of populations that are supposed to be taken.\n\n pdf_norm:\n\n The normalization constant c that will be used in the acceptance\n\n step.\n\n kernel_scale:\n\n Scale on which the pdf values are (linear or logarithmic).\n\n prev_temperature:\n\n The temperature that was used last time (or None if not\n\n applicable).\n\n acceptance_rate:\n\n The recently obtained rate.\n\n \"\"\"\n\n pass\n\n\n\n def requires_distances(self) -> bool:\n\n \"\"\"\n\n Whether the scheme requires the last generation's accepted distances.\n\n Default: False\n\n \"\"\"\n\n return False\n\n\n\n\n\nclass AcceptanceRateScheme(TemperatureScheme):\n\n \"\"\"\n\n Try to keep the acceptance rate constant at a value of\n\n `target_rate`. Note that this scheme will fail to\n\n reduce the temperature sufficiently in later iterations, if the\n\n problem's inherent acceptance rate is lower, but it has been\n\n observed to give big feasible temperature leaps in early iterations.\n\n In particular, this scheme can be used to propose an initial temperature.\n\n\n\n Parameters\n\n ----------\n\n target_rate: float, optional\n\n The target acceptance rate to match.\n\n min_rate: float, optional\n\n The minimum rate below which not to apply the acceptance step scheme\n\n any more. Setting this to a value of e.g. 0.05 can make sense\n\n 1) because it may be unlikely that the acceptance rate scheme will\n\n propose a useful temperature at such low acceptance levels, and\n\n 2) to avoid uneccessary computations.\n\n \"\"\"\n\n\n\n def __init__(self, target_rate: float = 0.3, min_rate: float = None):\n\n self.target_rate = target_rate\n\n self.min_rate = min_rate\n\n\n\n def configure_sampler(self, sampler):\n\n sampler.sample_factory.record_rejected = True\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # check minimum rate\n\n if self.min_rate is not None and acceptance_rate < self.min_rate:\n\n return np.inf\n\n\n\n # execute function (expensive if in calibration)\n\n records = get_all_records()\n\n # convert to dataframe for easier extraction\n\n records = pd.DataFrame(records)\n\n\n\n # previous and current transition densities\n\n t_pd_prev = np.array(records['transition_pd_prev'], dtype=float)\n\n t_pd = np.array(records['transition_pd'], dtype=float)\n\n # acceptance kernel likelihoods\n\n pds = np.array(records['distance'], dtype=float)\n\n\n\n # compute importance weights\n\n weights = t_pd / t_pd_prev\n\n # len would suffice, but maybe rather not rely on things to be normed\n\n weights /= sum(weights)\n\n\n\n temperature = match_acceptance_rate(\n\n weights, pds, pdf_norm, kernel_scale, self.target_rate)\n\n\n\n return temperature\n\n\n\n\n\ndef match_acceptance_rate(\n\n weights, pds, pdf_norm, kernel_scale, target_rate):\n\n \"\"\"\n\n For large temperature, changes become effective on an exponential scale,\n\n thus we optimize the logarithm of the inverse temperature beta.\n\n\n\n For a temperature close to 1, subtler changes are neccesary, however here\n\n the logarhtm is nearly linear anyway.\n\n \"\"\"\n\n # objective function which we wish to find a root for\n\n def obj(b):\n\n beta = np.exp(b)\n\n\n\n # compute rescaled posterior densities\n\n if kernel_scale == SCALE_LIN:\n\n acc_probs = (pds / pdf_norm) ** beta\n\n else: # kernel_scale == SCALE_LOG\n\n acc_probs = np.exp((pds - pdf_norm) * beta)\n\n\n\n # to acceptance probabilities to be sure\n\n acc_probs = np.minimum(acc_probs, 1.0)\n\n\n\n # objective function\n\n val = np.sum(weights * acc_probs) - target_rate\n\n return val\n\n\n\n # TODO the lower boundary min_b is somewhat arbitrary\n\n min_b = -100\n\n if obj(0) > 0:\n\n # function is monotonically decreasing\n\n # smallest possible value already > 0\n\n b_opt = 0\n\n elif obj(min_b) < 0:\n\n # it is obj(-inf) > 0 always\n\n logger.info(\"AcceptanceRateScheme: Numerics limit temperature.\")\n\n b_opt = min_b\n\n else:\n\n # perform binary search\n\n b_opt = optimize.bisect(obj, min_b, 0, maxiter=100000)\n\n\n\n beta_opt = np.exp(b_opt)\n\n\n\n temperature = 1. / beta_opt\n\n return temperature\n\n\n\n\n\nclass ExpDecayFixedIterScheme(TemperatureScheme):\n\n \"\"\"\n\n The next temperature is set as\n\n\n\n .. math::\n\n T_j = T_{max}^{(n-j)/n}\n\n\n\n where n denotes the number of populations, and j=1,...,n the iteration.\n\n This translates to\n\n\n\n .. math::\n\n T_j = T_{j-1}^{(n-j)/(n-(j-1))}.\n\n\n\n This ensures that a temperature of 1.0 is reached after exactly the\n\n remaining number of steps.\n\n\n\n So, in both cases the sequence of temperatures follows an exponential\n\n decay, also known as a geometric progression, or a linear progression\n\n in log-space.\n\n\n\n Note that the formula is applied anew in each iteration.\n\n This is advantageous if also other schemes are used s.t. T_{j-1}\n\n is smaller than by the above.\n\n\n\n Parameters\n\n ----------\n\n\n\n alpha: float\n\n Factor by which to reduce the temperature, if `max_nr_populations`\n\n is infinite.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n pass\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a finite number of iterations\n\n if max_nr_populations == np.inf:\n\n raise ValueError(\n\n \"The ExpDecayFixedIterScheme requires a finite \"\n\n \"`max_nr_populations`.\")\n\n\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n\n\n # how many steps left?\n\n t_to_go = max_nr_populations - t\n\n\n\n # compute next temperature according to exponential decay\n\n temperature = temp_base ** ((t_to_go - 1) / t_to_go)\n\n\n\n return temperature\n\n\n\n\n\nclass ExpDecayFixedRatioScheme(TemperatureScheme):\n\n \"\"\"\n\n The next temperature is chosen as\n\n\n\n .. math::\n\n T_j = \\\\alpha \\\\cdot T_{j-1}.\n\n\n\n Like the :class:`pyabc.epsilon.ExpDecayFixedIterScheme`,\n\n this yields a geometric progression, however with a fixed ratio,\n\n irrespective of the number of iterations. If a finite number of\n\n iterations is specified in ABCSMC, there is no influence on the final\n\n jump to a temperature of 1.0.\n\n\n\n This is quite similar to the :class:`pyabc.epsilon.DalyScheme`, although\n\n simpler in implementation. The alpha value here corresponds to a value of\n\n 1 - alpha there.\n\n\n\n Parameters\n\n ----------\n\n alpha: float, optional\n\n The ratio of subsequent temperatures.\n\n min_rate: float, optional\n\n A minimum acceptance rate. If this rate has been violated in the\n\n previous iteration, the alpha value is increased.\n\n max_rate: float, optional\n\n Maximum rate to not be exceeded, otherwise the alpha value is\n\n decreased.\n\n \"\"\"\n\n def __init__(self, alpha: float = 0.5,\n\n min_rate: float = 1e-4, max_rate: float = 0.5):\n\n self.alpha = alpha\n\n self.min_rate = min_rate\n\n self.max_rate = max_rate\n\n self.alphas = {}\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # previous alpha\n\n alpha = self.alphas.get(t-1, self.alpha)\n\n\n\n # check if acceptance rate criterion violated\n\n if acceptance_rate > self.max_rate and t > 1:\n\n logger.debug(\"ExpDecayFixedRatioScheme: \"\n\n \"Reacting to high acceptance rate.\")\n\n alpha = max(alpha / 2, alpha - (1 - alpha) * 2)\n\n if acceptance_rate < self.min_rate:\n\n logger.debug(\"ExpDecayFixedRatioScheme: \"\n\n \"Reacting to low acceptance rate.\")\n\n # increase alpha\n\n alpha = alpha + (1 - alpha) / 2\n\n # record\n\n self.alphas[t] = alpha\n\n\n\n # reduce temperature\n\n temperature = self.alphas[t] * prev_temperature\n\n\n\n return temperature\n\n\n\n\n\nclass PolynomialDecayFixedIterScheme(TemperatureScheme):\n\n \"\"\"\n\n Compute next temperature as pre-last entry in\n\n\n\n >>> np.linspace(1, (temp_base)**(1 / temp_decay_exponent),\n\n >>> t_to_go + 1) ** temp_decay_exponent)\n\n\n\n Requires finite `max_nr_populations`.\n\n\n\n Note that this is similar to the\n\n :class:`pyabc.epsilon.ExpDecayFixedIterScheme`, which is\n\n indeed the limit for `exponent -> infinity`. For smaller\n\n exponent, the sequence makes larger steps for low temperatures. This\n\n can be useful in cases, where lower temperatures (which are usually\n\n more expensive) can be traversed in few larger steps, however also\n\n the opposite may be true, i.e. that more steps at low temperatures\n\n are advantageous.\n\n\n\n Parameters\n\n ----------\n\n exponent: float, optional\n\n The exponent to use in the scheme.\n\n \"\"\"\n\n\n\n def __init__(self, exponent: float = 3):\n\n self.exponent = exponent\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n\n\n # check if we can compute a decay step\n\n if max_nr_populations == np.inf:\n\n raise ValueError(\"Can only perform PolynomialDecayScheme step \"\n\n \"with a finite max_nr_populations.\")\n\n\n\n # how many steps left?\n\n t_to_go = max_nr_populations - t\n\n\n\n # compute sequence\n\n temps = np.linspace(1, (temp_base)**(1 / self.exponent),\n\n t_to_go+1) ** self.exponent\n\n\n\n logger.debug(f\"Temperatures proposed by polynomial decay method: \"\n\n f\"{temps}.\")\n\n\n\n # pre-last step is the next step\n\n temperature = temps[-2]\n\n return temperature\n\n\n\n\n\nclass DalyScheme(TemperatureScheme):\n\n \"\"\"\n\n This scheme is loosely based on [#daly2017]_, however note that it does\n\n not try to replicate it entirely. In particular, the implementation\n\n of pyABC does not allow the sampling to be stopped when encountering\n\n too low acceptance rates, such that this can only be done ex-posteriori\n\n here.\n\n\n\n Parameters\n\n ----------\n\n alpha: float, optional\n\n The ratio by which to decrease the temperature value. More\n\n specifically, the next temperature is given as\n\n `(1-alpha) * temperature`.\n\n min_rate: float, optional\n\n A minimum acceptance rate. If this rate has been violated in the\n\n previous iteration, the alpha value is decreased.\n\n\n\n\n\n .. [#daly2017] Daly Aidan C., Cooper Jonathan, Gavaghan David J.,\n\n and Holmes Chris. \"Comparing two sequential Monte Carlo samplers\n\n for exact and approximate Bayesian inference on biological\n\n models\". Journal of The Royal Society Interface, 2017.\n\n \"\"\"\n\n\n\n def __init__(self, alpha: float = 0.5, min_rate: float = 1e-4):\n\n self.alpha = alpha\n\n self.min_rate = min_rate\n\n self.k = {}\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n\n\n # addressing the std, not the var\n\n eps_base = np.sqrt(temp_base)\n\n\n\n if not self.k:\n\n # initial iteration\n\n self.k[t - 1] = eps_base\n\n\n\n k_base = self.k[t - 1]\n\n\n\n if acceptance_rate < self.min_rate:\n\n logger.debug(\"DalyScheme: Reacting to low acceptance rate.\")\n\n # reduce reduction\n\n k_base = self.alpha * k_base\n\n\n\n self.k[t] = min(k_base, self.alpha * eps_base)\n\n eps = eps_base - self.k[t]\n\n temperature = eps**2\n\n\n\n return temperature\n\n\n\n\n\nclass FrielPettittScheme(TemperatureScheme):\n\n \"\"\"\n\n Basically takes linear steps in log-space. See [#vyshemirsky2008]_.\n\n\n\n .. [#vyshemirsky2008] Vyshemirsky, Vladislav, and Mark A. Girolami.\n\n \"Bayesian ranking of biochemical system models.\"\n\n Bioinformatics 24.6 (2007): 833-839.\n\n \"\"\"\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # needs a starting temperature\n\n # if not available, return infinite temperature\n\n if prev_temperature is None:\n\n return np.inf\n\n\n\n # check if we can compute a decay step\n\n if max_nr_populations == np.inf:\n\n raise ValueError(\"Can only perform FrielPettittScheme step with a \"\n\n \"finite max_nr_populations.\")\n\n\n\n # base temperature\n\n temp_base = prev_temperature\n\n beta_base = 1. / temp_base\n\n\n\n # time to go\n\n t_to_go = max_nr_populations - t\n\n\n\n beta = beta_base + ((1. - beta_base) * 1 / t_to_go) ** 2\n\n\n\n temperature = 1. / beta\n\n return temperature\n\n\n\n\n\nclass EssScheme(TemperatureScheme):\n\n \"\"\"\n\n Try to keep the effective sample size (ESS) constant.\n\n\n\n Parameters\n\n ----------\n\n target_relative_ess: float\n\n Targe relative effective sample size.\n\n \"\"\"\n\n\n\n def __init__(self, target_relative_ess: float = 0.8):\n\n self.target_relative_ess = target_relative_ess\n\n\n\n def __call__(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n pdf_norm: float,\n\n kernel_scale: str,\n\n prev_temperature: float,\n\n acceptance_rate: float):\n\n # execute function (expensive if in calibration)\n\n df = get_weighted_distances()\n\n\n\n weights = np.array(df['w'], dtype=float)\n\n pdfs = np.array(df['distance'], dtype=float)\n\n\n\n # compute rescaled posterior densities\n\n if kernel_scale == SCALE_LIN:\n\n values = pdfs / pdf_norm\n\n else: # kernel_scale == SCALE_LOG\n\n values = np.exp(pdfs - pdf_norm)\n\n\n\n # to probability mass function (i.e. normalize)\n\n weights /= np.sum(weights)\n\n\n\n target_ess = len(weights) * self.target_relative_ess\n\n\n\n if prev_temperature is None:\n\n beta_base = 0.0\n\n else:\n\n beta_base = 1. / prev_temperature\n\n\n\n # objective to minimize\n\n def obj(beta):\n\n return (_ess(values, weights, beta) - target_ess)**2\n\n\n\n bounds = sp.optimize.Bounds(lb=np.array([beta_base]),\n\n ub=np.array([1.]))\n\n # TODO make more efficient by providing gradients\n\n ret = sp.optimize.minimize(\n\n obj, x0=np.array([0.5 * (1 + beta_base)]),\n\n bounds=bounds)\n\n beta = ret.x\n\n\n\n temperature = 1. / beta\n\n return temperature\n\n\n\n def requires_distances(self) -> bool:\n\n return True\n\n\n\n\n\ndef _ess(pdfs, weights, beta):\n\n \"\"\"\n\n Effective sample size (ESS) of importance samples.\n\n \"\"\"\n\n num = np.sum(weights * pdfs**beta)**2\n\n den = np.sum((weights * pdfs**beta)**2)\n\n return num / den\n", "file_path": "pyABC/Modified/epsilon/temperature.py", "rank": 38, "score": 64082.56737505892 }, { "content": "\"\"\"\n\nEpsilons\n\n========\n\n\n\nEpsilon threshold updating strategies.\n\n\n\nAcceptance thresholds (= epsilon) can be calculated based on the distances from\n\nthe observed data, can follow a pre-defined list, can be constant, or can have\n\na user-defined implementation.\n\n\"\"\"\n\n\n\n\n\nfrom .base import (\n\n Epsilon,\n\n NoEpsilon,\n\n)\n\nfrom .epsilon import (\n\n ConstantEpsilon,\n\n ListEpsilon,\n\n QuantileEpsilon,\n\n MedianEpsilon,\n\n)\n\nfrom .temperature import (\n\n TemperatureBase,\n\n ListTemperature,\n\n Temperature,\n\n TemperatureScheme,\n\n AcceptanceRateScheme,\n\n ExpDecayFixedIterScheme,\n\n ExpDecayFixedRatioScheme,\n\n PolynomialDecayFixedIterScheme,\n\n DalyScheme,\n\n FrielPettittScheme,\n\n EssScheme,\n\n)\n", "file_path": "pyABC/0.10.14/epsilon/__init__.py", "rank": 39, "score": 63839.948378017565 }, { "content": "class ConstantEpsilon(Epsilon):\n\n \"\"\"\n\n Keep epsilon constant over all populations.\n\n This acceptance threshold scheduling strategy is most likely only\n\n interesting for debugging purposes.\n\n\n\n Parameters\n\n ----------\n\n\n\n constant_epsilon_value: float\n\n The epsilon value for all populations\n\n \"\"\"\n\n\n\n def __init__(self,\n\n constant_epsilon_value: float):\n\n super().__init__()\n\n self.constant_epsilon_value = constant_epsilon_value\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"constant_epsilon_value\"] = self.constant_epsilon_value\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 40, "score": 63462.01444754845 }, { "content": "class ListEpsilon(Epsilon):\n\n \"\"\"\n\n Return epsilon values from a predefined list. For every time point\n\n enquired later, an epsilon value must exist in the list.\n\n\n\n Parameters\n\n ----------\n\n\n\n values: List[float]\n\n List of epsilon values.\n\n ``values[t]`` is the value for population t.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n values: List[float]):\n\n super().__init__()\n\n self.epsilon_values = list(values)\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"epsilon_values\"] = self.epsilon_values\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n\n return self.epsilon_values[t]\n\n\n\n def __len__(self):\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 41, "score": 63461.44571872015 }, { "content": "class MedianEpsilon(QuantileEpsilon):\n\n \"\"\"\n\n Calculate epsilon as median of the distances from the last population.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n median_multiplier: float = 1,\n\n weighted: bool = True):\n\n super().__init__(initial_epsilon=initial_epsilon,\n\n alpha=0.5,\n\n quantile_multiplier=median_multiplier,\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 42, "score": 63457.00830537136 }, { "content": "class QuantileEpsilon(Epsilon):\n\n \"\"\"\n\n Calculate epsilon as alpha-quantile of the distances from the last\n\n population.\n\n\n\n This strategy works even if the posterior is multi-modal.\n\n Note that the acceptance threshold calculation is based on the distance\n\n to the observation, not on the parameters which generated data with that\n\n distance.\n\n\n\n If completely different parameter sets produce equally good samples,\n\n the distances of their samples to the ground truth data should be\n\n comparable.\n\n\n\n The idea behind weighting is that the probability p_k of obtaining a\n\n distance eps_k in the next generation should be proportional to the\n\n weight w_k of respective particle k in the current generation. Both\n\n weighted and non-weighted median should lead to correct results.\n\n\n\n Parameters\n\n ----------\n\n\n\n initial_epsilon: Union[str, int]\n\n * If 'from_sample', then the initial quantile is calculated from\n\n a sample of the current population size from the prior distribution.\n\n * If a number is given, this number is used.\n\n\n\n alpha: float\n\n The alpha-quantile to be used, e.g. alpha=0.5 means median.\n\n\n\n quantile_multiplier: float\n\n Multiplies the quantile by that number. also applies it\n\n to the initial quantile if it is calculated from samples.\n\n However, it does **not** apply to the initial quantile if\n\n it is given as a number.\n\n\n\n weighted: bool\n\n Flag indicating whether the new epsilon should be computed using\n\n weighted (True, default) or non-weighted (False) distances.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n alpha: float = 0.5,\n\n quantile_multiplier: float = 1,\n\n weighted: bool = True):\n\n\n\n logger.debug(\n\n \"init quantile_epsilon initial_epsilon={}, quantile_multiplier={}\"\n\n .format(initial_epsilon, quantile_multiplier))\n\n\n\n super().__init__()\n\n self._initial_epsilon = initial_epsilon\n\n self.alpha = alpha\n\n self.quantile_multiplier = quantile_multiplier\n\n self.weighted = weighted\n\n self._look_up = {}\n\n\n\n if self.alpha > 1 or self.alpha <= 0:\n\n raise ValueError(\"It must be 0 < alpha <= 1\")\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config.update({\"initial_epsilon\": self._initial_epsilon,\n\n \"alpha\": self.alpha,\n\n \"quantile_multiplier\": self.quantile_multiplier,\n\n \"weighted\": self.weighted})\n\n\n\n return config\n\n\n\n def requires_calibration(self) -> bool:\n\n return self._initial_epsilon == 'from_sample'\n\n\n\n def is_adaptive(self) -> bool:\n\n return True\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n if not self.requires_calibration():\n\n # safety check in __call__\n\n return\n\n\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # initialize epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logging\n\n logger.info(\"initial epsilon is {}\".format(self._look_up[t]))\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Epsilon value for time t, set before via update() method.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon value for time t (throws error if not existent).\n\n \"\"\"\n\n\n\n # initialize if necessary\n\n if not self._look_up:\n\n self._set_initial_value(t)\n\n try:\n\n eps = self._look_up[t]\n\n except KeyError as e:\n\n raise KeyError(\"The epsilon value for time {} does not exist: {} \"\n\n .format(t, repr(e)))\n\n\n\n return eps\n\n\n\n def _set_initial_value(self, t: int):\n\n self._look_up = {t: self._initial_epsilon}\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Compute quantile of the (weighted) distances given in population,\n\n and use this to update epsilon.\n\n \"\"\"\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # update epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logger\n\n logger.debug(\"new eps, t={}, eps={}\".format(t, self._look_up[t]))\n\n\n\n def _update(self,\n\n t: int,\n\n weighted_distances: pd.DataFrame):\n\n \"\"\"\n\n Here the real update happens, based on the weighted distances.\n\n \"\"\"\n\n\n\n # extract distances\n\n distances = weighted_distances.distance.values\n\n\n\n # extract weights\n\n if self.weighted:\n\n weights = weighted_distances.w.values.astype(float)\n\n # The sum of the weighted distances is larger than 1 if more than\n\n # a single simulation per parameter is performed.\n\n # Re-normalize in this case.\n\n weights /= weights.sum()\n\n else:\n\n len_distances = len(distances)\n\n weights = np.ones(len_distances) / len_distances\n\n\n\n # compute weighted quantile\n\n quantile = weighted_quantile(\n\n points=distances, weights=weights, alpha=self.alpha)\n\n\n\n # append to look_up property\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 43, "score": 63456.84713980644 }, { "content": "class ConstantEpsilon(Epsilon):\n\n \"\"\"\n\n Keep epsilon constant over all populations.\n\n This acceptance threshold scheduling strategy is most likely only\n\n interesting for debugging purposes.\n\n\n\n Parameters\n\n ----------\n\n\n\n constant_epsilon_value: float\n\n The epsilon value for all populations\n\n \"\"\"\n\n\n\n def __init__(self,\n\n constant_epsilon_value: float):\n\n super().__init__()\n\n self.constant_epsilon_value = constant_epsilon_value\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"constant_epsilon_value\"] = self.constant_epsilon_value\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 44, "score": 62765.6701403214 }, { "content": "class ListEpsilon(Epsilon):\n\n \"\"\"\n\n Return epsilon values from a predefined list. For every time point\n\n enquired later, an epsilon value must exist in the list.\n\n\n\n Parameters\n\n ----------\n\n\n\n values: List[float]\n\n List of epsilon values.\n\n ``values[t]`` is the value for population t.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n values: List[float]):\n\n super().__init__()\n\n self.epsilon_values = list(values)\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config[\"epsilon_values\"] = self.epsilon_values\n\n return config\n\n\n\n def __call__(self,\n\n t: int):\n\n return self.epsilon_values[t]\n\n\n\n def __len__(self):\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 45, "score": 62765.1014114931 }, { "content": "class MedianEpsilon(QuantileEpsilon):\n\n \"\"\"\n\n Calculate epsilon as median of the distances from the last population.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n median_multiplier: float = 1,\n\n weighted: bool = True):\n\n super().__init__(initial_epsilon=initial_epsilon,\n\n alpha=0.5,\n\n quantile_multiplier=median_multiplier,\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 46, "score": 62760.663998144315 }, { "content": "class QuantileEpsilon(Epsilon):\n\n \"\"\"\n\n Calculate epsilon as alpha-quantile of the distances from the last\n\n population.\n\n\n\n This strategy works even if the posterior is multi-modal.\n\n Note that the acceptance threshold calculation is based on the distance\n\n to the observation, not on the parameters which generated data with that\n\n distance.\n\n\n\n If completely different parameter sets produce equally good samples,\n\n the distances of their samples to the ground truth data should be\n\n comparable.\n\n\n\n The idea behind weighting is that the probability p_k of obtaining a\n\n distance eps_k in the next generation should be proportional to the\n\n weight w_k of respective particle k in the current generation. Both\n\n weighted and non-weighted median should lead to correct results.\n\n\n\n Parameters\n\n ----------\n\n\n\n initial_epsilon: Union[str, int]\n\n * If 'from_sample', then the initial quantile is calculated from\n\n a sample of the current population size from the prior distribution.\n\n * If a number is given, this number is used.\n\n\n\n alpha: float\n\n The alpha-quantile to be used, e.g. alpha=0.5 means median.\n\n\n\n quantile_multiplier: float\n\n Multiplies the quantile by that number. also applies it\n\n to the initial quantile if it is calculated from samples.\n\n However, it does **not** apply to the initial quantile if\n\n it is given as a number.\n\n\n\n weighted: bool\n\n Flag indicating whether the new epsilon should be computed using\n\n weighted (True, default) or non-weighted (False) distances.\n\n \"\"\"\n\n\n\n def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n alpha: float = 0.5,\n\n quantile_multiplier: float = 1,\n\n weighted: bool = True):\n\n\n\n logger.debug(\n\n \"init quantile_epsilon initial_epsilon={}, quantile_multiplier={}\"\n\n .format(initial_epsilon, quantile_multiplier))\n\n\n\n super().__init__()\n\n self._initial_epsilon = initial_epsilon\n\n self.alpha = alpha\n\n self.quantile_multiplier = quantile_multiplier\n\n self.weighted = weighted\n\n self._look_up = {}\n\n\n\n if self.alpha > 1 or self.alpha <= 0:\n\n raise ValueError(\"It must be 0 < alpha <= 1\")\n\n\n\n def get_config(self):\n\n config = super().get_config()\n\n config.update({\"initial_epsilon\": self._initial_epsilon,\n\n \"alpha\": self.alpha,\n\n \"quantile_multiplier\": self.quantile_multiplier,\n\n \"weighted\": self.weighted})\n\n\n\n return config\n\n\n\n def requires_calibration(self) -> bool:\n\n return self._initial_epsilon == 'from_sample'\n\n\n\n def is_adaptive(self) -> bool:\n\n return True\n\n\n\n def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n if not self.requires_calibration():\n\n # safety check in __call__\n\n return\n\n\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # initialize epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logging\n\n logger.info(\"initial epsilon is {}\".format(self._look_up[t]))\n\n\n\n def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Epsilon value for time t, set before via update() method.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon value for time t (throws error if not existent).\n\n \"\"\"\n\n\n\n # initialize if necessary\n\n if not self._look_up:\n\n self._set_initial_value(t)\n\n try:\n\n eps = self._look_up[t]\n\n except KeyError as e:\n\n raise KeyError(\"The epsilon value for time {} does not exist: {} \"\n\n .format(t, repr(e)))\n\n\n\n return eps\n\n\n\n def _set_initial_value(self, t: int):\n\n self._look_up = {t: self._initial_epsilon}\n\n\n\n def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Compute quantile of the (weighted) distances given in population,\n\n and use this to update epsilon.\n\n \"\"\"\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # update epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logger\n\n logger.debug(\"new eps, t={}, eps={}\".format(t, self._look_up[t]))\n\n\n\n def _update(self,\n\n t: int,\n\n weighted_distances: pd.DataFrame):\n\n \"\"\"\n\n Here the real update happens, based on the weighted distances.\n\n \"\"\"\n\n\n\n # extract distances\n\n distances = weighted_distances.distance.values\n\n\n\n # extract weights\n\n if self.weighted:\n\n weights = weighted_distances.w.values.astype(float)\n\n # The sum of the weighted distances is larger than 1 if more than\n\n # a single simulation per parameter is performed.\n\n # Re-normalize in this case.\n\n weights /= weights.sum()\n\n else:\n\n len_distances = len(distances)\n\n weights = np.ones(len_distances) / len_distances\n\n\n\n # compute weighted quantile\n\n quantile = weighted_quantile(\n\n points=distances, weights=weights, alpha=self.alpha)\n\n\n\n # append to look_up property\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 47, "score": 62760.5028325794 }, { "content": "\"\"\"\n\nEpsilons\n\n========\n\n\n\nEpsilon threshold updating strategies.\n\n\n\nAcceptance thresholds (= epsilon) can be calculated based on the distances from\n\nthe observed data, can follow a pre-defined list, can be constant, or can have\n\na user-defined implementation.\n\n\"\"\"\n\n\n\n\n\nfrom .base import (\n\n Epsilon,\n\n NoEpsilon,\n\n)\n\nfrom .epsilon import (\n\n ConstantEpsilon,\n\n ListEpsilon,\n\n QuantileEpsilon,\n\n MedianEpsilon,\n\n)\n\nfrom .temperature import (\n\n TemperatureBase,\n\n ListTemperature,\n\n Temperature,\n\n TemperatureScheme,\n\n AcceptanceRateScheme,\n\n ExpDecayFixedIterScheme,\n\n ExpDecayFixedRatioScheme,\n\n PolynomialDecayFixedIterScheme,\n\n DalyScheme,\n\n FrielPettittScheme,\n\n EssScheme,\n\n)\n", "file_path": "pyABC/Modified/epsilon/__init__.py", "rank": 48, "score": 62753.084160764076 }, { "content": " def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Epsilon value for time t, set before via update() method.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon value for time t (throws error if not existent).\n\n \"\"\"\n\n\n\n # initialize if necessary\n\n if not self._look_up:\n\n self._set_initial_value(t)\n\n try:\n\n eps = self._look_up[t]\n\n except KeyError as e:\n\n raise KeyError(\"The epsilon value for time {} does not exist: {} \"\n\n .format(t, repr(e)))\n\n\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 49, "score": 57989.77161453201 }, { "content": "class NoEpsilon(Epsilon):\n\n \"\"\"\n\n Implements a kind of null object as epsilon.\n\n\n\n This can be used as a dummy epsilon when the Acceptor integrates the\n\n acceptance threshold.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n super().__init__()\n\n\n\n def __call__(self,\n\n t: int) -> float:\n", "file_path": "pyABC/0.10.14/epsilon/base.py", "rank": 50, "score": 57985.5184231728 }, { "content": " def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Compute quantile of the (weighted) distances given in population,\n\n and use this to update epsilon.\n\n \"\"\"\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # update epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logger\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 51, "score": 57984.69377472815 }, { "content": " def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n if not self.requires_calibration():\n\n # safety check in __call__\n\n return\n\n\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # initialize epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logging\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 52, "score": 57979.65883464876 }, { "content": " def __len__(self):\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 53, "score": 57979.65883464876 }, { "content": " def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n median_multiplier: float = 1,\n\n weighted: bool = True):\n\n super().__init__(initial_epsilon=initial_epsilon,\n\n alpha=0.5,\n\n quantile_multiplier=median_multiplier,\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 54, "score": 57979.65883464876 }, { "content": " def _update(self,\n\n t: int,\n\n weighted_distances: pd.DataFrame):\n\n \"\"\"\n\n Here the real update happens, based on the weighted distances.\n\n \"\"\"\n\n\n\n # extract distances\n\n distances = weighted_distances.distance.values\n\n\n\n # extract weights\n\n if self.weighted:\n\n weights = weighted_distances.w.values.astype(float)\n\n # The sum of the weighted distances is larger than 1 if more than\n\n # a single simulation per parameter is performed.\n\n # Re-normalize in this case.\n\n weights /= weights.sum()\n\n else:\n\n len_distances = len(distances)\n\n weights = np.ones(len_distances) / len_distances\n\n\n\n # compute weighted quantile\n\n quantile = weighted_quantile(\n\n points=distances, weights=weights, alpha=self.alpha)\n\n\n\n # append to look_up property\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 55, "score": 57979.65883464876 }, { "content": " def is_adaptive(self) -> bool:\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 56, "score": 57979.65883464876 }, { "content": "#ifndef __SPARSE_MATRIX_H\n\n#define __SPARSE_MATRIX_H\n\n\n\n#include \"VoronoiDiagramExtended.h\"\n\n\n\n#define DEBUG 0\n\n\n\n#define COMPARE_WITH_EXACT_SOLUTION 0\n\n\n\ntypedef struct _SparseMatrix SparseMatrix;\n\ntypedef struct _SparseVector SparseVector;\n\n\n\nextern SparseMatrix *sA;\n\nextern SparseMatrix *M;\n\nextern SparseMatrix *J;\n\nextern float *x;\n\nextern float *b;\n\nextern float *v0;\n\nextern double *v0d;\n\nextern double *v1d;\n\nextern double *v2d;\n\nextern double *v3d;\n\nextern double *v4d;\n\nextern double *v5d;\n\nextern double *v6d;\n\nextern float *v1;\n\nextern float *v2;\n\nextern float *v3;\n\nextern float *v4;\n\nextern float *v5;\n\nextern float *v6;\n\nextern float *v7;\n\nextern float *v8;\n\n\n\n// voronoi cell type\n\nstruct _SparseMatrix {\n\n\t\n\n\tfloat **A; // values\n\n\tint **JA; // column index of values\t\n\n\tint *sizeA;\n\n\tint *maxSizeA;\n\n\t//int *IA; // indeces of first element of each row\n\n\t//int sizeIA;\n\n\t\n\n\t\n\n\tint dimI, dimJ; // dimensions\n\n\t\n\n\t\n\n\t// methodes\n\n\tstatic SparseMatrix *newSparseMatrix( int, int);\n\n\tstatic void deleteSparseMatrix(SparseMatrix *matrix);\n\n\t\n\n\tfloat get( int i, int j);\n\n\n\n\tvoid set( int i, int j, float value);\n\n\tvoid setLast( int i, int j, float value);\n\n\n\n\tvoid add( int i, int j, float value);\n\n\n\n\tvoid resetRow( int i);\n\n\n\n};\n\n\n\nstruct _SparseVector {\n\n\t\n\n\tfloat *v; // values\n\n\tint sizev;\n\n\tint *Iv; // row index of values\t\n\n\t\n\n\tint dim; // dimensions\n\n\t\n\n\t\n\n\t// methodes\n\n\tvoid newSparseVector( int);\n\n\tvoid deleteSparseVector();\n\n\t\n\n\tfloat get( int i);\n\n\tfloat set( int i);\n\n};\n\n\t\n\n\t\n\nvoid sparseMatrixVectorProduct( SparseMatrix *sA, float *b, float *x);\n\nvoid sparseMatrixVectorProduct( SparseMatrix *sA, double *b, double *x);\n\nvoid vectorSparseMatrixProduct( float *b, SparseMatrix *sA, float *x);\n\nvoid vectorSparseMatrixProduct( double *b, SparseMatrix *sA, double *x);\n\n\n\ndouble UpdateSystemImplicitSparse( VoronoiDiagram *voronoiDiagram, double timeStep, double timeDifference);\n\ndouble UpdateSystemNewtonSparse( VoronoiDiagram *voronoiDiagram, double timeStep, double timeDifference);\n\ndouble UpdateSystemNonLinearCGSparse( VoronoiDiagram *voronoiDiagram, double time, double end_time, double timeStep);\n\ndouble UpdateSystemNewtonCGSparse( VoronoiDiagram *voronoiDiagram, double time, double end_time, double timeStep);\n\ndouble UpdateGrowthFactorsNonLinearCGSparse( VoronoiDiagram *voronoiDiagram, double time, double end_time, double timeStep);\n\n\n\nvoid setupMatrixImplicitSparse( VoronoiDiagram *voronoiDiagram, double timeStep, char molecule);\n\nvoid JacobiPreconditioner( SparseMatrix *A, SparseMatrix *M);\n\nvoid SuccessiveOverRelaxationPreconditioner( SparseMatrix *A, SparseMatrix *M);\n\n\n\nvoid SolveExplicit( SparseMatrix *A, float *b, float *x);\n\nint SolveBiCGSTAB( SparseMatrix *A, float *b, float *x, int maxit, float minerr);\n\nint SolveBiCGSTAB( SparseMatrix *A, double *b, double *x, int maxit, double minerr);\n\nvoid SolveGaussSeidelMethod( SparseMatrix *A, float *b, float *x0, int maxit, float minerr);\n\nvoid SolveGaussSeidelMethod( SparseMatrix *A, double *b, double *x0, int maxit, double minerr);\n\nvoid SolveGaussSeidelMethod( SparseMatrix *A, double *b, double *x0, int maxit, double minerr);\n\nvoid SolveSuccessiveOverRelaxationMethod( SparseMatrix *A, double *b, double *x0, int maxit, double minerr, double omega);\n\nvoid SolveJacobiMethod( SparseMatrix *A, double *b, double *x0, int maxit, double minerr);\n\nfloat PreconditionedConjugateGradientSparse( SparseMatrix *A, SparseMatrix *M, float *b, float *x, int maxit, float minerr);\n\ndouble PreconditionedConjugateGradientSparse( SparseMatrix *A, SparseMatrix *M, double *b, double *x, int maxit, float minerr);\n\nvoid ConjugateGradientSparse( SparseMatrix *A, float *b, float *x, int maxit, float minerr);\n\nvoid ConjugateGradientSparse( SparseMatrix *A, double *b, double *x, int maxit, double minerr);\n\n\n\nvoid PreconditionJacobi( SparseMatrix *A, double *b);\n\nvoid PreconditionSOR( SparseMatrix *A, double *b, double omega);\n\nvoid SolveDirectly( SparseMatrix *Ai, double *bi, double *x, VoronoiDiagram *vd);\n\n\n\nfloat GetLactateProductionRate( VoronoiCell *cell, float glucose, float oxygen);\n\nfloat GetGlucoseConsumptionRate( VoronoiCell *cell, float glucose, float oxygen);\n\nfloat GetOxygenConsumptionRate( VoronoiCell *cell, float glucose, float oxygen);\n\nfloat OxygenConsumptionRate_PartialDerivativeOxygen( VoronoiCell *cell, float glucose, float oxygen);\n\nfloat OxygenConsumptionRate_PartialDerivativeGlucose( VoronoiCell *cell, float glucose, float oxygen);\n\nfloat GlucoseConsumptionRate_PartialDerivativeGlucose( VoronoiCell *cell, float glucose, float oxygen);\n\nfloat GlucoseConsumptionRate_PartialDerivativeOxygen( VoronoiCell *cell, float glucose, float oxygen);\n\n\n\n\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 57, "score": 57673.30089808038 }, { "content": "def to_file(df: pd.DataFrame, file: str, file_format=\"feather\"):\n\n df_json = sumstat_to_json(df)\n\n df_json_no_index = df_json.reset_index()\n", "file_path": "pyABC/0.10.14/storage/df_to_file.py", "rank": 58, "score": 57433.119097502575 }, { "content": " def __call__(self,\n\n t: int) -> float:\n\n \"\"\"\n\n Epsilon value for time t, set before via update() method.\n\n\n\n Returns\n\n -------\n\n\n\n eps: float\n\n The epsilon value for time t (throws error if not existent).\n\n \"\"\"\n\n\n\n # initialize if necessary\n\n if not self._look_up:\n\n self._set_initial_value(t)\n\n try:\n\n eps = self._look_up[t]\n\n except KeyError as e:\n\n raise KeyError(\"The epsilon value for time {} does not exist: {} \"\n\n .format(t, repr(e)))\n\n\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 59, "score": 57121.176904539985 }, { "content": "class NoEpsilon(Epsilon):\n\n \"\"\"\n\n Implements a kind of null object as epsilon.\n\n\n\n This can be used as a dummy epsilon when the Acceptor integrates the\n\n acceptance threshold.\n\n \"\"\"\n\n\n\n def __init__(self):\n\n super().__init__()\n\n\n\n def __call__(self,\n\n t: int) -> float:\n", "file_path": "pyABC/Modified/epsilon/base.py", "rank": 60, "score": 57116.923713180775 }, { "content": "def plot_epsilons(\n\n histories: Union[List, History],\n\n labels: Union[List, str] = None,\n\n colors: List = None,\n\n yscale: str = 'log',\n\n title: str = \"Epsilon values\",\n\n size: tuple = None,\n\n ax: mpl.axes.Axes = None) -> mpl.axes.Axes:\n\n \"\"\"\n\n Plot epsilon trajectory.\n\n\n\n Parameters\n\n ----------\n\n histories:\n\n The histories to plot from. History ids must be set correctly.\n\n labels:\n\n Labels corresponding to the histories. If None are provided,\n\n indices are used as labels.\n\n colors:\n\n Colors to use for the lines. If None, then the matplotlib\n\n default values are used.\n\n yscale:\n\n Scaling to apply to the y-axis. Use matplotlib's notation.\n\n title:\n\n Title for the plot.\n\n size:\n\n The size of the plot in inches.\n\n ax:\n\n The axis object to use. A new one is created if None.\n\n\n\n Returns\n\n -------\n\n ax: Axis of the generated plot.\n\n \"\"\"\n\n # preprocess input\n\n histories = to_lists(histories)\n\n labels = get_labels(labels, len(histories))\n\n if colors is None:\n\n colors = [None for _ in range(len(histories))]\n\n\n\n # create figure\n\n if ax is None:\n\n fig, ax = plt.subplots()\n\n else:\n\n fig = ax.get_figure()\n\n\n\n # extract epsilons\n\n eps = []\n\n for history in histories:\n\n # note: first entry is from calibration and thus translates to inf,\n\n # thus must be discarded\n\n eps.append(np.array(history.get_all_populations()['epsilon'][1:]))\n\n\n\n # plot\n\n for ep, label, color in zip(eps, labels, colors):\n\n ax.plot(ep, 'x-', label=label, color=color)\n\n\n\n # format\n\n ax.set_xlabel(\"Population index\")\n\n ax.set_ylabel(\"Epsilon\")\n\n if any(lab is not None for lab in labels):\n\n ax.legend()\n\n ax.set_title(title)\n\n ax.set_yscale(yscale)\n\n # enforce integer ticks\n\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n\n # set size\n\n if size is not None:\n\n fig.set_size_inches(size)\n\n fig.tight_layout()\n\n\n", "file_path": "pyABC/0.10.14/visualization/epsilon.py", "rank": 61, "score": 57116.51969900745 }, { "content": " def update(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n acceptance_rate: float,\n\n acceptor_config: dict):\n\n \"\"\"\n\n Compute quantile of the (weighted) distances given in population,\n\n and use this to update epsilon.\n\n \"\"\"\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # update epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logger\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 62, "score": 57116.099064736125 }, { "content": " def _update(self,\n\n t: int,\n\n weighted_distances: pd.DataFrame):\n\n \"\"\"\n\n Here the real update happens, based on the weighted distances.\n\n \"\"\"\n\n\n\n # extract distances\n\n distances = weighted_distances.distance.values\n\n\n\n # extract weights\n\n if self.weighted:\n\n weights = weighted_distances.w.values.astype(float)\n\n # The sum of the weighted distances is larger than 1 if more than\n\n # a single simulation per parameter is performed.\n\n # Re-normalize in this case.\n\n weights /= weights.sum()\n\n else:\n\n len_distances = len(distances)\n\n weights = np.ones(len_distances) / len_distances\n\n\n\n # compute weighted quantile\n\n quantile = weighted_quantile(\n\n points=distances, weights=weights, alpha=self.alpha)\n\n\n\n # append to look_up property\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 63, "score": 57111.06412465674 }, { "content": " def initialize(self,\n\n t: int,\n\n get_weighted_distances: Callable[[], pd.DataFrame],\n\n get_all_records: Callable[[], List[dict]],\n\n max_nr_populations: int,\n\n acceptor_config: dict):\n\n if not self.requires_calibration():\n\n # safety check in __call__\n\n return\n\n\n\n # execute function\n\n weighted_distances = get_weighted_distances()\n\n\n\n # initialize epsilon\n\n self._update(t, weighted_distances)\n\n\n\n # logging\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 64, "score": 57111.06412465674 }, { "content": " def requires_calibration(self) -> bool:\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 65, "score": 57111.06412465674 }, { "content": " def get_config(self):\n\n config = super().get_config()\n\n config.update({\"initial_epsilon\": self._initial_epsilon,\n\n \"alpha\": self.alpha,\n\n \"quantile_multiplier\": self.quantile_multiplier,\n\n \"weighted\": self.weighted})\n\n\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 66, "score": 57111.06412465674 }, { "content": " def __init__(self,\n\n initial_epsilon: Union[str, int, float] = 'from_sample',\n\n median_multiplier: float = 1,\n\n weighted: bool = True):\n\n super().__init__(initial_epsilon=initial_epsilon,\n\n alpha=0.5,\n\n quantile_multiplier=median_multiplier,\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 67, "score": 57111.06412465674 }, { "content": " def is_adaptive(self) -> bool:\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 68, "score": 57111.06412465674 }, { "content": " def __len__(self):\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 69, "score": 57111.06412465674 }, { "content": "\tstatic SparseMatrix *newSparseMatrix( int, int);\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 70, "score": 56809.29574395013 }, { "content": "\tstatic void deleteSparseMatrix(SparseMatrix *matrix);\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 71, "score": 56809.29574395013 }, { "content": "def to_file(df: pd.DataFrame, file: str, file_format=\"feather\"):\n\n df_json = sumstat_to_json(df)\n\n df_json_no_index = df_json.reset_index()\n", "file_path": "pyABC/Modified/storage/df_to_file.py", "rank": 72, "score": 56585.41163939442 }, { "content": "def plot_epsilons(\n\n histories: Union[List, History],\n\n labels: Union[List, str] = None,\n\n colors: List = None,\n\n yscale: str = 'log',\n\n title: str = \"Epsilon values\",\n\n size: tuple = None,\n\n ax: mpl.axes.Axes = None) -> mpl.axes.Axes:\n\n \"\"\"\n\n Plot epsilon trajectory.\n\n\n\n Parameters\n\n ----------\n\n histories:\n\n The histories to plot from. History ids must be set correctly.\n\n labels:\n\n Labels corresponding to the histories. If None are provided,\n\n indices are used as labels.\n\n colors:\n\n Colors to use for the lines. If None, then the matplotlib\n\n default values are used.\n\n yscale:\n\n Scaling to apply to the y-axis. Use matplotlib's notation.\n\n title:\n\n Title for the plot.\n\n size:\n\n The size of the plot in inches.\n\n ax:\n\n The axis object to use. A new one is created if None.\n\n\n\n Returns\n\n -------\n\n ax: Axis of the generated plot.\n\n \"\"\"\n\n # preprocess input\n\n histories = to_lists(histories)\n\n labels = get_labels(labels, len(histories))\n\n if colors is None:\n\n colors = [None for _ in range(len(histories))]\n\n\n\n # create figure\n\n if ax is None:\n\n fig, ax = plt.subplots()\n\n else:\n\n fig = ax.get_figure()\n\n\n\n # extract epsilons\n\n eps = []\n\n for history in histories:\n\n # note: first entry is from calibration and thus translates to inf,\n\n # thus must be discarded\n\n eps.append(np.array(history.get_all_populations()['epsilon'][1:]))\n\n\n\n # plot\n\n for ep, label, color in zip(eps, labels, colors):\n\n ax.plot(ep, 'x-', label=label, color=color)\n\n\n\n # format\n\n ax.set_xlabel(\"Population index\")\n\n ax.set_ylabel(\"Epsilon\")\n\n if any(lab is not None for lab in labels):\n\n ax.legend()\n\n ax.set_title(title)\n\n ax.set_yscale(yscale)\n\n # enforce integer ticks\n\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n\n # set size\n\n if size is not None:\n\n fig.set_size_inches(size)\n\n fig.tight_layout()\n\n\n", "file_path": "pyABC/Modified/visualization/epsilon.py", "rank": 73, "score": 56273.56574213154 }, { "content": " def get_config(self):\n\n config = super().get_config()\n\n config.update({\"initial_epsilon\": self._initial_epsilon,\n\n \"alpha\": self.alpha,\n\n \"quantile_multiplier\": self.quantile_multiplier,\n\n \"weighted\": self.weighted})\n\n\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 74, "score": 56268.11016778083 }, { "content": " def requires_calibration(self) -> bool:\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 75, "score": 56268.11016778083 }, { "content": " def _set_initial_value(self, t: int):\n", "file_path": "pyABC/0.10.14/epsilon/epsilon.py", "rank": 76, "score": 56268.11016778083 }, { "content": "void setupMatrixImplicitSparse( VoronoiDiagram *voronoiDiagram, double timeStep, char molecule);\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 77, "score": 55970.79586010675 }, { "content": "void vectorSparseMatrixProduct( double *b, SparseMatrix *sA, double *x);\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 78, "score": 55970.79586010675 }, { "content": "void sparseMatrixVectorProduct( SparseMatrix *sA, double *b, double *x);\n", "file_path": "tumor2d/src/SparseMatrix.h", "rank": 79, "score": 55970.79586010675 }, { "content": " def _set_initial_value(self, t: int):\n", "file_path": "pyABC/Modified/epsilon/epsilon.py", "rank": 80, "score": 55449.67811281735 }, { "content": "/*\n\n * matrix.hpp\n\n *\n\n * Created on: Oct 7, 2014\n\n * Author: jagiella\n\n */\n\n\n\n#ifndef MATRIX_HPP_\n\n#define MATRIX_HPP_\n\n\n\n\n\n#include \"matrix.ipp\"\n\n\n\n\n\n#endif /* MATRIX_HPP_ */\n", "file_path": "tumor2d/src/matrix.hpp", "rank": 81, "score": 53600.28947725416 }, { "content": "\tfor( int i=0; i<sA->dimI; i++){\n\n\t\tfor( int jj=0; jj<sA->sizeA[i]; jj++){\n\n\t\t\tint j = sA->JA[i][jj];\n\n\t\t\tx[j] += b[i] * sA->A[i][jj];\n\n#if DEBUG > 0\n\n\t\t\tif( isnan(x[j])){\n\n\t\t\t\tfprintf( stderr, \"nan occures in vectorsparseMatrixProduct\\n\");\n\n\t\t\t\tfprintf( stderr, \"vector b[%i] = %lf\\n\", i, b[i]);\n\n\t\t\t\tfor( int jj=0; jj<sA->sizeA[i]; jj++){\n\n\t\t\t\t\tj = sA->JA[i][jj];\n\n\t\t\t\t\tfprintf( stderr, \"matrix A[%i][%i] = %lf\\n\", i, j, sA->A[i][jj]);\n\n\t\t\t\t}\n\n\t\t\t\texit( 0);\n\n\t\t\t}\n\n#endif\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid LUdecomposition( SparseMatrix *sA, SparseMatrix *L, SparseMatrix *U, float *b)\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 82, "score": 52150.36370933124 }, { "content": "\t}\n\n\t\n\n\t//fprintf( stderr, \"error is still %e (=sqrt(%e)) < %e\\n\", myError, dotProduct( r, r, N), err);\n\n\t\n\n\t//return iterations;\n\n}\n\n\n\n\n\nvoid ConjugateGradientSparse( SparseMatrix *A, double *b, double *x, int maxit, double minerr)\n\n// If A is symmetric positive matrix\n\n{\n\n\tchar filename[512];\n\n\tFILE *fp;\n\n\n\n\tsprintf( filename, \"convergencePreCondCG_%iD_%iPoints.dat\", DIMENSIONS, A->dimI);\n\n\tfp = fopen( filename, \"w+\");\n\n\tlong passedTime = clock();\n\n\n\n\tint N = A->dimI;\n\n\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 83, "score": 30.024475024969743 }, { "content": "\t\t\tvectorDifference( b, f, f, N);\n\n\t\t\n\n\t\t\t// set J\n\n\t\t\tsetupJacobianMatrixImplicitSteadyState( voronoiDiagram, J, sA, b, x, 'O');\n\n\t\t\n\n\t\t\t// solve h*J = f\n\n\t\t\tConjugateGradientSparse( J, f, h, N, 2);\n\n\n\n\t\t\t// update x = x + h\n\n\t\t\tvectorSum( x, h, x, N);\n\n\n\n\t\t\terr = sqrt( dotProduct( h, h, N));\n\n\t\t\tit++;\n\n\n\n\t\t\tfprintf( stderr, \"\\r\\t\\t\\t\\t\\t Newton: error = %e \\b\", err);\n\n\n\n\t\t\t//fprintf( stderr, \"Newton Iteration %i -> error: %e\\n\", it, err);\n\n\t\t}while( err > 1e-5 && it < 10);\n\n\t\t//fprintf( stderr, \"...finished after %i Newton Iterations -> error: %e\\n\", i, err);\n\n\t\tfor(int m=0; m<N; m++)\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 84, "score": 29.64120826957426 }, { "content": "\t\tif( sqrt( dotProduct( r, r, N)) < minerr){\n\n\t\t\t//fprintf( stderr, \"ConjugateGradientSparse: reached error %e < %e after %i iterations\\n\", myError, err, i+1);\n\n\t\t\treturn;// i;\n\n\t\t}\n\n\t\t\n\n\t}\n\n\t\n\n\t//fprintf( stderr, \"error is still %e (=sqrt(%e)) < %e\\n\", myError, dotProduct( r, r, N), err);\n\n\t\n\n\t//return iterations;\n\n}*/\n\n\n\n\n\nvoid JacobiPreconditioner( SparseMatrix *A, SparseMatrix *M)\n\n{\n\n#pragma omp parallel for\n\n\tfor( int i=0; i<A->dimI; i++){\n\n\t\tM->set( i,i, 1. / A->get(i,i));\n\n\t\t//M->set( i,i, A->get(i,i));\n\n\t}\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 85, "score": 28.398524144873477 }, { "content": "\tfor( int i=0; i<N; i++)\n\n\t\tx[i] = y[i] + alpha*a[i] + beta*b[i];\n\n}\n\n\n\n// p = r - beta*(p - omega*s)\n\nvoid calculate_p1( double *x, double *y, double alpha, double *a, int N)\n\n{\n\n#pragma omp parallel for\n\n\tfor( int i=0; i<N; i++)\n\n\t\tx[i] = y[i] + alpha*a[i];\n\n}\n\n\n\n\n\nint SolveBiCGSTAB( SparseMatrix *A, float *b, float *x, int maxit, float minerr)\n\n// If A is symmetric positive matrix\n\n{\n\n\tint N = A->dimI;\n\n\t//fprintf( stderr, \"test\\n\");\n\n\t// vectors\n\n/*\tfloat r0[N];\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 86, "score": 28.01116542546676 }, { "content": "\t\t#endif\n\n\n\n\t\t}\n\n\t\t\n\n\t\t// border condition\n\n\t\telse{\n\n\t\t\t//matrix'\n\n\t\t\tJ->set(m, m, 0);\n\n\t\t}\n\n\t\t\n\n\t\t/*fprintf( stderr, \"A[%i]: \", m);\n\n\t\tfor( int jj=0; jj<J->sizeA[m]; jj++){\n\n\t\t\tint j = J->JA[m][jj];\n\n\t\t\tfprintf( stderr, \"%e \", J->A[m][jj]);\n\n\t\t}\n\n\t\tfprintf( stderr, \"\\n\");\n\n*/\n\n\t\t\n\n\t}\n\n\t//\t\tfprintf( stderr, \"...finished\\n \");\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 87, "score": 27.171353944765027 }, { "content": "}\n\n\n\n// NEW!!!\n\nvoid vectorSparseMatrixProduct( float *b, SparseMatrix *sA, float *x)\n\n{\n\n\t//x = b*A\n\n\t// (n x m) * (m x p) = (n x p)\n\n\t// (1 x i) * (i x j) = (1 x j)\n\n\t//int jj = 0;\n\n\tfor( int j=0; j<sA->dimI; j++)\n\n\t\tx[j] = 0.;\n\n\n\n\tfor( int i=0; i<sA->dimI; i++){\n\n\t\tfor( int jj=0; jj<sA->sizeA[i]; jj++){\n\n\t\t\tint j = sA->JA[i][jj];\n\n\t\t\tx[j] += b[i] * sA->A[i][jj];\n\n#if DEBUG > 0\n\n\t\t\tif( isnan(x[j])){\n\n\t\t\t\tfprintf( stderr, \"nan occures in vectorsparseMatrixProduct\\n\");\n\n\t\t\t\tfprintf( stderr, \"vector b[%i] = %lf\\n\", i, b[i]);\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 88, "score": 27.009077603558183 }, { "content": "\t\tm++;\n\n\t\tv = (v + 1) % d;\n\n\t}\n\n}\n\n\n\n\n\nvoid setupJacobianMatrixImplicitSteadyState( VoronoiDiagram *voronoiDiagram, SparseMatrix *J, float *x, char molecule)\n\n{\n\n\tint di = 1;\n\n\tint dii = voronoiDiagram->xN[0];\n\n\tint diii = voronoiDiagram->xN[0]*voronoiDiagram->xN[1];\n\n\tint d = voronoiDiagram->xN[0]*voronoiDiagram->xN[1]*voronoiDiagram->xN[2];\n\n\t\n\n\t//float a = 0.5;\n\n\t//float b = 1. - a;\n\n\t//float c = 1.\n\n\t\n\n\t//fprintf( stderr, \"Build Steady State Matrix: setupJacobianMatrixImplicitSteadyState()\\n \");\n\n\t\n\n\tfloat r = 0.;\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 89, "score": 26.926663568465322 }, { "content": "\tfloat h[2*N];\n\n\t//SparseMatrix *J = SparseMatrix::newSparseMatrix( N, N);\n\n\tfloat err, cg_err;\n\n\n\n\t// set x\n\n\t//fprintf( stderr, \"initialize vector x\\n\");\n\n\tfor(int m=0; m<N; m++){\n\n\t\tx[m] = voronoiDiagram->voronoiCells[m]->glucose;\n\n\t\tx[m+N] = voronoiDiagram->voronoiCells[m]->oxygen;\n\n\n\n\t\th[m]=0.;\n\n\t\th[m+N]=0.;\n\n\t}\n\n\n\n\t// timestep loop\n\n//\tfor( time = 0; time+timeStep <= timeDifference; time += timeStep){\n\n//\tfor(int i=0; i<10; i++){\n\n\tint i = 0;\n\n\tdo{\n\n\t\tfprintf( stderr, \"Outer Iteration %i...\\n\", i+1);\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 90, "score": 26.763411783418743 }, { "content": "\t}\n\n\t\n\n//\tfprintf( stderr, \"error is still %e < %e\\n\", myError, err);\n\n}*/\n\n\n\n\n\n\n\nvoid sparseMatrixVectorProduct( SparseMatrix *sA, float *b, float *x)\n\n{\n\n\t//x = A*b\n\n\t// (n x m) * (m x p) = (n x p)\n\n\t// (i x j) * (j x 1) = (i x 1)\n\n\tfor( int i=0; i<sA->dimI; i++){\n\n\t\tx[i] = 0.;\n\n\t\tfor( int jj=0; jj<sA->sizeA[i]; jj++){\n\n\t\t\tint j = sA->JA[i][jj];\n\n\t\t\tx[i] += sA->A[i][jj] * b[j];\n\n#if DEBUG > 0\n\n\t\t\tif( isnan(x[i])){\n\n\t\t\t\tfprintf( stderr, \"nan occures in sparseMatrixVectorProduct\\n\");\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 91, "score": 26.74280538359512 }, { "content": "\t\t//M->set( i,i, A->get(i,i));\n\n\t}\n\n//\tfprintf( stderr, \"SuccessiveOverRelaxationPreconditioner still not implimented\\n\");\n\n//\texit( 0);\n\n}*/\n\n\n\n\n\nfloat PreconditionedConjugateGradientSparse( SparseMatrix *A, SparseMatrix *M, float *b, float *x, int maxit, float minerr)\n\n{\n\n\t// vectors\n\n\t//float r[N];\n\n\t//float z[N];\n\n\t//float p[N];\n\n\tint N = A->dimI;\n\n\t\n\n\tfloat *r = v0;\n\n\tfloat *z = v1;\n\n\tfloat *p = v2;\n\n\t\n\n\t// scalars\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 92, "score": 26.716251247442433 }, { "content": "double logLikelihood( double *v1, double *v2, double *s21, double *s22, int n)\n\n{\n\n\tdouble logL = 0;\n\n\n\n\t/*if( s22){\n\n\t\tfor( int i=0; i<n; i++) if(s21[i])\n\n\t\t\tlogL += - pow( v1[i] - v2[i], 2) / s21[i] - pow(s21[i] - s22[i], 2) / s21[i];\n\n\t}else*/\n\n\tif( s21){\n\n\t\tfor( int i=0; i<n; i++)\n\n\t\t\tif( s21[i]>0){\n\n\t\t\t\tdouble last = logL;\n\n\t\t\t\tlogL += logLikelihood( v1[i], v2[i], s21[i]);\n\n\t\t\t\tif( isinf(logL) || isnan(logL) || isinf(-logL)){\n\n\t\t\t\t\tfprintf( stderr, \"%i: v1=%e, v2=%e, s21=%e -> %e + %e = %e -> %e\\n\", i, v1[i], v2[i], s21[i], - 0.5 * log(2*M_PI*s21[i]), - 0.5 * pow( v1[i] - v2[i], 2) / s21[i], - 0.5 * log(2*M_PI*s21[i]) - 0.5 * pow( v1[i] - v2[i], 2) / s21[i], last);\n\n\t\t\t\t\t\t\t\t\t\texit(0);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t}else\n\n\t\tfor( int i=0; i<n; i++)\n", "file_path": "tumor2d/src/statistics.cpp", "rank": 93, "score": 26.534049329820224 }, { "content": "\t\n\n\treturn 0.;\n\n}\n\n\n\n\n\n\n\nvoid SparseMatrix::resetRow( int i)\n\n{\n\n\tthis->sizeA[i] = 0;\n\n}\n\n\n\n\n\nvoid SparseMatrix::setLast( int i, int j, float value)\n\n{\n\n\tif( value == 0.) return;\n\n\t\n\n\tint k = this->sizeA[i];\n\n\tif( k > 0 && this->JA[i][k-1] >= j){\n\n\t\tfprintf( stderr, \"ERROR in SparseMatrix::setLast(): Element cannot be inserted at last position!! \\n(i,j) = (%i,%i), sizeA(i) = %i \\n\", i, j, k);\n\n\t\texit( 0);\t\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 94, "score": 26.529256534521984 }, { "content": "\n\n\tfor(int i=0; i<sA->dimI; i++){\n\n\t\tfloat aii = sA->get( i,i);\n\n\t\tfor( int jj=0; jj<sA->sizeA[i]; jj++){\n\n\t\t\t//int j=sA->JA[i][jj];\n\n\t\t\tsA->A[i][jj] /= aii;\n\n\t\t}\n\n\t\tb[i] /= aii;\n\n\t}\n\n}\n\n\n\n\n\n\n\n\n\nvoid setupJacobiMatrixSteadyState( VoronoiDiagram *voronoiDiagram, SparseMatrix *J, float* x)\n\n{\n\n\tint di = 1;\n\n\tint dii = voronoiDiagram->xN[0];\n\n\tint diii = voronoiDiagram->xN[0]*voronoiDiagram->xN[1];\n\n\tint d = voronoiDiagram->xN[0]*voronoiDiagram->xN[1]*voronoiDiagram->xN[2];\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 95, "score": 26.366938416323574 }, { "content": "{\n\n\n\n\tdouble time;\n\n\t\n\n\tint N = voronoiDiagram->xN[0]*voronoiDiagram->xN[1]*voronoiDiagram->xN[2];\n\n\t//float **B = newMatrix( N, N);\n\n\t\n\n\tfor( time = 0; time+timeStep <= timeDifference; time += timeStep){\n\n\t\t//fprintf( stderr, \"%i. iteration:\\nSetup Matrix\\n\", (int)(time / timeStep + 0.5));\n\n\t\tint passedTime = clock();\n\n\t\tfprintf( stderr, \"Set Matrix... \\n\");\n\n\t\tsetupMatrixImplicit( voronoiDiagram, timeStep, 'G');\n\n\t\tfprintf( stderr, \"...finished ( %li clocks, %.3lf sec)\\n\", (clock() - passedTime), (float)(clock() - passedTime)/CLOCKS_PER_SEC);\n\n\n\n\t\t/*for(int m=0; m<N; m++){\n\n\t\t\tfor(int n=0; n<N; n++)\n\n\t\t\t\tfprintf( stderr, \"%6.0lf \", A[m][n]);\n\n\t\t\tfprintf( stderr, \"\\n\");\n\n\t\t}*/\n\n\t\t/*for(int m=0; m<N; m++){\n", "file_path": "tumor2d/src/finiteDifferences.cpp", "rank": 96, "score": 26.192642524970278 }, { "content": "\t\t\tsetupJacobianMatrixImplicitSteadyState( voronoiDiagram, J, x, 'G');\n\n\n\n\t\t\t// solve h*J = f\n\n\t\t\t//ConjugateGradientSparse( J, f, h, 2*N, 2);\n\n\t\t\t//fprintf( stderr, \"JacobiPreconditioner()\\n\");\n\n\t\t\t//SuccessiveOverRelaxationPreconditioner( J, M);\n\n\t\t\tJacobiPreconditioner( J, M);\n\n\t\t\t//fprintf( stderr, \"PreconditionedConjugateGradientSparse()\\n\");\n\n\t\t\tcg_err = PreconditionedConjugateGradientSparse( J, M, f, h, 2*N, 100);\n\n\n\n\t\t\t// update x = x + h\n\n\t\t\t//fprintf( stderr, \"vectorSum()\\n\");\n\n\t\t\tvectorSum( x, h, x, 2*N);\n\n\n\n\t\t\terr = sqrt( dotProduct( h, h, 2*N));\n\n\t\t\tit++;\n\n\n\n\n\n\t\t//}while( err > 1e-5 && it < 100);\n\n\t\t//fprintf( stderr, \"...finished after %i Newton Iterations -> error: %e\\n\", i, err);\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 97, "score": 26.108643222840918 }, { "content": "\n\n\t\t//// GLUCOSE ////////////////////\n\n\n\n\t\t// set A and b\n\n\t\t//fprintf( stderr, \"setupMatrixImplicitSteadyState()\\n\");\n\n\t\tsetupMatrixImplicitSteadyState( voronoiDiagram, 'G');\n\n\n\n\t\t// newton loop\n\n\t\tint it = 0;\n\n\t\t//do{\n\n//\t\t\tfprintf( stderr, \"Newton Iteration %i\\n\", (int)((time + timeStep)/timeStep));\n\n\t\t\t\n\n\t\t\t// set f = b - A*x\n\n\t\t\t//fprintf( stderr, \"sparseMatrixVectorProduct()\\n\");\n\n\t\t\tsparseMatrixVectorProduct( sA, x, f);\n\n\t\t\t//fprintf( stderr, \"vectorDifference()\\n\");\n\n\t\t\tvectorDifference( b, f, f, 2*N);\n\n\n\n\t\t\t// set J\n\n\t\t\t//fprintf( stderr, \"setupJacobianMatrixImplicitSteadyState()\\n\");\n", "file_path": "tumor2d/src/SparseMatrix.cpp", "rank": 98, "score": 25.966378176733638 }, { "content": "\n\n\n\nvoid matrixTranspose( double **Ai, double **Ao, int n, int m)\n\n{\n\n//#pragma omp parallel for\n\n\tfor( int i=0; i<n; i++)\n\n\t\tfor( int j=0; j<m; j++)\n\n\t\t\tAo[j][i] = Ai[i][j];\n\n\n\n}\n\n/*****************************************************************************/\n\n\n\n\n\nvoid matrixInversion( double **Ai, double **Ao, int n)\n\n{\n\n\t//double **A = newDoubleMatrix( n, n);//[n][n];\n\n\tdouble A[n][n];\n\n\n\n\t// Init Ao & A\n\n\tfor( int i=0; i<n; i++)\n", "file_path": "tumor2d/src/Mathematix.cpp", "rank": 99, "score": 25.811625187773895 } ]
C++
gpAux/extensions/gps3ext/test/s3utils_test.cpp
chrishajas/gpdb
564b9235a46e2ead1650b753b2d070796cced6f6
#include "s3utils.cpp" #include "gtest/gtest.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> TEST(Utils, simplecurl) { CURL *c = CreateCurlHandler(NULL); EXPECT_EQ(c, (void *)NULL); c = CreateCurlHandler("www.google.com"); EXPECT_NE(c, (void *)NULL); curl_easy_cleanup(c); } TEST(Utils, nth) { const char *teststr = "aaabbbcccaaatttaaa"; EXPECT_EQ(find_Nth(teststr, 0, "aaa"), -1); EXPECT_EQ(find_Nth(teststr, 1, "aaa"), 0); EXPECT_EQ(find_Nth(teststr, 2, "aaa"), 9); EXPECT_EQ(find_Nth(teststr, 3, "aaa"), 15); EXPECT_EQ(find_Nth(teststr, 1, "abc"), -1); EXPECT_EQ(find_Nth(teststr, 1, ""), 0); } #define MD5TESTBUF "abcdefghijklmnopqrstuvwxyz\n" TEST(Utils, md5) { MD5Calc m; m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); EXPECT_STREQ("e302f9ecd2d189fa80aac1c3392e9b9c", m.Get()); m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); EXPECT_STREQ("3f8c2c6e2579e864071c33919fac61ee", m.Get()); } #define TEST_STRING "The quick brown fox jumps over the lazy dog" TEST(Utils, sha256) { char hash_str[65] = {0}; EXPECT_TRUE(sha256_hex(TEST_STRING, hash_str)); EXPECT_STREQ("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", hash_str); } TEST(Utils, sha1hmac) { char hash_hex[41] = {0}; EXPECT_TRUE(sha1hmac_hex(TEST_STRING, (char *)hash_hex, "key", 3)); EXPECT_STREQ("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", hash_hex); } TEST(Utils, sha256hmac) { char hash_str[65] = {0}; EXPECT_TRUE(sha256hmac_hex(TEST_STRING, hash_str, "key", 3)); EXPECT_STREQ("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", hash_str); } TEST(Utils, ConfigNull) { Config c1(NULL); uint64_t value = 0; EXPECT_FALSE(c1.Scan("configtest", "config7", "%" PRIu64, &value)); Config c2(""); EXPECT_FALSE(c2.Scan("configtest", "config7", "%" PRIu64, &value)); string str; Config c3(str); EXPECT_FALSE(c3.Scan("configtest", "config7", "%" PRIu64, &value)); } TEST(Utils, Config) { Config c("data/s3test.conf"); EXPECT_EQ(c.Get("configtest", "config1", "aaaaaa"), "abcdefg"); EXPECT_EQ(c.Get("configtest", "config2", "tttt"), "12345"); EXPECT_EQ(c.Get("configtest", "config3", "tttt"), "aaaaa"); EXPECT_EQ(c.Get("configtest", "config4", "tttt"), "123"); EXPECT_EQ(c.Get("configtest", "config5", "tttt"), "tttt"); EXPECT_EQ(c.Get("configtest", "config6", "tttt"), "tttt"); EXPECT_EQ(c.Get("configtest", "config7", "xx"), "xx"); EXPECT_EQ(c.Get("configtest", "", "xx"), "xx"); EXPECT_EQ(c.Get("configtest", "config7", ""), ""); EXPECT_EQ(c.Get("configtest", "", "xx"), "xx"); uint64_t value = 0; EXPECT_TRUE(c.Scan("configtest", "config2", "%" PRIu64, &value)); EXPECT_EQ(value, 12345); EXPECT_TRUE(c.Scan("configtest", "config4", "%" PRIu64, &value)); EXPECT_EQ(value, 123); EXPECT_FALSE(c.Scan("configtest", "config7", "%" PRIu64, &value)); EXPECT_FALSE(c.Scan("", "config7", "%" PRIu64, &value)); EXPECT_FALSE(c.Scan("configtest", "", "%" PRIu64, &value)); EXPECT_FALSE(c.Scan("configtest", "config5", "%" PRIu64, &value)); char str[128]; EXPECT_TRUE(c.Scan("configtest", "config3", "%s", str)); EXPECT_STREQ(str, "aaaaa"); } TEST(Utils, UriCoding) { string src1 = "This is a simple & short test."; string src2 = "$ & < > ? ; # : = , \" ' ~ + %-_"; string src3 = "! * ' ( ) ; : @ & = + $ , / ? % # [ ]"; string src4 = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i " "j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 - _ . ~"; string dst1 = "This%20is%20a%20simple%20%26%20short%20test."; string dst2 = "%24%20%26%20%3C%20%3E%20%3F%20%3B%20%23%20%3A%20%3D%20%2C%20%22%20%27%" "20~%20%2B%20%25-_"; string dst3 = "%21%20%2A%20%27%20%28%20%29%20%3B%20%3A%20%40%20%26%20%3D%20%2B%20%24%" "20%2C%20%2F%20%3F%20%25%20%23%20%5B%20%5D"; string dst4 = "A%20B%20C%20D%20E%20F%20G%20H%20I%20J%20K%20L%20M%20N%20O%20P%20Q%20R%" "20S%20T%20U%20V%20W%20X%20Y%20Z%20a%20b%20c%20d%20e%20f%20g%20h%20i%" "20j%20k%20l%20m%20n%20o%20p%20q%20r%20s%20t%20u%20v%20w%20x%20y%20z%" "200%201%202%203%204%205%206%207%208%209%20-%20_%20.%20~"; EXPECT_EQ(dst1, uri_encode(src1)); EXPECT_EQ(dst2, uri_encode(src2)); EXPECT_EQ(dst3, uri_encode(src3)); EXPECT_EQ(dst4, uri_encode(src4)); EXPECT_EQ(src1, uri_decode(dst1)); EXPECT_EQ(src2, uri_decode(dst2)); EXPECT_EQ(src3, uri_decode(dst3)); EXPECT_EQ(src4, uri_decode(dst4)); } TEST(Utils, find_replace) { string str1 = "This is a simple & short test."; find_replace(str1, "simple", ""); EXPECT_EQ("This is a & short test.", str1); find_replace(str1, "short ", ""); EXPECT_EQ("This is a & test.", str1); find_replace(str1, "test.", ""); EXPECT_EQ("This is a & ", str1); find_replace(str1, "This", ""); EXPECT_EQ(" is a & ", str1); find_replace(str1, "is a", "abcdefghijklmn"); EXPECT_EQ(" abcdefghijklmn & ", str1); find_replace(str1, " a", "a"); EXPECT_EQ("abcdefghijklmn & ", str1); find_replace(str1, "abc", "abcabc"); EXPECT_EQ("abcabcdefghijklmn & ", str1); }
#include "s3utils.cpp" #include "gtest/gtest.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> TEST(Utils, simplecurl) { CURL *c = CreateCurlHandler(NULL); EXPECT_EQ(c, (void *)NULL); c = CreateCurlHandler("www.google.com"); EXPECT_NE(c, (void *)NULL); curl_easy_cleanup(c); } TEST(Utils, nth) { const char *teststr = "aaabbbcccaaatttaaa"; EXPECT_EQ(find_Nth(teststr, 0, "aaa"), -1); EXPECT_EQ(find_Nth(teststr, 1, "aaa"), 0); EXPECT_EQ(find_Nth(teststr, 2, "aaa"), 9); EXPECT_EQ(find_Nth(teststr, 3, "aaa"), 15); EXPECT_EQ(find_Nth(teststr, 1, "abc"), -1); EXPECT_EQ(find_Nth(teststr, 1, ""), 0); } #define MD5TESTBUF "abcdefghijklmnopqrstuvwxyz\n" TEST(Utils, md5) { MD5Calc m; m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); EXPECT_STREQ("e302f9ecd2d189fa80aac1c3392e9b9c", m.Get()); m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); m.Update(MD5TESTBUF, strlen(MD5TESTBUF)); EXPECT_STREQ("3f8c2c6e2579e864071c33919fac61ee", m.Get()); } #define TEST_STRING "The quick brown fox jumps over the lazy dog" TEST(Utils, sha256) { char hash_str[65] = {0}; EXPECT_TRUE(sha256_hex(TEST_STRING, hash_str)); EXPECT_STREQ("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", hash_str); } TEST(Utils, sha1hmac) { char hash_hex[41] = {0}; EXPECT_TRUE(sha1hmac_hex(TEST_STRING, (char *)hash_hex, "key", 3)); EXPECT_STREQ("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", hash_hex); } TEST(Utils, sha256hmac) { char hash_str[65] = {0}; EXPECT_TRUE(sha256hmac_hex(TEST_STRING, hash_str, "key", 3)); EXPECT_STREQ("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", hash_str); } TEST(Utils, ConfigNull) { Config c1(NULL); uint64_t value = 0; EXPECT_FALSE(c1.Scan("configtest", "config7", "%" PRIu64, &value)); Config c2(""); EXPECT_FALSE(c2.Scan("configtest", "config7", "%" PRIu64, &value)); string str; Config c3(str); EXPECT_FALSE(c3.Scan("configtest", "config7", "%" PRIu64, &value)); } TEST(Utils, Config) { Config c("data/s3test.conf"); EXPECT_EQ(c.Get("configtest", "config1", "aaaaaa"), "abcdefg"); EXPECT_EQ(c.Get("configtest", "config2", "tttt"), "12345"); EXPECT_EQ(c.Get("configtest", "config3", "tttt"), "aaaaa"); EXPECT_EQ(c.Get("configtest", "config4", "tttt"), "123"); EXPECT_EQ(c.Get("configtest", "config5", "tttt"), "tttt"); EXPECT_EQ(c.Get("configtest", "config6", "tttt"), "tttt"); EXPECT_EQ(c.Get("configtest", "config7", "xx"), "xx"); EXPECT_EQ(c.Get("configtest", "", "xx"), "xx"); EXPECT_EQ(c.Get("configtest", "config7", ""), ""); EXPECT_EQ(c.Get("configtest", "", "xx"), "xx"); uint64_t value = 0; EXPECT_TRUE(c.Scan("configtest", "config2", "%" PRIu64, &value)); EXPECT_EQ(value, 12345); EXPECT_TRUE(c.Scan("configtest", "config4", "%" PRIu64, &value)); EXPECT_EQ(value, 123); EXPECT_FALSE(c.Scan("configtest", "config7", "%" PRIu64, &value)); EXPECT_FALSE(c.Scan("", "config7", "%" PRIu64, &value)); EXPECT_FALSE(c.Scan("configtest", "", "%" PRIu64, &value)); EXPECT_FALSE(c.Scan("configtest", "config5", "%" PRIu64, &value)); char str[128]; EXPECT_TRUE(c.Scan("configtest", "config3", "%s", str)); EXPECT_STREQ(str, "aaaaa"); } TEST(Utils, UriCoding) { string src1 = "This is a simple & short test."; string src2 = "$ & < > ? ; # : = , \" ' ~ + %-_"; string src3 = "! * ' ( ) ; : @ & = + $ , / ? % # [ ]"; string src4 = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i " "j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 - _ . ~"; string dst1 = "This%20is%20a%20simple%20%26%20short%20test."; string dst2 = "%24%20%26%20%3C%20%3E%20%3F%20%3B%20%23%20%3A%20%3D%20%2C%20%22%20%27%" "20~%20%2B%20%25-_"; string dst3 = "%21%20%2A%20%27%20%28%20%29%20%3B%20%3A%20%40%20%26%20%3D%20%2B%20%24%" "20%2C%20%2F%20%3F%20%25%20%23%20%5B%20%5D"; string dst4 = "A%20B%20C%20D%20E%20F%20G%20H%20I%20J%20K%20L%20M%20N%20O%20P%20Q%20R%" "20S%20T%20U%20V%20W%20X%20Y%20Z%20a%20b%20c%20d%20e%20f%20g%20h%20i%" "20j%20k%20l%20m%20n%20o%20p%20q%20r%20s%20t%20u%20v%20w%20x%20y%20z%" "200%201%202%203%204%205%206%207%208%209%20-%20_%20.%20~"; EXPECT_EQ(dst1, uri_encode(src1)); EXPECT_EQ(dst2, uri_encode(src2)); EXPECT_EQ(dst3, uri_encode(src3)); EXPECT_EQ(dst4, uri_encode(src4)); EXPECT_EQ(src1, uri_decode(dst1)); EXPECT_EQ(src2, uri_decode(dst2)); EXPECT_EQ(src3, uri_decode(dst3)
"); EXPECT_EQ("This is a & ", str1); find_replace(str1, "This", ""); EXPECT_EQ(" is a & ", str1); find_replace(str1, "is a", "abcdefghijklmn"); EXPECT_EQ(" abcdefghijklmn & ", str1); find_replace(str1, " a", "a"); EXPECT_EQ("abcdefghijklmn & ", str1); find_replace(str1, "abc", "abcabc"); EXPECT_EQ("abcabcdefghijklmn & ", str1); }
); EXPECT_EQ(src4, uri_decode(dst4)); } TEST(Utils, find_replace) { string str1 = "This is a simple & short test."; find_replace(str1, "simple", ""); EXPECT_EQ("This is a & short test.", str1); find_replace(str1, "short ", ""); EXPECT_EQ("This is a & test.", str1); find_replace(str1, "test.", "
random
[ { "content": "SELECT regexp_split_to_array('the quick brown fox jumped over the lazy dog', '');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 0, "score": 651884.2648369842 }, { "content": "SELECT regexp_split_to_array('the quick brown fox jumped over the lazy dog', 'nomatch');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 1, "score": 635491.5349505515 }, { "content": "SELECT regexp_split_to_array('the quick brown fox jumped over the lazy dog', $re$\\s+$re$);\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 2, "score": 614234.7740103761 }, { "content": "SELECT regexp_split_to_array('the quick brown fox jumped over the lazy dog', $re$\\s*$re$);\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 3, "score": 614234.7740103761 }, { "content": "select foo from regexp_split_to_table('the quick brown fox jumped over the lazy dog',E'\\\\\\s+') AS foo;\n\n\n", "file_path": "src/test/regress/sql/regex_gp.sql", "rank": 4, "score": 608269.5814849548 }, { "content": "SELECT errfunc1('The quick brown fox jumps over the lazy dog');\n", "file_path": "src/interfaces/gppc/test/sql/gppc_basic.sql", "rank": 5, "score": 587025.5017537896 }, { "content": "SELECT foo, length(foo) FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog', '') AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 6, "score": 582790.1299645326 }, { "content": "select a, decode(a, 10, 'J', 11, 'K', 12, 'L', 13, 'M', 14, 'N', 15, 'O', 16, 'P', 'Z') as decode_nomatch_def\n\n from decodeint order by a, b;\n\n\n\nbegin;\n", "file_path": "src/test/regress/sql/decode_expr.sql", "rank": 7, "score": 572870.8373423017 }, { "content": "-- no match of pattern\n\nSELECT foo, length(foo) FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog', 'nomatch') AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 8, "score": 570737.8673855043 }, { "content": "-- split string on regexp\n\nSELECT foo, length(foo) FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog', $re$\\s+$re$) AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 9, "score": 555753.7518646568 }, { "content": "SELECT foo, length(foo) FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog', $re$\\s*$re$) AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 10, "score": 555745.8650193124 }, { "content": "SELECT regexp_split_to_array('thE QUick bROWn FOx jUMPed ovEr THE lazy dOG', 'e', 'g');\n\n\n\n-- change NULL-display back\n\n\\pset null ''\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 11, "score": 521015.7517940594 }, { "content": "select a, decode(a, 1, 'A', 2, 'B', 3, 'C', 4, 'D', 5, 'E', 'Z') as decode from decodeint order by a, b;\n", "file_path": "src/test/regress/sql/decode_expr.sql", "rank": 12, "score": 511857.55372913287 }, { "content": "select a, decode(a, 10, 'J', 11, 'K', 12, 'L', 13, 'M', 14, 'N', 15, 'O', 16, 'P') as decode_nomatch\n\n from decodeint order by a, b;\n", "file_path": "src/test/regress/sql/decode_expr.sql", "rank": 13, "score": 507925.62322701304 }, { "content": "SELECT regexp_split_to_array('thE QUick bROWn FOx jUMPed ovEr THE lazy dOG', 'e', 'i');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 14, "score": 490388.129766476 }, { "content": "SELECT regexp_split_to_array('thE QUick bROWn FOx jUMPed ovEr THE lazy dOG', 'e', 'iz');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 15, "score": 485172.56309676694 }, { "content": "select decode(10, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, null, 1);\n\n\n", "file_path": "src/test/regress/sql/decode_expr.sql", "rank": 16, "score": 474119.4685844127 }, { "content": "select decode(11, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, null);\n", "file_path": "src/test/regress/sql/decode_expr.sql", "rank": 17, "score": 463668.7317699437 }, { "content": "struct RemoveConstFromKey<std::pair<const K, V> > {\n\n typedef std::pair<K, V> type;\n\n};\n\n\n\n// Mapping from booleans to types. Similar to boost::bool_<kValue> and\n\n// std::integral_constant<bool, kValue>.\n\ntemplate <bool kValue>\n", "file_path": "gpAux/extensions/gmock/include/gmock/internal/gmock-internal-utils.h", "rank": 18, "score": 458354.3683861253 }, { "content": "-- global option meaningless for regexp_split\n\nSELECT foo, length(foo) FROM regexp_split_to_table('thE QUick bROWn FOx jUMPed ovEr THE lazy dOG', 'e', 'g') AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 19, "score": 458165.7253456337 }, { "content": "struct RemoveConstFromKey<std::pair<const K, V> > {\n\n typedef std::pair<K, V> type;\n\n};\n\n\n\n// Mapping from booleans to types. Similar to boost::bool_<kValue> and\n\n// std::integral_constant<bool, kValue>.\n\ntemplate <bool kValue>\n", "file_path": "gpAux/extensions/gmock/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 20, "score": 453346.0581516874 }, { "content": "SELECT foo FROM regexp_split_to_table('the quick brown fox', E'\\\\s*') AS foo;\n\n\n", "file_path": "src/test/regress/sql/regex_gp.sql", "rank": 21, "score": 444268.1432540099 }, { "content": "-- Null inputs should return NULL\n\nSELECT SUBSTRING('abcdefg' FROM '(b|c)' FOR NULL) IS NULL AS \"True\";\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 22, "score": 440790.5356767133 }, { "content": "select a, decode(a, 1, 'A', 2, 'B', 3, 'C', 4, 'D', 5, 'E') as decode from decodeint order by a, b;\n", "file_path": "src/test/regress/sql/decode_expr.sql", "rank": 23, "score": 438278.84295260184 }, { "content": "SELECT regexp_replace('AAA', '^|$', 'Z', 'g');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 24, "score": 435934.7248635334 }, { "content": "-- case insensitive\n\nSELECT foo, length(foo) FROM regexp_split_to_table('thE QUick bROWn FOx jUMPed ovEr THE lazy dOG', 'e', 'i') AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 25, "score": 434690.2233983745 }, { "content": "-- errors\n\nSELECT foo, length(foo) FROM regexp_split_to_table('thE QUick bROWn FOx jUMPed ovEr THE lazy dOG', 'e', 'zippy') AS foo;\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 26, "score": 430068.863692821 }, { "content": "select x, select_f(x) from (values (0), (1), (2), (3), (4), (5), (6)) r(x);\n\n\n", "file_path": "src/test/regress/sql/select.sql", "rank": 27, "score": 422939.8034393422 }, { "content": "-- invalid regexp option\n\nSELECT regexp_replace('AAA aaa', 'A+', 'Z', 'z');\n\n\n\n-- set so we can tell NULL from empty string\n\n\\pset null '\\\\N'\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 28, "score": 421788.07125214767 }, { "content": "-- PostgreSQL extension to allow using back reference in replace string;\n\nSELECT regexp_replace('1112223333', E'(\\\\d{3})(\\\\d{3})(\\\\d{4})', E'(\\\\1) \\\\2-\\\\3');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 29, "score": 419908.16341829987 }, { "content": "-- From Python List of values\n\nSELECT test_return_setof_bytea(E'[None, True, \"value\", [1], {\"\\\\0\": \"B\"}]');\n\nSELECT * FROM test_return_setof_bytea(E'[None, True, \"value\", [1], {\"\\\\0\": \"B\"}]');\n", "file_path": "src/pl/plpython/sql/plpython_returns.sql", "rank": 30, "score": 404742.79867387575 }, { "content": "SELECT test_return_setof_bytea(E'[None, True, \"value\", [1], {\"\\\\0\": \"B\"}]') \n\nFROM gp_single_row;\n\n\n\n\n\n-- Error conditions\n\n\n", "file_path": "src/pl/plpython/sql/plpython_returns.sql", "rank": 31, "score": 404734.9266248325 }, { "content": "select string_to_array('1|2|3', NULL);\n", "file_path": "src/test/regress/sql/arrays.sql", "rank": 32, "score": 403821.7136952308 }, { "content": "SELECT regexp_replace('AAA aaa', 'A+', 'Z', 'gi');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 33, "score": 396848.6806611585 }, { "content": "SELECT regexp_replace('AAA BBB CCC ', E'\\\\s+', ' ', 'g');\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 34, "score": 393650.44070776325 }, { "content": "SELECT E'1&(''2''&('' 4''&(\\\\|5 | ''6 \\\\'' !|&'')))'::tsquery;\n\nSELECT $$'\\\\as'$$::tsquery;\n\n\n\nSELECT 'a' < 'b & c'::tsquery as \"true\";\n\nSELECT 'a' > 'b & c'::tsquery as \"false\";\n\nSELECT 'a | f' < 'b & c'::tsquery as \"true\";\n\nSELECT 'a | ff' < 'b & c'::tsquery as \"false\";\n\nSELECT 'a | f | g' < 'b & c'::tsquery as \"false\";\n\n\n", "file_path": "src/test/regress/sql/tstypes.sql", "rank": 35, "score": 390374.64672741794 }, { "content": "select string_agg(a,',') from (values(null),(null)) g(a);\n\n\n", "file_path": "src/test/regress/sql/aggregates.sql", "rank": 36, "score": 389864.2041823863 }, { "content": "select 1 a, NULL b, NULL c UNION SELECT 2, 3, NULL UNION SELECT 3, NULL, 4;\n\n\n", "file_path": "src/test/regress/sql/union_gp.sql", "rank": 37, "score": 389698.70414041536 }, { "content": "SELECT SUBSTRING('abcdefg' FROM NULL FOR '#') IS NULL AS \"True\";\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 38, "score": 384980.37779050623 }, { "content": "select lower(\"B B\") \"B_B\", upper (\"C\") C, (\"D+1\") \"D+1\" from xyz1;\n\n-- end_equiv\n\n\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 39, "score": 377310.1293101104 }, { "content": "select upper(\"C\") \"C\", lower (\"B B\") \"%B_B%\", \"D+1\" \"D+1\" from xyz1;\n\n-- end_equiv\n\n\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 40, "score": 377310.1293101104 }, { "content": "select md5('abc') = '900150983cd24fb0d6963f7d28e17f72' AS \"TRUE\";\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 41, "score": 376235.8241877161 }, { "content": "select string_agg(a,',') from (values(null),(null),('bbbb'),('cccc')) g(a);\n", "file_path": "src/test/regress/sql/aggregates.sql", "rank": 42, "score": 370700.8510652224 }, { "content": "select upper(\"B B\") \"B_B\", lower (\"C\") C, (\"D+1\"||'9_nine') \"D+1\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 43, "score": 369541.45736161317 }, { "content": "class FooTest : public ::testing::TestWithParam<const char*> {\n\n // You can implement all the usual class fixture members here.\n\n};\n\n\n\n// Then, use the TEST_P macro to define as many parameterized tests\n\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n\n// or \"pattern\", whichever you prefer to think.\n\n\n\nTEST_P(FooTest, DoesBlah) {\n\n // Inside a test, access the test parameter with the GetParam() method\n\n // of the TestWithParam<T> class:\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n ...\n\n}\n\n\n\nTEST_P(FooTest, HasBlahBlah) {\n\n ...\n\n}\n\n\n\n// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test\n", "file_path": "gpAux/extensions/gtest/include/gtest/gtest-param-test.h", "rank": 44, "score": 366240.9290492021 }, { "content": "select lower(\"B B\") \"B_B\", lower (\"C\") C, substr(\"D+1\",1,1) \"D+1\" from xyz1;\n\n-- end_equiv\n\n\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 45, "score": 364716.58418794133 }, { "content": "select upper(\"B B\") \"B_B\", lower (\"C\") C, substr(\"D+1\",1,1) \"D+1%\" from xyz1;\n\n-- end_equiv\n\n\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 46, "score": 364716.58418794133 }, { "content": "SELECT E'''1 \\\\''2'' '' 3'' 4 '::tsvector;\n\nSELECT $$'\\\\as' ab\\c ab\\\\c AB\\\\\\c ab\\\\\\\\c$$::tsvector;\n", "file_path": "src/test/regress/sql/tstypes.sql", "rank": 47, "score": 364299.0417646116 }, { "content": "select md5('abc'::bytea) = '900150983cd24fb0d6963f7d28e17f72' AS \"TRUE\";\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 48, "score": 363852.6797996606 }, { "content": "-- doesn't work because cannot have nested declaration in template\n\ncreate table ggg (a char(1), b char(2), d char(3), e int)\n\ndistributed by (a)\n\npartition by hash (b)\n\nsubpartition by hash (d) \n\nsubpartition template ( \n\nsubpartition cc (subpartition ee, subpartition ff),\n\nsubpartition dd (subpartition ee, subpartition ff)\n\n), \n\nsubpartition by hash (e) \n\n(\n\npartition aa,\n\npartition bb\n\n);\n\n\n", "file_path": "src/test/regress/sql/partition1.sql", "rank": 49, "score": 363706.0081676196 }, { "content": "-- mixed inline subpartition declarations with templates\n\ncreate table ggg (a char(1), b char(2), d char(3), e numeric)\n\ndistributed by (a)\n\npartition by hash (b)\n\nsubpartition by hash (d) , \n\nsubpartition by hash (e) \n\nsubpartition template ( \n\nsubpartition ee,\n\nsubpartition ff\n\n) \n\n(\n\npartition aa (subpartition cc, subpartition dd),\n\npartition bb (subpartition cc, subpartition dd)\n\n);\n\n\n", "file_path": "src/test/regress/sql/partition1.sql", "rank": 50, "score": 363706.0081676195 }, { "content": "-- start_equiv\n\nselect lower(\"B B\") AS \"B_B\", upper (\"C\") AS C, (\"D+1\") AS \"D+1\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 51, "score": 362796.6721276122 }, { "content": "-- start_equiv\n\nselect upper(\"C\") AS \"C\", lower (\"B B\") AS \"%B_B%\", \"D+1\" AS \"D+1\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 52, "score": 362796.6721276122 }, { "content": "select C.j from C where not exists (select max(B.i) from B where C.i = B.i having max(B.i) is not null) order by C.j;\n", "file_path": "src/test/regress/sql/qp_correlated_query.sql", "rank": 53, "score": 358034.9190106753 }, { "content": "select lower(\"C\") \"%C%\", upper (\"B B\") \"BB\", \"D+1\"||'9_nine' \"D+1\" from xyz1;\n\n-- end_equiv\n\n\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 54, "score": 357201.6646639874 }, { "content": "-- start_equiv\n\nselect upper(\"B B\") AS \"B_B\", lower (\"C\") AS C, (\"D+1\"||'9_nine') AS \"D+1\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 55, "score": 356036.8883394009 }, { "content": "-- No match should return NULL\n\nSELECT SUBSTRING('abcdefg' FROM '#\"(b_d)#\"%' FOR '#') IS NULL AS \"True\";\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 56, "score": 353371.2288855983 }, { "content": "-- Test column lookup works\n\ncreate table ggg (a char(1), b char(2), d char(3))\n\ndistributed by (a)\n\npartition by hash(doesnotexist)\n\npartitions 3;\n\n\n", "file_path": "src/test/regress/sql/partition1.sql", "rank": 57, "score": 353142.7960618657 }, { "content": "select upper(\"B B\") \"B_B\", upper (\"C\") C, substr(\"D+1\",1,1) \"D\" from xyz1;\n\n-- end_equiv\n\n\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 58, "score": 352463.25511658454 }, { "content": "-- start_equiv\n\nselect upper(\"B B\") AS \"B_B\", lower (\"C\") AS C, substr(\"D+1\",1,1) AS \"D+1%\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 59, "score": 352119.1632370569 }, { "content": "-- start_equiv\n\nselect lower(\"B B\") AS \"B_B\", lower (\"C\") AS C, substr(\"D+1\",1,1) AS \"D+1\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 60, "score": 352119.1632370569 }, { "content": "create table ggg (a char(1), b char(2), d char(3));\n\ninsert into ggg values ('x', 'a', 'c');\n\ninsert into ggg values ('x', 'a');\n\ninsert into ggg values ('x');\n\n\n", "file_path": "src/test/regress/sql/gp_optimizer.sql", "rank": 61, "score": 351037.4093522389 }, { "content": "SELECT SUBSTRING(NULL FROM '(b|c)' FOR '#') IS NULL AS \"True\";\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 62, "score": 348206.6680170754 }, { "content": "#define ERRCODE_E_R_I_E_NULL_VALUE_NOT_ALLOWED\tMAKE_SQLSTATE('3','9', '0','0','4')\n", "file_path": "src/include/utils/errcodes.h", "rank": 63, "score": 347865.692338887 }, { "content": "select nvl2(NULL::text, 'B', 'C');\n", "file_path": "gpAux/extensions/orafce/sql/gp-orafunk.sql", "rank": 64, "score": 343878.9813424245 }, { "content": "-- start_equiv\n\nselect lower(\"C\") AS \"%C%\", upper (\"B B\") AS \"BB\", \"D+1\"||'9_nine' AS \"D+1\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 65, "score": 343697.0956417751 }, { "content": "create table xyz_ctas2 as (select \"B B\" \"B+1\", \"C\" \"_%A\", \"D+1\" \"D\" from xyz) DISTRIBUTED RANDOMLY;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 66, "score": 343341.0209198706 }, { "content": "-- start_equiv\n\nselect upper(\"B B\") AS \"B_B\", upper (\"C\") AS C, substr(\"D+1\",1,1) AS \"D\" from xyz1;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 67, "score": 340094.6752397984 }, { "content": "create table orca.t ( timest character varying(6), user_id numeric(16,0) not null, to_be_drop char(5), tag1 char(5), tag2 char(5)) \n\ndistributed by (user_id) \n\npartition by list (timest) (partition part201203 values('201203') with (appendonly=true, compresslevel=5, orientation=column), partition part201204 values('201204') with (appendonly=true, compresslevel=5, orientation=row), partition part201205 values('201205'));\n\n\n\ninsert into orca.t values('201203',0,'drop', 'tag1','tag2');\n\n\n", "file_path": "src/test/regress/sql/gp_optimizer.sql", "rank": 68, "score": 338157.31375906605 }, { "content": "-- Invalid use of RANGE boundary specification in partition \"cc\" of \n\n-- type HASH (at depth 2)\n\ncreate table ggg (a char(1), b char(2), d char(3), e int) distributed by (a)\n\npartition by hash (b) subpartition by hash (d),\n\nsubpartition by hash (e) \n\nsubpartition template ( subpartition ee, subpartition ff ) (\n\npartition aa (subpartition cc, subpartition dd), partition bb\n\n(subpartition cc start ('a') , subpartition dd) );\n\n\n", "file_path": "src/test/regress/sql/partition1.sql", "rank": 69, "score": 338097.46360180445 }, { "content": "-- With a parenthesized subexpression, return only what matches the subexpr\n\nSELECT SUBSTRING('abcdefg' FROM 'b(.*)f') AS \"cde\";\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 70, "score": 337156.01772053854 }, { "content": "create table mmm_l1 (a char(1), b char(1), d char(3))\n\ndistributed by (a)\n\npartition by list (b)\n\n(\n\npartition aa values ('a', 'b', 'c'),\n\npartition bb values ('d', 'e', 'f'),\n\npartition cc values ('g', 'h', 'i')\n\n);\n\n\n", "file_path": "src/test/regress/sql/partition1.sql", "rank": 71, "score": 337078.9845912449 }, { "content": "UPDATE uao_update_toast SET c = 'sIyI/Ynw/BliTF5FTltp/BQgVpo2aSxT6qXI0+xJc8VnFJ4XPFyFV9V2b1qHhfmLpbEHOW2APhtuJYwk5z2JbXltD1yOY1mgHJ9NH4rwxHMvOwMBOQkqx/WH7wH+QY6DckUhbdzooSgGnaPZNc5J/KsxPhVb2AsiQDB4O2Kwb0dIe6DHVRtRDHxSfueTBgVNANGO1AG5hp/UTuiWF2TJRFQEAKeU9BfNTIwUl/gEgTmZT8WP4OyH0jMi6sNj42D19t7oNx6P46OY0VndlpDB8X0Ilg1n3TAJ8iRJQCCEVCjgc2jzaSKJrsZ+VYcoOBFYgXhARevfvLLJcPbPmVZVitkCcq4JHF0JplwATsyJopGpppnsE68XNe/T5sj3UgMfUYzjkmTsM1ty5BpwAx/8quwSe0BoI/Kqi3ZqWjS1mTtHyZB5DeP0xxrKn7mNgbrRgdcpP+52c5lQMxXLcl+IvPJWH+SnzeDQrCHS0Ylu2M24q25FCJlSBcjcEKMig+PE0ct6w2QcXB3cMruMJsueJQg6xZxkhYeMzysbAzo0mj9whGzoeWWFlz6KwXbW6GSvH/AsNMR5JprnkSFzuzUNJBGh/0AmYAJ1K8N1FSVhwYH2UCm6mQMEydD9U/YMvGWa2S2yH2ShMtW/+Pw0N4TrA1yVFnAMAUBe0tGX6QO3Tm3DKjFv3T9GhJ8DDrxEOftUq2i0cOVDa8Ul5ZdIZ3V8sa3l4mtBrRNGiVbNl3LD/9Juf3s6AAE5MgvTtSNYS1uVOzYeuse/669ZNgo1xc0TQ5qpozHvdCAQPTM5uEOKuK18vs5eEh+KgfKa1IGxg5nU/t5Jmwwcoc9FYcA4vqZDb+dPBnNW/Bd4oql9Xe5S5kNFC5xhTyuEttCWPPAGWdYTzio1nnFFnTyn3uuwtNCggoSI2iP1dlfjmNhGHYOjlSerEElpz6obY2oIz5j0LXVPX04BJjXUP+0OXRe+HaGwVPShVbSBZgcFu07aXuFLMA5ZQBrsgsZMbLYi7PtFCQYpiYaLJ2vp44FAAS5zx6/sLjVdQLY22aVCmN/YmktcS4dMOtQ/bZUbichftUnG9sve5hM0ePsbbkCgILHbpw2hL8aK0I1a8PoAHVhnLrAbATd4qvlCGCcI6QFWTeFu+EWVVWQBDitKCF/j1O4/Alu6xXFjto4bnDXYSsSELK3a+bPJWpx+9lIWlziWThyeRCIq6AbwD4+71OVJaK/USJMBfyQV0O+3AyKz1I0UcvU+yqUXq3j86R1FcPvMCgGP0ANAkFpf8S55Ra17df3OIgP6GSbF8g3Mk46oZnkF+IyTIZ9x4Yab2aer9lMb+qqvlAcoxXftrHl8pfMXAf5yqAN5tXBb+4Sq/9kMChrkLSuNeeYjmzFNbO2+smu9yvba9YFyjhmxdePQltxyt8eDYEvGbnUgXIsn3Gngkh7hzPW2Ao7m8uWPZ37HV5Jfm0rukubMD149IocSwnX1UYzAigBSZUc9vl91AHOc/1Q1ePDzR4egM1fJPoDeKAsDOr37UhF3DLeEbusSetvlkrvY6eV2ER1fiZI9IMdmjqUbRabp8F814eyvx54HMKpA/QhEXXdFsEJvwkVcH5ApFU1FXh7le7mSHHN8HaUsG5R93W0w7gCtxCAxVIu01ChXqni7EyVDTM7Qq+7y4+0P6jjrOQhy0CcImO4hPWy7kt3DUQ1SIWTOE1TPnCwiup1aWztJBGI8cogOVZMrEnIfdvnJXKtPeNSnct9UdlO/GnSJ1qGuuGuR6WP62XUn1Ax4GO61gFoR14RG1IzA6SXN0yE6b6AZFrDkE7QgnetvDXOF47uA4kQYUrrkrJptHPaU2iOzDK4hVNziHvBAozPEqrG+dD7q4qYpk/R0LV5HGNEpn33WAJwn5FOXanIgQJsKqMdzD2ELMY4S6utGmxx1waDi8dX642to9q0yaemblI6jbY1j7fCave6QkFRaKnmbk7IPB6BDwgu1dwTjxFDov5jtki2NCmLZb9WlVS/NWNoSx7kK4GcsOEhWszVSRjM0GpmEmLMJgQNrcoUb8aANCKy0UFqRZyflC9Gu30jc8Tx0Cb0+PJt6Z/l15n5zOhpsBJD2CCHBfKddor2DwPbutjthLGwFx9bigkAnP9bRPy72AgP/SNLOCyilKGjybhYMo2FSsH6Mh+5f9AsZse0mmY3i+cUiwk+gKfbJ/SJWlG6An9zauNyYFbGt3SmG/QCw7sxjrc9G+dVVBNZASkNGDQz8xg4OpRi4ZyVBTr1kd/b6KR2P44KqN1kGpQRT5mhfT1CefAvqy36YsTrjFYwgjc4O/DioVi25o1a5qt3oqtH8TgqpWFnPIVChm1vblUV8xKbdJ6dQXe5CaksigAQo2ynpDbCpNwWEGm3VmyGCgWnh6PNuxU779YptR8HSwfN6KGL1iRihPq38ohxA/TGGpXhzKPAcKXRZ+d1q/3vCx8xZBwweDA5J4LDb4AppGh/sYzeHmLod42g6XAz4CdIDgJUg35ZTyamUMr60d9CPeVi95CaiGheGCXAyvrHVTxXYlhVw8QI3ZOCimQVbdSQDYHDnWhK6wzjD77vR92qMOzoSd5w09mnfw2ZNqtHXUUlZeW9JVn9PW7W+vbjIhjHDxz398pPsAqzHjQFqegZo3+tSH3BAnNxLHDiI5hKm2Y2/6nV1O//A8U2KQ9rv635QWokuTeGdV4ItMwNPhhKQHB6WqDIv3dMkKkIlBtt9uWMFZOG89biuSJJjydgzeW4EfFLqyQMQ5L5d2RyCzCjMe0XbvTEaA/rASs2tan1eMSrexpiq+eAc3w4HP5zw7YW1IJFpBVbyYt4UQNYYO7sKUK7GfGkzTKE0rHm5MHECn8QXl00YC/jz58xSThQdYvxmEmwyqDMkPTH8WHWtpHJ1Zvkn3n4Z/v3KVU8ijLfX9QuMb4aIsx4KPvf6TSuiOeYNemrB+FF5ExLlC/pazJj6pELOlGIuS5YjNDWxfLT4hZNpOXxwagbdtNBdkpPjw+SW3JUDHOizXSaiYbYyuCHsfi9m0yRerDHEUmUwIXJtWrusr7t9i2S29AValDiNVH8BLxi7KjW5pRuY+u/3hTHXmB8U/YcUFNwZzTokzYBxVW2aDJ1boXrtpEvKpwGKp73aCGkoVAVrLyvXtdMhkTuvyJG3v0Hq6ePelH3ie/9SuQ5UP+K3yqyz9et60ArZXM8dPaaHOYINUheiA/YqysepCy24S3xW8MlH5LT51FadfcLlQq/kz+MF79v7papxJXphgI8VfU7oM1v+tZv1y1ajeZ2FmfTGGP/hjLAcoPmStDqFo1nfhIKvdXmTH7IY6xQna8Uh/UKtrcXXIzvevgKYBa/CDW72gWK9vR5r0STnwTCct1aeCOjsh64bZkTM3tktU4owR+nenSuJ3FfXKan0wCQLrCo/Ywd8583DaOrIjc3H7RYkOvZoPkqO3F6LmXuxsCqU1FvPSnSfWOs+z/TWTsRmMDQk0DIAYyPs/SjMO2ISO3VbuD61XHenQ9PCUz6xtI+ivSGEeREp7EvDdKgZ4Bj0qB03Fodx7N7vt6vDh9JtcSZEe+1dqiDOtzbfy+OuoZD1wOuPTW0NW3aeAamd70NcBBCcN9Vm9gwkiVlVzw/jKIiv3YJcWz5rAUDefKv98tkbwQw6iZRwsu/OQPKQY8i7fbbB+RimDMxBhAzjTsF0XzHFAR5EcdUoKMRsOrOQXU4NcWx8S9cYqtI1o8RMv8ICaxB+bHnXzuF5LzRmtcuC0dJZlj3V9imzJeT1+mx70dzBXwHqDweYVYTTRCRzmaHgq9uRAcUqTeFhMSnCmmlwukl3MVBTxdnsASBeDlp/A5PxUZaFBll9W8aNTXUrrIt2j8vuznYID3buiAn/Bcvo7YfKO7tgtJVpDrXqNJKQvA4NWBxXDyZqo8xQF73EnwEOsJc+D7/RTf+Y9D5zXbZ+ufvMGkKaMFd4n+17PyMJ3nxFRw0+EieGJX0AIvA/69KBxcJ7U5RJ4prHKOiyUbH36hZka8qBd4dTUdEUjGzcf3iR21bIHdf0eeXjpcykbrxkQ62YDDWl1buTrYGvypBtC+bGzkKCXoHSKigod0i4nmV5h7qSZe3OtG69o7i9khd7stoglQEHQegVeHZkq/T3dIXhX8Z2tFvVLJr/40h18g2JHUpZQsp1ejjJ7/woTXCtEER1LQi0kUT/5XPmRqzAR6kEAQvsDSjH2wizytBYb5IEddAf9dkCBEAOfwK3I6AVXijz5FScxSMislBaA6MDf4HAXzmJhgePdgdPoxYIoF9w/xrnBQW9BocBNBP+e6uYRrx4B1gI35rfXhIF0R4iIYBULFUYT9gnOw6swlsiGmqtfLsLzyw0WABD4Za1dT+WhsMFHAf8oo8RjW1RgbeGkbZk9Sr10GfL9aqianmOOOg7s7LYuvN/ppLtmA29YKUKKQktB7AMmkN2SOT54W8ykc+8bt0kgOhmjz5UPxqC/n4dHv0apCG5ORElv9fXAPxaTSLxs6ngmTchuGJmVS7liH+pxtstDysf6fMPA4E6sfX7/+0rKYXdIH1JQIxUePzvuV1wXcUKfW8YWdBT6KyVDRyOFjSlwbuo3QRMLf+dgz7SujqD7Ba550K/Zt/ALNouF2+q13jNYQ5EJsgHcc+uT0b6kkHuOI7SuqMZA/kRYufl3/ZzLWpGjuVKPztT7YY3MsgyBNfkQehXBvnjRfl51mrppQXoVejKkMJR+b/bcLZ1hPnf7ss4NNSdyu9yMsCX0bneqpwe2tZsa3kgsFNNZuTlLE4YwneaRwZC/OkYgHXyM8SWVa87fSQfyrx5ZAQ4v9vc3R4UAaezT2bYk9JKM+AJg96CUp7+VGGk3U6Ij7LbahTCG/4OxhX484PZ7VksEV5+kK36b6pZK8ec6WM2CJUO0KychYE0t3mdCmvRCfGzaYOQpm23+go6NmutxKx7WnrV2fSENlgHUVnYAIqKy17nXg2MLtOfNKSdk1UOqr2P+THhESYfm/Zd9owJJ4bqzvbRV3ZNo888rq3F1MqQrN9PpNK5LcxugOpTgtBbXzzL1RzhBOO3LSDClv307IFbNSL9bOloZGYHT8IMV0S9HLlssj0PymgWY2gis4co5DG3y2QHv3SC1FAyCj4QnCQAz1m/ZqyaO/avT535SLBq71j3ImkGSum7pHCKZUm87CgC+33mj8LJKj9NQ1DmozICtJ6XiR/BGPG5sOT9+p0VYHat9iGqAEM1NDDF7iOuIBd0aj1eP636UOvWX3Y5qMDZ9UXwfPLPmMp48B8gx09bAqarEooVtClmRw8R9u1BiaBy5449iAyqeDGF/NmQJ8Rqbg9jFSFUcdvi75LKlVT+8Eu83aaeWuUjILlqksEw+7s8/jnbaMWam1j3HTdk3iV+RaUlsKDpUV980QgOYQkCo0rd4+0Cr5xZ2aKAo2ttisebF4ypo7pru7n2X1L6nbIpGqEcHFH3s+O3RpndMnYk6H+kK3HyxqC5/7dENRsAq5Np5IrnmVnaP8HvUVzv2YAtkk2vDhGS/LBsmzdPGiJjCEncgiq5DRQFLbW9GfHkYb5Wj4di3unDzXfP+yHeyJQY6IUr7zJ/FEf7x9l23EPUEssv3nwjK492bmG+s4POZTHKTblcIjHb/WT+wvwoI4zlNXRxPwwybLKMRMyJRJfAFQEZqhWLO2J/NsRgYiOrIVfO4xqWISQakLBoU0WYbcWH256k4hO5l702BjMdxSV9DdKEgoBbXvdo59pXp72/EaRi0l7W7HMB4Z5VmKWhWhn/PEloWL76Te4DlsPhfckcQQdCkCU9w83rkNtZuY0PfL6aRxxbFn1lKw8/Hb4d5c9pSXKheMx4hXTJgz5AdfDflDG+0NY78yVzEQlxglrqx10twz9QHCdoZGLWVGD5rCHTTxnQ7X2iQalehYuB9nKXzL/XNXZYKKHTPDFHaCNqPy7NR81cv/vWPhQF5W2qefWPHGbB5Tamr3rFCSxgFP19nBHIxeGcJbQUepS8hmk0+q3x7JNdiMo6yqLAKoV8D9oYNvr2tXX/txStIN8YNt52iq+DVJ0E5kuLHbptTa1G5Gf5B5FKthyLrGrXfQ6wfwizrOjyrHUTZzEx5VVjbngT8dXM7bMtpUh8I940wMPXA78g1ovm9VjoSmeF3NgFOxID1W77lHwck8dZmwOnxFVnqw8koKODRWmENnOmUPnZCkAPBDomVoUwhETUmjnMw5E67Trnei4s6Vv+CHhQOZXYqj3loqyM2fqYClROFSfnSRSxRvOzye9yVEYexnV429tRs4TfkHnzjKLPlA9dSARDsOwc3hwfU4C7BtT9UZCNcoozC2AYCXKM4Hq3bOUomyJWHlm+ig6icAGMS4TQjAjf6jTy4bMHKePEb5raNiu8b2F/NDICIv+YwnaAX9KX5xtuKV0XbrUWQgDwkRhPPFzvPtCxwtgsHx5xNU31XAToQWt7k9acWmJ0DGurIFFpUKO5t7tEYWGaB9p0Xnrz3GjaCpjUZ9C9VKRuxAi2eDf9a0ER8+KYjEL+z25S07P5+YTOgvRFz8cBHtQbpuU5rVr6H3rS3XdOK6yc2MCTWUDlGGMfNdxjW3a7afxgsHPadH0HR+CEhVOjHH6nA7/SX9A4J2D/3eVzwKseHtecmKmUvumDgpxq0a33ji6042lLHx2+DSQb0zUxShQbXxkCqGsERMVKvsKaPJB0QXB0scWXJDGudxKJrKpRvIOsrSeiMPlTR5s4ELObvGYaUGHZ1cLytr7qoRYOewV6iLRsh9mTrqquFXXa1TUS04oNn6+oGWX1aFDSyQogdLkmOMKhkbSOoEuIruUWCAlHb+KV4VmeU1DBw2xBjfhUZo9SjTAuEeDD9uihPXtx7zIAkXhwrc0/fy8Lp05Zz4rMWyUkXxdQbikTTFk2a6PuH+OS2yW1iDRRgki/5/vVVHXDXI5EW0EuvhdV0jsodf6b4b0lVM6MaEFzuqCj01TxA0XX8mbGDUUUV9gEyzXB0hdGl5id5YO3saz2rK9PmGVcFqMpBmz4mEcRIQ7RZPunUXlIt+g8ZINCNYfAsPr5IuVqZIIKOtRlYVPWVAQDmegwjhumzZ4tgvqhKUlPjzsgnR1MtP8QwP1bMDrzt/xuiIotnjmZA+hgrGOqdbqhnSRUCejE3b+uVTvdjHvl0eGm5JIXRJcFqfcFplyn7N1RYQ8uV9uGh8ymP66NsXwxJ9k9OwW8I5Fq3q3Xcpl23UdOeaSdG9nUR6BhhkCuOb5PwVWcO/LJLZSLWuPul2/F6l5FZFVrmNutfgDgwejJpqMVYugrpIurh/LVrBqFCUWKg8iix+xeWgGIhCqzusD7o2n2Ci0m3WIgOCJE5MQo9Wvo61LCiqDCYom0nxcM3fZsdondSmEOhz3lSs/5k8UQ3tJZYsB/2e6+iAOuTWgRj5ys/dGyaDhKCsDtgFZdiKttJ2LmcT4t1I6dMt0oOn7LLoQt/R6uKRP5pkzTg5fV5VVpnpuXmWTlMfy9v27mPpxHiN2rIR+dcy1khKrjhKeEIfAjAxWpcLT8BqIPjQ7IEEotn7977/bLOmEl5eFAuXEanyGQtNlp6jlvzRoIiCm8Y1gKtnF/dmmh2aeEkrAyDkHmlvpAFnDojM56db7YfmHYC1i1+BHZVFJWEu8wDFNslL6Y8hZpvb52/rckx0qN5SIMoFpqUy7h7nGN/XV/PJ+K1ev6wr+lTqNPuYJm3qVbUlPkBKUbQ/5rRy9Nh9VFD4St0LTlIfgZWS5uV/i7haWT6i5PWjmWSW3yN4tLmmgr3F8KGvOp4lScf1cV01RVsihhqFngQz7CPGwmNCIuHwR04XBvS0S61THQMM26UU2PukdHNZK9yurlYCDAJ85rWzFbTfwMi/n3VhSpwkiiRxrvaKmBFRLophrYD7XvqpmfbVWDlV5+pfR6RaujCWbv5+V17YioO1MDJSbGK1JLGEOJrmBgqhDZRJNFkWpKhPTTc95x8QqyuGWgkNnRK9IS+xXy+61nqNB8u03pq7m+CwjasQ7Ozm+TRovm+9a4MHGjMbUmzlsrB2P7swY5ZZ7uriy77Xea0YivRWT709DS+bJZKUMuzFz3O2CDM+3oVeh2zP5Wn3Qan674qqYR1zoP+ttHWNLKN8lVAbUu7p55J0dU/oa4kk4SDia6MX2owUwNKqTb7b8XKjuGab/A7CxDRXSMpD/RP8YVQIr5XZBxebpZmg4LMC0DqmTf4MfLaux3WKblWb9JRkS951H6S/GLIkT3gB0pmDSg5pzOEK/Jylyd2gHYBPkVTWE2G72JrRCOw9Ta01F4gnRGRV/+QqClVmcAnh+Ru9g6PtToJjpd0dWoNV/uQypkybazU2hpcwkDv0ryKDUavBINGSvXpIbZoCHvZ5rYJshdrt2PgaGAv9aoirRNgydu0HhmdaBr4Et1tXimmnE/BYX370daMKnszlyjjvOm1w7ggJFDHWy6gImNNoUNgmh/KYJtsXyUdDzC+Epn8TlnJgJE0wjbrY+Nl/ZpqzFudeW3+cwxjvzjOHm3XLoziZd8pINMdWqgJyA7WJ8fneZW+Giy/qYYmFntFGAcM6JFCarL1dl6+x4i5Nh1AfFQSSDvozUxdG/RlyzYCtRP51QS1axIrvhmG1JQFqSdk527z3or0zhfLx60H/MOuzbyGaucqCAxVfRWEobsdT7Al3kud9JuB3u82i+r8V/M1AlHYALkESoCh33o1dvHyQjnqoQWWSy1G7QY5zmbXMJa24JOh3ih2HBWS6s6v9mrHmQB/pLOBFS0rLeNofUJ8Im8cuU4lrW+1I8HBExfAYvxCW6ILtt4o53OB2m5tH1fb9DDxbov9wZmbfX5a/xWIFNeH9BRAWKHSiUGo4mf8l3Nafm/aN0ZfcnzI0t1xl0fXFFeRUMiV6eBWFy9dEdn1mLiCOXgVZMZVFEPDWG1yP1GvM1ZD0yaKmSQVjQHN3KETm1zQxwN4eYIh6fvchtXs9ySzYpKizbGdpet5QJvkz2/xH/hRvYmK0DyNqdKm7+PthevEaz6nLGQd7qAPAkpjpe3JzDu4MnmKFN1Weis8VeaUygXtAFLIlBvYlQagk9SnThfnUu5orX5jBzq6OruZqEwg7W3rk2g7IMo33S7vqlDpe338oB1JmEGIf+AC9qIJ12rup8AOiWCV0v3L4OFc7nBf//VJf391XVHFyPcCVDsA8Vc75NEw1mNC8CWsjc0Fb0apRhips3v6mKF1fmF5utHz0V+nzWvAfEiaXFsf/fHqsqluLvkOo24JimsZB3MwevrKPmVsLSCcui4uIMKXHxKp5AQy+L7hIes6JdXcGNyhD6N3VyII9wCHv8v8BDyQVVvKgxlzcixmWbuc5zZPqUk7iQozLgiyGgbhecqXU+RnCFax08dEK3/JGDRaUjxppIK72/b1xYtGMPBIbs7mPvbhwc+L3wGsd6TU03gxmj5dEBaQrfe3VFkJsFEmcjVrKY1hBtu+FZEWGWkSPn/kzpdKFHYt8TtSjTeGBgOn3x6lYV62l83qdXzWWqYCwy9zMYe7YIbtB6uJiLG6S5PbGXmj5beM9mse/w6TR1E7Ajr/6lFI6HmMpvqLbgViKGF+L4hlR73j3Z3yzIik83uyLVb9S5+0HM+uh3gY/Kd6mpXnCNwfxTvlv78yWh1XkQASqDUAGWndblurkFa5FDucUxULtH0x9+jMl3D1xFGIaLkPx/qYz9HXzbriGIz/0u8rXw7WR9YbXK5bitjATg7rdu1rq4gl9eMeRG+AhzsFzwUHmkUSahZ62uhagK+b6bZeZHW+L/3/lKgcwqfW6oKmvj0M2cb95IoSwjA17ua3qDp1wmGnTVUzsutpfNERMM/82FHEsFinIbE5nq/3PFB1Yl6Bxp48LL5WTbbInO2HA0l/yOgI7EGTDD1vR/Ch9tEjv0t9U84Ljm9nHHIkb79Tn6bWcdyOwXAXleSkAqyxf4sFKsXEwEBwiPJkXJB/wYlfEl0n9GAAn5rTuSNGg8781pU3FpshzpcxpqgenDEBFKQqJW2uyfGTKY85FOolWS6dxs0Fr224pHjFEC2j6ssU90+CiexAnb0nIMgkxbF/HdBVl9zIxQwo5UTEvbzFC7d3L2kJIkX0rTI2mU131kWwDVvskvG0s9dfzfqEOal1NAMIHgnYeYAROrr8xfLmEmjAavtp6EdBrULHGFobd1hQxtlj99F8btMBdGf4cyqmzQbOhkjCOm0VGPS2JzlGoWVSiM8aNssRQoHroXPGOy3ypgVI8xTbTYeDniqjEd9Ysp67j2kJsh+FC1EovS79QeyqaQNTmFmdATPcjG7APrpYtU+QOt2tbI9Lkw6KJvUMnFg/PkaHSo/4+ylaXuwEGLImFKS4n2coLbz25xFGuN9imHEoEIVM+KYPB/i3d1gb6pyHN6mXxZVidtXVkHb3qwHsm0XGpIkU0/5Tlpwwfw9K9mNzJBb813GNsTA5GnGkNBQeCb0488OyFRRo6tysecdc2a5nBDomtovLwQ/7LXzW7v1itWU7yy54VJwn34Q1UtzGaGUMRfjRuDTXsKvrYa1Ui2VmiZKqMZ3H2wUIBoNmfARZUxxnJodS8nPHaUio9aB6SRD9M/QQcYojuN4PCOQ6YqMUuAgScnj+3OUs+mQfSkQegkapL/oLCTdpL8p4LFCY62ujXZyJCTMTb0lodhjvRM6rIPd9UExzoP83dKRaM/xSg85Sn/2baVaonWCZNePA/tT0oENqqr2epZYA74fV5d+pwDOVaQo4T1b1UuitUkom/RpEvVZFmfYBY+gkBNSdjsBExY4JWv5dU0KZfUB02yiVFPZzpaWe/8f1SvaEGYe8yCDLR2F6DTxXTx7YN7dKBU9SwZxm1mnJfkMYzcBr1EeexPLac/Ih6f8RhfmNPF3SkNFS472HzOzwDYfyyOmDTAy7rPq1d052LyYPEWnyC6T52yZUgnB25dy/MXwYBydJZaPa5pdZ9sNZRQWw9qOwDZIPAoxS2mdgD2LPy3tU4DJN2YYq+bwwSRFAjN1E7PTOIP6LaV00X9yt0uiCOMyWthpB7Wy0+ctFlSNmRssjW6d8yTgKivYRcmq3jeUIdV7me2zMz1+OHYA3iJIMguGKOPh4yECwQFZ1bQBEtCaPmTNPed7s0rc1RRKmXjSSIpU2tsv2iCj2x6mGdltZhFYZ5J1uVRVxyx0PcYO8d4hrNbRHHcVaKLeQgodUe+vghj/i2hK7jxLO1LupEBua9kztk0YJiWWtrMkQR6O49mUssQMWgIGY4r7UqEoD7sM6fC8eihUa/3AAFor/ydO4nn1PT+WWkkmYa2jMIp+kSNTtJxssT2oFv1TY7exHm8YhqR0lXMTJqsZ4vOeND4aAq14uuaOs9Ejn1+3oeD178hAQcji/Q7vwB2DRHClag/EVVZFPrTwjpeR9sGerQSbuhkvVNjcnfYegG00k4Hmjxgk6rrO2IV/Dd7j0iBcz1ZLSRNe6EuPawXo3Tpq9lbqmIBNZpKEg/xf8BmKYRSwgQPZrq4Xl96YIKasgM5RQs8mnSJy+mqM7omkm0U1FfrNiyAb64Z/ZbEJg6CuFIeW/Gv3pi/MLCbNejRQzmcxeJML6XbyRjl7S5dqD7b1WJkRaLLW7S+kEw7WTR1jN/8wNvfQT2omZhYBWJnsihpVxlLX5oCF7ieVzdjqEL+4hHYAFpm8nhG4qTh8/Y+v0p31jb77oJKxEaWmFR8DlwzJ71NdhyeL62Xq+VvnzYtl6rOgVr1m/+TkJkOFzkPyC6gtne6SjXCO9h3p2sCdYbA4RGEZ8UdVkmkB53Obg54C7+yws2UOWgsfm3Ft4+3hnh/ZTigxXl10qjKFzNMeFCduS+TTqjWjYUZethkcJxZKsu9xXMxicOKKZOL8rYvalyZmcNWUOx+EEfgiCW2Qr4RGvNJzVO+v78kxMkxlHPDb50cWHQUsaN8f2/M9GdQTwlxkBwzF2iDh0SA3Kihe5Jpe4+XByTNfOVFNUSAx+bGshn4mu6zZbeichw6/4m034R/RPKxTH92WsdbdoYmMoKknWbLMs1gNUueFWuOLX/Ck1m1GQtpyThEBNNhpgZJXB0kOcfRYD9uzF8Kgs6QGIhWQsfEvj7IG/XWH9hidIxjsQOaTXlR1PcTOROVMlxCyrXtvq0gJdwal4l9r0SQ5ecdPYcKJ+mnU2IGMMJhGvQQ14Hi/dB+vlIToTDSwkdL3kwmJXBd4LDoQLk88NGzoVeU320MvE7mXW+SQxknSLUMqLedAVwxQIvx3TnK8o2/hvktwTSCW5ie56/kmVQ9Ttx28kzMQiqAPACm5odIVagF9qfyjnGQGxgCrnaPaDTsxRXO9XJcH1yyA0Sy3WY03kBzAqhtNfyUJWJm0/zSePPCmzbjMNOPYcE+zVzsxAks41dhg+XEzbQ5IqUT2KmnySKomumUpx8jDdaQSCx/RA9mo/MjACK1KrSJFeoh74k8y0YaPrJdnwkzNW+nHqs0V9HT/vCZTsNCpN/oeLhL639IcQKO7jjt5jLf0CrHsy/u+0yhqO6W1SBub2DfeD3AZDTMz3cqL8Wbg8/2nBmZ3/3gRjXE6cFIVNM2ctXmDXJndhDzADHFTxlkmcdGmkIYrmIb6X6kicnx0qjbwEL6o6ZnjVutlGPCa4dXPXS2kfiHZbd9imHjBXv6Wm6Q1LAuknIY1d4llGM0qF2FTylchzmvl5gi9K4GPzE+fcitcQ4vfZj1Q1j6bDyhsXwLIEyoE8zQ8hHiBlumOmbvyHZsmR+WEQfV0gGsXVB/Ek8gRrChaqJgbu7AYhpvtjI/hslv/E8Amj2tW5ytEishtf6Hoad3A9KK7Uyhcz+QhFpgWvLANwldAqtFS1bBAE7ZKl3bm1Tdtw1pVisUBjmFel59ZqKm92+Sqm32T4xsVFx2GNwyyxdFfKCTVvpzKuNrlgyxxV7Yl56Q4zz3WhREgjGSoEs8lNMTM7J/ya02NdxRx/dP/Lnrqcm+W+T58F4u6SR/ZExPkP8r70GIaKzIifuZzG9Hju2aE45YgoI2+K/9wq+pVMfma7uBo5ZahDh8m6UWXbnorjlivDVyD+9ragVtg4rmydpgyEqHlo5+uPlOMhjXpkLnppEc/Kc8BIC1GbVd2SfFjKbgRovDMKzAvSQXJmA0ffT/B24/0rbhbXHUK1wccRlkVHGRcgXj0RI3ete45zcQ9ifxOTvAWR/PrY0ZaFuUp0SSkcerOWXwJNZvlbjlOnYfVcWGuIGJDfhuwiMV+eDZoFhdHbQH0EAsp5l/A3cwMUkrOJdc6Gy8euwBIVzGVaMW6RQ==' WHERE a > 10 AND a <= 20;\n", "file_path": "src/test/regress/sql/uao_compaction/update_toast.sql", "rank": 72, "score": 335011.744929999 }, { "content": "--ERROR: Missing boundary specification in partition 'aa' of type LIST \n\ncreate table fff (a char(1), b char(2), d char(3)) distributed by\n\n(a) partition by list (b) (partition aa ); \n\n\n\n\n", "file_path": "src/test/regress/sql/partition1.sql", "rank": 73, "score": 334563.531391571 }, { "content": "SELECT E'''1 \\\\''2''3'::tsvector;\n", "file_path": "src/test/regress/sql/tstypes.sql", "rank": 74, "score": 334137.7885828209 }, { "content": "SELECT E'''1 \\\\''2'' 3'::tsvector;\n", "file_path": "src/test/regress/sql/tstypes.sql", "rank": 75, "score": 334137.7885828208 }, { "content": "select string_agg(a,',') from (values('aaaa'),(null),('bbbb'),('cccc')) g(a);\n", "file_path": "src/test/regress/sql/aggregates.sql", "rank": 76, "score": 333501.0824674672 }, { "content": "-- create required tables\n\nCREATE TABLE CHAR_STRINGS_TBL(f1 char(4));\n\nINSERT INTO CHAR_STRINGS_TBL (f1) VALUES ('a'),\n\n('ab'),\n\n('abcd'),\n\n('abcd ');\n\n\n", "file_path": "src/test/regress/sql/strings.sql", "rank": 77, "score": 333218.9630449824 }, { "content": "--\n", "file_path": "src/test/regress/sql/polygon.sql", "rank": 78, "score": 332134.6090601398 }, { "content": "--\n\n-- POLYGON\n\n--\n\n-- polygon logic\n\n--\n\n-- 3\t o\n\n--\t |\n\n-- 2\t + |\n\n--\t / |\n\n-- 1\t # o +\n\n-- / |\n\n-- 0\t#-----o-+\n\n--\n\n--\t0 1 2 3 4\n\n--\n\n\n", "file_path": "src/test/regress/sql/polygon.sql", "rank": 79, "score": 332134.6090601398 }, { "content": "-- start_equiv\n\ncreate table xyz_ctas1 as (select \"B B\" AS \"B+1\", \"C\" AS \"_%A\", \"D+1\" AS \"D\" from xyz) DISTRIBUTED RANDOMLY;\n", "file_path": "src/test/regress/sql/as_alias.sql", "rank": 80, "score": 331131.12405947107 }, { "content": "SELECT COUNT(*) FROM (SELECT A,B, case when c ='s' then C else NULL end as C FROM (SELECT sum(dml_heap_p.a) as A, dml_heap_p.a as B, dml_heap_s.c as C FROM dml_heap_p, dml_heap_s WHERE dml_heap_p.a = dml_heap_s.a GROUP BY dml_heap_p.a,dml_heap_s.c)as x GROUP BY A,B,C)foo;\n\nINSERT INTO dml_heap_r SELECT A,B, case when c ='s' then C else NULL end as C FROM (SELECT sum(dml_heap_p.a) as A, dml_heap_p.a as B, dml_heap_s.c as C FROM dml_heap_p, dml_heap_s WHERE dml_heap_p.a = dml_heap_s.a GROUP BY dml_heap_p.a,dml_heap_s.c)as x GROUP BY A,B,C;\n", "file_path": "src/test/regress/optfunctional/sql/dml_functional_3.sql", "rank": 81, "score": 330197.92412477295 }, { "content": "SELECT COUNT(*) FROM (SELECT A,B, case when c ='s' then C else NULL end as C FROM (SELECT sum(dml_ao_p.a) as A, dml_ao_p.a as B, dml_ao_s.c as C FROM dml_ao_p, dml_ao_s WHERE dml_ao_p.a = dml_ao_s.a GROUP BY dml_ao_p.a,dml_ao_s.c)as x GROUP BY A,B,C)foo;\n\nINSERT INTO dml_ao_r SELECT A,B, case when c ='s' then C else NULL end as C FROM (SELECT sum(dml_ao_p.a) as A, dml_ao_p.a as B, dml_ao_s.c as C FROM dml_ao_p, dml_ao_s WHERE dml_ao_p.a = dml_ao_s.a GROUP BY dml_ao_p.a,dml_ao_s.c)as x GROUP BY A,B,C;\n", "file_path": "src/test/regress/optfunctional/sql/dml_functional_1.sql", "rank": 82, "score": 330197.924124773 }, { "content": "SELECT COUNT(*) FROM (SELECT A,B, case when c ='s' then C else NULL end as C FROM (SELECT sum(dml_co_p.a) as A, dml_co_p.a as B, dml_co_s.c as C FROM dml_co_p, dml_co_s WHERE dml_co_p.a = dml_co_s.a GROUP BY dml_co_p.a,dml_co_s.c)as x GROUP BY A,B,C)foo;\n\nINSERT INTO dml_co_r SELECT A,B, case when c ='s' then C else NULL end as C FROM (SELECT sum(dml_co_p.a) as A, dml_co_p.a as B, dml_co_s.c as C FROM dml_co_p, dml_co_s WHERE dml_co_p.a = dml_co_s.a GROUP BY dml_co_p.a,dml_co_s.c)as x GROUP BY A,B,C;\n", "file_path": "src/test/regress/optfunctional/sql/dml_functional_2.sql", "rank": 83, "score": 330197.92412477295 }, { "content": "CREATE DOMAIN country_code char(2) NOT NULL;\n", "file_path": "src/test/regress/bugbuster/sql/DMLstmnt.sql", "rank": 84, "score": 329987.4429341956 }, { "content": " 0, 0, '*', '+', 0, '-', '.', 0,\n\n /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */\n\n '0', '1', '2', '3', '4', '5', '6', '7',\n\n /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */\n\n '8', '9', 0, 0, 0, 0, 0, 0,\n\n /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */\n\n 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g',\n\n /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */\n\n 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n\n /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */\n\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',\n\n /* 88 X 89 Y 90 Z 91 [ 92 \\ 93 ] 94 ^ 95 _ */\n\n 'x', 'y', 'z', 0, 0, 0, '^', '_',\n\n /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */\n\n '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',\n\n /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */\n\n 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n\n /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */\n\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',\n\n /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */\n", "file_path": "gpAux/extensions/gps3ext/lib/http_parser.cpp", "rank": 86, "score": 92.29850606442685 }, { "content": " /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 88 X 89 Y 90 Z 91 [ 92 \\ 93 ] 94 ^ 95 _ */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,\n\n /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */\n\n 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,\n\n};\n\n\n\n#undef T\n\n\n", "file_path": "gpAux/extensions/gps3ext/lib/http_parser.cpp", "rank": 87, "score": 89.43568292374341 }, { "content": " EXPECT_EQ(\"s3://neverland.amazonaws.com\",\n\n truncate_options(string(\"s3://neverland.amazonaws.com secret=secret_test\")));\n\n\n\n EXPECT_EQ(\n\n \"s3://neverland.amazonaws.com\",\n\n truncate_options(string(\"s3://neverland.amazonaws.com accessid=\\\".\\\\!@#$%^&*()DFGHJK\\\"\")));\n\n\n\n EXPECT_EQ(\"s3://neverland.amazonaws.com\",\n\n truncate_options(string(\"s3://neverland.amazonaws.com secret=secret_test \"\n\n \"accessid=\\\".\\\\!@#$%^&*()DFGHJK\\\" chunksize=3456789\")));\n\n\n\n EXPECT_EQ(\"s3://neverland.amazonaws.com\",\n\n truncate_options(string(\"s3://neverland.amazonaws.com secret=secret_test \"\n\n \"blah= accessid=\\\".\\\\!@#$%^&*()DFGHJK\\\" \"\n\n \"chunksize=3456789 KingOfTheWorld=sanpang\")));\n\n}\n\n\n\nTEST(Common, EncodeQuery) {\n\n string src1 = \"This is a simple & short test.\";\n\n string src2 = \"$ & < > ? ; # : = , \\\" ' ~ + %-_\";\n\n\n\n string dst1 = \"This%20is%20a%20simple%20&%20short%20test.\";\n\n string dst2 =\n\n \"%24%20&%20%3C%20%3E%20%3F%20%3B%20%23%20%3A%20=%20%2C%20%22%20%27%\"\n\n \"20~%20%2B%20%25-_\";\n\n\n\n EXPECT_EQ(dst1.c_str(), encode_query_str(src1));\n\n EXPECT_EQ(dst2.c_str(), encode_query_str(src2));\n\n}", "file_path": "gpAux/extensions/gps3ext/test/s3common_test.cpp", "rank": 93, "score": 51.977582028377626 }, { "content": "}\n\n\n\nbool Config::Scan(const string &sec, const string &key, const char *scanfmt, void *dst) {\n\n if ((key == \"\") || (sec == \"\") || (this->_conf == NULL)) return false;\n\n\n\n return ini_sget(this->_conf, sec.c_str(), key.c_str(), scanfmt, dst);\n\n}\n\n\n\nbool to_bool(std::string str) {\n\n std::transform(str.begin(), str.end(), str.begin(), ::tolower);\n\n if ((str == \"yes\") || (str == \"true\") || (str == \"y\") || (str == \"t\") || (str == \"1\")) {\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n}\n\n\n\nconst char uri_mapping[256] = {\n\n /* 0 1 2 3 4 5 6 7\n\n * 8 9 A B C D E F */\n", "file_path": "gpAux/extensions/gps3ext/src/s3utils.cpp", "rank": 94, "score": 51.5172929189444 }, { "content": "// Tests using StreamableToString() on a NULL non-char pointer.\n\nTEST(StreamableToStringTest, NullPointer) {\n\n int* p = NULL;\n\n EXPECT_STREQ(\"(null)\", StreamableToString(p).c_str());\n\n}\n\n\n\n// Tests using StreamableToString() on a C string.\n\nTEST(StreamableToStringTest, CString) {\n\n EXPECT_STREQ(\"Foo\", StreamableToString(\"Foo\").c_str());\n\n}\n\n\n\n// Tests using StreamableToString() on a NULL C string.\n\nTEST(StreamableToStringTest, NullCString) {\n\n char* p = NULL;\n\n EXPECT_STREQ(\"(null)\", StreamableToString(p).c_str());\n\n}\n\n\n\n// Tests using streamable values as assertion messages.\n\n\n\n// Tests using std::string as an assertion message.\n", "file_path": "gpAux/extensions/gtest/test/gtest_unittest.cc", "rank": 95, "score": 45.460404060873515 }, { "content": " char signature_hex[SHA256_DIGEST_STRING_LENGTH] = {0};\n\n\n\n unsigned char key_date[SHA256_DIGEST_LENGTH] = {0};\n\n unsigned char key_region[SHA256_DIGEST_LENGTH] = {0};\n\n unsigned char key_service[SHA256_DIGEST_LENGTH] = {0};\n\n unsigned char signing_key[SHA256_DIGEST_LENGTH] = {0};\n\n\n\n // YYYYMMDD'T'HHMMSS'Z'\n\n time_t t = time(NULL);\n\n gmtime_r(&t, &tm_info);\n\n strftime(timestamp_str, TIME_STAMP_STR_LEN, \"%Y%m%dT%H%M%SZ\", &tm_info);\n\n\n\n // for unit tests' convenience\n\n if (!h->Get(X_AMZ_DATE)) {\n\n h->Add(X_AMZ_DATE, timestamp_str);\n\n }\n\n memcpy(date_str, h->Get(X_AMZ_DATE), DATE_STR_LEN - 1);\n\n\n\n string query_encoded = encode_query_str(query);\n\n stringstream canonical_str;\n", "file_path": "gpAux/extensions/gps3ext/src/s3common.cpp", "rank": 96, "score": 45.45674816367018 }, { "content": "\n\n// Tests String::ShowWideCString().\n\nTEST(StringTest, ShowWideCString) {\n\n EXPECT_STREQ(\"(null)\",\n\n String::ShowWideCString(NULL).c_str());\n\n EXPECT_STREQ(\"\", String::ShowWideCString(L\"\").c_str());\n\n EXPECT_STREQ(\"foo\", String::ShowWideCString(L\"foo\").c_str());\n\n}\n\n\n\n# if GTEST_OS_WINDOWS_MOBILE\n\nTEST(StringTest, AnsiAndUtf16Null) {\n\n EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));\n\n EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));\n\n}\n\n\n\nTEST(StringTest, AnsiAndUtf16ConvertBasic) {\n\n const char* ansi = String::Utf16ToAnsi(L\"str\");\n\n EXPECT_STREQ(\"str\", ansi);\n\n delete [] ansi;\n\n const WCHAR* utf16 = String::AnsiToUtf16(\"str\");\n", "file_path": "gpAux/extensions/gtest/test/gtest_unittest.cc", "rank": 97, "score": 44.83256141342156 }, { "content": "// const char*.\n\nTEST(PrintCStringTest, Const) {\n\n const char* p = \"World\";\n\n EXPECT_EQ(PrintPointer(p) + \" pointing to \\\"World\\\"\", Print(p));\n\n}\n\n\n\n// char*.\n\nTEST(PrintCStringTest, NonConst) {\n\n char p[] = \"Hi\";\n\n EXPECT_EQ(PrintPointer(p) + \" pointing to \\\"Hi\\\"\",\n\n Print(static_cast<char*>(p)));\n\n}\n\n\n\n// NULL C string.\n\nTEST(PrintCStringTest, Null) {\n\n const char* p = NULL;\n\n EXPECT_EQ(\"NULL\", Print(p));\n\n}\n\n\n\n// Tests that C strings are escaped properly.\n", "file_path": "gpAux/extensions/gtest/test/gtest-printers_test.cc", "rank": 98, "score": 44.06374215412243 }, { "content": "#define SHA256_DIGEST_STRING_LENGTH 65\n\n\n\nbool sha1hmac(const char* str, unsigned char out_hash[SHA_DIGEST_LENGTH], const char* secret,\n\n int secret_len);\n\n\n\nbool sha1hmac_hex(const char* str, char out_hash_hex[SHA_DIGEST_STRING_LENGTH], const char* secret,\n\n int secret_len);\n\n\n\nbool sha256(const char* string, unsigned char out_hash[SHA256_DIGEST_LENGTH]);\n\n\n\nbool sha256_hex(const char* string, char out_hash_hex[SHA256_DIGEST_STRING_LENGTH]);\n\n\n\nbool sha256hmac(const char* str, unsigned char out_hash[SHA256_DIGEST_LENGTH], const char* secret,\n\n int secret_len);\n\n\n\nbool sha256hmac_hex(const char* str, char out_hash_hex[SHA256_DIGEST_STRING_LENGTH],\n\n const char* secret, int secret_len);\n\n\n\nsize_t find_Nth(const string& str, // where to work\n\n unsigned N, // N'th occurrence\n\n const string& find // what to 'find'\n\n );\n\n\n", "file_path": "gpAux/extensions/gps3ext/include/s3utils.h", "rank": 99, "score": 43.11437655589918 } ]
C++
toolsrc/src/vcpkg/parse.cpp
TheScarfix/vcpkg
8db6db5dac70c25b04cd4dd84392484dee822fbe
#include "pch.h" #include <utility> #include <vcpkg/base/system.print.h> #include <vcpkg/base/util.h> #include <vcpkg/packagespec.h> #include <vcpkg/paragraphparser.h> #include <vcpkg/parse.h> using namespace vcpkg; namespace vcpkg::Parse { std::string ParseError::format() const { return Strings::concat("Error: ", origin, ":", row, ":", column, ": ", message, "\n" " on expression: \"", line, "\"\n", " ", std::string(column - 1, ' '), "^\n"); } void ParserBase::add_error(std::string message, const ParserBase::SourceLoc& loc) { if (!m_err) { auto linestart = loc.it; while (linestart != m_text.c_str()) { if (linestart[-1] == '\n') break; --linestart; } auto lineend = loc.it; while (*lineend != '\n' && *lineend != '\r' && *lineend != '\0') ++lineend; m_err.reset( new ParseError(m_origin.c_str(), loc.row, loc.column, {linestart, lineend}, std::move(message))); } skip_to_eof(); } static Optional<std::string> remove_field(RawParagraph* fields, const std::string& fieldname) { auto it = fields->find(fieldname); if (it == fields->end()) { return nullopt; } const std::string value = std::move(it->second); fields->erase(it); return value; } void ParagraphParser::required_field(const std::string& fieldname, std::string& out) { auto maybe_field = remove_field(&fields, fieldname); if (const auto field = maybe_field.get()) out = std::move(*field); else missing_fields.push_back(fieldname); } std::string ParagraphParser::optional_field(const std::string& fieldname) const { return remove_field(&fields, fieldname).value_or(""); } std::unique_ptr<ParseControlErrorInfo> ParagraphParser::error_info(const std::string& name) const { if (!fields.empty() || !missing_fields.empty()) { auto err = std::make_unique<ParseControlErrorInfo>(); err->name = name; err->extra_fields = Util::extract_keys(fields); err->missing_fields = std::move(missing_fields); return err; } return nullptr; } template<class T, class F> static Optional<std::vector<T>> parse_list_until_eof(StringLiteral plural_item_name, Parse::ParserBase& parser, F f) { std::vector<T> ret; parser.skip_whitespace(); if (parser.at_eof()) return std::vector<T>{}; do { auto item = f(parser); if (!item) return nullopt; ret.push_back(std::move(item).value_or_exit(VCPKG_LINE_INFO)); parser.skip_whitespace(); if (parser.at_eof()) return {std::move(ret)}; if (parser.cur() != ',') { parser.add_error(Strings::concat("expected ',' or end of text in ", plural_item_name, " list")); return nullopt; } parser.next(); parser.skip_whitespace(); } while (true); } ExpectedS<std::vector<std::string>> parse_default_features_list(const std::string& str, CStringView origin) { Parse::ParserBase parser; parser.init(str, origin); auto opt = parse_list_until_eof<std::string>("default features", parser, &parse_feature_name); if (!opt) return {parser.get_error()->format(), expected_right_tag}; return {std::move(opt).value_or_exit(VCPKG_LINE_INFO), expected_left_tag}; } ExpectedS<std::vector<ParsedQualifiedSpecifier>> parse_qualified_specifier_list(const std::string& str, CStringView origin) { Parse::ParserBase parser; parser.init(str, origin); auto opt = parse_list_until_eof<ParsedQualifiedSpecifier>( "dependencies", parser, [](ParserBase& parser) { return parse_qualified_specifier(parser); }); if (!opt) return {parser.get_error()->format(), expected_right_tag}; return {std::move(opt).value_or_exit(VCPKG_LINE_INFO), expected_left_tag}; } ExpectedS<std::vector<Dependency>> parse_dependencies_list(const std::string& str, CStringView origin) { Parse::ParserBase parser; parser.init(str, origin); auto opt = parse_list_until_eof<Dependency>("dependencies", parser, [](ParserBase& parser) { auto loc = parser.cur_loc(); return parse_qualified_specifier(parser).then([&](ParsedQualifiedSpecifier&& pqs) -> Optional<Dependency> { if (pqs.triplet) { parser.add_error("triplet specifier not allowed in this context", loc); return nullopt; } return Dependency{{pqs.name, pqs.features.value_or({})}, pqs.qualifier.value_or({})}; }); }); if (!opt) return {parser.get_error()->format(), expected_right_tag}; return {std::move(opt).value_or_exit(VCPKG_LINE_INFO), expected_left_tag}; } }
#include "pch.h" #include <utility> #include <vcpkg/base/system.print.h> #include <vcpkg/base/util.h> #include <vcpkg/packagespec.h> #include <vcpkg/paragraphparser.h> #include <vcpkg/parse.h> using namespace vcpkg; namespace vcpkg::Parse { std::string ParseError::format() const { return Strings::concat("Error: ", origin, ":", row, ":", column, ": ", message, "\n" " on expression: \"
_whitespace(); } while (true); } ExpectedS<std::vector<std::string>> parse_default_features_list(const std::string& str, CStringView origin) { Parse::ParserBase parser; parser.init(str, origin); auto opt = parse_list_until_eof<std::string>("default features", parser, &parse_feature_name); if (!opt) return {parser.get_error()->format(), expected_right_tag}; return {std::move(opt).value_or_exit(VCPKG_LINE_INFO), expected_left_tag}; } ExpectedS<std::vector<ParsedQualifiedSpecifier>> parse_qualified_specifier_list(const std::string& str, CStringView origin) { Parse::ParserBase parser; parser.init(str, origin); auto opt = parse_list_until_eof<ParsedQualifiedSpecifier>( "dependencies", parser, [](ParserBase& parser) { return parse_qualified_specifier(parser); }); if (!opt) return {parser.get_error()->format(), expected_right_tag}; return {std::move(opt).value_or_exit(VCPKG_LINE_INFO), expected_left_tag}; } ExpectedS<std::vector<Dependency>> parse_dependencies_list(const std::string& str, CStringView origin) { Parse::ParserBase parser; parser.init(str, origin); auto opt = parse_list_until_eof<Dependency>("dependencies", parser, [](ParserBase& parser) { auto loc = parser.cur_loc(); return parse_qualified_specifier(parser).then([&](ParsedQualifiedSpecifier&& pqs) -> Optional<Dependency> { if (pqs.triplet) { parser.add_error("triplet specifier not allowed in this context", loc); return nullopt; } return Dependency{{pqs.name, pqs.features.value_or({})}, pqs.qualifier.value_or({})}; }); }); if (!opt) return {parser.get_error()->format(), expected_right_tag}; return {std::move(opt).value_or_exit(VCPKG_LINE_INFO), expected_left_tag}; } }
", line, "\"\n", " ", std::string(column - 1, ' '), "^\n"); } void ParserBase::add_error(std::string message, const ParserBase::SourceLoc& loc) { if (!m_err) { auto linestart = loc.it; while (linestart != m_text.c_str()) { if (linestart[-1] == '\n') break; --linestart; } auto lineend = loc.it; while (*lineend != '\n' && *lineend != '\r' && *lineend != '\0') ++lineend; m_err.reset( new ParseError(m_origin.c_str(), loc.row, loc.column, {linestart, lineend}, std::move(message))); } skip_to_eof(); } static Optional<std::string> remove_field(RawParagraph* fields, const std::string& fieldname) { auto it = fields->find(fieldname); if (it == fields->end()) { return nullopt; } const std::string value = std::move(it->second); fields->erase(it); return value; } void ParagraphParser::required_field(const std::string& fieldname, std::string& out) { auto maybe_field = remove_field(&fields, fieldname); if (const auto field = maybe_field.get()) out = std::move(*field); else missing_fields.push_back(fieldname); } std::string ParagraphParser::optional_field(const std::string& fieldname) const { return remove_field(&fields, fieldname).value_or(""); } std::unique_ptr<ParseControlErrorInfo> ParagraphParser::error_info(const std::string& name) const { if (!fields.empty() || !missing_fields.empty()) { auto err = std::make_unique<ParseControlErrorInfo>(); err->name = name; err->extra_fields = Util::extract_keys(fields); err->missing_fields = std::move(missing_fields); return err; } return nullptr; } template<class T, class F> static Optional<std::vector<T>> parse_list_until_eof(StringLiteral plural_item_name, Parse::ParserBase& parser, F f) { std::vector<T> ret; parser.skip_whitespace(); if (parser.at_eof()) return std::vector<T>{}; do { auto item = f(parser); if (!item) return nullopt; ret.push_back(std::move(item).value_or_exit(VCPKG_LINE_INFO)); parser.skip_whitespace(); if (parser.at_eof()) return {std::move(ret)}; if (parser.cur() != ',') { parser.add_error(Strings::concat("expected ',' or end of text in ", plural_item_name, " list")); return nullopt; } parser.next(); parser.skip
random
[ { "content": "namespace vcpkg::Util\n\n{\n\n template<class Container>\n\n using ElementT =\n\n std::remove_reference_t<decltype(*std::declval<typename std::remove_reference_t<Container>::iterator>())>;\n\n\n\n namespace Vectors\n\n {\n\n template<class Container, class T = ElementT<Container>>\n\n void append(std::vector<T>* augend, const Container& addend)\n\n {\n\n augend->insert(augend->end(), addend.begin(), addend.end());\n\n }\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 0, "score": 175182.56035036073 }, { "content": "namespace vcpkg::Test\n\n{\n\n std::unique_ptr<SourceControlFile> make_control_file(\n\n const char* name,\n\n const char* depends,\n\n const std::vector<std::pair<const char*, const char*>>& features = {},\n\n const std::vector<const char*>& default_features = {});\n\n\n\n std::unique_ptr<vcpkg::StatusParagraph> make_status_pgh(const char* name,\n\n const char* depends = \"\",\n\n const char* default_features = \"\",\n\n const char* triplet = \"x86-windows\");\n\n\n\n std::unique_ptr<vcpkg::StatusParagraph> make_status_feature_pgh(const char* name,\n\n const char* feature,\n\n const char* depends = \"\",\n\n const char* triplet = \"x86-windows\");\n\n\n\n /// <summary>\n\n /// Map of source control files by their package name.\n\n /// </summary>\n\n struct PackageSpecMap\n\n {\n\n std::unordered_map<std::string, SourceControlFileLocation> map;\n\n Triplet triplet;\n\n PackageSpecMap(Triplet t = Triplet::X86_WINDOWS) noexcept : triplet(t) {}\n\n\n\n PackageSpec emplace(const char* name,\n\n const char* depends = \"\",\n\n const std::vector<std::pair<const char*, const char*>>& features = {},\n\n const std::vector<const char*>& default_features = {});\n\n\n\n PackageSpec emplace(vcpkg::SourceControlFileLocation&& scfl);\n\n };\n\n\n\n template<class T, class S>\n\n T&& unwrap(vcpkg::ExpectedT<T, S>&& p)\n\n {\n\n REQUIRE(p.has_value());\n\n return std::move(*p.get());\n\n }\n\n\n\n template<class T>\n\n T&& unwrap(vcpkg::Optional<T>&& opt)\n\n {\n\n REQUIRE(opt.has_value());\n\n return std::move(*opt.get());\n\n }\n\n\n\n struct AllowSymlinks\n\n {\n\n enum Tag : bool\n\n {\n\n No = false,\n\n Yes = true,\n\n } tag;\n\n\n\n constexpr AllowSymlinks(Tag tag) noexcept : tag(tag) {}\n\n\n\n constexpr explicit AllowSymlinks(bool b) noexcept : tag(b ? Yes : No) {}\n\n\n\n constexpr operator bool() const noexcept { return tag == Yes; }\n\n };\n\n\n\n AllowSymlinks can_create_symlinks() noexcept;\n\n\n\n const fs::path& base_temporary_directory() noexcept;\n\n\n\n void create_symlink(const fs::path& file, const fs::path& target, std::error_code& ec);\n\n\n\n void create_directory_symlink(const fs::path& file, const fs::path& target, std::error_code& ec);\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 1, "score": 175182.56035036073 }, { "content": " m_origin = origin;\n", "file_path": "toolsrc/include/vcpkg/parse.h", "rank": 2, "score": 173683.91670746935 }, { "content": " int row = 0;\n", "file_path": "toolsrc/include/vcpkg/textrowcol.h", "rank": 3, "score": 173673.80120994477 }, { "content": " row = init_rowcol.row ? init_rowcol.row : 1;\n", "file_path": "toolsrc/include/vcpkg/parse.h", "rank": 4, "score": 173668.2040193366 }, { "content": " int column = 0;\n", "file_path": "toolsrc/include/vcpkg/textrowcol.h", "rank": 5, "score": 173654.1638335052 }, { "content": " const PackageSpec& spec() const { return m_spec; }\n", "file_path": "toolsrc/include/vcpkg/packagespec.h", "rank": 6, "score": 173651.80259339866 }, { "content": " column = init_rowcol.column ? init_rowcol.column : 1;\n", "file_path": "toolsrc/include/vcpkg/parse.h", "rank": 7, "score": 173648.57357374037 }, { "content": " namespace details\n\n {\n\n template<class Container>\n\n void shuffle(Container& c, Randomizer* r)\n\n {\n", "file_path": "toolsrc/include/vcpkg/base/graphs.h", "rank": 8, "score": 170121.53127530176 }, { "content": " typename std::add_pointer<const T>::type get() const\n\n {\n\n return this->m_base.has_value() ? &this->m_base.value() : nullptr;\n", "file_path": "toolsrc/include/vcpkg/base/optional.h", "rank": 9, "score": 170089.76592607505 }, { "content": " constexpr explicit AllowSymlinks(bool b) noexcept : tag(b ? Yes : No) {}\n\n\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 10, "score": 136199.9245809268 }, { "content": " ~ResourceBase() = default;\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 11, "score": 136199.9245809268 }, { "content": "namespace vcpkg\n\n{\n\n /// <summary>Status paragraphs</summary>\n\n ///\n\n /// Collection of <see cref=\"vcpkg::StatusParagraph\"/>, e.g. contains the information\n\n /// about whether a package is installed or not.\n\n ///\n\n struct StatusParagraphs\n\n {\n\n StatusParagraphs();\n\n explicit StatusParagraphs(std::vector<std::unique_ptr<StatusParagraph>>&& ps);\n\n\n\n using container = std::vector<std::unique_ptr<StatusParagraph>>;\n\n using iterator = container::reverse_iterator;\n\n using const_iterator = container::const_reverse_iterator;\n\n\n\n /// <summary>Find the StatusParagraph for given spec.</summary>\n\n /// <param name=\"spec\">Package specification to find the status paragraph for</param>\n\n /// <returns>Iterator for found spec</returns>\n\n const_iterator find(const PackageSpec& spec) const { return find(spec.name(), spec.triplet()); }\n\n\n\n /// <summary>Find the StatusParagraph for given feature spec.</summary>\n\n /// <param name=\"spec\">Feature specification to find the status paragraph for</param>\n\n /// <returns>Iterator for found spec</returns>\n\n const_iterator find(const FeatureSpec& spec) const { return find(spec.name(), spec.triplet(), spec.feature()); }\n\n\n\n /// <summary>Find a StatusParagraph by name, triplet and feature.</summary>\n\n /// <param name=\"name\">Package name</param>\n\n /// <param name=\"triplet\">Triplet</param>\n\n /// <param name=\"feature\">Feature name</param>\n\n /// <returns>Iterator for found spec</returns>\n\n iterator find(const std::string& name, Triplet triplet, const std::string& feature = \"\");\n\n const_iterator find(const std::string& name, Triplet triplet, const std::string& feature = \"\") const;\n\n\n\n std::vector<std::unique_ptr<StatusParagraph>*> find_all(const std::string& name, Triplet triplet);\n\n\n\n Optional<InstalledPackageView> find_all_installed(const PackageSpec& spec) const;\n\n\n\n /// <summary>Find the StatusParagraph for given spec if installed</summary>\n\n /// <param name=\"spec\">Package specification to find the status for</param>\n\n /// <returns>Iterator for found spec</returns>\n\n const_iterator find_installed(const PackageSpec& spec) const;\n\n\n\n /// <summary>Find the StatusParagraph for given feature spec if installed</summary>\n\n /// <param name=\"spec\">Feature specification to find the status for</param>\n\n /// <returns>Iterator for found spec</returns>\n\n const_iterator find_installed(const FeatureSpec& spec) const;\n\n\n\n /// <summary>Find the StatusParagraph for given spec and return its install status</summary>\n\n /// <param name=\"spec\">Package specification to check if installed</param>\n\n /// <returns>`true` if installed, `false` if not or not found.</returns>\n\n bool is_installed(const PackageSpec& spec) const;\n\n\n\n /// <summary>Find the StatusParagraph for given feature spec and return its install status</summary>\n\n /// <param name=\"spec\">Feature specification to check if installed</param>\n\n /// <returns>`true` if installed, `false` if not or not found.</returns>\n\n bool is_installed(const FeatureSpec& spec) const;\n\n\n\n iterator insert(std::unique_ptr<StatusParagraph>);\n\n\n\n friend void serialize(const StatusParagraphs& pgh, std::string& out_str);\n\n\n\n iterator end() { return paragraphs.rend(); }\n\n\n\n const_iterator end() const { return paragraphs.rend(); }\n\n\n\n iterator begin() { return paragraphs.rbegin(); }\n\n\n\n const_iterator begin() const { return paragraphs.rbegin(); }\n\n\n\n private:\n\n std::vector<std::unique_ptr<StatusParagraph>> paragraphs;\n", "file_path": "toolsrc/include/vcpkg/statusparagraphs.h", "rank": 12, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct TripletInstance;\n\n\n\n struct Triplet\n\n {\n\n public:\n\n constexpr Triplet() noexcept : m_instance(&DEFAULT_INSTANCE) {}\n\n\n\n static Triplet from_canonical_name(std::string&& triplet_as_string);\n\n\n\n static const Triplet X86_WINDOWS;\n\n static const Triplet X64_WINDOWS;\n\n static const Triplet X86_UWP;\n\n static const Triplet X64_UWP;\n\n static const Triplet ARM_UWP;\n\n static const Triplet ARM64_UWP;\n\n static const Triplet ARM_WINDOWS;\n\n static const Triplet ARM64_WINDOWS;\n\n\n\n const std::string& canonical_name() const;\n\n const std::string& to_string() const;\n\n void to_string(std::string& out) const;\n\n size_t hash_code() const;\n\n\n\n bool operator==(Triplet other) const { return this->m_instance == other.m_instance; }\n\n bool operator<(Triplet other) const { return canonical_name() < other.canonical_name(); }\n\n\n\n private:\n\n static const TripletInstance DEFAULT_INSTANCE;\n\n\n\n constexpr Triplet(const TripletInstance* ptr) : m_instance(ptr) {}\n\n\n\n const TripletInstance* m_instance;\n", "file_path": "toolsrc/include/vcpkg/triplet.h", "rank": 13, "score": 133320.46582587465 }, { "content": "namespace vcpkg::Parse\n\n{\n\n struct TextRowCol\n\n {\n\n /// '0' indicates uninitialized; '1' is the first row.\n\n int row = 0;\n\n /// '0' indicates uninitialized; '1' is the first column.\n\n int column = 0;\n\n };\n", "file_path": "toolsrc/include/vcpkg/textrowcol.h", "rank": 14, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n ///\n\n /// <summary>\n\n /// Full specification of a package. Contains all information to reference\n\n /// a specific package.\n\n /// </summary>\n\n ///\n\n struct PackageSpec\n\n {\n\n PackageSpec() noexcept = default;\n\n PackageSpec(std::string name, Triplet triplet) : m_name(std::move(name)), m_triplet(triplet) {}\n\n\n\n static std::vector<PackageSpec> to_package_specs(const std::vector<std::string>& ports, Triplet triplet);\n\n\n\n const std::string& name() const;\n\n\n\n Triplet triplet() const;\n\n\n\n std::string dir() const;\n\n\n\n std::string to_string() const;\n\n void to_string(std::string& s) const;\n\n\n\n bool operator<(const PackageSpec& other) const\n\n {\n\n if (name() < other.name()) return true;\n\n if (name() > other.name()) return false;\n\n return triplet() < other.triplet();\n\n }\n\n\n\n private:\n\n std::string m_name;\n\n Triplet m_triplet;\n", "file_path": "toolsrc/include/vcpkg/packagespec.h", "rank": 15, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n enum class InstallState\n\n {\n\n ERROR_STATE,\n\n NOT_INSTALLED,\n\n HALF_INSTALLED,\n\n INSTALLED,\n\n };\n\n\n\n enum class Want\n\n {\n\n ERROR_STATE,\n\n UNKNOWN,\n\n INSTALL,\n\n HOLD,\n\n DEINSTALL,\n\n PURGE\n\n };\n\n\n\n /// <summary>\n\n /// Installed package metadata\n\n /// </summary>\n\n struct StatusParagraph\n\n {\n\n StatusParagraph() noexcept;\n\n explicit StatusParagraph(Parse::RawParagraph&& fields);\n\n\n\n bool is_installed() const { return want == Want::INSTALL && state == InstallState::INSTALLED; }\n\n\n\n BinaryParagraph package;\n\n Want want;\n\n InstallState state;\n\n };\n\n\n\n void serialize(const StatusParagraph& pgh, std::string& out_str);\n\n\n\n std::string to_string(InstallState f);\n\n\n\n std::string to_string(Want f);\n\n\n\n struct InstalledPackageView\n\n {\n\n InstalledPackageView() noexcept : core(nullptr) {}\n\n\n\n InstalledPackageView(const StatusParagraph* c, std::vector<const StatusParagraph*>&& fs)\n\n : core(c), features(std::move(fs))\n\n {\n\n }\n\n\n\n const PackageSpec& spec() const { return core->package.spec; }\n\n std::vector<PackageSpec> dependencies() const;\n\n std::unordered_map<std::string, std::vector<FeatureSpec>> feature_dependencies() const;\n\n\n\n const StatusParagraph* core;\n\n std::vector<const StatusParagraph*> features;\n\n };\n", "file_path": "toolsrc/include/vcpkg/statusparagraph.h", "rank": 16, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n StatusParagraphs database_load_check(const VcpkgPaths& paths);\n\n\n\n void write_update(const VcpkgPaths& paths, const StatusParagraph& p);\n\n\n\n struct StatusParagraphAndAssociatedFiles\n\n {\n\n StatusParagraph pgh;\n\n SortedVector<std::string> files;\n\n };\n\n\n\n std::vector<InstalledPackageView> get_installed_ports(const StatusParagraphs& status_db);\n\n std::vector<StatusParagraphAndAssociatedFiles> get_installed_files(const VcpkgPaths& paths,\n\n const StatusParagraphs& status_db);\n\n\n\n std::string shorten_text(const std::string& desc, const size_t length);\n", "file_path": "toolsrc/include/vcpkg/vcpkglib.h", "rank": 17, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n enum class ParagraphParseResult\n\n {\n\n SUCCESS = 0,\n\n EXPECTED_ONE_PARAGRAPH\n\n };\n\n\n\n struct ParagraphParseResultCategoryImpl final : std::error_category\n\n {\n\n virtual const char* name() const noexcept override;\n\n\n\n virtual std::string message(int ev) const noexcept override;\n\n };\n\n\n\n const std::error_category& paragraph_parse_result_category();\n\n\n\n std::error_code make_error_code(ParagraphParseResult e);\n\n\n\n ParagraphParseResult to_paragraph_parse_result(int i);\n\n\n\n ParagraphParseResult to_paragraph_parse_result(std::error_code ec);\n\n}\n\n\n\nnamespace std\n\n{\n\n // Enable implicit conversion to std::error_code\n\n template<>\n\n struct is_error_code_enum<vcpkg::ParagraphParseResult> : ::std::true_type\n\n {\n\n };\n", "file_path": "toolsrc/include/vcpkg/paragraphparseresult.h", "rank": 18, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct ParsedArguments\n\n {\n\n std::unordered_set<std::string> switches;\n\n std::unordered_map<std::string, std::string> settings;\n\n std::unordered_map<std::string, std::vector<std::string>> multisettings;\n\n };\n\n\n\n struct VcpkgPaths;\n\n\n\n struct CommandSwitch\n\n {\n\n constexpr CommandSwitch(const StringLiteral& name, const StringLiteral& short_help_text)\n\n : name(name), short_help_text(short_help_text)\n\n {\n\n }\n\n\n\n StringLiteral name;\n\n StringLiteral short_help_text;\n\n };\n\n\n\n struct CommandSetting\n\n {\n\n constexpr CommandSetting(const StringLiteral& name, const StringLiteral& short_help_text)\n\n : name(name), short_help_text(short_help_text)\n\n {\n\n }\n\n\n\n StringLiteral name;\n\n StringLiteral short_help_text;\n\n };\n\n\n\n struct CommandMultiSetting\n\n {\n\n constexpr CommandMultiSetting(const StringLiteral& name, const StringLiteral& short_help_text)\n\n : name(name), short_help_text(short_help_text)\n\n {\n\n }\n\n\n\n StringLiteral name;\n\n StringLiteral short_help_text;\n\n };\n\n\n\n struct CommandOptionsStructure\n\n {\n\n Span<const CommandSwitch> switches;\n\n Span<const CommandSetting> settings;\n\n Span<const CommandMultiSetting> multisettings;\n\n };\n\n\n\n struct CommandStructure\n\n {\n\n std::string example_text;\n\n\n\n size_t minimum_arity;\n\n size_t maximum_arity;\n\n\n\n CommandOptionsStructure options;\n\n\n\n std::vector<std::string> (*valid_arguments)(const VcpkgPaths& paths);\n\n };\n\n\n\n void display_usage(const CommandStructure& command_structure);\n\n\n\n#if defined(_WIN32)\n\n using CommandLineCharType = wchar_t;\n\n#else\n\n using CommandLineCharType = char;\n\n#endif\n\n\n\n struct VcpkgCmdArguments\n\n {\n\n static VcpkgCmdArguments create_from_command_line(const int argc, const CommandLineCharType* const* const argv);\n\n static VcpkgCmdArguments create_from_arg_sequence(const std::string* arg_begin, const std::string* arg_end);\n\n\n\n std::unique_ptr<std::string> vcpkg_root_dir;\n\n std::unique_ptr<std::string> scripts_root_dir;\n\n std::unique_ptr<std::string> triplet;\n\n std::unique_ptr<std::vector<std::string>> overlay_ports;\n\n std::unique_ptr<std::vector<std::string>> overlay_triplets;\n\n Optional<bool> debug = nullopt;\n\n Optional<bool> sendmetrics = nullopt;\n\n Optional<bool> printmetrics = nullopt;\n\n\n\n // feature flags\n\n Optional<bool> featurepackages = nullopt;\n\n Optional<bool> binarycaching = nullopt;\n\n\n\n std::string command;\n\n std::vector<std::string> command_arguments;\n\n\n\n ParsedArguments parse_arguments(const CommandStructure& command_structure) const;\n\n\n\n private:\n\n std::unordered_map<std::string, Optional<std::vector<std::string>>> optional_command_arguments;\n\n };\n", "file_path": "toolsrc/include/vcpkg/vcpkgcmdarguments.h", "rank": 19, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct GlobalState\n\n {\n\n static Util::LockGuarded<Chrono::ElapsedTimer> timer;\n\n static Util::LockGuarded<std::string> g_surveydate;\n\n\n\n static std::atomic<bool> g_binary_caching;\n\n\n\n static std::atomic<int> g_init_console_cp;\n\n static std::atomic<int> g_init_console_output_cp;\n\n static std::atomic<bool> g_init_console_initialized;\n\n };\n", "file_path": "toolsrc/include/vcpkg/globalstate.h", "rank": 20, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct UserConfig\n\n {\n\n std::string user_id;\n\n std::string user_time;\n\n std::string user_mac;\n\n\n\n std::string last_completed_survey;\n\n\n\n static UserConfig try_read_data(const Files::Filesystem& fs);\n\n\n\n void try_write_data(Files::Filesystem& fs) const;\n\n };\n\n\n\n fs::path get_user_dir();\n", "file_path": "toolsrc/include/vcpkg/userconfig.h", "rank": 21, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n /// <summary>\n\n /// Built package metadata\n\n /// </summary>\n\n struct BinaryParagraph\n\n {\n\n BinaryParagraph();\n\n explicit BinaryParagraph(Parse::RawParagraph fields);\n\n BinaryParagraph(const SourceParagraph& spgh,\n\n Triplet triplet,\n\n const std::string& abi_tag,\n\n const std::vector<FeatureSpec>& deps);\n\n BinaryParagraph(const SourceParagraph& spgh,\n\n const FeatureParagraph& fpgh,\n\n Triplet triplet,\n\n const std::vector<FeatureSpec>& deps);\n\n\n\n std::string displayname() const;\n\n\n\n std::string fullstem() const;\n\n\n\n std::string dir() const;\n\n\n\n PackageSpec spec;\n\n std::string version;\n\n std::string description;\n\n std::string maintainer;\n\n std::string feature;\n\n std::vector<std::string> default_features;\n\n std::vector<std::string> depends;\n\n std::string abi;\n\n Type type;\n\n };\n\n\n\n struct BinaryControlFile\n\n {\n\n BinaryParagraph core_paragraph;\n\n std::vector<BinaryParagraph> features;\n\n };\n\n\n\n void serialize(const BinaryParagraph& pgh, std::string& out_str);\n", "file_path": "toolsrc/include/vcpkg/binaryparagraph.h", "rank": 22, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n std::vector<FullPackageSpec> filter_dependencies(const std::vector<Dependency>& deps,\n\n Triplet t,\n\n const std::unordered_map<std::string, std::string>& cmake_vars);\n\n\n\n struct Type\n\n {\n\n enum\n\n {\n\n UNKNOWN,\n\n PORT,\n\n ALIAS,\n\n } type;\n\n\n\n static std::string to_string(const Type&);\n\n static Type from_string(const std::string&);\n\n };\n\n\n\n /// <summary>\n\n /// Port metadata of additional feature in a package (part of CONTROL file)\n\n /// </summary>\n\n struct FeatureParagraph\n\n {\n\n std::string name;\n\n std::string description;\n\n std::vector<Dependency> depends;\n\n };\n\n\n\n /// <summary>\n\n /// Port metadata of the core feature of a package (part of CONTROL file)\n\n /// </summary>\n\n struct SourceParagraph\n\n {\n\n std::string name;\n\n std::string version;\n\n std::string description;\n\n std::string maintainer;\n\n std::string homepage;\n\n std::vector<Dependency> depends;\n\n std::vector<std::string> default_features;\n\n Type type;\n\n std::string supports_expression;\n\n };\n\n\n\n /// <summary>\n\n /// Full metadata of a package: core and other features.\n\n /// </summary>\n\n struct SourceControlFile\n\n {\n\n SourceControlFile() = default;\n\n SourceControlFile(const SourceControlFile& scf)\n\n : core_paragraph(std::make_unique<SourceParagraph>(*scf.core_paragraph))\n\n {\n\n for (const auto& feat_ptr : scf.feature_paragraphs)\n\n {\n\n feature_paragraphs.emplace_back(std::make_unique<FeatureParagraph>(*feat_ptr));\n\n }\n\n }\n\n\n\n static Parse::ParseExpected<SourceControlFile> parse_control_file(\n\n const fs::path& path_to_control, std::vector<Parse::RawParagraph>&& control_paragraphs);\n\n\n\n std::unique_ptr<SourceParagraph> core_paragraph;\n\n std::vector<std::unique_ptr<FeatureParagraph>> feature_paragraphs;\n\n\n\n Optional<const FeatureParagraph&> find_feature(const std::string& featurename) const;\n\n Optional<const std::vector<Dependency>&> find_dependencies_for_feature(const std::string& featurename) const;\n", "file_path": "toolsrc/include/vcpkg/sourceparagraph.h", "rank": 23, "score": 133320.46582587465 }, { "content": "namespace vcpkg::Parse\n\n{\n\n struct IParseError\n\n {\n\n virtual ~IParseError() = default;\n\n virtual std::string format() const = 0;\n\n };\n\n\n\n struct ParseError : IParseError\n\n {\n\n ParseError(std::string origin, int row, int column, std::string line, std::string message)\n\n : origin(std::move(origin)), row(row), column(column), line(std::move(line)), message(std::move(message))\n\n {\n\n }\n\n\n\n const std::string origin;\n\n const int row;\n\n const int column;\n\n const std::string line;\n\n const std::string message;\n\n\n\n virtual std::string format() const override;\n\n };\n\n\n\n struct ParserBase\n\n {\n\n struct SourceLoc\n\n {\n\n const char* it;\n\n int row;\n\n int column;\n\n };\n\n\n\n void init(CStringView text, CStringView origin, TextRowCol init_rowcol = {})\n\n {\n\n m_text = text;\n\n m_origin = origin;\n\n m_it = text.c_str();\n\n row = init_rowcol.row ? init_rowcol.row : 1;\n\n column = init_rowcol.column ? init_rowcol.column : 1;\n\n }\n\n\n\n static constexpr bool is_whitespace(char ch) { return ch == ' ' || ch == '\\t' || ch == '\\r' || ch == '\\n'; }\n\n static constexpr bool is_lower_alpha(char ch) { return ch >= 'a' && ch <= 'z'; }\n\n static constexpr bool is_upper_alpha(char ch) { return ch >= 'A' && ch <= 'Z'; }\n\n static constexpr bool is_ascii_digit(char ch) { return ch >= '0' && ch <= '9'; }\n\n static constexpr bool is_lineend(char ch) { return ch == '\\r' || ch == '\\n' || ch == '\\0'; }\n\n static constexpr bool is_alphanum(char ch)\n\n {\n\n return is_upper_alpha(ch) || is_lower_alpha(ch) || is_ascii_digit(ch);\n\n }\n\n static constexpr bool is_alphanumdash(char ch) { return is_alphanum(ch) || ch == '-'; }\n\n\n\n StringView skip_whitespace() { return match_zero_or_more(is_whitespace); }\n\n StringView skip_tabs_spaces()\n\n {\n\n return match_zero_or_more([](char ch) { return ch == ' ' || ch == '\\t'; });\n\n }\n\n void skip_to_eof()\n\n {\n\n while (cur())\n\n ++m_it;\n\n }\n\n void skip_newline()\n\n {\n\n if (cur() == '\\r') next();\n\n if (cur() == '\\n') next();\n\n }\n\n void skip_line()\n\n {\n\n match_until(is_lineend);\n\n skip_newline();\n\n }\n\n\n\n template<class Pred>\n\n StringView match_zero_or_more(Pred p)\n\n {\n\n const char* start = m_it;\n\n auto ch = cur();\n\n while (ch != '\\0' && p(ch))\n\n ch = next();\n\n return {start, m_it};\n\n }\n\n template<class Pred>\n\n StringView match_until(Pred p)\n\n {\n\n const char* start = m_it;\n\n auto ch = cur();\n\n while (ch != '\\0' && !p(ch))\n\n ch = next();\n\n return {start, m_it};\n\n }\n\n\n\n CStringView text() const { return m_text; }\n\n const char* it() const { return m_it; }\n\n char cur() const { return *m_it; }\n\n SourceLoc cur_loc() const { return {m_it, row, column}; }\n\n char next()\n\n {\n\n char ch = *m_it;\n\n // See https://www.gnu.org/prep/standards/standards.html#Errors\n\n if (ch == '\\t')\n\n column = (column + 7) / 8 * 8 + 1; // round to next 8-width tab stop\n\n else if (ch == '\\n')\n\n {\n\n row++;\n\n column = 1;\n\n }\n\n else if (ch == '\\0')\n\n {\n\n return '\\0';\n\n }\n\n else\n\n {\n\n ++column;\n\n }\n\n return *++m_it;\n\n }\n\n bool at_eof() const { return *m_it == 0; }\n\n\n\n void add_error(std::string message) { add_error(std::move(message), cur_loc()); }\n\n void add_error(std::string message, const SourceLoc& loc);\n\n\n\n const Parse::IParseError* get_error() const { return m_err.get(); }\n\n std::unique_ptr<Parse::IParseError> extract_error() { return std::move(m_err); }\n\n\n\n private:\n\n const char* m_it;\n\n int row;\n\n int column;\n\n\n\n CStringView m_text;\n\n CStringView m_origin;\n\n\n\n std::unique_ptr<IParseError> m_err;\n", "file_path": "toolsrc/include/vcpkg/parse.h", "rank": 24, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct VersionT\n\n {\n\n VersionT() noexcept;\n\n VersionT(std::string&& value);\n\n VersionT(const std::string& value);\n\n\n\n const std::string& to_string() const;\n\n\n\n private:\n\n std::string value;\n\n };\n\n\n\n bool operator==(const VersionT& left, const VersionT& right);\n\n bool operator!=(const VersionT& left, const VersionT& right);\n\n\n\n struct VersionDiff\n\n {\n\n VersionT left;\n\n VersionT right;\n\n\n\n VersionDiff() noexcept;\n\n VersionDiff(const VersionT& left, const VersionT& right);\n\n\n\n std::string to_string() const;\n\n };\n", "file_path": "toolsrc/include/vcpkg/versiont.h", "rank": 25, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct ExpressionContext\n\n {\n\n // map of cmake variables and their values.\n\n const std::unordered_map<std::string, std::string>& cmake_context;\n\n\n\n // The legacy context is a string (typically the name of the triplet).\n\n // An identifier was considered 'true' if it is a substring of this.\n\n // It is now used for backwards compatability diagnostic messages and\n\n // will be eventually removed.\n\n const std::string& legacy_context;\n\n };\n\n\n\n // Evaluate simple vcpkg logic expressions. An identifier in the expression is considered 'true'\n\n // if it is a substring of the evaluation_context (typically the name of the triplet)\n\n ExpectedT<bool, std::string> evaluate_expression(const std::string& expression, const ExpressionContext& context);\n", "file_path": "toolsrc/include/vcpkg/logicexpression.h", "rank": 26, "score": 133320.46582587465 }, { "content": "namespace vcpkg::Input\n\n{\n\n PackageSpec check_and_get_package_spec(std::string&& spec_string,\n\n Triplet default_triplet,\n\n CStringView example_text);\n\n FullPackageSpec check_and_get_full_package_spec(std::string&& spec_string,\n\n Triplet default_triplet,\n\n CStringView example_text);\n\n\n\n void check_triplet(Triplet t, const VcpkgPaths& paths);\n", "file_path": "toolsrc/include/vcpkg/input.h", "rank": 27, "score": 133320.46582587465 }, { "content": "namespace vcpkg::Help\n\n{\n\n extern const CommandStructure COMMAND_STRUCTURE;\n\n\n\n void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths);\n\n\n\n void help_topic_valid_triplet(const VcpkgPaths& paths);\n\n\n\n void print_usage();\n\n\n\n std::string create_example_string(const std::string& command_and_arguments);\n", "file_path": "toolsrc/include/vcpkg/help.h", "rank": 28, "score": 133320.46582587465 }, { "content": "namespace vcpkg\n\n{\n\n struct VcpkgPaths;\n\n\n\n struct ToolCache\n\n {\n\n virtual ~ToolCache() {}\n\n\n\n virtual const fs::path& get_tool_path(const VcpkgPaths& paths, const std::string& tool) const = 0;\n\n virtual const std::string& get_tool_version(const VcpkgPaths& paths, const std::string& tool) const = 0;\n\n };\n\n\n\n std::unique_ptr<ToolCache> get_tool_cache();\n", "file_path": "toolsrc/include/vcpkg/tools.h", "rank": 29, "score": 133320.46582587465 }, { "content": "namespace vcpkg::Parse\n\n{\n\n struct ParseControlErrorInfo\n\n {\n\n std::string name;\n\n std::vector<std::string> missing_fields;\n\n std::vector<std::string> extra_fields;\n\n std::string error;\n\n };\n\n\n\n template<class P>\n\n using ParseExpected = vcpkg::ExpectedT<std::unique_ptr<P>, std::unique_ptr<ParseControlErrorInfo>>;\n\n\n\n using RawParagraph = std::unordered_map<std::string, std::string>;\n\n\n\n struct ParagraphParser\n\n {\n\n ParagraphParser(RawParagraph&& fields) : fields(std::move(fields)) {}\n\n\n\n void required_field(const std::string& fieldname, std::string& out);\n\n std::string optional_field(const std::string& fieldname) const;\n\n std::unique_ptr<ParseControlErrorInfo> error_info(const std::string& name) const;\n\n\n\n private:\n\n RawParagraph&& fields;\n\n std::vector<std::string> missing_fields;\n\n };\n\n\n\n ExpectedS<std::vector<std::string>> parse_default_features_list(const std::string& str,\n\n CStringView origin = \"<unknown>\");\n\n ExpectedS<std::vector<ParsedQualifiedSpecifier>> parse_qualified_specifier_list(const std::string& str,\n\n CStringView origin = \"<unknown>\");\n\n ExpectedS<std::vector<Dependency>> parse_dependencies_list(const std::string& str,\n\n CStringView origin = \"<unknown>\");\n", "file_path": "toolsrc/include/vcpkg/paragraphparser.h", "rank": 30, "score": 133320.46582587465 }, { "content": " mutable vcpkg::Cache<Triplet, fs::path> m_triplets_cache;\n", "file_path": "toolsrc/include/vcpkg/vcpkgpaths.h", "rank": 31, "score": 133320.46582587465 }, { "content": " namespace Maps\n\n {\n\n template<class K, class V1, class V2, class Func>\n\n void transform_values(const std::unordered_map<K, V1>& container, std::unordered_map<K, V2>& output, Func func)\n\n {\n\n std::for_each(container.cbegin(), container.cend(), [&](const std::pair<const K, V1>& p) {\n\n output[p.first] = func(p.second);\n\n });\n\n }\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 32, "score": 132639.3846547587 }, { "content": " PackageSpec emplace(vcpkg::SourceControlFileLocation&& scfl);\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 33, "score": 132639.3846547587 }, { "content": " namespace Sets\n\n {\n\n template<class Container, class Key>\n\n bool contains(const Container& container, const Key& item)\n\n {\n\n return container.find(item) != container.end();\n\n }\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 34, "score": 132639.3846547587 }, { "content": " constexpr operator bool() const noexcept { return tag == Yes; }\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 35, "score": 132639.3846547587 }, { "content": " namespace Enum\n\n {\n\n template<class E>\n\n E to_enum(bool b)\n\n {\n\n return b ? E::YES : E::NO;\n\n }\n\n\n\n template<class E>\n\n bool to_bool(E e)\n\n {\n\n return e == E::YES;\n\n }\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 36, "score": 132639.3846547587 }, { "content": " constexpr operator bool() const noexcept { return tag == Yes; }\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 37, "score": 132639.3846547587 }, { "content": " ResourceBase& operator=(ResourceBase&&) = delete;\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 38, "score": 132639.3846547587 }, { "content": " Triplet triplet;\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 39, "score": 132639.3846547587 }, { "content": " PackageSpecMap(Triplet t = Triplet::X86_WINDOWS) noexcept : triplet(t) {}\n\n\n\n PackageSpec emplace(const char* name,\n\n const char* depends = \"\",\n\n const std::vector<std::pair<const char*, const char*>>& features = {},\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 40, "score": 132639.3846547587 }, { "content": "namespace vcpkg\n\n{\n\n template<class T>\n\n using View = Span<const T>;\n", "file_path": "toolsrc/include/vcpkg/base/view.h", "rank": 41, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n struct NullOpt\n\n {\n\n explicit constexpr NullOpt(int) {}\n\n };\n\n\n\n const static constexpr NullOpt nullopt{0};\n\n\n\n namespace details\n\n {\n\n template<class T, bool B = std::is_copy_constructible<T>::value>\n\n struct OptionalStorage\n\n {\n\n#if defined(_WIN32)\n\n#pragma warning(suppress : 26495)\n\n#endif\n\n constexpr OptionalStorage() noexcept : m_is_present(false), m_inactive() {}\n\n constexpr OptionalStorage(const T& t) : m_is_present(true), m_t(t) {}\n\n constexpr OptionalStorage(T&& t) : m_is_present(true), m_t(std::move(t)) {}\n\n\n\n ~OptionalStorage() noexcept\n\n {\n\n if (m_is_present) m_t.~T();\n\n }\n\n\n\n#if defined(_WIN32)\n\n#pragma warning(suppress : 26495)\n\n#endif\n\n OptionalStorage(const OptionalStorage& o) : m_is_present(o.m_is_present), m_inactive()\n\n {\n\n if (m_is_present) new (&m_t) T(o.m_t);\n\n }\n\n\n\n#if defined(_WIN32)\n\n#pragma warning(suppress : 26495)\n\n#endif\n\n OptionalStorage(OptionalStorage&& o) noexcept : m_is_present(o.m_is_present), m_inactive()\n\n {\n\n if (m_is_present)\n\n {\n\n new (&m_t) T(std::move(o.m_t));\n\n }\n\n }\n\n\n\n OptionalStorage& operator=(const OptionalStorage& o)\n\n {\n\n if (m_is_present && o.m_is_present)\n\n {\n\n m_t = o.m_t;\n\n }\n\n else if (!m_is_present && o.m_is_present)\n\n {\n\n m_is_present = true;\n\n new (&m_t) T(o.m_t);\n\n }\n\n else if (m_is_present && !o.m_is_present)\n\n {\n\n clear();\n\n }\n\n return *this;\n\n }\n\n\n\n OptionalStorage& operator=(OptionalStorage&& o) noexcept\n\n {\n\n if (m_is_present && o.m_is_present)\n\n {\n\n m_t = std::move(o.m_t);\n\n }\n\n else if (!m_is_present && o.m_is_present)\n\n {\n\n m_is_present = true;\n\n new (&m_t) T(std::move(o.m_t));\n\n }\n\n else if (m_is_present && !o.m_is_present)\n\n {\n\n clear();\n\n }\n\n return *this;\n\n }\n\n\n\n constexpr bool has_value() const { return m_is_present; }\n\n\n\n const T& value() const { return this->m_t; }\n\n T& value() { return this->m_t; }\n\n\n\n private:\n\n void clear()\n\n {\n\n m_is_present = false;\n\n m_t.~T();\n\n m_inactive = '\\0';\n\n }\n\n\n\n bool m_is_present;\n\n union {\n\n char m_inactive;\n\n T m_t;\n\n };\n", "file_path": "toolsrc/include/vcpkg/base/optional.h", "rank": 42, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n struct CStringView\n\n {\n\n constexpr CStringView() noexcept : cstr(nullptr) {}\n\n constexpr CStringView(const char* cstr) : cstr(cstr) {}\n\n constexpr CStringView(const CStringView&) = default;\n\n CStringView(const std::string& str) : cstr(str.c_str()) {}\n\n\n\n constexpr const char* c_str() const { return cstr; }\n\n\n\n void to_string(std::string& str) const { str.append(cstr); }\n\n\n\n private:\n\n const char* cstr;\n", "file_path": "toolsrc/include/vcpkg/base/cstringview.h", "rank": 43, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n struct StringView\n\n {\n\n static std::vector<StringView> find_all_enclosed(const StringView& input,\n\n const std::string& left_delim,\n\n const std::string& right_delim);\n\n\n\n static StringView find_exactly_one_enclosed(const StringView& input,\n\n const std::string& left_tag,\n\n const std::string& right_tag);\n\n\n\n static Optional<StringView> find_at_most_one_enclosed(const StringView& input,\n\n const std::string& left_tag,\n\n const std::string& right_tag);\n\n\n\n constexpr StringView() = default;\n\n StringView(const std::string& s); // Implicit by design\n\n template<size_t Sz>\n\n StringView(const char (&arr)[Sz]) : m_ptr(arr), m_size(Sz - 1)\n\n {\n\n }\n\n\n\n constexpr StringView(const char* ptr, size_t size) : m_ptr(ptr), m_size(size) {}\n\n constexpr StringView(const char* b, const char* e) : m_ptr(b), m_size(static_cast<size_t>(e - b)) {}\n\n\n\n constexpr const char* begin() const { return m_ptr; }\n\n constexpr const char* end() const { return m_ptr + m_size; }\n\n\n\n constexpr const char* data() const { return m_ptr; }\n\n constexpr size_t size() const { return m_size; }\n\n\n\n std::string to_string() const;\n\n void to_string(std::string& out) const;\n\n\n\n private:\n\n const char* m_ptr = 0;\n\n size_t m_size = 0;\n", "file_path": "toolsrc/include/vcpkg/base/stringview.h", "rank": 44, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n template<class Key, class Value>\n\n struct Cache\n\n {\n\n template<class F>\n\n Value const& get_lazy(const Key& k, const F& f) const\n\n {\n\n auto it = m_cache.find(k);\n\n if (it != m_cache.end()) return it->second;\n\n return m_cache.emplace(k, f()).first->second;\n\n }\n\n\n\n private:\n\n mutable std::map<Key, Value> m_cache;\n\n };\n", "file_path": "toolsrc/include/vcpkg/base/cache.h", "rank": 45, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n enum class MachineType : uint16_t\n\n {\n\n UNKNOWN = 0x0, // The contents of this field are assumed to be applicable to any machine type\n\n AM33 = 0x1d3, // Matsushita AM33\n\n AMD64 = 0x8664, // x64\n\n ARM = 0x1c0, // ARM little endian\n\n ARM64 = 0xaa64, // ARM64 little endian\n\n ARMNT = 0x1c4, // ARM Thumb-2 little endian\n\n EBC = 0xebc, // EFI byte code\n\n I386 = 0x14c, // Intel 386 or later processors and compatible processors\n\n IA64 = 0x200, // Intel Itanium processor family\n\n M32R = 0x9041, // Mitsubishi M32R little endian\n\n MIPS16 = 0x266, // MIPS16\n\n MIPSFPU = 0x366, // MIPS with FPU\n\n MIPSFPU16 = 0x466, // MIPS16 with FPU\n\n POWERPC = 0x1f0, // Power PC little endian\n\n POWERPCFP = 0x1f1, // Power PC with floating point support\n\n R4000 = 0x166, // MIPS little endian\n\n RISCV32 = 0x5032, // RISC-V 32-bit address space\n\n RISCV64 = 0x5064, // RISC-V 64-bit address space\n\n RISCV128 = 0x5128, // RISC-V 128-bit address space\n\n SH3 = 0x1a2, // Hitachi SH3\n\n SH3DSP = 0x1a3, // Hitachi SH3 DSP\n\n SH4 = 0x1a6, // Hitachi SH4\n\n SH5 = 0x1a8, // Hitachi SH5\n\n THUMB = 0x1c2, // Thumb\n\n WCEMIPSV2 = 0x169, // MIPS little-endian WCE v2\n\n };\n\n\n\n MachineType to_machine_type(const uint16_t value);\n", "file_path": "toolsrc/include/vcpkg/base/machinetype.h", "rank": 46, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n // A counted view of a null-terminated string\n\n struct ZStringView\n\n {\n\n using value_type = char;\n\n\n\n constexpr ZStringView() : m_size(0), m_cstr(\"\") {}\n\n\n\n template<int N>\n\n constexpr ZStringView(const char (&str)[N])\n\n : m_size(N - 1) /* -1 here accounts for the null byte at the end*/, m_cstr(str)\n\n {\n\n }\n\n\n\n ZStringView(const std::string& s) : m_size(s.size()), m_cstr(s.c_str()) {}\n\n constexpr ZStringView(const char* str, size_t sz) : m_size(sz), m_cstr(str) {}\n\n\n\n constexpr const char* data() const { return m_cstr; }\n\n constexpr size_t size() const { return m_size; }\n\n constexpr char operator[](ptrdiff_t off) const { return m_cstr[off]; }\n\n\n\n constexpr const char* c_str() const { return m_cstr; }\n\n\n\n constexpr const char* begin() const { return m_cstr; }\n\n constexpr const char* end() const { return m_cstr + m_size; }\n\n\n\n std::string to_string() const { return std::string(m_cstr, m_size); }\n\n void to_string(std::string& out) const { out.append(m_cstr, m_size); }\n\n\n\n constexpr operator StringView() const { return StringView(m_cstr, m_size); }\n\n\n\n private:\n\n size_t m_size;\n\n const char* m_cstr;\n", "file_path": "toolsrc/include/vcpkg/base/zstringview.h", "rank": 47, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n template<class T>\n\n struct Span\n\n {\n\n public:\n\n static_assert(std::is_object<T>::value, \"Span<non-object-type> is illegal\");\n\n\n\n using value_type = std::decay_t<T>;\n\n using element_type = T;\n\n using pointer = std::add_pointer_t<T>;\n\n using reference = std::add_lvalue_reference_t<T>;\n\n using iterator = pointer;\n\n\n\n constexpr Span() noexcept : m_ptr(nullptr), m_count(0) {}\n\n constexpr Span(std::nullptr_t) noexcept : m_ptr(nullptr), m_count(0) {}\n\n constexpr Span(pointer ptr, size_t count) noexcept : m_ptr(ptr), m_count(count) {}\n\n constexpr Span(pointer ptr_begin, pointer ptr_end) noexcept : m_ptr(ptr_begin), m_count(ptr_end - ptr_begin) {}\n\n\n\n template<size_t N>\n\n constexpr Span(T (&arr)[N]) noexcept : m_ptr(arr), m_count(N)\n\n {\n\n }\n\n\n\n template<size_t N, class = std::enable_if_t<std::is_const_v<T>>>\n\n constexpr Span(std::remove_const_t<T> (&arr)[N]) noexcept : m_ptr(arr), m_count(N)\n\n {\n\n }\n\n\n\n template<class Range,\n\n class = decltype(std::declval<Range>().data()),\n\n class = std::enable_if_t<!std::is_same<std::decay_t<Range>, Span>::value>>\n\n constexpr Span(Range&& v) noexcept : Span(v.data(), v.size())\n\n {\n\n static_assert(std::is_same<typename std::decay_t<Range>::value_type, value_type>::value,\n\n \"Cannot convert incompatible ranges\");\n\n }\n\n\n\n constexpr iterator begin() const { return m_ptr; }\n\n constexpr iterator end() const { return m_ptr + m_count; }\n\n\n\n constexpr reference operator[](size_t i) const { return m_ptr[i]; }\n\n constexpr pointer data() const { return m_ptr; }\n\n constexpr size_t size() const { return m_count; }\n\n\n\n private:\n\n pointer m_ptr;\n\n size_t m_count;\n\n };\n", "file_path": "toolsrc/include/vcpkg/base/span.h", "rank": 48, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n struct LineInfo\n\n {\n\n constexpr LineInfo() noexcept : m_line_number(0), m_file_name(\"\") {}\n\n constexpr LineInfo(const int lineno, const char* filename) : m_line_number(lineno), m_file_name(filename) {}\n\n\n\n std::string to_string() const;\n\n void to_string(std::string& out) const;\n\n\n\n private:\n\n int m_line_number;\n\n const char* m_file_name;\n\n };\n", "file_path": "toolsrc/include/vcpkg/base/lineinfo.h", "rank": 49, "score": 131285.39758559735 }, { "content": "namespace vcpkg\n\n{\n\n struct StringLiteral : ZStringView\n\n {\n\n template<int N>\n\n constexpr StringLiteral(const char (&str)[N]) : ZStringView(str)\n\n {\n\n }\n\n\n\n operator std::string() const { return std::string(data(), size()); }\n\n };\n", "file_path": "toolsrc/include/vcpkg/base/stringliteral.h", "rank": 50, "score": 131285.39758559735 }, { "content": "namespace vcpkg::Files\n\n{\n\n struct Filesystem\n\n {\n\n std::string read_contents(const fs::path& file_path, LineInfo linfo) const;\n\n virtual Expected<std::string> read_contents(const fs::path& file_path) const = 0;\n\n virtual Expected<std::vector<std::string>> read_lines(const fs::path& file_path) const = 0;\n\n virtual fs::path find_file_recursively_up(const fs::path& starting_dir, const std::string& filename) const = 0;\n\n virtual std::vector<fs::path> get_files_recursive(const fs::path& dir) const = 0;\n\n virtual std::vector<fs::path> get_files_non_recursive(const fs::path& dir) const = 0;\n\n void write_lines(const fs::path& file_path, const std::vector<std::string>& lines, LineInfo linfo);\n\n virtual void write_lines(const fs::path& file_path,\n\n const std::vector<std::string>& lines,\n\n std::error_code& ec) = 0;\n\n void write_contents(const fs::path& path, const std::string& data, LineInfo linfo);\n\n virtual void write_contents(const fs::path& file_path, const std::string& data, std::error_code& ec) = 0;\n\n void rename(const fs::path& oldpath, const fs::path& newpath, LineInfo linfo);\n\n virtual void rename(const fs::path& oldpath, const fs::path& newpath, std::error_code& ec) = 0;\n\n virtual void rename_or_copy(const fs::path& oldpath,\n\n const fs::path& newpath,\n\n StringLiteral temp_suffix,\n\n std::error_code& ec) = 0;\n\n bool remove(const fs::path& path, LineInfo linfo);\n\n virtual bool remove(const fs::path& path, std::error_code& ec) = 0;\n\n\n\n virtual void remove_all(const fs::path& path, std::error_code& ec, fs::path& failure_point) = 0;\n\n void remove_all(const fs::path& path, LineInfo li);\n\n bool exists(const fs::path& path, std::error_code& ec) const;\n\n bool exists(LineInfo li, const fs::path& path) const;\n\n // this should probably not exist, but would require a pass through of\n\n // existing code to fix\n\n bool exists(const fs::path& path) const;\n\n virtual bool is_directory(const fs::path& path) const = 0;\n\n virtual bool is_regular_file(const fs::path& path) const = 0;\n\n virtual bool is_empty(const fs::path& path) const = 0;\n\n virtual bool create_directory(const fs::path& path, std::error_code& ec) = 0;\n\n virtual bool create_directories(const fs::path& path, std::error_code& ec) = 0;\n\n virtual void copy(const fs::path& oldpath, const fs::path& newpath, fs::copy_options opts) = 0;\n\n virtual bool copy_file(const fs::path& oldpath,\n\n const fs::path& newpath,\n\n fs::copy_options opts,\n\n std::error_code& ec) = 0;\n\n virtual void copy_symlink(const fs::path& oldpath, const fs::path& newpath, std::error_code& ec) = 0;\n\n virtual fs::file_status status(const fs::path& path, std::error_code& ec) const = 0;\n\n virtual fs::file_status symlink_status(const fs::path& path, std::error_code& ec) const = 0;\n\n fs::file_status status(LineInfo li, const fs::path& p) const noexcept;\n\n fs::file_status symlink_status(LineInfo li, const fs::path& p) const noexcept;\n\n virtual fs::path canonical(const fs::path& path, std::error_code& ec) const = 0;\n\n fs::path canonical(LineInfo li, const fs::path& path) const;\n\n\n\n virtual std::vector<fs::path> find_from_PATH(const std::string& name) const = 0;\n\n };\n\n\n\n Filesystem& get_real_filesystem();\n\n\n\n static constexpr const char* FILESYSTEM_INVALID_CHARACTERS = R\"(\\/:*?\"<>|)\";\n\n\n\n bool has_invalid_chars_for_filesystem(const std::string& s);\n\n\n\n void print_paths(const std::vector<fs::path>& paths);\n", "file_path": "toolsrc/include/vcpkg/base/files.h", "rank": 51, "score": 131285.39758559735 }, { "content": "namespace vcpkg::Hash\n\n{\n\n enum class Algorithm\n\n {\n\n Sha1,\n\n Sha256,\n\n Sha512,\n\n };\n\n\n\n const char* to_string(Algorithm algo) noexcept;\n\n Optional<Algorithm> algorithm_from_string(StringView sv) noexcept;\n\n\n\n struct Hasher\n\n {\n\n virtual void add_bytes(const void* start, const void* end) noexcept = 0;\n\n\n\n // one may only call this once before calling `clear()` or the dtor\n\n virtual std::string get_hash() noexcept = 0;\n\n virtual void clear() noexcept = 0;\n\n virtual ~Hasher() = default;\n\n };\n\n\n\n std::unique_ptr<Hasher> get_hasher_for(Algorithm algo) noexcept;\n\n\n\n std::string get_bytes_hash(const void* first, const void* last, Algorithm algo) noexcept;\n\n std::string get_string_hash(StringView s, Algorithm algo) noexcept;\n\n std::string get_file_hash(const Files::Filesystem& fs,\n\n const fs::path& path,\n\n Algorithm algo,\n\n std::error_code& ec) noexcept;\n\n inline std::string get_file_hash(LineInfo li,\n\n const Files::Filesystem& fs,\n\n const fs::path& path,\n\n Algorithm algo) noexcept\n\n {\n\n std::error_code ec;\n\n const auto result = get_file_hash(fs, path, algo, ec);\n\n if (ec)\n\n {\n\n Checks::exit_with_message(li, \"Failure to read file for hashing: %s\", ec.message());\n\n }\n\n\n\n return result;\n\n }\n", "file_path": "toolsrc/include/vcpkg/base/hash.h", "rank": 52, "score": 131285.39758559735 }, { "content": "namespace vcpkg::Enums\n\n{\n\n std::string nullvalue_to_string(const CStringView enum_name);\n\n\n\n [[noreturn]] void nullvalue_used(const LineInfo& line_info, const CStringView enum_name);\n", "file_path": "toolsrc/include/vcpkg/base/enums.h", "rank": 53, "score": 131285.39758559735 }, { "content": "namespace vcpkg::Debug\n\n{\n\n extern std::atomic<bool> g_debugging;\n\n\n\n template<class... Args>\n\n void print(System::Color c, const Args&... args)\n\n {\n\n if (g_debugging) System::print2(c, \"[DEBUG] \", args...);\n\n }\n\n\n\n template<class... Args>\n\n void print(const Args&... args)\n\n {\n\n if (g_debugging) System::print2(\"[DEBUG] \", args...);\n\n }\n\n\n\n template<class F, class R = std::result_of_t<F && ()>, class = std::enable_if_t<!std::is_void<R>::value>>\n\n R time(LineInfo line, F&& f)\n\n {\n\n if (g_debugging)\n\n {\n\n auto timer = Chrono::ElapsedTimer::create_started();\n\n auto&& result = f();\n\n System::print2(\"[DEBUG] \", line, \" took \", timer, '\\n');\n\n return static_cast<R&&>(result);\n\n }\n\n else\n\n return f();\n\n }\n\n\n\n template<class F, class R = std::result_of_t<F && ()>, class = std::enable_if_t<std::is_void<R>::value>>\n\n void time(LineInfo line, F&& f)\n\n {\n\n if (g_debugging)\n\n {\n\n auto timer = Chrono::ElapsedTimer::create_started();\n\n f();\n\n System::print2(\"[DEBUG] \", line, \" took \", timer, '\\n');\n\n }\n\n else\n\n f();\n\n }\n", "file_path": "toolsrc/include/vcpkg/base/system.debug.h", "rank": 54, "score": 129345.4141561022 }, { "content": "namespace vcpkg\n\n{\n\n template<class Action>\n\n struct WorkQueue\n\n {\n\n WorkQueue(LineInfo li) : m_line_info(li) {}\n\n WorkQueue(const WorkQueue&) = delete;\n\n\n\n ~WorkQueue()\n\n {\n\n auto lck = std::unique_lock<std::mutex>(m_mutex, std::try_to_lock);\n\n /*\n\n if we don't own the lock, there isn't much we can do\n\n it is likely a spurious failure\n\n */\n\n if (lck && m_running_workers != 0)\n\n {\n\n Checks::exit_with_message(\n\n m_line_info, \"Internal error -- outstanding workers (%u) at destruct point\", m_running_workers);\n\n }\n\n }\n\n\n\n template<class F>\n\n void run_and_join(unsigned num_threads, const F& tld_init) noexcept\n\n {\n\n if (m_actions.empty()) return;\n\n\n\n std::vector<std::thread> threads;\n\n threads.reserve(num_threads);\n\n for (unsigned i = 0; i < num_threads; ++i)\n\n {\n\n threads.emplace_back(Worker<decltype(tld_init())>{this, tld_init()});\n\n }\n\n\n\n for (auto& thrd : threads)\n\n {\n\n thrd.join();\n\n }\n\n }\n\n\n\n // useful in the case of errors\n\n // doesn't stop any existing running tasks\n\n // returns immediately, so that one can call this in a task\n\n void cancel() const\n\n {\n\n {\n\n auto lck = std::lock_guard<std::mutex>(m_mutex);\n\n m_cancelled = true;\n\n m_actions.clear();\n\n }\n\n m_cv.notify_all();\n\n }\n\n\n\n void enqueue_action(Action a) const\n\n {\n\n {\n\n auto lck = std::lock_guard<std::mutex>(m_mutex);\n\n if (m_cancelled) return;\n\n\n\n m_actions.push_back(std::move(a));\n\n }\n\n m_cv.notify_one();\n\n }\n\n\n\n private:\n\n template<class ThreadLocalData>\n\n struct Worker\n\n {\n\n const WorkQueue* work_queue;\n\n ThreadLocalData tld;\n\n\n\n void operator()()\n\n {\n\n auto lck = std::unique_lock<std::mutex>(work_queue->m_mutex);\n\n for (;;)\n\n {\n\n const auto& w = *work_queue;\n\n work_queue->m_cv.wait(lck, [&w] {\n\n if (w.m_cancelled)\n\n return true;\n\n else if (!w.m_actions.empty())\n\n return true;\n\n else if (w.m_running_workers == 0)\n\n return true;\n\n else\n\n return false;\n\n });\n\n\n\n if (work_queue->m_cancelled || work_queue->m_actions.empty())\n\n {\n\n /*\n\n if we've been cancelled, or if the work queue is empty\n\n and there are no other workers, we want to return\n\n immediately; we don't check for the latter condition\n\n since if we're at this point, then either the queue\n\n is not empty, or there are no other workers, or both.\n\n We can't have an empty queue, and other workers, or\n\n we would still be in the wait.\n\n */\n\n break;\n\n }\n\n\n\n ++work_queue->m_running_workers;\n\n\n\n auto action = std::move(work_queue->m_actions.back());\n\n work_queue->m_actions.pop_back();\n\n\n\n lck.unlock();\n\n work_queue->m_cv.notify_one();\n\n std::move(action)(tld, *work_queue);\n\n lck.lock();\n\n\n\n const auto after = --work_queue->m_running_workers;\n\n if (work_queue->m_actions.empty() && after == 0)\n\n {\n\n work_queue->m_cv.notify_all();\n\n return;\n\n }\n\n }\n\n }\n\n };\n\n\n\n mutable std::mutex m_mutex{};\n\n // these are all under m_mutex\n\n mutable bool m_cancelled = false;\n\n mutable std::vector<Action> m_actions{};\n\n mutable std::condition_variable m_cv{};\n\n mutable unsigned long m_running_workers = 0;\n\n\n\n LineInfo m_line_info;\n", "file_path": "toolsrc/include/vcpkg/base/work_queue.h", "rank": 55, "score": 129345.4141561022 }, { "content": " void print_error_message(Span<const std::unique_ptr<Parse::ParseControlErrorInfo>> error_info_list);\n", "file_path": "toolsrc/include/vcpkg/sourceparagraph.h", "rank": 56, "score": 129316.84417821864 }, { "content": " UseHeadVersion use_head_version;\n", "file_path": "toolsrc/include/vcpkg/build.h", "rank": 57, "score": 129307.71462590605 }, { "content": " struct ResourceBase\n\n {\n\n ResourceBase() = default;\n\n ResourceBase(const ResourceBase&) = delete;\n\n ResourceBase(ResourceBase&&) = delete;\n\n\n\n ResourceBase& operator=(const ResourceBase&) = delete;\n\n ResourceBase& operator=(ResourceBase&&) = delete;\n\n\n\n ~ResourceBase() = default;\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 58, "score": 129266.64524898112 }, { "content": " MoveOnlyBase& operator=(MoveOnlyBase&&) = default;\n", "file_path": "toolsrc/include/vcpkg/base/util.h", "rank": 59, "score": 129266.64524898112 }, { "content": " constexpr AllowSymlinks(Tag tag) noexcept : tag(tag) {}\n\n\n", "file_path": "toolsrc/include/vcpkg-test/util.h", "rank": 60, "score": 129266.64524898112 }, { "content": "class Column {\n\n\tstd::vector<std::string> m_strings;\n\n\tsize_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;\n\n\tsize_t m_indent = 0;\n\n\tsize_t m_initialIndent = std::string::npos;\n\n\n\npublic:\n", "file_path": "toolsrc/include/catch2/catch.hpp", "rank": 61, "score": 121736.54328309494 }, { "content": "#define USE_ICONV 1\n\n\n", "file_path": "ports/fontconfig/include/win32/config.h", "rank": 62, "score": 118111.98117077928 }, { "content": "#define USE_ICONV 1\n\n\n", "file_path": "ports/fontconfig/include/unix/config.h", "rank": 63, "score": 118111.98117077928 }, { "content": "class Spacer : public Column {\n\n\n\npublic:\n\n\texplicit Spacer(size_t spaceWidth) : Column(\"\") {\n\n\t\twidth(spaceWidth);\n\n\t}\n\n};\n\n\n", "file_path": "toolsrc/include/catch2/catch.hpp", "rank": 64, "score": 106857.76611575644 }, { "content": " static std::atomic<bool> g_init_console_initialized;\n", "file_path": "toolsrc/include/vcpkg/globalstate.h", "rank": 65, "score": 93275.57683718667 }, { "content": " Graphs::Randomizer* randomizer = nullptr;\n", "file_path": "toolsrc/include/vcpkg/dependencies.h", "rank": 66, "score": 93275.57683718667 }, { "content": " std::string name;\n", "file_path": "toolsrc/include/vcpkg/packagespec.h", "rank": 67, "score": 93275.57683718667 }, { "content": "#include <catch2/catch.hpp>\n\n#include <vcpkg-test/util.h>\n\n\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/statusparagraphs.h>\n\n\n\nusing namespace vcpkg;\n\nusing namespace vcpkg::Paragraphs;\n\nusing namespace vcpkg::Test;\n\n\n\nTEST_CASE (\"find installed\", \"[statusparagraphs]\")\n\n{\n\n auto pghs = parse_paragraphs(R\"(\n\nPackage: ffmpeg\n\nVersion: 3.3.3\n\nArchitecture: x64-windows\n\nMulti-Arch: same\n\nDescription:\n\nStatus: install ok installed\n", "file_path": "toolsrc/src/vcpkg-test/statusparagraphs.cpp", "rank": 69, "score": 26.265933110527072 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/system.debug.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/binaryparagraph.h>\n\n#include <vcpkg/paragraphparseresult.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/parse.h>\n\n\n\nusing namespace vcpkg::Parse;\n\nusing namespace vcpkg;\n\n\n\nnamespace vcpkg::Paragraphs\n\n{\n\n struct PghParser : private Parse::ParserBase\n\n {\n\n private:\n\n void get_fieldvalue(std::string& fieldvalue)\n", "file_path": "toolsrc/src/vcpkg/paragraphs.cpp", "rank": 70, "score": 24.98996935609883 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/graphs.h>\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/packagespec.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/portfileprovider.h>\n\n#include <vcpkg/statusparagraphs.h>\n\n#include <vcpkg/vcpkglib.h>\n\n#include <vcpkg/vcpkgpaths.h>\n\n\n\nusing namespace vcpkg;\n\n\n\nnamespace vcpkg::Dependencies\n\n{\n\n namespace\n\n {\n", "file_path": "toolsrc/src/vcpkg/dependencies.cpp", "rank": 71, "score": 24.874938057695857 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/help.h>\n\n#include <vcpkg/input.h>\n\n#include <vcpkg/install.h>\n\n#include <vcpkg/packagespec.h>\n\n#include <vector>\n\n\n\nusing vcpkg::Dependencies::ActionPlan;\n\nusing vcpkg::Dependencies::InstallPlanAction;\n\nusing vcpkg::PortFileProvider::PathsPortFileProvider;\n\n\n\nnamespace vcpkg::Commands::DependInfo\n\n{\n\n namespace\n", "file_path": "toolsrc/src/vcpkg/commands.dependinfo.cpp", "rank": 72, "score": 24.469593555811986 }, { "content": "#include <catch2/catch.hpp>\n\n#include <vcpkg-test/mockcmakevarprovider.h>\n\n#include <vcpkg-test/util.h>\n\n\n\n#include <vcpkg/base/graphs.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/portfileprovider.h>\n\n#include <vcpkg/sourceparagraph.h>\n\n#include <vcpkg/triplet.h>\n\n\n\n#include <memory>\n\n#include <unordered_map>\n\n#include <vector>\n\n\n\nusing namespace vcpkg;\n\n\n\nusing Test::make_control_file;\n\nusing Test::make_status_feature_pgh;\n\nusing Test::make_status_pgh;\n\nusing Test::MockCMakeVarProvider;\n", "file_path": "toolsrc/src/vcpkg-test/plan.cpp", "rank": 73, "score": 24.066757740339384 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/help.h>\n\n#include <vcpkg/input.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/remove.h>\n\n#include <vcpkg/update.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\nnamespace vcpkg::Remove\n\n{\n\n using Dependencies::RemovePlanAction;\n\n using Dependencies::RemovePlanType;\n\n using Dependencies::RequestType;\n\n using Update::OutdatedPackage;\n\n\n", "file_path": "toolsrc/src/vcpkg/remove.cpp", "rank": 74, "score": 24.033442578767556 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/logicexpression.h>\n\n#include <vcpkg/packagespec.h>\n\n#include <vcpkg/sourceparagraph.h>\n\n#include <vcpkg/triplet.h>\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/expected.h>\n\n#include <vcpkg/base/span.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n\n\nnamespace vcpkg\n\n{\n\n using namespace vcpkg::Parse;\n\n\n\n namespace SourceParagraphFields\n\n {\n\n static const std::string BUILD_DEPENDS = \"Build-Depends\";\n", "file_path": "toolsrc/src/vcpkg/sourceparagraph.cpp", "rank": 75, "score": 23.89648986278238 }, { "content": "#include <catch2/catch.hpp>\n\n#include <vcpkg-test/mockcmakevarprovider.h>\n\n#include <vcpkg-test/util.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/paragraphparser.h>\n\n#include <vcpkg/sourceparagraph.h>\n\n\n\nusing namespace vcpkg;\n\nusing namespace vcpkg::Parse;\n\n\n\nTEST_CASE (\"parse depends\", \"[dependencies]\")\n\n{\n\n auto w = parse_dependencies_list(\"liba (windows)\");\n\n REQUIRE(w);\n\n auto& v = *w.get();\n\n REQUIRE(v.size() == 1);\n\n REQUIRE(v.at(0).depend.name == \"liba\");\n\n REQUIRE(v.at(0).qualifier == \"windows\");\n\n}\n\n\n", "file_path": "toolsrc/src/vcpkg-test/dependencies.cpp", "rank": 76, "score": 23.827874891257856 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/globalstate.h>\n\n#include <vcpkg/help.h>\n\n#include <vcpkg/input.h>\n\n#include <vcpkg/install.h>\n\n#include <vcpkg/statusparagraphs.h>\n\n#include <vcpkg/update.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n\n\nnamespace vcpkg::Commands::Upgrade\n\n{\n\n using Install::KeepGoing;\n\n using Install::to_keep_going;\n\n\n", "file_path": "toolsrc/src/vcpkg/commands.upgrade.cpp", "rank": 77, "score": 23.60242746936293 }, { "content": "#include <catch2/catch.hpp>\n\n#include <vcpkg-test/util.h>\n\n\n\n#include <vcpkg/base/sortedvector.h>\n\n\n\n#include <vcpkg/update.h>\n\n\n\nusing namespace vcpkg;\n\nusing namespace vcpkg::Update;\n\nusing namespace vcpkg::Test;\n\n\n\nusing Pgh = std::vector<std::unordered_map<std::string, std::string>>;\n\n\n\nTEST_CASE (\"find outdated packages basic\", \"[update]\")\n\n{\n\n std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs;\n\n status_paragraphs.push_back(make_status_pgh(\"a\"));\n\n status_paragraphs.back()->package.version = \"2\";\n\n\n\n StatusParagraphs status_db(std::move(status_paragraphs));\n", "file_path": "toolsrc/src/vcpkg-test/update.cpp", "rank": 78, "score": 22.789881076623807 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n\n\nnamespace vcpkg::System\n\n{\n\n namespace details\n\n {\n\n void print(StringView message) { fwrite(message.data(), 1, message.size(), stdout); }\n\n\n\n void print(const Color c, StringView message)\n\n {\n\n#if defined(_WIN32)\n\n const HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n\n\n\n CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info{};\n\n GetConsoleScreenBufferInfo(console_handle, &console_screen_buffer_info);\n\n const auto original_color = console_screen_buffer_info.wAttributes;\n\n\n", "file_path": "toolsrc/src/vcpkg/base/system.print.cpp", "rank": 79, "score": 22.597897526274778 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/optional.h>\n\n#include <vcpkg/base/span.h>\n\n#include <vcpkg/base/util.h>\n\n\n\n#include <vcpkg/cmakevars.h>\n\n\n\nusing namespace vcpkg;\n\nusing vcpkg::Optional;\n\nusing vcpkg::CMakeVars::TripletCMakeVarProvider;\n\n\n\nnamespace vcpkg::CMakeVars\n\n{\n\n fs::path TripletCMakeVarProvider::create_tag_extraction_file(\n\n const Span<const std::pair<const FullPackageSpec*, std::string>>& spec_abi_settings) const\n\n {\n\n Files::Filesystem& fs = paths.get_filesystem();\n\n static int tag_extract_id = 0;\n\n\n", "file_path": "toolsrc/src/vcpkg/cmakevars.cpp", "rank": 80, "score": 21.94177831817236 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/cache.h>\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/graphs.h>\n\n#include <vcpkg/base/stringliteral.h>\n\n#include <vcpkg/base/system.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/build.h>\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/globalstate.h>\n\n#include <vcpkg/help.h>\n\n#include <vcpkg/input.h>\n\n#include <vcpkg/install.h>\n\n#include <vcpkg/logicexpression.h>\n\n#include <vcpkg/packagespec.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\nusing namespace vcpkg;\n", "file_path": "toolsrc/src/vcpkg/commands.ci.cpp", "rank": 81, "score": 21.859266407270695 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/cofffilereader.h>\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/system.process.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/build.h>\n\n#include <vcpkg/packagespec.h>\n\n#include <vcpkg/postbuildlint.buildtype.h>\n\n#include <vcpkg/postbuildlint.h>\n\n#include <vcpkg/vcpkgpaths.h>\n\n\n\nusing vcpkg::Build::BuildInfo;\n\nusing vcpkg::Build::BuildPolicy;\n\nusing vcpkg::Build::PreBuildInfo;\n\n\n\nnamespace vcpkg::PostBuildLint\n\n{\n\n static auto not_extension_pred(const Files::Filesystem& fs, const std::string& ext)\n\n {\n\n return [&fs, ext](const fs::path& path) { return fs.is_directory(path) || path.extension() != ext; };\n\n }\n\n\n", "file_path": "toolsrc/src/vcpkg/postbuildlint.cpp", "rank": 82, "score": 21.418739153143132 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/system.process.h>\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/export.h>\n\n#include <vcpkg/export.ifw.h>\n\n#include <vcpkg/install.h>\n\n\n\nnamespace vcpkg::Export::IFW\n\n{\n\n using Dependencies::ExportPlanAction;\n\n using Dependencies::ExportPlanType;\n\n using Install::InstallDir;\n\n\n\n namespace\n\n {\n\n std::string create_release_date()\n\n {\n\n const tm date_time = Chrono::get_current_date_time_local();\n", "file_path": "toolsrc/src/vcpkg/commands.exportifw.cpp", "rank": 83, "score": 21.16525864752142 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/enums.h>\n\n\n\nnamespace vcpkg::Enums\n\n{\n\n std::string nullvalue_to_string(const CStringView enum_name) { return Strings::format(\"%s_NULLVALUE\", enum_name); }\n\n\n\n [[noreturn]] void nullvalue_used(const LineInfo& line_info, const CStringView enum_name)\n\n {\n\n Checks::exit_with_message(line_info, \"NULLVALUE of enum %s was used\", enum_name);\n\n }\n\n}\n", "file_path": "toolsrc/src/vcpkg/base/enums.cpp", "rank": 84, "score": 21.041867676759377 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/statusparagraph.h>\n\n\n\nusing namespace vcpkg::Parse;\n\n\n\nnamespace vcpkg\n\n{\n\n namespace BinaryParagraphRequiredField\n\n {\n\n static const std::string STATUS = \"Status\";\n\n }\n\n\n\n StatusParagraph::StatusParagraph() noexcept : want(Want::ERROR_STATE), state(InstallState::ERROR_STATE) {}\n\n\n\n void serialize(const StatusParagraph& pgh, std::string& out_str)\n\n {\n\n serialize(pgh.package, out_str);\n\n out_str.append(\"Status: \")\n", "file_path": "toolsrc/src/vcpkg/statusparagraph.cpp", "rank": 85, "score": 20.91349818038144 }, { "content": "#include <catch2/catch.hpp>\n\n#include <vcpkg-test/util.h>\n\n\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/strings.h>\n\n\n\n#include <iostream>\n\n#include <random>\n\n\n\n#include <vector>\n\n\n\nusing vcpkg::Test::AllowSymlinks;\n\nusing vcpkg::Test::base_temporary_directory;\n\nusing vcpkg::Test::can_create_symlinks;\n\n\n\n#define CHECK_EC_ON_FILE(file, ec) \\\n\n do \\\n\n { \\\n\n if (ec) \\\n\n { \\\n", "file_path": "toolsrc/src/vcpkg-test/files.cpp", "rank": 86, "score": 20.765429230031145 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/logicexpression.h>\n\n#include <vcpkg/parse.h>\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\nnamespace vcpkg\n\n{\n\n using vcpkg::Parse::ParseError;\n\n\n", "file_path": "toolsrc/src/vcpkg/logicexpression.cpp", "rank": 87, "score": 20.67330361338628 }, { "content": "#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/postbuildlint.h>\n\n#include <vcpkg/statusparagraphs.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\nusing namespace vcpkg;\n\nusing vcpkg::Build::BuildResult;\n\nusing vcpkg::Parse::ParseControlErrorInfo;\n\nusing vcpkg::Parse::ParseExpected;\n\nusing vcpkg::PortFileProvider::PathsPortFileProvider;\n\n\n\nnamespace vcpkg::Build::Command\n\n{\n\n using Dependencies::InstallPlanAction;\n\n using Dependencies::InstallPlanType;\n\n\n\n void perform_and_exit_ex(const FullPackageSpec& full_spec,\n\n const SourceControlFileLocation& scfl,\n\n const PathsPortFileProvider& provider,\n\n const ParsedArguments& options,\n", "file_path": "toolsrc/src/vcpkg/build.cpp", "rank": 88, "score": 20.314658203044164 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n\n\n#include <vcpkg/binaryparagraph.h>\n\n#include <vcpkg/paragraphparser.h>\n\n\n\nnamespace vcpkg\n\n{\n\n namespace Fields\n\n {\n\n static const std::string PACKAGE = \"Package\";\n\n static const std::string VERSION = \"Version\";\n\n static const std::string ARCHITECTURE = \"Architecture\";\n\n static const std::string MULTI_ARCH = \"Multi-Arch\";\n\n }\n\n\n\n namespace Fields\n", "file_path": "toolsrc/src/vcpkg/binaryparagraph.cpp", "rank": 89, "score": 20.086612464492745 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/metrics.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\nnamespace vcpkg\n\n{\n\n static StatusParagraphs load_current_database(Files::Filesystem& fs,\n\n const fs::path& vcpkg_dir_status_file,\n\n const fs::path& vcpkg_dir_status_file_old)\n\n {\n\n if (!fs.exists(vcpkg_dir_status_file))\n\n {\n\n if (!fs.exists(vcpkg_dir_status_file_old))\n\n {\n\n // no status file, use empty db\n", "file_path": "toolsrc/src/vcpkg/vcpkglib.cpp", "rank": 90, "score": 20.061188557211853 }, { "content": "#include <catch2/catch.hpp>\n\n#include <vcpkg-test/util.h>\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/statusparagraph.h>\n\n\n\n// used to get the implementation specific compiler flags (i.e., __cpp_lib_filesystem)\n\n#include <ciso646>\n\n\n\n#include <iostream>\n\n#include <memory>\n\n\n\n#if defined(_WIN32)\n\n#include <windows.h>\n\n#endif\n\n\n\n#define FILESYSTEM_SYMLINK_STD 0\n\n#define FILESYSTEM_SYMLINK_UNIX 1\n", "file_path": "toolsrc/src/vcpkg-test/util.cpp", "rank": 91, "score": 19.766082884303643 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/export.chocolatey.h>\n\n#include <vcpkg/export.h>\n\n#include <vcpkg/export.ifw.h>\n\n#include <vcpkg/help.h>\n\n#include <vcpkg/input.h>\n\n#include <vcpkg/install.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\n#include <vcpkg/base/stringliteral.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/system.process.h>\n\n#include <vcpkg/base/util.h>\n\n\n\nnamespace vcpkg::Export\n\n{\n", "file_path": "toolsrc/src/vcpkg/export.cpp", "rank": 92, "score": 19.570952855433955 }, { "content": "\n\n// start catch_stats.hpp\n\n\n\n// Statistical analysis tools\n\n\n\n\n\n#include <algorithm>\n\n#include <functional>\n\n#include <vector>\n\n#include <numeric>\n\n#include <tuple>\n\n#include <cmath>\n\n#include <utility>\n\n#include <cstddef>\n\n\n\nnamespace Catch {\n\n namespace Benchmark {\n\n namespace Detail {\n\n using sample = std::vector<double>;\n\n\n", "file_path": "toolsrc/include/catch2/catch.hpp", "rank": 93, "score": 19.491878916227087 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/hash.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/build.h>\n\n#include <vcpkg/cmakevars.h>\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/dependencies.h>\n\n#include <vcpkg/globalstate.h>\n\n#include <vcpkg/help.h>\n\n#include <vcpkg/input.h>\n\n#include <vcpkg/install.h>\n\n#include <vcpkg/metrics.h>\n\n#include <vcpkg/paragraphs.h>\n\n#include <vcpkg/remove.h>\n\n#include <vcpkg/vcpkglib.h>\n\n\n\nnamespace vcpkg::Install\n", "file_path": "toolsrc/src/vcpkg/install.cpp", "rank": 94, "score": 19.214035732119704 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/archives.h>\n\n#include <vcpkg/tools.h>\n\n#include <vcpkg/vcpkgpaths.h>\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/downloads.h>\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/optional.h>\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/stringview.h>\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/system.process.h>\n\n#include <vcpkg/base/util.h>\n\n\n\nnamespace vcpkg\n\n{\n\n struct ToolData\n\n {\n", "file_path": "toolsrc/src/vcpkg/tools.cpp", "rank": 95, "score": 19.20643384141482 }, { "content": "#include <catch2/catch.hpp>\n\n\n\n#include <vcpkg/base/system.print.h>\n\n#include <vcpkg/base/util.h>\n\n#include <vcpkg/packagespec.h>\n\n\n\nusing namespace vcpkg;\n\n\n\nTEST_CASE (\"specifier conversion\", \"[specifier]\")\n\n{\n\n SECTION (\"full package spec to feature specs\")\n\n {\n\n constexpr std::size_t SPEC_SIZE = 6;\n\n\n\n PackageSpec a_spec(\"a\", Triplet::X64_WINDOWS);\n\n PackageSpec b_spec(\"b\", Triplet::X64_WINDOWS);\n\n\n\n auto fspecs = FullPackageSpec{a_spec, {\"0\", \"1\"}}.to_feature_specs({}, {});\n\n auto fspecs2 = FullPackageSpec{b_spec, {\"2\", \"3\"}}.to_feature_specs({}, {});\n\n Util::Vectors::append(&fspecs, fspecs2);\n", "file_path": "toolsrc/src/vcpkg-test/specifier.cpp", "rank": 96, "score": 19.174774086113132 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/commands.h>\n\n#include <vcpkg/metrics.h>\n\n\n\n#include <vcpkg/base/chrono.h>\n\n#include <vcpkg/base/files.h>\n\n#include <vcpkg/base/hash.h>\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/system.process.h>\n\n\n\n#if defined(_WIN32)\n\n#pragma comment(lib, \"version\")\n\n#pragma comment(lib, \"winhttp\")\n\n#endif\n\n\n\nnamespace vcpkg::Metrics\n\n{\n\n Util::LockGuarded<Metrics> g_metrics;\n\n\n", "file_path": "toolsrc/src/vcpkg/metrics.cpp", "rank": 97, "score": 18.87512676810652 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/hash.h>\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/strings.h>\n\n#include <vcpkg/base/system.process.h>\n\n#include <vcpkg/base/util.h>\n\n\n\n#if defined(_WIN32)\n\n#include <bcrypt.h>\n\n#pragma comment(lib, \"bcrypt\")\n\n\n\n#ifndef NT_SUCCESS\n\n#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)\n\n#endif\n\n\n\n#endif\n\n\n\nnamespace vcpkg::Hash\n", "file_path": "toolsrc/src/vcpkg/base/hash.cpp", "rank": 98, "score": 18.84061086189783 }, { "content": "#include \"pch.h\"\n\n\n\n#include <vcpkg/base/checks.h>\n\n#include <vcpkg/base/cofffilereader.h>\n\n#include <vcpkg/base/stringliteral.h>\n\n\n\nusing namespace std;\n\n\n\nnamespace vcpkg::CoffFileReader\n\n{\n\n#if defined(_WIN32)\n\n template<class T>\n\n static T reinterpret_bytes(const char* data)\n\n {\n\n return (*reinterpret_cast<const T*>(&data[0]));\n\n }\n\n\n\n template<class T>\n\n static T read_value_from_stream(fstream& fs)\n\n {\n", "file_path": "toolsrc/src/vcpkg/base/cofffilereader.cpp", "rank": 99, "score": 18.643204748301407 } ]
C++
fly/logger/detail/win/styler_proxy_impl.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
#include "fly/logger/detail/win/styler_proxy_impl.hpp" namespace fly::logger::detail { StylerProxyImpl::StylerProxyImpl( std::ostream &stream, std::stack<fly::logger::Style> &&styles, std::stack<fly::logger::Color> &&colors, std::stack<fly::logger::Cursor> &&cursors) noexcept : StylerProxy(stream) { if (m_stream_is_stdout) { m_handle = ::GetStdHandle(STD_OUTPUT_HANDLE); } else if (m_stream_is_stderr) { m_handle = ::GetStdHandle(STD_ERROR_HANDLE); } if (m_handle == INVALID_HANDLE_VALUE) { return; } CONSOLE_SCREEN_BUFFER_INFO console_info; if (!::GetConsoleScreenBufferInfo(m_handle, &console_info)) { m_handle = INVALID_HANDLE_VALUE; return; } if (!styles.empty() || !colors.empty()) { apply_styles_and_colors(console_info, std::move(styles), std::move(colors)); } if (!cursors.empty()) { apply_cursors(console_info, std::move(cursors)); } } StylerProxyImpl::~StylerProxyImpl() { if (m_did_apply_style_or_color) { ::SetConsoleTextAttribute(m_handle, m_original_attributes); } } template <> void StylerProxyImpl::apply_value<WORD, fly::logger::Style>( WORD &attributes, const fly::logger::Style &modifier) { switch (modifier) { case fly::logger::Style::Bold: attributes |= FOREGROUND_INTENSITY; break; case fly::logger::Style::Underline: attributes |= COMMON_LVB_UNDERSCORE; break; default: break; } } template <> void StylerProxyImpl::apply_value<WORD, fly::logger::Color>( WORD &attributes, const fly::logger::Color &modifier) { auto apply_color = [&attributes, &modifier](bool red, bool green, bool blue) { if (modifier.m_plane == fly::logger::Color::Foreground) { attributes = red ? (attributes | FOREGROUND_RED) : (attributes & ~FOREGROUND_RED); attributes = green ? (attributes | FOREGROUND_GREEN) : (attributes & ~FOREGROUND_GREEN); attributes = blue ? (attributes | FOREGROUND_BLUE) : (attributes & ~FOREGROUND_BLUE); } else { attributes = red ? (attributes | BACKGROUND_RED) : (attributes & ~BACKGROUND_RED); attributes = green ? (attributes | BACKGROUND_GREEN) : (attributes & ~BACKGROUND_GREEN); attributes = blue ? (attributes | BACKGROUND_BLUE) : (attributes & ~BACKGROUND_BLUE); } }; switch (modifier.m_color) { case fly::logger::Color::Black: apply_color(false, false, false); break; case fly::logger::Color::Red: apply_color(true, false, false); break; case fly::logger::Color::Green: apply_color(false, true, false); break; case fly::logger::Color::Blue: apply_color(false, false, true); break; case fly::logger::Color::Yellow: apply_color(true, true, false); break; case fly::logger::Color::Magenta: apply_color(true, false, true); break; case fly::logger::Color::Cyan: apply_color(false, true, true); break; case fly::logger::Color::White: apply_color(true, true, true); break; } } template <> void StylerProxyImpl::apply_value<COORD, fly::logger::Cursor>( COORD &attributes, const fly::logger::Cursor &modifier) { const std::uint8_t &distance = modifier.m_distance; switch (modifier.m_direction) { case fly::logger::Cursor::Up: attributes.Y = (attributes.Y > distance) ? (attributes.Y - distance) : 0; break; case fly::logger::Cursor::Down: attributes.Y += distance; break; case fly::logger::Cursor::Forward: attributes.X += distance; break; case fly::logger::Cursor::Backward: attributes.X = (attributes.X > distance) ? (attributes.X - distance) : 0; break; } } void StylerProxyImpl::apply_styles_and_colors( const CONSOLE_SCREEN_BUFFER_INFO &console_info, std::stack<fly::logger::Style> &&styles, std::stack<fly::logger::Color> &&colors) { m_original_attributes = console_info.wAttributes; WORD attributes = m_original_attributes; for (; !styles.empty(); styles.pop()) { apply_value(attributes, styles.top()); } for (; !colors.empty(); colors.pop()) { apply_value(attributes, colors.top()); } m_did_apply_style_or_color = ::SetConsoleTextAttribute(m_handle, attributes); } void StylerProxyImpl::apply_cursors( const CONSOLE_SCREEN_BUFFER_INFO &console_info, std::stack<fly::logger::Cursor> &&cursors) { COORD cursor_position = console_info.dwCursorPosition; for (; !cursors.empty(); cursors.pop()) { apply_value(cursor_position, cursors.top()); } ::SetConsoleCursorPosition(m_handle, cursor_position); } }
#include "fly/logger/detail/win/styler_proxy_impl.hpp" namespace fly::logger::detail { StylerProxyImpl::StylerProxyImpl( std::ostream &stream, std::stack<fly::logger::Style> &&styles, std::stack<fly::logger::Color> &&colors, std::stack<fly::logger::Cursor> &&cursors) noexcept : StylerProxy(stream) {
if (m_handle == INVALID_HANDLE_VALUE) { return; } CONSOLE_SCREEN_BUFFER_INFO console_info; if (!::GetConsoleScreenBufferInfo(m_handle, &console_info)) { m_handle = INVALID_HANDLE_VALUE; return; } if (!styles.empty() || !colors.empty()) { apply_styles_and_colors(console_info, std::move(styles), std::move(colors)); } if (!cursors.empty()) { apply_cursors(console_info, std::move(cursors)); } } StylerProxyImpl::~StylerProxyImpl() { if (m_did_apply_style_or_color) { ::SetConsoleTextAttribute(m_handle, m_original_attributes); } } template <> void StylerProxyImpl::apply_value<WORD, fly::logger::Style>( WORD &attributes, const fly::logger::Style &modifier) { switch (modifier) { case fly::logger::Style::Bold: attributes |= FOREGROUND_INTENSITY; break; case fly::logger::Style::Underline: attributes |= COMMON_LVB_UNDERSCORE; break; default: break; } } template <> void StylerProxyImpl::apply_value<WORD, fly::logger::Color>( WORD &attributes, const fly::logger::Color &modifier) { auto apply_color = [&attributes, &modifier](bool red, bool green, bool blue) { if (modifier.m_plane == fly::logger::Color::Foreground) { attributes = red ? (attributes | FOREGROUND_RED) : (attributes & ~FOREGROUND_RED); attributes = green ? (attributes | FOREGROUND_GREEN) : (attributes & ~FOREGROUND_GREEN); attributes = blue ? (attributes | FOREGROUND_BLUE) : (attributes & ~FOREGROUND_BLUE); } else { attributes = red ? (attributes | BACKGROUND_RED) : (attributes & ~BACKGROUND_RED); attributes = green ? (attributes | BACKGROUND_GREEN) : (attributes & ~BACKGROUND_GREEN); attributes = blue ? (attributes | BACKGROUND_BLUE) : (attributes & ~BACKGROUND_BLUE); } }; switch (modifier.m_color) { case fly::logger::Color::Black: apply_color(false, false, false); break; case fly::logger::Color::Red: apply_color(true, false, false); break; case fly::logger::Color::Green: apply_color(false, true, false); break; case fly::logger::Color::Blue: apply_color(false, false, true); break; case fly::logger::Color::Yellow: apply_color(true, true, false); break; case fly::logger::Color::Magenta: apply_color(true, false, true); break; case fly::logger::Color::Cyan: apply_color(false, true, true); break; case fly::logger::Color::White: apply_color(true, true, true); break; } } template <> void StylerProxyImpl::apply_value<COORD, fly::logger::Cursor>( COORD &attributes, const fly::logger::Cursor &modifier) { const std::uint8_t &distance = modifier.m_distance; switch (modifier.m_direction) { case fly::logger::Cursor::Up: attributes.Y = (attributes.Y > distance) ? (attributes.Y - distance) : 0; break; case fly::logger::Cursor::Down: attributes.Y += distance; break; case fly::logger::Cursor::Forward: attributes.X += distance; break; case fly::logger::Cursor::Backward: attributes.X = (attributes.X > distance) ? (attributes.X - distance) : 0; break; } } void StylerProxyImpl::apply_styles_and_colors( const CONSOLE_SCREEN_BUFFER_INFO &console_info, std::stack<fly::logger::Style> &&styles, std::stack<fly::logger::Color> &&colors) { m_original_attributes = console_info.wAttributes; WORD attributes = m_original_attributes; for (; !styles.empty(); styles.pop()) { apply_value(attributes, styles.top()); } for (; !colors.empty(); colors.pop()) { apply_value(attributes, colors.top()); } m_did_apply_style_or_color = ::SetConsoleTextAttribute(m_handle, attributes); } void StylerProxyImpl::apply_cursors( const CONSOLE_SCREEN_BUFFER_INFO &console_info, std::stack<fly::logger::Cursor> &&cursors) { COORD cursor_position = console_info.dwCursorPosition; for (; !cursors.empty(); cursors.pop()) { apply_value(cursor_position, cursors.top()); } ::SetConsoleCursorPosition(m_handle, cursor_position); } }
if (m_stream_is_stdout) { m_handle = ::GetStdHandle(STD_OUTPUT_HANDLE); } else if (m_stream_is_stderr) { m_handle = ::GetStdHandle(STD_ERROR_HANDLE); }
if_condition
[ { "content": "struct Color\n\n{\n\n /**\n\n * Constants for standard colors.\n\n *\n\n * On Linux and macOS, a color may be any value in the range [0, 255]. While only the 8 standard\n\n * colors are listed here, any 8-bit integer value may be cast to a color. The color values\n\n * correspond to the ANSI 256-color lookup table:\n\n *\n\n * https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit.\n\n *\n\n * On Windows, the color may only be one of the 8 standard colors listed here.\n\n */\n\n enum StandardColor\n\n {\n\n Black,\n\n Red,\n\n Green,\n\n Yellow,\n\n Blue,\n", "file_path": "fly/logger/styler.hpp", "rank": 0, "score": 83202.41014058485 }, { "content": "struct Cursor\n\n{\n\n /**\n\n * Constants for the direction that the cursor should move.\n\n */\n\n enum Direction\n\n {\n\n Up,\n\n Down,\n\n Forward,\n\n Backward,\n\n };\n\n\n\n /**\n\n * Construct a Cursor instance with a direction and distance.\n\n *\n\n * @param direction The direction to move the cursor.\n\n * @param distance The distance to move the cursor.\n\n */\n\n constexpr Cursor(Direction direction, std::uint8_t distance = 1) noexcept :\n", "file_path": "fly/logger/styler.hpp", "rank": 1, "score": 83202.41014058485 }, { "content": " enum class Stream : std::uint8_t\n\n {\n\n Stdout,\n\n Stderr\n\n };\n\n\n\n /**\n\n * Constructor. Flush and redirect the given standard stream to a file.\n\n *\n\n * @param stream The standard stream to redirect.\n\n */\n\n CaptureStream(Stream stream) noexcept;\n\n\n\n /**\n\n * Destructor. Flush and restore the redirected stream and delete the redirect file.\n\n */\n\n ~CaptureStream();\n\n\n\n /**\n\n * Flush and restore the redirected stream, read the contents of the redirect file, and delete\n", "file_path": "test/util/capture_stream.hpp", "rank": 2, "score": 78838.87139218471 }, { "content": "enum class Style : std::uint8_t\n\n{\n\n Default,\n\n Blink,\n\n Bold,\n\n Dim,\n\n Italic,\n\n Strike,\n\n Underline,\n\n};\n\n\n\n/**\n\n * Struct to modify the foreground or background color of a std::ostream.\n\n */\n", "file_path": "fly/logger/styler.hpp", "rank": 3, "score": 67175.53166013025 }, { "content": "class BitStreamWriter : public detail::BitStream\n\n{\n\npublic:\n\n /**\n\n * Constructor. Write the header byte onto the stream.\n\n *\n\n * @param stream The stream to write binary data into.\n\n */\n\n explicit BitStreamWriter(std::ostream &stream) noexcept;\n\n\n\n /**\n\n * Write a multibyte word to the byte buffer.\n\n *\n\n * Flush the buffer to the stream if it is filled during this operation.\n\n *\n\n * @param word The word to write.\n\n */\n\n void write_word(word_type word);\n\n\n\n /**\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 4, "score": 59376.49918741066 }, { "content": "class BitStreamReader : public detail::BitStream\n\n{\n\npublic:\n\n /**\n\n * Constructor. Decode the header byte from the stream. If the header byte is invalid, the\n\n * stream's fail bit is set.\n\n *\n\n * @param stream The stream to read binary data from.\n\n */\n\n explicit BitStreamReader(std::istream &stream) noexcept;\n\n\n\n /**\n\n * Read a multibyte word from the byte buffer.\n\n *\n\n * Fill the buffer from the stream if the number of bits to read exceeds the number of bits\n\n * available.\n\n *\n\n * @param word The location to store the read word.\n\n *\n\n * @return True if the word was successfully read and filling the byte buffer was successful (if\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 5, "score": 59376.49918741066 }, { "content": "class BitStream\n\n{\n\npublic:\n\n /**\n\n * Destructor.\n\n */\n\n virtual ~BitStream();\n\n\n\nprotected:\n\n /**\n\n * Protected constructor to prevent instantiating this class directly.\n\n *\n\n * @param stream_buffer Pointer to the stream's underlying stream buffer.\n\n * @param starting_position Initial cursor position.\n\n */\n\n BitStream(std::streambuf *stream_buffer, byte_type starting_position) noexcept;\n\n\n\n /**\n\n * Create a bit-mask with the least-significant bits set. The size of the mask is determined by\n\n * the template DataType parameter.\n", "file_path": "fly/types/bit_stream/detail/bit_stream.hpp", "rank": 6, "score": 59271.056506074834 }, { "content": "struct BitStreamTraits\n\n{\n\n /**\n\n * Define a trait for testing if type T is an unsigned integral type.\n\n */\n\n template <typename T>\n\n using is_unsigned_integer = std::conjunction<\n\n std::is_integral<std::decay_t<T>>,\n\n std::is_unsigned<std::decay_t<T>>,\n\n std::negation<std::is_same<bool, std::decay_t<T>>>>;\n\n\n\n template <typename T>\n\n constexpr inline static bool is_unsigned_integer_v = is_unsigned_integer<T>::value;\n\n\n\n /**\n\n * Define a trait for testing if type T is buffer_type.\n\n */\n\n template <typename T>\n\n using is_buffer_type = std::is_same<buffer_type, std::decay_t<T>>;\n\n\n\n template <typename T>\n\n constexpr inline static bool is_buffer_type_v = is_buffer_type<T>::value;\n\n};\n\n\n\n} // namespace fly::detail\n", "file_path": "fly/types/bit_stream/detail/bit_stream_traits.hpp", "rank": 7, "score": 57348.59925201717 }, { "content": "#include \"fly/types/bit_stream/bit_stream_reader.hpp\"\n\n#include \"fly/types/bit_stream/bit_stream_writer.hpp\"\n\n#include \"fly/types/bit_stream/detail/bit_stream_constants.hpp\"\n\n#include \"fly/types/numeric/literals.hpp\"\n\n\n\n#include \"catch2/catch_test_macros.hpp\"\n\n\n\n#include <limits>\n\n#include <sstream>\n\n\n\nusing namespace fly::literals::numeric_literals;\n\n\n\nCATCH_TEST_CASE(\"BitStream\", \"[bit_stream]\")\n\n{\n\n std::istringstream input_stream(std::ios::in | std::ios::binary);\n\n std::ostringstream output_stream(std::ios::out | std::ios::binary);\n\n\n\n auto create_header = [](fly::byte_type remainder) -> fly::byte_type\n\n {\n\n return (fly::detail::s_magic << fly::detail::s_magic_shift) |\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 8, "score": 56257.8538030988 }, { "content": " {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_bits(1_u8, 1);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 1-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 2_u64);\n\n\n\n // The header should be the magic value and 7 remainder bits.\n\n verify_header(7_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(7_u8));\n\n\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 9, "score": 56249.93810322805 }, { "content": " {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_byte(0xa);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 1-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 2_u64);\n\n\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(0_u8));\n\n\n\n // Close the stream and read some bits. BitStreamReader will try to fill the internal\n\n // byte buffer, which will fail.\n\n input_stream.setstate(std::ios::failbit);\n\n CATCH_CHECK_FALSE(stream.read_byte(byte));\n\n }\n\n }\n\n}\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 10, "score": 56249.92619500088 }, { "content": " }\n\n\n\n CATCH_SECTION(\"Write and read a single word\")\n\n {\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_word(0xae);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 2-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 3_u64);\n\n\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::word_type word;\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 11, "score": 56249.91152129103 }, { "content": " fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header doesn't exist thus should not have been read.\n\n CATCH_CHECK(stream.header() == 0);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(input_stream.fail());\n\n }\n\n\n\n CATCH_SECTION(\"Writing no data to a writer stream must result in only the header being written\")\n\n {\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // Only a 1-byte header should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 1_u64);\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 12, "score": 56249.89698873078 }, { "content": " CATCH_SECTION(\"Try to peek more bits than are available\")\n\n {\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_bits(0x7f_u8, 7_u8);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 1-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 2_u64);\n\n\n\n // The header should be the magic value and 1 remainder bit.\n\n verify_header(1_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read.\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 13, "score": 56249.85601864301 }, { "content": " // Fill the internal byte buffer with all but one bit.\n\n stream.write_bits(buffer, length);\n\n\n\n // Close the stream and write more bits. BitStreamWriter will try to flush the stream,\n\n // which will fail.\n\n output_stream.setstate(std::ios::failbit);\n\n stream.write_bits(3_u8, 2);\n\n CATCH_CHECK_FALSE(stream.finish());\n\n }\n\n\n\n // A 1-byte header should have been written. Buffer bytes will be dropped.\n\n CATCH_CHECK(output_stream.str().size() == 1_u64);\n\n\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 14, "score": 56249.85667236089 }, { "content": " {\n\n fly::BitStreamWriter stream(output_stream);\n\n\n\n // Fill the internal byte buffer. BitStreamWriter will try to flush the stream, which\n\n // will fail.\n\n stream.write_bits(buffer, length);\n\n CATCH_CHECK_FALSE(stream.finish());\n\n }\n\n\n\n // The 1-byte should not have been written.\n\n CATCH_CHECK(output_stream.str().empty());\n\n }\n\n\n\n CATCH_SECTION(\"Verify detection of a writer stream that becomes invalid\")\n\n {\n\n constexpr auto buffer = std::numeric_limits<fly::buffer_type>::max() >> 1;\n\n constexpr auto length = std::numeric_limits<fly::buffer_type>::digits - 1;\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 15, "score": 56249.83624883051 }, { "content": "\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(0_u8));\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Verify detection of a reader stream that is initially invalid\")\n\n {\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_byte(0xa);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 1-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 2_u64);\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 16, "score": 56249.819466576766 }, { "content": " CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Verify peeking bits does not discard bits\")\n\n {\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_byte(0xa);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 1-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 2_u64);\n\n\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 17, "score": 56249.78849048311 }, { "content": "\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(0_u8));\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Verify detection of bad bit stream headers\")\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 18, "score": 56249.7491754472 }, { "content": "\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n // Close the stream before handing it to BitStreamReader.\n\n input_stream.setstate(std::ios::failbit);\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header doesn't exist thus should not have been read.\n\n CATCH_CHECK(stream.header() == 0);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Verify detection of a reader stream that becomes invalid\")\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 19, "score": 56249.73617445065 }, { "content": " // Reading a single bit should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 1_u8);\n\n CATCH_CHECK(byte == 1_u8);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Write and read a single byte\")\n\n {\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_byte(0xa);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header and a 1-byte buffer should have been written.\n\n CATCH_CHECK(output_stream.str().size() == 2_u64);\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 20, "score": 56249.68468235077 }, { "content": " fly::byte_type header = (fly::detail::s_magic - 1) << fly::detail::s_magic_shift;\n\n output_stream << static_cast<std::ios::char_type>(header);\n\n output_stream << \"data\";\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read, even though it's invalid.\n\n CATCH_CHECK(stream.header() == header);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(input_stream.fail());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Write and read a single bit\")\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 21, "score": 56249.67879478309 }, { "content": "\n\n // The header should be the magic value and 0 remainder bits.\n\n verify_header(0_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(0_u8));\n\n\n\n // Reading a single byte should succeed.\n\n CATCH_CHECK(stream.read_byte(byte));\n\n CATCH_CHECK(byte == 0xa);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 22, "score": 56249.67193578877 }, { "content": " stream.write_bits(0x1f_u8, 5);\n\n stream.write_bits(0xbc9bc9bc9bc9bc9b_u64, length);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header, 2 full internal byte buffers, and a 1-byte buffer should have been\n\n // written.\n\n CATCH_CHECK(\n\n output_stream.str().size() ==\n\n 2_u64 + ((length * 2) / std::numeric_limits<fly::byte_type>::digits));\n\n\n\n // The header should be the magic value and 3 remainder bits.\n\n verify_header(3_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n\n fly::BitStreamReader stream(input_stream);\n\n fly::buffer_type buffer;\n\n\n\n // The 1-byte header should have been read.\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 23, "score": 56249.62144651743 }, { "content": " constexpr auto length = std::numeric_limits<fly::buffer_type>::digits;\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_bits(0xae1ae1ae1ae1ae1a_u64, length);\n\n stream.write_bits(0x1f_u8, 5);\n\n stream.write_bits(0xbc9bc9bc9bc9bc9b_u64, length);\n\n CATCH_CHECK(stream.finish());\n\n }\n\n\n\n // A 1-byte header, 2 full internal byte buffers, and a 1-byte buffer should have been\n\n // written.\n\n CATCH_CHECK(\n\n output_stream.str().size() ==\n\n 2_u64 + ((length * 2) / std::numeric_limits<fly::byte_type>::digits));\n\n\n\n // The header should be the magic value and 3 remainder bits.\n\n verify_header(3_u8);\n\n\n\n input_stream.str(output_stream.str());\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 24, "score": 56249.62192990363 }, { "content": " fly::BitStreamReader stream(input_stream);\n\n fly::byte_type byte;\n\n\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(0_u8));\n\n\n\n // Peeking a single byte multiple times should succeed.\n\n for (std::uint8_t i = 0; i < 10; ++i)\n\n {\n\n CATCH_CHECK(stream.peek_bits(byte, 8_u8) == 8_u8);\n\n CATCH_CHECK(byte == 0xa);\n\n }\n\n\n\n // After discarding the peeked bits, no further reads should succeed.\n\n stream.discard_bits(8_u8);\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 25, "score": 56249.56498543631 }, { "content": "\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(0_u8));\n\n\n\n // Reading a single word should succeed.\n\n CATCH_CHECK(stream.read_word(word));\n\n CATCH_CHECK(word == 0xae);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(word, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Write and read multiple byte buffers\")\n\n {\n\n constexpr auto length = std::numeric_limits<fly::buffer_type>::digits;\n\n {\n\n fly::BitStreamWriter stream(output_stream);\n\n stream.write_bits(0xae1ae1ae1ae1ae1a_u64, length);\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 26, "score": 56249.48299793817 }, { "content": " CATCH_CHECK(stream.header() == create_header(1_u8));\n\n\n\n // Trying to peek 8 bits now should result in only 7 bits being peeked.\n\n CATCH_CHECK(stream.peek_bits(byte, 8_u8) == 7_u8);\n\n CATCH_CHECK(byte == 0x7f << 1);\n\n\n\n // After discarding the peeked bits, no further reads should succeed.\n\n stream.discard_bits(7_u8);\n\n CATCH_CHECK(stream.read_bits(byte, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Verify detection of a writer stream that is initially invalid\")\n\n {\n\n // Close the stream before handing it to BitStreamWriter.\n\n output_stream.setstate(std::ios::failbit);\n\n\n\n constexpr auto buffer = std::numeric_limits<fly::buffer_type>::max();\n\n constexpr auto length = std::numeric_limits<fly::buffer_type>::digits;\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 27, "score": 56249.38036811462 }, { "content": " fly::BitStreamReader stream(input_stream);\n\n fly::buffer_type buffer;\n\n\n\n // The 1-byte header should have been read.\n\n CATCH_CHECK(stream.header() == create_header(3_u8));\n\n\n\n // Reading all written bits should succeed. Here, the bits are read in an order such\n\n // that the second and third read must be split because they each read more than is\n\n // available in the internal byte buffer.\n\n CATCH_CHECK(stream.read_bits(buffer, 6) == 6_u8);\n\n CATCH_CHECK(buffer == 0x2b);\n\n\n\n CATCH_CHECK(stream.read_bits(buffer, 64) == 64_u8);\n\n CATCH_CHECK(buffer == 0x86b86b86b86b86bf_u64);\n\n\n\n CATCH_CHECK(stream.read_bits(buffer, 63) == 63_u8);\n\n CATCH_CHECK(buffer == 0x3c9bc9bc9bc9bc9b_u64);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(buffer, 1) == 0_u8);\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 28, "score": 56249.29966459881 }, { "content": " CATCH_CHECK(stream.header() == create_header(3_u8));\n\n\n\n // Reading all written bits should succeed.\n\n CATCH_CHECK(stream.read_bits(buffer, 64) == 64_u8);\n\n CATCH_CHECK(buffer == 0xae1ae1ae1ae1ae1a_u64);\n\n\n\n CATCH_CHECK(stream.read_bits(buffer, 15) == 15_u8);\n\n CATCH_CHECK(buffer == 0x7ef2);\n\n\n\n CATCH_CHECK(stream.read_bits(buffer, 54) == 54_u8);\n\n CATCH_CHECK(buffer == 0x1bc9bc9bc9bc9b_u64);\n\n\n\n // No further reads should succeed.\n\n CATCH_CHECK(stream.read_bits(buffer, 1) == 0_u8);\n\n CATCH_CHECK(stream.fully_consumed());\n\n }\n\n }\n\n\n\n CATCH_SECTION(\"Write and read multiple byte buffers, reading in an order that splits a read\")\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 29, "score": 56249.08545763156 }, { "content": " (remainder << fly::detail::s_remainder_shift);\n\n };\n\n\n\n auto verify_header = [&output_stream](fly::byte_type expected_remainder)\n\n {\n\n const std::string buffer = output_stream.str();\n\n CATCH_REQUIRE_FALSE(buffer.empty());\n\n\n\n const fly::byte_type header = static_cast<fly::byte_type>(buffer[0]);\n\n\n\n fly::byte_type magic = (header >> fly::detail::s_magic_shift) & fly::detail::s_magic_mask;\n\n fly::byte_type remainder =\n\n (header >> fly::detail::s_remainder_shift) & fly::detail::s_remainder_mask;\n\n\n\n CATCH_CHECK(magic == fly::detail::s_magic);\n\n CATCH_CHECK(remainder == expected_remainder);\n\n };\n\n\n\n CATCH_SECTION(\"Empty reader streams have no header and cannot be read\")\n\n {\n", "file_path": "test/types/bit_stream/bit_stream.cpp", "rank": 30, "score": 56247.80784742025 }, { "content": "class CaptureStream\n\n{\n\npublic:\n", "file_path": "test/util/capture_stream.hpp", "rank": 31, "score": 56243.19713850798 }, { "content": "#include \"fly/types/bit_stream/detail/bit_stream.hpp\"\n\n\n\nnamespace fly::detail {\n\n\n\n//==================================================================================================\n\nBitStream::BitStream(std::streambuf *stream_buffer, byte_type starting_position) noexcept :\n\n m_stream_buffer(stream_buffer),\n\n m_position(starting_position)\n\n{\n\n}\n\n\n\n//==================================================================================================\n\nBitStream::~BitStream() = default;\n\n\n\n} // namespace fly::detail\n", "file_path": "fly/types/bit_stream/detail/bit_stream.cpp", "rank": 32, "score": 54951.580619063636 }, { "content": "#include \"fly/types/bit_stream/bit_stream_writer.hpp\"\n\n\n\n#include \"fly/types/bit_stream/detail/bit_stream_constants.hpp\"\n\n#include \"fly/types/numeric/literals.hpp\"\n\n\n\nnamespace fly {\n\n\n\n//==================================================================================================\n\nBitStreamWriter::BitStreamWriter(std::ostream &stream) noexcept :\n\n BitStream(stream.rdbuf(), detail::s_most_significant_bit_position),\n\n m_stream(stream)\n\n{\n\n flush_header(0_u8);\n\n}\n\n\n\n//==================================================================================================\n\nvoid BitStreamWriter::write_word(word_type word)\n\n{\n\n write_bits(word, detail::s_bits_per_word);\n\n}\n", "file_path": "fly/types/bit_stream/bit_stream_writer.cpp", "rank": 33, "score": 54950.19864317391 }, { "content": "#include \"fly/types/bit_stream/bit_stream_reader.hpp\"\n\n\n\n#include \"fly/types/bit_stream/detail/bit_stream_constants.hpp\"\n\n#include \"fly/types/numeric/literals.hpp\"\n\n\n\nnamespace fly {\n\n\n\n//==================================================================================================\n\nBitStreamReader::BitStreamReader(std::istream &stream) noexcept :\n\n BitStream(stream.rdbuf(), 0),\n\n m_stream(stream)\n\n{\n\n byte_type magic = 0;\n\n\n\n // Cannot use read_byte because the remainder bits are not known yet.\n\n const byte_type bytes_read = fill(m_header, detail::s_byte_type_size);\n\n\n\n if (bytes_read == 1_u8)\n\n {\n\n magic = (m_header >> detail::s_magic_shift) & detail::s_magic_mask;\n", "file_path": "fly/types/bit_stream/bit_stream_reader.cpp", "rank": 34, "score": 54949.515632444665 }, { "content": "#pragma once\n\n\n\n#include \"fly/types/bit_stream/bit_stream_types.hpp\"\n\n#include \"fly/types/bit_stream/detail/bit_stream.hpp\"\n\n#include \"fly/types/bit_stream/detail/bit_stream_traits.hpp\"\n\n#include \"fly/types/numeric/endian.hpp\"\n\n\n\n#include <algorithm>\n\n#include <bit>\n\n#include <cstdint>\n\n#include <istream>\n\n\n\nnamespace fly {\n\n\n\n/**\n\n * Implementation of the BitStream interface for reading from a binary stream.\n\n *\n\n * The stream is read in a lazy manner; bytes are not read from the stream until they are needed.\n\n * The number of bytes read from the stream at once is defined by the size of buffer_type. That\n\n * buffer is stored in-memory until it has been entirely consumed by the caller, at which point it\n\n * is refilled.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version July 7, 2019\n\n */\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 35, "score": 54947.905592291194 }, { "content": "#pragma once\n\n\n\n#include \"fly/types/bit_stream/bit_stream_types.hpp\"\n\n#include \"fly/types/bit_stream/detail/bit_stream.hpp\"\n\n#include \"fly/types/bit_stream/detail/bit_stream_traits.hpp\"\n\n#include \"fly/types/numeric/endian.hpp\"\n\n\n\n#include <bit>\n\n#include <ostream>\n\n\n\nnamespace fly {\n\n\n\n/**\n\n * Implementation of the BitStream interface for writing to a binary stream.\n\n *\n\n * Bits are written to an in-memory byte buffer until that buffer is full, at which point that\n\n * buffer is flushed to the stream. When done writing, callers should invoke the finish() method to\n\n * flush the BitStream header and any bytes remaining in the buffer.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version July 7, 2019\n\n */\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 36, "score": 54947.61858934704 }, { "content": "#pragma once\n\n\n\n#include \"fly/types/bit_stream/bit_stream_types.hpp\"\n\n#include \"fly/types/bit_stream/detail/bit_stream_traits.hpp\"\n\n\n\n#include <limits>\n\n#include <streambuf>\n\n\n\nnamespace fly::detail {\n\n\n\n/**\n\n * Base class for writing to and reading from a binary stream. The first byte of the binary stream\n\n * is reserved as a header for internal use.\n\n *\n\n * The BitStream implementations allow reading and writing content bit-by-bit. Of course, files\n\n * cannot contain partial bytes. If a BitStream is closed with a partial byte remaining to be\n\n * written, that byte is zero-filled, and the number of extra bits written is encoded into the\n\n * header.\n\n *\n\n * The format of the header byte is then:\n", "file_path": "fly/types/bit_stream/detail/bit_stream.hpp", "rank": 37, "score": 54946.91860411063 }, { "content": "#pragma once\n\n\n\n#include <cstdint>\n\n\n\nnamespace fly {\n\n\n\nusing byte_type = std::uint8_t;\n\nusing word_type = std::uint16_t;\n\nusing buffer_type = std::uint64_t;\n\n\n\n} // namespace fly\n", "file_path": "fly/types/bit_stream/bit_stream_types.hpp", "rank": 38, "score": 54942.50612196718 }, { "content": "{\n\n static_assert(\n\n detail::BitStreamTraits::is_unsigned_integer_v<DataType>,\n\n \"DataType must be an unsigned integer type\");\n\n\n\n if (m_stream)\n\n {\n\n const std::streamsize bytes_read = m_stream_buffer->sgetn(\n\n reinterpret_cast<std::ios::char_type *>(&buffer),\n\n static_cast<std::streamsize>(bytes));\n\n\n\n buffer = endian_swap_if_non_native<std::endian::big>(buffer);\n\n return static_cast<byte_type>(bytes_read);\n\n }\n\n\n\n return 0;\n\n}\n\n\n\n} // namespace fly\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 39, "score": 54941.06120879675 }, { "content": " const byte_type remainder = (bits_to_flush - bits_in_buffer);\n\n flush_header(remainder);\n\n }\n\n\n\n return m_stream.good();\n\n}\n\n\n\n//==================================================================================================\n\nvoid BitStreamWriter::flush_header(byte_type remainder)\n\n{\n\n m_stream_buffer->pubseekpos(0);\n\n\n\n const byte_type header =\n\n (detail::s_magic << detail::s_magic_shift) | (remainder << detail::s_remainder_shift);\n\n flush(header, detail::s_byte_type_size);\n\n}\n\n\n\n//==================================================================================================\n\nvoid BitStreamWriter::flush_buffer()\n\n{\n\n flush(m_buffer, detail::s_buffer_type_size);\n\n\n\n m_position = detail::s_most_significant_bit_position;\n\n m_buffer = 0;\n\n}\n\n\n\n} // namespace fly\n", "file_path": "fly/types/bit_stream/bit_stream_writer.cpp", "rank": 40, "score": 54941.04112533898 }, { "content": " const byte_type lshift = m_position - size;\n\n\n\n m_buffer |= static_cast<buffer_type>(bits) << lshift;\n\n m_position = lshift;\n\n}\n\n\n\n//==================================================================================================\n\ntemplate <typename DataType>\n\nvoid BitStreamWriter::flush(const DataType &buffer, byte_type bytes)\n\n{\n\n static_assert(\n\n detail::BitStreamTraits::is_unsigned_integer_v<DataType>,\n\n \"DataType must be an unsigned integer type\");\n\n\n\n if (m_stream)\n\n {\n\n const DataType data = endian_swap_if_non_native<std::endian::big>(buffer);\n\n\n\n m_stream_buffer->sputn(\n\n reinterpret_cast<const std::ios::char_type *>(&data),\n\n static_cast<std::streamsize>(bytes));\n\n }\n\n}\n\n\n\n} // namespace fly\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 41, "score": 54940.587728562256 }, { "content": " static_assert(\n\n BitStreamTraits::is_unsigned_integer_v<DataType>,\n\n \"DataType must be an unsigned integer type\");\n\n\n\n static constexpr auto s_filled = std::numeric_limits<DataType>::max();\n\n static constexpr auto s_digits = std::numeric_limits<DataType>::digits;\n\n\n\n return (bits == 0) ? 0 : s_filled >> (s_digits - bits);\n\n}\n\n\n\n} // namespace fly::detail\n", "file_path": "fly/types/bit_stream/detail/bit_stream.hpp", "rank": 42, "score": 54939.719045445345 }, { "content": "\n\n//==================================================================================================\n\nbool BitStreamReader::fully_consumed() const\n\n{\n\n if (m_position == 0)\n\n {\n\n return m_stream_buffer->sgetc() == EOF;\n\n }\n\n\n\n return false;\n\n}\n\n\n\n//==================================================================================================\n\nbyte_type BitStreamReader::header() const\n\n{\n\n return m_header;\n\n}\n\n\n\n//==================================================================================================\n\nvoid BitStreamReader::refill_buffer()\n", "file_path": "fly/types/bit_stream/bit_stream_reader.cpp", "rank": 43, "score": 54938.983880862375 }, { "content": " */\n\n void discard_bits(byte_type size);\n\n\n\n /**\n\n * Check if the stream has reached end-of-file and the byte buffer has been fully consumed.\n\n *\n\n * @return True if the stream has been fully consumed.\n\n */\n\n bool fully_consumed() const;\n\n\n\n /**\n\n * @return The header byte decoded from the stream.\n\n */\n\n byte_type header() const;\n\n\n\nprivate:\n\n /**\n\n * Read from the stream to fill the byte buffer.\n\n */\n\n void refill_buffer();\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 44, "score": 54938.696162813976 }, { "content": " void write_bits(DataType bits, byte_type size);\n\n\n\n /**\n\n * If needed, zero-fill the byte buffer, flush it to the stream, and update the header byte.\n\n *\n\n * @return True if the stream remains in a good state.\n\n */\n\n bool finish();\n\n\n\nprivate:\n\n /**\n\n * Flush the header byte onto the stream.\n\n *\n\n * @param remainder The number of zero-filled bits in the byte buffer.\n\n */\n\n void flush_header(byte_type remainder);\n\n\n\n /**\n\n * Flush the byte buffer onto the stream.\n\n */\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 45, "score": 54938.365708910256 }, { "content": " *\n\n * | 5 bits | 3 bits |\n\n * ---------------------------------------------\n\n * | Magic number | Number of zero-filled bits |\n\n *\n\n * Each BitStream implementation essentially serves as a wrapper around an already existing\n\n * std::istream or std::ostream. It is expected that the pre-existing stream outlive the wrapper\n\n * BitStream instance.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version July 7, 2019\n\n */\n", "file_path": "fly/types/bit_stream/detail/bit_stream.hpp", "rank": 46, "score": 54938.27504329019 }, { "content": " void flush_buffer();\n\n\n\n /**\n\n * Flush a byte buffer to the stream.\n\n *\n\n * @tparam DataType The type of the byte buffer to flush.\n\n *\n\n * @param buffer The byte buffer to flush.\n\n * @param bytes The number of bytes to flush.\n\n */\n\n template <typename DataType>\n\n void flush(const DataType &buffer, byte_type bytes);\n\n\n\n std::ostream &m_stream;\n\n};\n\n\n\n//==================================================================================================\n\ntemplate <typename DataType>\n\nvoid BitStreamWriter::write_bits(DataType bits, byte_type size)\n\n{\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 47, "score": 54937.82441117405 }, { "content": " m_remainder = (m_header >> detail::s_remainder_shift) & detail::s_remainder_mask;\n\n }\n\n\n\n if (magic != detail::s_magic)\n\n {\n\n m_stream.setstate(std::ios::failbit);\n\n }\n\n}\n\n\n\n//==================================================================================================\n\nbool BitStreamReader::read_word(word_type &word)\n\n{\n\n return read_bits(word, detail::s_bits_per_word) == detail::s_bits_per_word;\n\n}\n\n\n\n//==================================================================================================\n\nbool BitStreamReader::read_byte(byte_type &byte)\n\n{\n\n return read_bits(byte, detail::s_bits_per_byte) == detail::s_bits_per_byte;\n\n}\n", "file_path": "fly/types/bit_stream/bit_stream_reader.cpp", "rank": 48, "score": 54937.77609722777 }, { "content": " {\n\n // At end-of-file, discard any encoded zero-filled bits.\n\n m_position -= m_remainder;\n\n m_buffer >>= m_remainder;\n\n }\n\n }\n\n}\n\n\n\n} // namespace fly\n", "file_path": "fly/types/bit_stream/bit_stream_reader.cpp", "rank": 49, "score": 54937.55160481816 }, { "content": "\n\n /**\n\n * Read from the stream to fill a byte buffer.\n\n *\n\n * @tparam DataType The type of the byte buffer to fill.\n\n *\n\n * @param buffer The byte buffer to fill.\n\n * @param bytes The number of bytes to read.\n\n *\n\n * @return The number of bytes actually read.\n\n */\n\n template <typename DataType>\n\n byte_type fill(DataType &buffer, byte_type bytes);\n\n\n\n std::istream &m_stream;\n\n\n\n byte_type m_header {0};\n\n byte_type m_remainder {0};\n\n};\n\n\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 50, "score": 54937.30468455127 }, { "content": " *\n\n * @tparam DataType The data type storing the number of bits to set.\n\n *\n\n * @param starting_position The number of bits to set.\n\n *\n\n * @return The created mask.\n\n */\n\n template <typename DataType>\n\n DataType bit_mask(const DataType bits);\n\n\n\n std::streambuf *m_stream_buffer;\n\n\n\n buffer_type m_buffer {0};\n\n byte_type m_position {0};\n\n};\n\n\n\n//==================================================================================================\n\ntemplate <typename DataType>\n\ninline DataType BitStream::bit_mask(const DataType bits)\n\n{\n", "file_path": "fly/types/bit_stream/detail/bit_stream.hpp", "rank": 51, "score": 54937.18922224852 }, { "content": " }\n\n\n\n const byte_type rshift = m_position - peeked - size;\n\n const DataType buffer = static_cast<DataType>(m_buffer >> rshift);\n\n\n\n bits |= (buffer & bit_mask<DataType>(size)) << lshift;\n\n peeked += size;\n\n\n\n return peeked;\n\n}\n\n\n\n//==================================================================================================\n\ninline void BitStreamReader::discard_bits(byte_type size)\n\n{\n\n m_position -= size;\n\n}\n\n\n\n//==================================================================================================\n\ntemplate <typename DataType>\n\nbyte_type BitStreamReader::fill(DataType &buffer, byte_type bytes)\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 52, "score": 54937.10631514885 }, { "content": "\n\n // Peek operations the site of the byte buffer are not supported because the byte buffer could\n\n // be in a state where it cannot be refilled.\n\n //\n\n // For example, consider a 64-bit byte buffer, and reading 6 bits and then 64 bits. After the\n\n // 6-bit read, there will be 58 bits left in the buffer; not enough for the next 64 bit read.\n\n // The buffer must then be refilled, but it cannot because there is less than 1 byte free in the\n\n // byte buffer.\n\n //\n\n // Ideally, given the split peek operations below, the given bits could be filled with the 58\n\n // available, then the byte buffer entirely refilled. But the caller then cannot discard more\n\n // than 6 bits, which invalidates the whole peek_bits/discard_bits semantic. BitStreamReader\n\n // would need to support putting bits back onto the stream.\n\n static_assert(\n\n !detail::BitStreamTraits::is_buffer_type_v<DataType>,\n\n \"peek_bits only supports types smaller than buffer_type\");\n\n\n\n byte_type peeked = 0, lshift = 0;\n\n bits = 0;\n\n\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 53, "score": 54937.07386864962 }, { "content": "\n\n//==================================================================================================\n\nvoid BitStreamWriter::write_byte(byte_type byte)\n\n{\n\n write_bits(byte, detail::s_bits_per_byte);\n\n}\n\n\n\n//==================================================================================================\n\nbool BitStreamWriter::finish()\n\n{\n\n const byte_type bits_in_buffer = detail::s_most_significant_bit_position - m_position;\n\n\n\n if (bits_in_buffer > 0)\n\n {\n\n const byte_type bits_to_flush = bits_in_buffer + (m_position % detail::s_bits_per_byte);\n\n\n\n flush(m_buffer, bits_to_flush / detail::s_bits_per_byte);\n\n m_position = detail::s_most_significant_bit_position;\n\n m_buffer = 0;\n\n\n", "file_path": "fly/types/bit_stream/bit_stream_writer.cpp", "rank": 54, "score": 54937.02638154422 }, { "content": "//==================================================================================================\n\ntemplate <typename DataType>\n\nbyte_type BitStreamReader::read_bits(DataType &bits, byte_type size)\n\n{\n\n static_assert(\n\n detail::BitStreamTraits::is_unsigned_integer_v<DataType>,\n\n \"DataType must be an unsigned integer type\");\n\n\n\n if constexpr (detail::BitStreamTraits::is_buffer_type_v<DataType>)\n\n {\n\n // See peek_bits for why buffer_type reads must be split.\n\n const byte_type size_high = size / 2;\n\n const byte_type size_low = size - size_high;\n\n std::uint32_t bits_high, bits_low;\n\n\n\n const byte_type bits_read_high = peek_bits(bits_high, size_high);\n\n discard_bits(bits_read_high);\n\n\n\n const byte_type bits_read_low = peek_bits(bits_low, size_low);\n\n discard_bits(bits_read_low);\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 55, "score": 54936.919056169354 }, { "content": "\n\n bits = (static_cast<DataType>(bits_high) << size_low) | bits_low;\n\n return bits_read_high + bits_read_low;\n\n }\n\n else\n\n {\n\n const byte_type bits_read = peek_bits(bits, size);\n\n discard_bits(bits_read);\n\n\n\n return bits_read;\n\n }\n\n}\n\n\n\n//==================================================================================================\n\ntemplate <typename DataType>\n\nbyte_type BitStreamReader::peek_bits(DataType &bits, byte_type size)\n\n{\n\n static_assert(\n\n detail::BitStreamTraits::is_unsigned_integer_v<DataType>,\n\n \"DataType must be an unsigned integer type\");\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 56, "score": 54936.874817101554 }, { "content": " * Write a full byte to the byte buffer.\n\n *\n\n * Flush the buffer to the stream if it is filled during this operation.\n\n *\n\n * @param byte The byte to write.\n\n */\n\n void write_byte(byte_type byte);\n\n\n\n /**\n\n * Write a number of bits to the byte buffer. The least-significant bits in the provided data\n\n * type will be written, starting from the position pointed to by the provided number of bits.\n\n *\n\n * Flush the buffer to the stream if it is filled during this operation.\n\n *\n\n * @tparam DataType The data type storing the bits to write.\n\n *\n\n * @param bits The bits to write.\n\n * @param size The number of bits to write.\n\n */\n\n template <typename DataType>\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 57, "score": 54936.874817101554 }, { "content": " static_assert(\n\n detail::BitStreamTraits::is_unsigned_integer_v<DataType>,\n\n \"DataType must be an unsigned integer type\");\n\n\n\n // If there are more bits to write than are available in the byte buffer, break the bits into\n\n // two chunks.\n\n if (size > m_position)\n\n {\n\n const byte_type rshift = size - m_position;\n\n\n\n // Fill the remainder of the byte buffer with as many bits as are available, and flush it\n\n // onto the stream.\n\n m_buffer |= static_cast<buffer_type>(bits) >> rshift;\n\n flush_buffer();\n\n\n\n // Then update the input bits to retain only those bits that have not been written yet.\n\n bits &= bit_mask<DataType>(rshift);\n\n size = rshift;\n\n }\n\n\n", "file_path": "fly/types/bit_stream/bit_stream_writer.hpp", "rank": 58, "score": 54936.826601323904 }, { "content": " * than that number available between the byte buffer and stream. If any bits were peeked, the\n\n * least-significant bits in the provided data type will be filled, starting from the position\n\n * pointed to by the requested number of bits.\n\n *\n\n * Fill the buffer from the stream if the number of bits to peek exceeds the number of bits\n\n * available.\n\n *\n\n * @param bits The location to store the peeked bits.\n\n * @param size The number of bits to peek.\n\n *\n\n * @return The number of bits successfully peeked.\n\n */\n\n template <typename DataType>\n\n byte_type peek_bits(DataType &bits, byte_type size);\n\n\n\n /**\n\n * Discard a number of bits from the byte buffer. Should only be used after a successful call to\n\n * peek_bits.\n\n *\n\n * @param size The number of bits to discard.\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 59, "score": 54936.62258084915 }, { "content": " * byte buffer and stream. If any bits were read, the least-significant bits in the provided\n\n * data type will be filled, starting from the position pointed to by the requested number of\n\n * bits.\n\n *\n\n * Fill the buffer from the stream if the number of bits to read exceeds the number of bits\n\n * available.\n\n *\n\n * @tparam DataType The data type of the location to store the read bits.\n\n *\n\n * @param bits The location to store the read bits.\n\n * @param size The number of bits to read.\n\n *\n\n * @return The number of bits successfully read.\n\n */\n\n template <typename DataType>\n\n byte_type read_bits(DataType &bits, byte_type size);\n\n\n\n /**\n\n * Read a number of bits from the byte buffer without discarding those bits. There is no\n\n * guarantee that the requested number of bits will actually be peeked, as there may be less\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 60, "score": 54936.45726208119 }, { "content": " * needed).\n\n */\n\n bool read_word(word_type &word);\n\n\n\n /**\n\n * Read a full byte from the byte buffer.\n\n *\n\n * Fill the buffer from the stream if the number of bits to read exceeds the number of bits\n\n * available.\n\n *\n\n * @param byte The location to store the read byte.\n\n *\n\n * @return True if the byte was successfully read and filling the byte buffer was successful (if\n\n * needed).\n\n */\n\n bool read_byte(byte_type &byte);\n\n\n\n /**\n\n * Read a number of bits from the byte buffer. There is no guarantee that the requested number\n\n * of bits will actually be read, as there may be less than that number available between the\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 61, "score": 54935.66655092996 }, { "content": " // If there are more bits to peek than are available in the byte buffer, break the peek into two\n\n // peeks.\n\n if (size > m_position)\n\n {\n\n peeked = m_position;\n\n\n\n const DataType buffer = static_cast<DataType>(m_buffer);\n\n lshift = size - m_position;\n\n\n\n // Fill the input bits with the remainder of byte buffer.\n\n bits = buffer & bit_mask<DataType>(m_position);\n\n bits <<= lshift - 1;\n\n bits <<= 1;\n\n\n\n // Refill the buffer from the stream.\n\n refill_buffer();\n\n\n\n // Then update the input to only peek any remaining bits next.\n\n size = std::min(lshift, static_cast<byte_type>(m_position - peeked));\n\n lshift -= size;\n", "file_path": "fly/types/bit_stream/bit_stream_reader.hpp", "rank": 62, "score": 54935.570247073316 }, { "content": "{\n\n const byte_type bits_to_fill = detail::s_most_significant_bit_position - m_position;\n\n buffer_type buffer = 0;\n\n\n\n const byte_type bytes_read = fill(buffer, bits_to_fill / detail::s_bits_per_byte);\n\n\n\n if (bytes_read > 0)\n\n {\n\n const byte_type bits_read = bytes_read * detail::s_bits_per_byte;\n\n m_position += bits_read;\n\n\n\n // It is undefined behavior to bit-shift by the size of the value being shifted, i.e. when\n\n // bits_read == detail::s_most_significant_bit_position. Because bits_read is at least 1\n\n // here, the left-shift can be broken into two operations in order to avoid that behavior.\n\n m_buffer <<= bits_read - 1;\n\n m_buffer <<= 1;\n\n\n\n m_buffer |= buffer >> (detail::s_most_significant_bit_position - bits_read);\n\n\n\n if (m_stream_buffer->sgetc() == EOF)\n", "file_path": "fly/types/bit_stream/bit_stream_reader.cpp", "rank": 63, "score": 54935.221340497694 }, { "content": "#pragma once\n\n\n\n#include \"fly/types/bit_stream/bit_stream_types.hpp\"\n\n\n\n#include <type_traits>\n\n\n\nnamespace fly::detail {\n\n\n\n/**\n\n * Traits for type safety in the BitStream template methods.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version July 7, 2019\n\n */\n", "file_path": "fly/types/bit_stream/detail/bit_stream_traits.hpp", "rank": 64, "score": 53697.13575092901 }, { "content": "#pragma once\n\n\n\n#include \"fly/types/bit_stream/bit_stream_types.hpp\"\n\n\n\n#include <limits>\n\n\n\nnamespace fly::detail {\n\n\n\nconstexpr const byte_type s_magic = 0x1a;\n\nconstexpr const byte_type s_magic_mask = 0x1f;\n\nconstexpr const byte_type s_magic_shift = 0x03;\n\n\n\nstatic_assert(s_magic <= s_magic_mask, \"Magic header has exceeded 5 bits\");\n\n\n\nconstexpr const byte_type s_remainder_mask = 0x07;\n\nconstexpr const byte_type s_remainder_shift = 0x00;\n\n\n\nconstexpr const byte_type s_byte_type_size = sizeof(byte_type);\n\nconstexpr const byte_type s_buffer_type_size = sizeof(buffer_type);\n\n\n\nconstexpr const byte_type s_bits_per_word = std::numeric_limits<word_type>::digits;\n\nconstexpr const byte_type s_bits_per_byte = std::numeric_limits<byte_type>::digits;\n\n\n\nconstexpr const byte_type s_most_significant_bit_position = s_buffer_type_size * s_bits_per_byte;\n\n\n\n} // namespace fly::detail\n", "file_path": "fly/types/bit_stream/detail/bit_stream_constants.hpp", "rank": 65, "score": 53691.79261467618 }, { "content": "var namespaces_dup =\n\n[\n\n [ \"fly\", null, [\n\n [ \"coders\", null, [\n\n [ \"Base64Coder\", \"classfly_1_1coders_1_1_base64_coder.html\", \"classfly_1_1coders_1_1_base64_coder\" ],\n\n [ \"Encoder\", \"classfly_1_1coders_1_1_encoder.html\", \"classfly_1_1coders_1_1_encoder\" ],\n\n [ \"BinaryEncoder\", \"classfly_1_1coders_1_1_binary_encoder.html\", \"classfly_1_1coders_1_1_binary_encoder\" ],\n\n [ \"Decoder\", \"classfly_1_1coders_1_1_decoder.html\", \"classfly_1_1coders_1_1_decoder\" ],\n\n [ \"BinaryDecoder\", \"classfly_1_1coders_1_1_binary_decoder.html\", \"classfly_1_1coders_1_1_binary_decoder\" ],\n\n [ \"CoderConfig\", \"classfly_1_1coders_1_1_coder_config.html\", \"classfly_1_1coders_1_1_coder_config\" ],\n\n [ \"HuffmanDecoder\", \"classfly_1_1coders_1_1_huffman_decoder.html\", \"classfly_1_1coders_1_1_huffman_decoder\" ],\n\n [ \"HuffmanEncoder\", \"classfly_1_1coders_1_1_huffman_encoder.html\", \"classfly_1_1coders_1_1_huffman_encoder\" ],\n\n [ \"HuffmanNode\", \"structfly_1_1coders_1_1_huffman_node.html\", \"structfly_1_1coders_1_1_huffman_node\" ],\n\n [ \"HuffmanNodeComparator\", \"structfly_1_1coders_1_1_huffman_node_comparator.html\", \"structfly_1_1coders_1_1_huffman_node_comparator\" ],\n\n [ \"HuffmanCode\", \"structfly_1_1coders_1_1_huffman_code.html\", \"structfly_1_1coders_1_1_huffman_code\" ],\n\n [ \"code_type\", \"huffman__types_8hpp.html#a6a8b9146f83ba6adbd311f53cdf3723c\", null ],\n\n [ \"frequency_type\", \"huffman__types_8hpp.html#a5d89d03aa42d61275fcc78a3761e122f\", null ],\n\n [ \"HuffmanNodeQueue\", \"huffman__types_8hpp.html#aed4cebdd5e8de75631bc045103b50cb4\", null ],\n\n [ \"length_type\", \"huffman__types_8hpp.html#a5adb0c186354b8f3dbcbf468f21acdab\", null ],\n\n [ \"symbol_type\", \"huffman__types_8hpp.html#a66c77f9c5e76da2f6b30c701b46aa820\", null ],\n\n [ \"operator<\", \"huffman__types_8cpp.html#ae98293aa8d369dbf3d8adfc9be33df94\", null ]\n\n ] ],\n\n [ \"config\", null, [\n\n [ \"Config\", \"classfly_1_1config_1_1_config.html\", \"classfly_1_1config_1_1_config\" ],\n\n [ \"ConfigManager\", \"classfly_1_1config_1_1_config_manager.html\", \"classfly_1_1config_1_1_config_manager\" ]\n\n ] ],\n\n [ \"detail\", null, [\n\n [ \"BitStream\", \"classfly_1_1detail_1_1_bit_stream.html\", \"classfly_1_1detail_1_1_bit_stream\" ],\n\n [ \"BitStreamTraits\", \"structfly_1_1detail_1_1_bit_stream_traits.html\", \"structfly_1_1detail_1_1_bit_stream_traits\" ],\n\n [ \"ConcurrentContainer\", \"classfly_1_1detail_1_1_concurrent_container.html\", \"classfly_1_1detail_1_1_concurrent_container\" ],\n\n [ \"JsonReverseIterator\", \"classfly_1_1detail_1_1_json_reverse_iterator.html\", \"classfly_1_1detail_1_1_json_reverse_iterator\" ],\n\n [ \"JsonIterator\", \"classfly_1_1detail_1_1_json_iterator.html\", \"classfly_1_1detail_1_1_json_iterator\" ],\n\n [ \"EndianTraits\", \"structfly_1_1detail_1_1_endian_traits.html\", \"structfly_1_1detail_1_1_endian_traits\" ],\n\n [ \"Aggregator\", \"structfly_1_1detail_1_1_aggregator.html\", null ],\n\n [ \"Aggregator< T, Base, Digit, Literals... >\", \"structfly_1_1detail_1_1_aggregator_3_01_t_00_01_base_00_01_digit_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"Aggregator< T, Base, '\\\\'', Literals... >\", \"structfly_1_1detail_1_1_aggregator_3_01_t_00_01_base_00_01'_0c''_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"Aggregator< T, Base >\", \"structfly_1_1detail_1_1_aggregator_3_01_t_00_01_base_01_4.html\", null ],\n\n [ \"ParserBase\", \"structfly_1_1detail_1_1_parser_base.html\", null ],\n\n [ \"Parser\", \"structfly_1_1detail_1_1_parser.html\", null ],\n\n [ \"Parser< T, '0', 'b', Literals... >\", \"structfly_1_1detail_1_1_parser_3_01_t_00_01'0'_00_01'b'_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"Parser< T, '0', 'B', Literals... >\", \"structfly_1_1detail_1_1_parser_3_01_t_00_01'0'_00_01'_b'_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"Parser< T, '0', Literals... >\", \"structfly_1_1detail_1_1_parser_3_01_t_00_01'0'_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"Parser< T, '0', 'x', Literals... >\", \"structfly_1_1detail_1_1_parser_3_01_t_00_01'0'_00_01'x'_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"Parser< T, '0', 'X', Literals... >\", \"structfly_1_1detail_1_1_parser_3_01_t_00_01'0'_00_01'_x'_00_01_literals_8_8_8_01_4.html\", null ],\n\n [ \"BasicFormatContext\", \"classfly_1_1detail_1_1_basic_format_context.html\", \"classfly_1_1detail_1_1_basic_format_context\" ],\n\n [ \"MonoState\", \"structfly_1_1detail_1_1_mono_state.html\", null ],\n\n [ \"UserDefinedValue\", \"structfly_1_1detail_1_1_user_defined_value.html\", \"structfly_1_1detail_1_1_user_defined_value\" ],\n\n [ \"StringValue\", \"structfly_1_1detail_1_1_string_value.html\", \"structfly_1_1detail_1_1_string_value\" ],\n\n [ \"BasicFormatParameter\", \"classfly_1_1detail_1_1_basic_format_parameter.html\", \"classfly_1_1detail_1_1_basic_format_parameter\" ],\n\n [ \"BasicFormatParameters\", \"classfly_1_1detail_1_1_basic_format_parameters.html\", \"classfly_1_1detail_1_1_basic_format_parameters\" ],\n\n [ \"BasicFormatSpecifier\", \"structfly_1_1detail_1_1_basic_format_specifier.html\", \"structfly_1_1detail_1_1_basic_format_specifier\" ],\n\n [ \"BasicFormatString\", \"classfly_1_1detail_1_1_basic_format_string.html\", \"classfly_1_1detail_1_1_basic_format_string\" ],\n\n [ \"BasicStreamModifiers\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html\", \"classfly_1_1detail_1_1_basic_stream_modifiers\" ],\n\n [ \"PositivePaddingFacet\", \"classfly_1_1detail_1_1_positive_padding_facet.html\", \"classfly_1_1detail_1_1_positive_padding_facet\" ],\n\n [ \"BasicStringClassifier\", \"classfly_1_1detail_1_1_basic_string_classifier.html\", \"classfly_1_1detail_1_1_basic_string_classifier\" ],\n\n [ \"BasicStringConverter\", \"structfly_1_1detail_1_1_basic_string_converter.html\", null ],\n\n [ \"BasicStringConverter< StringType, float >\", \"structfly_1_1detail_1_1_basic_string_converter_3_01_string_type_00_01float_01_4.html\", \"structfly_1_1detail_1_1_basic_string_converter_3_01_string_type_00_01float_01_4\" ],\n\n [ \"BasicStringConverter< StringType, double >\", \"structfly_1_1detail_1_1_basic_string_converter_3_01_string_type_00_01double_01_4.html\", \"structfly_1_1detail_1_1_basic_string_converter_3_01_string_type_00_01double_01_4\" ],\n\n [ \"BasicStringConverter< StringType, long double >\", \"structfly_1_1detail_1_1_basic_string_converter_3_01_string_type_00_01long_01double_01_4.html\", \"structfly_1_1detail_1_1_basic_string_converter_3_01_string_type_00_01long_01double_01_4\" ],\n\n [ \"is_like_supported_string\", \"structfly_1_1detail_1_1is__like__supported__string.html\", \"structfly_1_1detail_1_1is__like__supported__string\" ],\n\n [ \"BasicStringTraits\", \"structfly_1_1detail_1_1_basic_string_traits.html\", \"structfly_1_1detail_1_1_basic_string_traits\" ],\n\n [ \"BasicFormatTraits\", \"structfly_1_1detail_1_1_basic_format_traits.html\", \"structfly_1_1detail_1_1_basic_format_traits\" ],\n\n [ \"BasicStringUnicode\", \"classfly_1_1detail_1_1_basic_string_unicode.html\", \"classfly_1_1detail_1_1_basic_string_unicode\" ],\n\n [ \"BasicCharacterLiteral\", \"structfly_1_1detail_1_1_basic_character_literal.html\", null ],\n\n [ \"BasicStringLiteral\", \"structfly_1_1detail_1_1_basic_string_literal.html\", null ],\n\n [ \"BasicStringArray\", \"structfly_1_1detail_1_1_basic_string_array.html\", null ],\n\n [ \"BasicCharacterLiteral< char >\", \"structfly_1_1detail_1_1_basic_character_literal_3_01char_01_4.html\", null ],\n\n [ \"BasicCharacterLiteral< wchar_t >\", \"structfly_1_1detail_1_1_basic_character_literal_3_01wchar__t_01_4.html\", null ],\n\n [ \"BasicCharacterLiteral< char8_t >\", \"structfly_1_1detail_1_1_basic_character_literal_3_01char8__t_01_4.html\", null ],\n\n [ \"BasicCharacterLiteral< char16_t >\", \"structfly_1_1detail_1_1_basic_character_literal_3_01char16__t_01_4.html\", null ],\n\n [ \"BasicCharacterLiteral< char32_t >\", \"structfly_1_1detail_1_1_basic_character_literal_3_01char32__t_01_4.html\", null ],\n\n [ \"BasicStringLiteral< char >\", \"structfly_1_1detail_1_1_basic_string_literal_3_01char_01_4.html\", null ],\n\n [ \"BasicStringLiteral< wchar_t >\", \"structfly_1_1detail_1_1_basic_string_literal_3_01wchar__t_01_4.html\", null ],\n\n [ \"BasicStringLiteral< char8_t >\", \"structfly_1_1detail_1_1_basic_string_literal_3_01char8__t_01_4.html\", null ],\n\n [ \"BasicStringLiteral< char16_t >\", \"structfly_1_1detail_1_1_basic_string_literal_3_01char16__t_01_4.html\", null ],\n\n [ \"BasicStringLiteral< char32_t >\", \"structfly_1_1detail_1_1_basic_string_literal_3_01char32__t_01_4.html\", null ],\n\n [ \"BasicStringArray< char >\", \"structfly_1_1detail_1_1_basic_string_array_3_01char_01_4.html\", null ],\n\n [ \"BasicStringArray< wchar_t >\", \"structfly_1_1detail_1_1_basic_string_array_3_01wchar__t_01_4.html\", null ],\n\n [ \"BasicStringArray< char8_t >\", \"structfly_1_1detail_1_1_basic_string_array_3_01char8__t_01_4.html\", null ],\n\n [ \"BasicStringArray< char16_t >\", \"structfly_1_1detail_1_1_basic_string_array_3_01char16__t_01_4.html\", null ],\n\n [ \"BasicStringArray< char32_t >\", \"structfly_1_1detail_1_1_basic_string_array_3_01char32__t_01_4.html\", null ],\n\n [ \"is_like_supported_string_t\", \"string__traits_8hpp.html#abbc5a6d6f52709adb89046400c8295d7\", null ],\n\n [ \"is_supported_character\", \"string__traits_8hpp.html#aa79ec48ae8730a74a9ea7caef6858e9b\", null ],\n\n [ \"is_supported_string\", \"string__traits_8hpp.html#a97bd12bc3835c5b9f4126c4b9562ef54\", null ],\n\n [ \"OstreamDeclaration\", \"string__traits_8hpp.html#a6723051239d0674fdc4b1145fce27592\", null ],\n\n [ \"OstreamTraits\", \"string__traits_8hpp.html#a85ab16094f1c19ebb476f2d9c6bd5e85\", null ],\n\n [ \"format_string_value\", \"format__parameters_8hpp.html#ae4eeb70ac5c1756e5412106cbd233f59\", null ],\n\n [ \"format_user_defined_value\", \"format__parameters_8hpp.html#afd4b45d391c23023489e90a5853d9a57\", null ],\n\n [ \"literal\", \"literal__parser_8hpp.html#ae10175ef46e7e26df2376841dc50f208\", null ],\n\n [ \"make_format_parameters\", \"format__parameters_8hpp.html#a0e6e33079466f364c8a50219db2d0747\", null ],\n\n [ \"operator+\", \"json__iterator_8hpp.html#a12ae62f0498e7da313c81bbc736da329\", null ],\n\n [ \"operator==\", \"format__specifier_8hpp.html#a4cd29face9b23760fb1bdc926b5cf8b6\", null ],\n\n [ \"validate_and_convert\", \"literal__parser_8hpp.html#a73c17515365bc699c47912a09039a0af\", null ],\n\n [ \"is_like_supported_string_v\", \"string__traits_8hpp.html#acf3dbd981abbcc02c35aab1b7c7eb3e8\", null ],\n\n [ \"is_supported_character_v\", \"string__traits_8hpp.html#a8cd01d1705e1bb99491ae0193019991f\", null ],\n\n [ \"is_supported_string_v\", \"string__traits_8hpp.html#a4038d5a1ace2bf8a8c22f991b57cbc14\", null ],\n\n [ \"s_bits_per_byte\", \"bit__stream__constants_8hpp.html#a2a70682e18497125add74373329ebdf4\", null ],\n\n [ \"s_bits_per_word\", \"bit__stream__constants_8hpp.html#abff4c4b4decbb7511312422d3d85ce75\", null ],\n\n [ \"s_buffer_type_size\", \"bit__stream__constants_8hpp.html#a09feba246029f260d6e80ad5cfc266eb\", null ],\n\n [ \"s_byte_type_size\", \"bit__stream__constants_8hpp.html#a827ffd941f6db4f517ca27ff7a9594ee\", null ],\n\n [ \"s_magic\", \"bit__stream__constants_8hpp.html#a2ac9026d689d5b4a85bdcb94b69c7d0c\", null ],\n\n [ \"s_magic_mask\", \"bit__stream__constants_8hpp.html#a9a007b7ad146d2536026607d5dbb0f54\", null ],\n\n [ \"s_magic_shift\", \"bit__stream__constants_8hpp.html#a45c57452cebb683cfb132f85949055ad\", null ],\n\n [ \"s_most_significant_bit_position\", \"bit__stream__constants_8hpp.html#ae6fb206ffad29c7480e920ae8b4d7ac1\", null ],\n\n [ \"s_remainder_mask\", \"bit__stream__constants_8hpp.html#a0efec74e4bd5f79a72d97e7f92998305\", null ],\n\n [ \"s_remainder_shift\", \"bit__stream__constants_8hpp.html#a4bedf9afdb3f058e07dbb5871d0ff84c\", null ]\n\n ] ],\n\n [ \"literals\", \"namespacefly_1_1literals.html\", [\n\n [ \"operator\\\"\\\"_c\", \"namespacefly_1_1literals.html#aab73da5383b956458ae369bf8b790c6b\", null ],\n\n [ \"operator\\\"\\\"_i16\", \"namespacefly_1_1literals.html#ab2d17c25a604b147b5dede02fd1e1c59\", null ],\n\n [ \"operator\\\"\\\"_i32\", \"namespacefly_1_1literals.html#a1538b6095f7f6f336c57a1d6d14bc67b\", null ],\n\n [ \"operator\\\"\\\"_i64\", \"namespacefly_1_1literals.html#aba8abef8380a63c75307350b937d6698\", null ],\n\n [ \"operator\\\"\\\"_i8\", \"namespacefly_1_1literals.html#a469306f602d00cf6458aeecac107e6c2\", null ],\n\n [ \"operator\\\"\\\"_u16\", \"namespacefly_1_1literals.html#aa6cba2c5b8906dd840d449074f430c60\", null ],\n\n [ \"operator\\\"\\\"_u32\", \"namespacefly_1_1literals.html#a8a2e6a139be896c60987e84ce744ea4a\", null ],\n\n [ \"operator\\\"\\\"_u64\", \"namespacefly_1_1literals.html#a78696311ec724b34a791f157c5462bcd\", null ],\n\n [ \"operator\\\"\\\"_u8\", \"namespacefly_1_1literals.html#ad59e4eed49d42d20ebcefa8bf194dd36\", null ],\n\n [ \"operator\\\"\\\"_zu\", \"namespacefly_1_1literals.html#a1787d311c579478bb7402265d80a1998\", null ]\n\n ] ],\n\n [ \"logger\", null, [\n\n [ \"detail\", null, [\n\n [ \"ConsoleSink\", \"classfly_1_1logger_1_1detail_1_1_console_sink.html\", \"classfly_1_1logger_1_1detail_1_1_console_sink\" ],\n\n [ \"FileSink\", \"classfly_1_1logger_1_1detail_1_1_file_sink.html\", \"classfly_1_1logger_1_1detail_1_1_file_sink\" ],\n\n [ \"StylerProxyImpl\", \"classfly_1_1logger_1_1detail_1_1_styler_proxy_impl.html\", \"classfly_1_1logger_1_1detail_1_1_styler_proxy_impl\" ],\n\n [ \"Registry\", \"classfly_1_1logger_1_1detail_1_1_registry.html\", \"classfly_1_1logger_1_1detail_1_1_registry\" ],\n\n [ \"StylerProxy\", \"classfly_1_1logger_1_1detail_1_1_styler_proxy.html\", \"classfly_1_1logger_1_1detail_1_1_styler_proxy\" ],\n\n [ \"StylerProxyImpl::apply_value< COORD, fly::logger::Cursor >\", \"win_2styler__proxy__impl_8cpp.html#a2681a2032c36893abe962bfa4254c3aa\", null ],\n\n [ \"StylerProxyImpl::apply_value< WORD, fly::logger::Color >\", \"win_2styler__proxy__impl_8cpp.html#a348a9e5e93de7b00061b65e05fe3cca8\", null ],\n\n [ \"StylerProxyImpl::apply_value< WORD, fly::logger::Style >\", \"win_2styler__proxy__impl_8cpp.html#ac3f632c34294a091269852baeefe4dbd\", null ],\n\n [ \"StylerProxyImpl::stream_value< fly::logger::Color >\", \"nix_2styler__proxy__impl_8cpp.html#ac382e5373b75c95f128e459eb992f9ac\", null ],\n\n [ \"StylerProxyImpl::stream_value< fly::logger::Cursor >\", \"nix_2styler__proxy__impl_8cpp.html#a9de2385bbf71b3b4eeccf148115ca65f\", null ],\n\n [ \"StylerProxyImpl::stream_value< fly::logger::Style >\", \"nix_2styler__proxy__impl_8cpp.html#a51e9d183be8dd97a6eaaa340476ecb0a\", null ]\n\n ] ],\n\n [ \"Trace\", \"structfly_1_1logger_1_1_trace.html\", \"structfly_1_1logger_1_1_trace\" ],\n\n [ \"Log\", \"structfly_1_1logger_1_1_log.html\", \"structfly_1_1logger_1_1_log\" ],\n\n [ \"Logger\", \"classfly_1_1logger_1_1_logger.html\", \"classfly_1_1logger_1_1_logger\" ],\n\n [ \"LoggerConfig\", \"classfly_1_1logger_1_1_logger_config.html\", \"classfly_1_1logger_1_1_logger_config\" ],\n\n [ \"Sink\", \"classfly_1_1logger_1_1_sink.html\", \"classfly_1_1logger_1_1_sink\" ],\n\n [ \"Color\", \"structfly_1_1logger_1_1_color.html\", \"structfly_1_1logger_1_1_color\" ],\n\n [ \"Cursor\", \"structfly_1_1logger_1_1_cursor.html\", \"structfly_1_1logger_1_1_cursor\" ],\n\n [ \"Styler\", \"classfly_1_1logger_1_1_styler.html\", \"classfly_1_1logger_1_1_styler\" ],\n\n [ \"Level\", \"log_8hpp.html#a9d98ca6bc3afae6096f0d908ded6263a\", [\n\n [ \"Debug\", \"log_8hpp.html#a9d98ca6bc3afae6096f0d908ded6263aaa603905470e2a5b8c13e96b579ef0dba\", null ],\n\n [ \"Info\", \"log_8hpp.html#a9d98ca6bc3afae6096f0d908ded6263aa4059b0251f66a18cb56f544728796875\", null ],\n\n [ \"Warn\", \"log_8hpp.html#a9d98ca6bc3afae6096f0d908ded6263aa56525ae64d370c0b448ac0d60710ef17\", null ],\n\n [ \"Error\", \"log_8hpp.html#a9d98ca6bc3afae6096f0d908ded6263aa902b0d55fddef6f8d651fe1035b7d4bd\", null ],\n\n [ \"NumLevels\", \"log_8hpp.html#a9d98ca6bc3afae6096f0d908ded6263aa033418104e7ef5dcb8495b7c7fe622f4\", null ]\n\n ] ],\n\n [ \"Style\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195\", [\n\n [ \"Default\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195a7a1920d61156abc05a60135aefe8bc67\", null ],\n\n [ \"Blink\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195acfad0a7419f44ea0c64db24197abbf70\", null ],\n\n [ \"Bold\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195a114c3050111d8b8ddd830b99ccebd246\", null ],\n\n [ \"Dim\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195a8ed64ce6e8032ddb62a463ffa78881d9\", null ],\n\n [ \"Italic\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195a1d874710ccdcd46b95397049d2e7500c\", null ],\n\n [ \"Strike\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195a861bb8830b30ae92120225676fe880bb\", null ],\n\n [ \"Underline\", \"styler_8hpp.html#adbd8ca191132207a0462df44de004195a852721aa5fc738dfedff2945d71da439\", null ]\n\n ] ],\n\n [ \"create_console_logger\", \"logger_8cpp.html#ac6493a1f6b0f376d790523f4d622c4ed\", null ],\n\n [ \"create_console_logger\", \"logger_8cpp.html#a5ad19204fadd5c7d2271225ba87881ea\", null ],\n\n [ \"create_file_logger\", \"logger_8cpp.html#a480d4d35b4d73364d10e02000626f332\", null ],\n\n [ \"create_file_logger\", \"logger_8cpp.html#a86d59a94963bdb2fb7290b0be95f1ab7\", null ],\n\n [ \"operator<<\", \"log_8cpp.html#ae64c7d7edc6cb4e722c17031a8e08522\", null ],\n\n [ \"operator<<\", \"log_8cpp.html#ac2c6267e2d59b40c5f8eb6e835b47099\", null ],\n\n [ \"operator<<\", \"styler_8cpp.html#a571fedb9dc19d6d70243db8b51df8ea4\", null ],\n\n [ \"operator<<\", \"log_8cpp.html#a8b7efcc1a7c225f6018ff0d728adb163\", null ]\n\n ] ],\n\n [ \"net\", null, [\n\n [ \"detail\", null, [\n\n [ \"BaseSocket\", \"classfly_1_1net_1_1detail_1_1_base_socket.html\", \"classfly_1_1net_1_1detail_1_1_base_socket\" ],\n\n [ \"accept\", \"nix_2socket__operations_8cpp.html#a05ce1045490d5d6d76a3fcb9fa8d15c4\", null ],\n\n [ \"accept\", \"nix_2socket__operations_8cpp.html#ad8a8909e044e04a707d70c6c2e8e77bb\", null ],\n\n [ \"accept\", \"nix_2socket__operations_8cpp.html#a4f5ea13c8b5db21dbfdfd8b0b7e05e0e\", null ],\n\n [ \"bind\", \"nix_2socket__operations_8cpp.html#aa123bf20df53cdc5ce56d149f820eb91\", null ],\n\n [ \"bind\", \"nix_2socket__operations_8cpp.html#ad3f127d56f8378dae88ab6ed0dbf5703\", null ],\n\n [ \"bind\", \"nix_2socket__operations_8cpp.html#a6ed890bed5e90fcac612fa29c98ae56a\", null ],\n\n [ \"close\", \"nix_2socket__operations_8cpp.html#a370e5ce68487016c102ed60a1c93e71f\", null ],\n\n [ \"connect\", \"nix_2socket__operations_8cpp.html#ae782870634888353efe2ef64b3acc352\", null ],\n\n [ \"connect\", \"nix_2socket__operations_8cpp.html#addfbe5c6130bd0b3dd6f059906e27831\", null ],\n\n [ \"connect\", \"nix_2socket__operations_8cpp.html#a0fdda7faf94f26fbcf6310289a7710b4\", null ],\n\n [ \"deinitialize\", \"nix_2socket__operations_8cpp.html#a984893356d3d2f5f9fc1aedb1a1a397b\", null ],\n\n [ \"hostname_to_endpoint\", \"nix_2socket__operations_8cpp.html#a17f02b0053d2b3f7539a434757b256b0\", null ],\n\n [ \"initialize\", \"nix_2socket__operations_8cpp.html#a93c723860db7494d354afa37b561b816\", null ],\n\n [ \"invalid_socket\", \"nix_2socket__operations_8cpp.html#aeaf24ffb20fd7b3f0f371c61ba48be69\", null ],\n\n [ \"is_error_free\", \"nix_2socket__operations_8cpp.html#a9a17822859d720566662e0ccb5a588cd\", null ],\n\n [ \"listen\", \"nix_2socket__operations_8cpp.html#a5d2cbec6caa35c59f9832a4bcfe515fb\", null ],\n\n [ \"local_endpoint\", \"nix_2socket__operations_8cpp.html#a105741a53e8e7361feb17782aa854ea6\", null ],\n\n [ \"recv\", \"nix_2socket__operations_8cpp.html#adf955cef33a5e048ef29ae0b500ac588\", null ],\n\n [ \"recv_from\", \"nix_2socket__operations_8cpp.html#a7d6570911b6ba9e25a174dd0b0b4516c\", null ],\n\n [ \"recv_from\", \"nix_2socket__operations_8cpp.html#a2e9ae6844112117570074daa4aff5a84\", null ],\n\n [ \"recv_from\", \"nix_2socket__operations_8cpp.html#aed3e8c4fd691e1ad6ee56ce5f77f1c0b\", null ],\n\n [ \"remote_endpoint\", \"nix_2socket__operations_8cpp.html#ac97ccb439f1259ca6b45bf88a9d162bf\", null ],\n\n [ \"select\", \"nix_2socket__operations_8cpp.html#a7552a57228db51a0b7482c2a1f9efa8e\", null ],\n\n [ \"send\", \"nix_2socket__operations_8cpp.html#a771b6a6b86013664705ca9dd5a4dabc8\", null ],\n\n [ \"send_to\", \"nix_2socket__operations_8cpp.html#a68f7b67dd0989f45e5c5d712109a4202\", null ],\n\n [ \"send_to\", \"nix_2socket__operations_8cpp.html#a9b6bc69f4a3e74a570cfc450ff4b9a7c\", null ],\n\n [ \"send_to\", \"nix_2socket__operations_8cpp.html#a06de6171bd15ee4354c6ebdce638d043\", null ],\n\n [ \"set_io_mode\", \"nix_2socket__operations_8cpp.html#a29f94efb721a158e5ff5d86ba467549d\", null ],\n\n [ \"socket\", \"socket__operations_8hpp.html#a1b7cc7ec160f906d7fc83d4464f41ef5\", null ],\n\n [ \"socket< IPv4Endpoint, fly::net::TcpSocket< IPv4Endpoint > >\", \"nix_2socket__operations_8cpp.html#a3187e3db382566c4eed5fa502d35b602\", null ],\n\n [ \"socket< IPv4Endpoint, fly::net::UdpSocket< IPv4Endpoint > >\", \"nix_2socket__operations_8cpp.html#a7f2e94c4132618cc0a3518e152e9b091\", null ],\n\n [ \"socket< IPv6Endpoint, fly::net::TcpSocket< IPv6Endpoint > >\", \"nix_2socket__operations_8cpp.html#aec5aacba60707ade759c1837c2867f19\", null ],\n\n [ \"socket< IPv6Endpoint, fly::net::UdpSocket< IPv6Endpoint > >\", \"nix_2socket__operations_8cpp.html#ac3f993afe48427503cca82dcfbfbb98a\", null ]\n\n ] ],\n\n [ \"Endpoint\", \"classfly_1_1net_1_1_endpoint.html\", \"classfly_1_1net_1_1_endpoint\" ],\n\n [ \"IPv4Address\", \"classfly_1_1net_1_1_i_pv4_address.html\", \"classfly_1_1net_1_1_i_pv4_address\" ],\n\n [ \"IPv6Address\", \"classfly_1_1net_1_1_i_pv6_address.html\", \"classfly_1_1net_1_1_i_pv6_address\" ],\n\n [ \"NetworkConfig\", \"classfly_1_1net_1_1_network_config.html\", \"classfly_1_1net_1_1_network_config\" ],\n\n [ \"TcpSocket\", \"classfly_1_1net_1_1_tcp_socket.html\", \"classfly_1_1net_1_1_tcp_socket\" ],\n\n [ \"UdpSocket\", \"classfly_1_1net_1_1_udp_socket.html\", \"classfly_1_1net_1_1_udp_socket\" ],\n\n [ \"ListenSocket\", \"classfly_1_1net_1_1_listen_socket.html\", \"classfly_1_1net_1_1_listen_socket\" ],\n\n [ \"SocketService\", \"classfly_1_1net_1_1_socket_service.html\", \"classfly_1_1net_1_1_socket_service\" ],\n\n [ \"port_type\", \"socket__types_8hpp.html#a3a08f0cf67bcb9755c21a46bf7639bad\", null ],\n\n [ \"BindMode\", \"socket__types_8hpp.html#ad8e2bc8249313eebdedb4e3bbbc2b1c2\", [\n\n [ \"SingleUse\", \"socket__types_8hpp.html#ad8e2bc8249313eebdedb4e3bbbc2b1c2a3aaa7b452617e34a9178fdb0d6160ea3\", null ],\n\n [ \"AllowReuse\", \"socket__types_8hpp.html#ad8e2bc8249313eebdedb4e3bbbc2b1c2a3dad76812aa22603d8c766f15b96fc48\", null ]\n\n ] ],\n\n [ \"ConnectedState\", \"socket__types_8hpp.html#a65d03f19c39fb7f2c514fc23608515d5\", [\n\n [ \"Disconnected\", \"socket__types_8hpp.html#a65d03f19c39fb7f2c514fc23608515d5aef70e46fd3bbc21e3e1f0b6815e750c0\", null ],\n\n [ \"Connecting\", \"socket__types_8hpp.html#a65d03f19c39fb7f2c514fc23608515d5ae321c53b354930ba96f0243e652df458\", null ],\n\n [ \"Connected\", \"socket__types_8hpp.html#a65d03f19c39fb7f2c514fc23608515d5a2ec0d16e4ca169baedb9b2d50ec5c6d7\", null ]\n\n ] ],\n\n [ \"IOMode\", \"socket__types_8hpp.html#a5c83c8dd863e6fffc982779486a39053\", [\n\n [ \"Synchronous\", \"socket__types_8hpp.html#a5c83c8dd863e6fffc982779486a39053a2fe4167817733fec8e6ba1afddf78f1b\", null ],\n\n [ \"Asynchronous\", \"socket__types_8hpp.html#a5c83c8dd863e6fffc982779486a39053a288aae25bc408055f50c21c991903a44\", null ]\n\n ] ],\n\n [ \"operator<<\", \"ipv4__address_8cpp.html#aec730fc49737ac96ce803f7eb707f960\", null ],\n\n [ \"operator<<\", \"ipv6__address_8cpp.html#aa1f6015cca99633d563b1ee180b8957d\", null ]\n\n ] ],\n\n [ \"parser\", null, [\n\n [ \"IniParser\", \"classfly_1_1parser_1_1_ini_parser.html\", \"classfly_1_1parser_1_1_ini_parser\" ],\n\n [ \"JsonParser\", \"classfly_1_1parser_1_1_json_parser.html\", \"classfly_1_1parser_1_1_json_parser\" ],\n\n [ \"Parser\", \"classfly_1_1parser_1_1_parser.html\", \"classfly_1_1parser_1_1_parser\" ],\n\n [ \"operator&\", \"json__parser_8cpp.html#ae4c351e109ff55b4ace3b0ac5fba0a7e\", null ],\n\n [ \"operator|\", \"json__parser_8cpp.html#acbbc797830f46cf86f0149e95913a786\", null ]\n\n ] ],\n\n [ \"path\", null, [\n\n [ \"PathMonitorImpl\", \"classfly_1_1path_1_1_path_monitor_impl.html\", \"classfly_1_1path_1_1_path_monitor_impl\" ],\n\n [ \"PathConfig\", \"classfly_1_1path_1_1_path_config.html\", \"classfly_1_1path_1_1_path_config\" ],\n\n [ \"PathMonitor\", \"classfly_1_1path_1_1_path_monitor.html\", \"classfly_1_1path_1_1_path_monitor\" ],\n\n [ \"operator<<\", \"path__monitor_8cpp.html#a51c684d4c49c2cc4a0e5a7b25ed1de49\", null ]\n\n ] ],\n\n [ \"system\", null, [\n\n [ \"detail\", null, [\n\n [ \"host_basic_info\", \"mach__api_8hpp.html#af05aed8cddeed7012b0c2448a1564a24\", null ],\n\n [ \"host_cpu_load\", \"mach__api_8hpp.html#a925b22f5160c171dd1913b2ffc03fe3a\", null ],\n\n [ \"host_page_size\", \"mach__api_8hpp.html#aa71e2b7832e58bac86e4a293bd6214ec\", null ],\n\n [ \"host_vm_info\", \"mach__api_8hpp.html#a5bffb5afe95281288c3e8b49ac73d47a\", null ],\n\n [ \"task_basic_info\", \"mach__api_8hpp.html#a172d4bc85855f4a3f9e41642aba61188\", null ],\n\n [ \"task_thread_times\", \"mach__api_8hpp.html#a31ee437b58b5311a79518d88647b6db6\", null ]\n\n ] ],\n\n [ \"SystemMonitorImpl\", \"classfly_1_1system_1_1_system_monitor_impl.html\", \"classfly_1_1system_1_1_system_monitor_impl\" ],\n\n [ \"SystemConfig\", \"classfly_1_1system_1_1_system_config.html\", \"classfly_1_1system_1_1_system_config\" ],\n\n [ \"SystemMonitor\", \"classfly_1_1system_1_1_system_monitor.html\", \"classfly_1_1system_1_1_system_monitor\" ],\n\n [ \"SignalHandler\", \"system_8hpp.html#a1142bfeb7ffd00673d0ff6f6ab93e8b5\", null ],\n\n [ \"get_error_code\", \"nix_2system__impl_8cpp.html#ae94e3237652a31139178e2447c513fa1\", null ],\n\n [ \"get_error_string\", \"system_8cpp.html#abbf2a38d3d65b7aba824d787675fc59a\", null ],\n\n [ \"get_error_string\", \"system_8cpp.html#a50c6d5cea901cf837665cd95ca1ba8ea\", null ],\n\n [ \"local_time\", \"nix_2system__impl_8cpp.html#a1d94d53c1c34ad1e078869f440b03a68\", null ],\n\n [ \"print_backtrace\", \"nix_2system__impl_8cpp.html#a889dfcc0a9c787068100685940fbf2d1\", null ],\n\n [ \"set_signal_handler\", \"system_8cpp.html#ab4d0f0b7b872bd2d3a6513ba88336e8f\", null ]\n\n ] ],\n\n [ \"task\", null, [\n\n [ \"TaskManager\", \"classfly_1_1task_1_1_task_manager.html\", \"classfly_1_1task_1_1_task_manager\" ],\n\n [ \"TaskRunner\", \"classfly_1_1task_1_1_task_runner.html\", \"classfly_1_1task_1_1_task_runner\" ],\n\n [ \"ParallelTaskRunner\", \"classfly_1_1task_1_1_parallel_task_runner.html\", \"classfly_1_1task_1_1_parallel_task_runner\" ],\n\n [ \"SequencedTaskRunner\", \"classfly_1_1task_1_1_sequenced_task_runner.html\", \"classfly_1_1task_1_1_sequenced_task_runner\" ],\n\n [ \"TaskLocation\", \"structfly_1_1task_1_1_task_location.html\", \"structfly_1_1task_1_1_task_location\" ],\n\n [ \"Task\", \"task__types_8hpp.html#a28bf36cb95b063293a6cdfcde0763bcd\", null ]\n\n ] ],\n\n [ \"all_same\", \"structfly_1_1all__same.html\", null ],\n\n [ \"any_same\", \"structfly_1_1any__same.html\", null ],\n\n [ \"visitation\", \"structfly_1_1visitation.html\", null ],\n\n [ \"DeclarationTraits\", \"structfly_1_1_declaration_traits.html\", \"structfly_1_1_declaration_traits\" ],\n\n [ \"BitStreamReader\", \"classfly_1_1_bit_stream_reader.html\", \"classfly_1_1_bit_stream_reader\" ],\n\n [ \"BitStreamWriter\", \"classfly_1_1_bit_stream_writer.html\", \"classfly_1_1_bit_stream_writer\" ],\n\n [ \"ConcurrentQueue\", \"classfly_1_1_concurrent_queue.html\", \"classfly_1_1_concurrent_queue\" ],\n\n [ \"ConcurrentStack\", \"classfly_1_1_concurrent_stack.html\", \"classfly_1_1_concurrent_stack\" ],\n\n [ \"Json\", \"classfly_1_1_json.html\", \"classfly_1_1_json\" ],\n\n [ \"JsonException\", \"classfly_1_1_json_exception.html\", \"classfly_1_1_json_exception\" ],\n\n [ \"JsonIteratorException\", \"classfly_1_1_json_iterator_exception.html\", \"classfly_1_1_json_iterator_exception\" ],\n\n [ \"BadJsonComparisonException\", \"classfly_1_1_bad_json_comparison_exception.html\", \"classfly_1_1_bad_json_comparison_exception\" ],\n\n [ \"NullJsonException\", \"classfly_1_1_null_json_exception.html\", \"classfly_1_1_null_json_exception\" ],\n\n [ \"OutOfRangeJsonException\", \"classfly_1_1_out_of_range_json_exception.html\", \"classfly_1_1_out_of_range_json_exception\" ],\n\n [ \"JsonTraits\", \"structfly_1_1_json_traits.html\", \"structfly_1_1_json_traits\" ],\n\n [ \"BasicString\", \"classfly_1_1_basic_string.html\", \"classfly_1_1_basic_string\" ],\n\n [ \"Formatter\", \"structfly_1_1_formatter.html\", null ],\n\n [ \"Formatter< T, CharType, fly::enable_if< detail::BasicFormatTraits::is_generic< T > > >\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1_basic_forma5bfafee5a5083697d4615eaf7388ff4d.html\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1_basic_forma5bfafee5a5083697d4615eaf7388ff4d\" ],\n\n [ \"Formatter< T, CharType, fly::enable_if< detail::is_like_supported_string< T > > >\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1is__like__su639ac3ba0af338079231f79cbbfa9612.html\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1is__like__su639ac3ba0af338079231f79cbbfa9612\" ],\n\n [ \"Formatter< T, CharType, fly::enable_if< detail::BasicFormatTraits::is_pointer< T > > >\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1_basic_forma90d926c13691e82172abe465283e0866.html\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1_basic_forma90d926c13691e82172abe465283e0866\" ],\n\n [ \"Formatter< T, CharType, fly::enable_if< detail::BasicFormatTraits::is_integral< T > > >\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1_basic_forma17e7fd5e889182ae65e5008bcdd6a4aa.html\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01detail_1_1_basic_forma17e7fd5e889182ae65e5008bcdd6a4aa\" ],\n\n [ \"Formatter< T, CharType, fly::enable_if< std::is_floating_point< T > > >\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01std_1_1is__floating__point_3_01_t_01_4_01_4_01_4.html\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01std_1_1is__floating__point_3_01_t_01_4_01_4_01_4\" ],\n\n [ \"Formatter< T, CharType, fly::enable_if< std::is_same< T, bool > > >\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01std_1_1is__same_3_01_t_00_01bool_01_4_01_4_01_4.html\", \"structfly_1_1_formatter_3_01_t_00_01_char_type_00_01fly_1_1enable__if_3_01std_1_1is__same_3_01_t_00_01bool_01_4_01_4_01_4\" ],\n\n [ \"BasicStringLexer\", \"classfly_1_1_basic_string_lexer.html\", \"classfly_1_1_basic_string_lexer\" ],\n\n [ \"buffer_type\", \"bit__stream__types_8hpp.html#a8df846c425a54eacf84cda830ebbde30\", null ],\n\n [ \"byte_type\", \"bit__stream__types_8hpp.html#a528709182b2815ab68a727c7b055e45a\", null ],\n\n [ \"disable_if\", \"traits_8hpp.html#ae96fd3b7364f76b02cb08ab5e8699ab5\", null ],\n\n [ \"disable_if_all\", \"traits_8hpp.html#a1c0679d2104e8cc42e6e64c3bbed457e\", null ],\n\n [ \"disable_if_any\", \"traits_8hpp.html#a15e376ca457e847575c6d549e6eb7bf0\", null ],\n\n [ \"enable_if\", \"traits_8hpp.html#a01429d12616f8da16e922cdfd1d6f70f\", null ],\n\n [ \"enable_if_all\", \"traits_8hpp.html#a1608c1a8ae7d20fb59a1260374327e05\", null ],\n\n [ \"enable_if_any\", \"traits_8hpp.html#a35199c3ccbb51c022834475d7cd8a2f6\", null ],\n\n [ \"size_of_type_is\", \"traits_8hpp.html#a0ef285410a3dced024ef3d0d4d3e95dc\", null ],\n\n [ \"String\", \"string_8hpp.html#a373760203b771c4f7bfb24d408825b10\", null ],\n\n [ \"String16\", \"string_8hpp.html#aa9961c766e24973debc8d979b8fb979a\", null ],\n\n [ \"String16Traits\", \"string_8hpp.html#a3b24de8ab96ac8d494ea6bef68bc67b2\", null ],\n\n [ \"String32\", \"string_8hpp.html#ab334d4b458cc855237b1f099e24ea7d4\", null ],\n\n [ \"String32Traits\", \"string_8hpp.html#ad80f5c7226f8c9fc58eeb754842aa0ba\", null ],\n\n [ \"String8\", \"string_8hpp.html#af0402c129630d13d0fcd2c71ece33641\", null ],\n\n [ \"String8Traits\", \"string_8hpp.html#ac333783790d9f1439074bba3d4c40921\", null ],\n\n [ \"StringTraits\", \"string_8hpp.html#a70f08e699f6ad7c5346a3c6b0e3cec2e\", null ],\n\n [ \"word_type\", \"bit__stream__types_8hpp.html#a73d80bd13fe7aa429b25816f93ee656b\", null ],\n\n [ \"WString\", \"string_8hpp.html#af74c858b862daee9196cb6db57ffcd3c\", null ],\n\n [ \"WStringTraits\", \"string_8hpp.html#ab27349ffb800c4de6cfe26535d521a8a\", null ],\n\n [ \"endian_swap\", \"endian_8hpp.html#aaea89236e92293873dafc1c95bfe8ea7\", null ],\n\n [ \"endian_swap_if_non_native\", \"endian_8hpp.html#abe31f813d350967b078b5aa551b5c8af\", null ],\n\n [ \"is_clang\", \"fly_8hpp.html#aeaaff59f6ef3dc2d7baaad2f010fce85\", null ],\n\n [ \"is_gcc\", \"fly_8hpp.html#a63c1c3a7560f81ffbb1b4b4a7919e88a\", null ],\n\n [ \"is_linux\", \"fly_8hpp.html#a7298c9d2407415e2d0df5e264208911e\", null ],\n\n [ \"is_macos\", \"fly_8hpp.html#acc4f9e87f3405cd2beec30daa4562db9\", null ],\n\n [ \"is_msvc\", \"fly_8hpp.html#aeedd551272c6c788e57e1411373d2d78\", null ],\n\n [ \"is_windows\", \"fly_8hpp.html#a43943f8bb33d0c60d96136a3ed1b9cbc\", null ],\n\n [ \"operator!=\", \"json_8cpp.html#a66aeb64d2b9c73a13d6d80f83262cbb9\", null ],\n\n [ \"operator\\\"\\\"_c\", \"namespacefly_1_1literals.html#aab73da5383b956458ae369bf8b790c6b\", null ],\n\n [ \"operator\\\"\\\"_i16\", \"namespacefly_1_1literals.html#ab2d17c25a604b147b5dede02fd1e1c59\", null ],\n\n [ \"operator\\\"\\\"_i32\", \"namespacefly_1_1literals.html#a1538b6095f7f6f336c57a1d6d14bc67b\", null ],\n\n [ \"operator\\\"\\\"_i64\", \"namespacefly_1_1literals.html#aba8abef8380a63c75307350b937d6698\", null ],\n\n [ \"operator\\\"\\\"_i8\", \"namespacefly_1_1literals.html#a469306f602d00cf6458aeecac107e6c2\", null ],\n\n [ \"operator\\\"\\\"_u16\", \"namespacefly_1_1literals.html#aa6cba2c5b8906dd840d449074f430c60\", null ],\n\n [ \"operator\\\"\\\"_u32\", \"namespacefly_1_1literals.html#a8a2e6a139be896c60987e84ce744ea4a\", null ],\n\n [ \"operator\\\"\\\"_u64\", \"namespacefly_1_1literals.html#a78696311ec724b34a791f157c5462bcd\", null ],\n\n [ \"operator\\\"\\\"_u8\", \"namespacefly_1_1literals.html#ad59e4eed49d42d20ebcefa8bf194dd36\", null ],\n\n [ \"operator\\\"\\\"_zu\", \"namespacefly_1_1literals.html#a1787d311c579478bb7402265d80a1998\", null ],\n\n [ \"operator<<\", \"json_8cpp.html#a2210291d61381ac50ac427b42d030389\", null ],\n\n [ \"operator==\", \"json_8cpp.html#afb205a987b9da3c4288ded84dbe440c6\", null ],\n\n [ \"supports_consteval\", \"fly_8hpp.html#a70efbc7c8bc68fd2c821b1359aaf6317\", null ],\n\n [ \"visitation\", \"traits_8hpp.html#a2f3fee6bc396502ab71e9485297313f7\", null ],\n\n [ \"all_same_v\", \"traits_8hpp.html#acbc6868029d8571d5db466b767a7525a\", null ],\n\n [ \"any_same_v\", \"traits_8hpp.html#af965b66270c821e82a8ddd75dea928a4\", null ],\n\n [ \"size_of_type_is_v\", \"traits_8hpp.html#a095f06d995b2bb24c0fdd9369d47d9af\", null ]\n\n ] ]\n", "file_path": "docs/namespaces_dup.js", "rank": 66, "score": 52698.42792182503 }, { "content": "class ScopedStreamModifiers\n\n{\n\npublic:\n\n /**\n\n * Constructor. Store the stream's current state to be restored upon destruction.\n\n *\n\n * @param stream The stream to be modified.\n\n */\n\n explicit ScopedStreamModifiers(std::ostream &stream) noexcept;\n\n\n\n /**\n\n * Destructor. Restore the stream's orginal state.\n\n */\n\n ~ScopedStreamModifiers();\n\n\n\n /**\n\n * Sets a formatting flag on the stream.\n\n *\n\n * @param flag The new formatting setting.\n\n */\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 67, "score": 52486.61982183365 }, { "content": "var structfly_1_1logger_1_1_cursor =\n\n[\n\n [ \"Direction\", \"structfly_1_1logger_1_1_cursor.html#a54e75c04cb830fb3596869958377d7aa\", [\n\n [ \"Up\", \"structfly_1_1logger_1_1_cursor.html#a54e75c04cb830fb3596869958377d7aaa4c4fcf8d4fab94b1541d87a2568504a6\", null ],\n\n [ \"Down\", \"structfly_1_1logger_1_1_cursor.html#a54e75c04cb830fb3596869958377d7aaa1cd174b2a02a29b2597d2fad576662ac\", null ],\n\n [ \"Forward\", \"structfly_1_1logger_1_1_cursor.html#a54e75c04cb830fb3596869958377d7aaacd659ef42f048dbc6c1a982ac13164ec\", null ],\n\n [ \"Backward\", \"structfly_1_1logger_1_1_cursor.html#a54e75c04cb830fb3596869958377d7aaa446f985e4c2af4fd3a6916370bdb5baf\", null ]\n\n ] ],\n\n [ \"Cursor\", \"structfly_1_1logger_1_1_cursor.html#aab78c0b7733869fd4a113bc8ebcd49cf\", null ],\n\n [ \"m_direction\", \"structfly_1_1logger_1_1_cursor.html#af1c32a7782a1fffe4be76a31dde0bd79\", null ],\n\n [ \"m_distance\", \"structfly_1_1logger_1_1_cursor.html#a5809ac9fd575cf1a5f14981773533ea5\", null ]\n", "file_path": "docs/structfly_1_1logger_1_1_cursor.js", "rank": 68, "score": 50454.03572883528 }, { "content": "var structfly_1_1logger_1_1_color =\n\n[\n\n [ \"Plane\", \"structfly_1_1logger_1_1_color.html#a095a19efe382d2b0028ef6498d336183\", [\n\n [ \"Foreground\", \"structfly_1_1logger_1_1_color.html#a095a19efe382d2b0028ef6498d336183a748fe91896846cc34c98bbb8c501a018\", null ],\n\n [ \"Background\", \"structfly_1_1logger_1_1_color.html#a095a19efe382d2b0028ef6498d336183a8454c5445fe7c0ad2057204aa7421ca7\", null ]\n\n ] ],\n\n [ \"StandardColor\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388\", [\n\n [ \"Black\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388a57177f2a1c3cf5816f2a1dfc33bd42ee\", null ],\n\n [ \"Red\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388a65af39a2e6fdec6db1de83417961e0ba\", null ],\n\n [ \"Green\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388a6eb97760d5b12ec7f0371b9b023d2b1c\", null ],\n\n [ \"Yellow\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388a4a250d367ccbd3bb2752b242ec6a026c\", null ],\n\n [ \"Blue\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388a445949a2fb58ea0eca117184a2fd03a2\", null ],\n\n [ \"Magenta\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388ad4f0dc3d27e96bafe545c48285500764\", null ],\n\n [ \"Cyan\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388ae49f05a8327df63ccccb4bdc5494ddd1\", null ],\n\n [ \"White\", \"structfly_1_1logger_1_1_color.html#a128f0d308fbbcd45fbdc9dfd1ed7a388aa8b487edf04f9885ae943b5ec6cfaca6\", null ]\n\n ] ],\n\n [ \"Color\", \"structfly_1_1logger_1_1_color.html#a54c222024a3e797ec2eda80321b92eb7\", null ],\n\n [ \"m_color\", \"structfly_1_1logger_1_1_color.html#aee0b7f05b2539a337985b466ebf09ae7\", null ],\n\n [ \"m_plane\", \"structfly_1_1logger_1_1_color.html#a277305c04ee3b28c323c201a2e1b95ba\", null ]\n", "file_path": "docs/structfly_1_1logger_1_1_color.js", "rank": 69, "score": 50454.03572883528 }, { "content": "var classfly_1_1detail_1_1_bit_stream =\n\n[\n\n [ \"~BitStream\", \"classfly_1_1detail_1_1_bit_stream.html#af64292199c3c8cf40aa1fbddc2645650\", null ],\n\n [ \"BitStream\", \"classfly_1_1detail_1_1_bit_stream.html#a7e1e91c217c6d8d59e90bd6a1e0aac12\", null ],\n\n [ \"bit_mask\", \"classfly_1_1detail_1_1_bit_stream.html#a66874d07d3cc560f82dde53e2924bf25\", null ],\n\n [ \"m_buffer\", \"classfly_1_1detail_1_1_bit_stream.html#a789ad3d52703af8cc466afd529565872\", null ],\n\n [ \"m_position\", \"classfly_1_1detail_1_1_bit_stream.html#ac7203dc65e683413c1a1bda194da974b\", null ],\n\n [ \"m_stream_buffer\", \"classfly_1_1detail_1_1_bit_stream.html#afac2fc0345a934f0995c6efb778a90b1\", null ]\n", "file_path": "docs/classfly_1_1detail_1_1_bit_stream.js", "rank": 70, "score": 48194.6206050556 }, { "content": "var classfly_1_1_bit_stream_writer =\n\n[\n\n [ \"BitStreamWriter\", \"classfly_1_1_bit_stream_writer.html#aac978a668121bd958d340f6f3d567ccf\", null ],\n\n [ \"finish\", \"classfly_1_1_bit_stream_writer.html#a3a4eae04f57794995a0c445b72073fbe\", null ],\n\n [ \"write_bits\", \"classfly_1_1_bit_stream_writer.html#a8adc929ff06cf2c95d7d0a2e74b83b40\", null ],\n\n [ \"write_byte\", \"classfly_1_1_bit_stream_writer.html#a4c1d23024a1c07b13e32b78c52491367\", null ],\n\n [ \"write_word\", \"classfly_1_1_bit_stream_writer.html#a8f28589dc377c9d8110cd86d82e249a6\", null ]\n", "file_path": "docs/classfly_1_1_bit_stream_writer.js", "rank": 71, "score": 48194.6206050556 }, { "content": "var classfly_1_1_bit_stream_reader =\n\n[\n\n [ \"BitStreamReader\", \"classfly_1_1_bit_stream_reader.html#ab7b91f6b9946e55aa91a031979a5cf4a\", null ],\n\n [ \"discard_bits\", \"classfly_1_1_bit_stream_reader.html#ac7913ca8928506ce76bd312ef4a491be\", null ],\n\n [ \"fully_consumed\", \"classfly_1_1_bit_stream_reader.html#a202625e6fbdf891906f77b6c3c6496e2\", null ],\n\n [ \"header\", \"classfly_1_1_bit_stream_reader.html#ae94a974ec686bffc6dd7a91d0b1cf2dc\", null ],\n\n [ \"peek_bits\", \"classfly_1_1_bit_stream_reader.html#aa204853b1f929ce7a72c993f68805466\", null ],\n\n [ \"read_bits\", \"classfly_1_1_bit_stream_reader.html#a9006c73c0109014483d0333cbe91e639\", null ],\n\n [ \"read_byte\", \"classfly_1_1_bit_stream_reader.html#aeda8cd118fadf808f960faf13acaa632\", null ],\n\n [ \"read_word\", \"classfly_1_1_bit_stream_reader.html#a1131f84ee9372f967a3f5b3ea725fba7\", null ]\n", "file_path": "docs/classfly_1_1_bit_stream_reader.js", "rank": 72, "score": 48194.6206050556 }, { "content": "#include \"bench/util/stream_util.hpp\"\n\n\n\nnamespace fly::benchmark {\n\n\n\n//==================================================================================================\n\nstd::ios::char_type CommaPunctuation::do_thousands_sep() const\n\n{\n\n return ',';\n\n}\n\n\n\n//==================================================================================================\n\nstd::string CommaPunctuation::do_grouping() const\n\n{\n\n return \"\\3\";\n\n}\n\n\n\n} // namespace fly::benchmark\n", "file_path": "bench/util/stream_util.cpp", "rank": 73, "score": 46845.26921052533 }, { "content": "\n\nnamespace fly::test {\n\n\n\n//==================================================================================================\n\nCaptureStream::CaptureStream(Stream stream) noexcept :\n\n m_file(m_path.file()),\n\n m_stream(stream),\n\n m_stdio(-1),\n\n m_original(-1)\n\n{\n\n FILE *target = nullptr;\n\n\n\n#if defined(FLY_LINUX) || defined(FLY_MACOS)\n\n target = ::fopen(m_file.string().c_str(), \"w\");\n\n#elif defined(FLY_WINDOWS)\n\n ::fopen_s(&target, m_file.string().c_str(), \"w\");\n\n#else\n\n# error Unknown file open command.\n\n#endif\n\n\n", "file_path": "test/util/capture_stream.cpp", "rank": 74, "score": 46844.6486351921 }, { "content": "#pragma once\n\n\n\n#include \"test/util/path_util.hpp\"\n\n\n\n#include <cstdint>\n\n#include <filesystem>\n\n#include <string>\n\n\n\nnamespace fly::test {\n\n\n\n/**\n\n * RAII helper class to redirect either stdout or stderr to a file for reading. On destruction, the\n\n * redirected stream is restored and the file is deleted. Only meant to be used by unit tests.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version August 12, 2018\n\n */\n", "file_path": "test/util/capture_stream.hpp", "rank": 75, "score": 46844.494024589316 }, { "content": "#pragma once\n\n\n\n#include <locale>\n\n#include <ostream>\n\n\n\nnamespace fly::benchmark {\n\n\n\n/**\n\n * Locale facet to format numbers with comma separators.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version Decmber 12, 2020\n\n */\n", "file_path": "bench/util/stream_util.hpp", "rank": 76, "score": 46841.44950038718 }, { "content": "#include \"test/util/capture_stream.hpp\"\n\n\n\n#include \"fly/fly.hpp\"\n\n\n\n#include \"catch2/catch_test_macros.hpp\"\n\n\n\n#include <cstdio>\n\n#include <cstdlib>\n\n\n\n#if defined(FLY_LINUX) || defined(FLY_MACOS)\n\n# include <unistd.h>\n\n#elif defined(FLY_WINDOWS)\n\n# include <io.h>\n\n# define close _close\n\n# define dup _dup\n\n# define dup2 _dup2\n\n# define fileno _fileno\n\n#else\n\n# error Unknown file IO include.\n\n#endif\n", "file_path": "test/util/capture_stream.cpp", "rank": 77, "score": 46841.341475129346 }, { "content": " {\n\n switch (m_stream)\n\n {\n\n case Stream::Stdout:\n\n ::fflush(stdout);\n\n break;\n\n\n\n case Stream::Stderr:\n\n ::fflush(stderr);\n\n break;\n\n }\n\n\n\n ::dup2(m_original, m_stdio);\n\n ::close(m_original);\n\n\n\n if (read)\n\n {\n\n contents = fly::test::PathUtil::read_file(m_file);\n\n }\n\n\n\n m_original = -1;\n\n }\n\n\n\n return contents;\n\n}\n\n\n\n} // namespace fly::test\n", "file_path": "test/util/capture_stream.cpp", "rank": 78, "score": 46841.05772283058 }, { "content": " * the file.\n\n *\n\n * @return The contents of the redirected stream.\n\n */\n\n std::string operator()();\n\n\n\nprivate:\n\n /**\n\n * Restore the redirected stream, read the contents of the redirect file if specified, and\n\n * delete the file.\n\n *\n\n * @param read True if the file should be read before deletion.\n\n *\n\n * @return The contents of the redirected stream.\n\n */\n\n std::string restore(bool read);\n\n\n\n fly::test::PathUtil::ScopedTempDirectory m_path;\n\n std::filesystem::path m_file;\n\n\n\n Stream m_stream;\n\n int m_stdio;\n\n int m_original;\n\n};\n\n\n\n} // namespace fly::test\n", "file_path": "test/util/capture_stream.hpp", "rank": 79, "score": 46840.658694799255 }, { "content": "}\n\n\n\n//==================================================================================================\n\nCaptureStream::~CaptureStream()\n\n{\n\n restore(false);\n\n}\n\n\n\n//==================================================================================================\n\nstd::string CaptureStream::operator()()\n\n{\n\n return restore(true);\n\n}\n\n\n\n//==================================================================================================\n\nstd::string CaptureStream::restore(bool read)\n\n{\n\n std::string contents;\n\n\n\n if (m_original != -1)\n", "file_path": "test/util/capture_stream.cpp", "rank": 80, "score": 46837.85359608171 }, { "content": " CATCH_REQUIRE(target != nullptr);\n\n int target_fd = ::fileno(target);\n\n\n\n switch (m_stream)\n\n {\n\n case Stream::Stdout:\n\n m_stdio = ::fileno(stdout);\n\n ::fflush(stdout);\n\n break;\n\n\n\n case Stream::Stderr:\n\n m_stdio = ::fileno(stderr);\n\n ::fflush(stderr);\n\n break;\n\n }\n\n\n\n m_original = ::dup(m_stdio);\n\n ::dup2(target_fd, m_stdio);\n\n\n\n ::fclose(target);\n", "file_path": "test/util/capture_stream.cpp", "rank": 81, "score": 46837.08856986376 }, { "content": "var classfly_1_1detail_1_1_basic_stream_modifiers =\n\n[\n\n [ \"BasicStreamModifiers\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#a28a29ca8df1f57e9c982fe63b6eb5383\", null ],\n\n [ \"~BasicStreamModifiers\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#a3fab6eb586503610ac92865e50fc429d\", null ],\n\n [ \"fill\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#a0153f614a22ee4fc5537c85b4c8ab0d4\", null ],\n\n [ \"locale\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#a1113dd1bf5bae8bd31d99aeb226467bb\", null ],\n\n [ \"precision\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#af98e0e09b7117cd9db35d997a77a43dd\", null ],\n\n [ \"setf\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#a63baf71fd3a26d203b95a10edd717440\", null ],\n\n [ \"setf\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#a9ed89a58ac34eddbc29660990257f85f\", null ],\n\n [ \"width\", \"classfly_1_1detail_1_1_basic_stream_modifiers.html#afdb7ddb6717f908ddd24680c70186ecb\", null ]\n", "file_path": "docs/classfly_1_1detail_1_1_basic_stream_modifiers.js", "rank": 82, "score": 46301.50916314491 }, { "content": "var structfly_1_1detail_1_1_bit_stream_traits =\n\n[\n\n [ \"is_buffer_type\", \"structfly_1_1detail_1_1_bit_stream_traits.html#a52fdab40afaa07b7dc51a6cda190ec1b\", null ],\n\n [ \"is_unsigned_integer\", \"structfly_1_1detail_1_1_bit_stream_traits.html#a2ead88269ccc5e33990ced6ac49c89fe\", null ]\n", "file_path": "docs/structfly_1_1detail_1_1_bit_stream_traits.js", "rank": 83, "score": 46301.50916314491 }, { "content": "#pragma once\n\n\n\n#include \"fly/types/string/literals.hpp\"\n\n\n\n#include <cctype>\n\n#include <ios>\n\n#include <locale>\n\n#include <ostream>\n\n\n\nnamespace fly::detail {\n\n\n\n/**\n\n * RAII helper class to make formatting modifications to a stream and ensure those modifications\n\n * are reset upon destruction.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version January 3, 2021\n\n */\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 84, "score": 43398.11581816191 }, { "content": "{\n\n}\n\n\n\n//==================================================================================================\n\ninline ScopedStreamModifiers::~ScopedStreamModifiers()\n\n{\n\n if (m_changed_flags)\n\n {\n\n m_stream.flags(m_flags);\n\n }\n\n if (m_changed_locale)\n\n {\n\n m_stream.imbue(m_locale);\n\n }\n\n if (m_changed_fill)\n\n {\n\n m_stream.fill(m_fill);\n\n }\n\n if (m_changed_width)\n\n {\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 85, "score": 43390.75197406192 }, { "content": "}\n\n\n\n//==================================================================================================\n\ntemplate <typename Facet>\n\ninline void ScopedStreamModifiers::locale()\n\n{\n\n m_stream.imbue({m_stream.getloc(), new Facet()});\n\n m_changed_locale = true;\n\n}\n\n\n\n//==================================================================================================\n\ninline void ScopedStreamModifiers::fill(char ch)\n\n{\n\n m_stream.fill(ch);\n\n m_changed_fill = true;\n\n}\n\n\n\n//==================================================================================================\n\ninline void ScopedStreamModifiers::width(std::streamsize size)\n\n{\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 86, "score": 43390.5731279889 }, { "content": " m_stream.width(m_width);\n\n }\n\n if (m_changed_precision)\n\n {\n\n m_stream.precision(m_precision);\n\n }\n\n}\n\n\n\n//==================================================================================================\n\ninline void ScopedStreamModifiers::setf(std::ios_base::fmtflags flag)\n\n{\n\n m_stream.setf(flag);\n\n m_changed_flags = true;\n\n}\n\n\n\n//==================================================================================================\n\ninline void ScopedStreamModifiers::setf(std::ios_base::fmtflags flag, std::ios_base::fmtflags mask)\n\n{\n\n m_stream.setf(flag, mask);\n\n m_changed_flags = true;\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 87, "score": 43390.445102814985 }, { "content": " ScopedStreamModifiers(const ScopedStreamModifiers &) = delete;\n\n ScopedStreamModifiers &operator=(const ScopedStreamModifiers &) = delete;\n\n\n\n std::ostream &m_stream;\n\n\n\n const std::ios_base::fmtflags m_flags;\n\n bool m_changed_flags {false};\n\n\n\n const std::locale m_locale;\n\n bool m_changed_locale {false};\n\n\n\n const char m_fill;\n\n bool m_changed_fill {false};\n\n\n\n const std::streamsize m_width;\n\n bool m_changed_width {false};\n\n\n\n const std::streamsize m_precision;\n\n bool m_changed_precision {false};\n\n};\n\n\n\n/**\n\n * Helper facet to support BasicFormatSpecifier::Sign::NegativeOnlyWithPositivePadding. Overrides\n\n * std::ctype to replace the positive sign character with a space.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version January 3, 2021\n\n */\n\ntemplate <typename CharType>\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 88, "score": 43389.600150370374 }, { "content": " m_stream.width(size);\n\n m_changed_width = true;\n\n}\n\n\n\n//==================================================================================================\n\ninline void ScopedStreamModifiers::precision(std::streamsize size)\n\n{\n\n m_stream.precision(size);\n\n m_changed_precision = true;\n\n}\n\n\n\n//==================================================================================================\n\ntemplate <typename CharType>\n\nCharType PositivePaddingFacet<CharType>::do_widen(char ch) const\n\n{\n\n return (ch == s_plus_sign) ? s_space : static_cast<CharType>(ch);\n\n}\n\n\n\n//==================================================================================================\n\ntemplate <typename CharType>\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 89, "score": 43389.496036283985 }, { "content": " void setf(std::ios_base::fmtflags flag);\n\n\n\n /**\n\n * Clears a mask of formatting flags on the stream and sets a specific flag.\n\n *\n\n * @param flag The new formatting setting.\n\n * @param mask The formatting mask to clear.\n\n */\n\n void setf(std::ios_base::fmtflags flag, std::ios_base::fmtflags mask);\n\n\n\n /**\n\n * Imbue a new locale onto the stream with a specific facet.\n\n *\n\n * @tparam Facet The type of facet to imbue.\n\n */\n\n template <typename Facet>\n\n void locale();\n\n\n\n /**\n\n * Set the fill character of the stream.\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 90, "score": 43389.273338102685 }, { "content": " *\n\n * @param ch The new fill setting.\n\n */\n\n void fill(char ch);\n\n\n\n /**\n\n * Set the width of the stream.\n\n *\n\n * @param size The new width setting.\n\n */\n\n void width(std::streamsize size);\n\n\n\n /**\n\n * Set the precision of the stream.\n\n *\n\n * @param size The new precision setting.\n\n */\n\n void precision(std::streamsize size);\n\n\n\nprivate:\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 91, "score": 43389.21027774623 }, { "content": "const char *\n\nPositivePaddingFacet<CharType>::do_widen(const char *begin, const char *end, CharType *dest) const\n\n{\n\n while (begin != end)\n\n {\n\n *dest++ = do_widen(*begin++);\n\n }\n\n\n\n return end;\n\n}\n\n\n\n} // namespace fly::detail\n", "file_path": "fly/types/string/detail/stream_util.hpp", "rank": 92, "score": 43388.59632225414 }, { "content": "class BitStreamWriter;\n\n} // namespace fly\n\n\n\nnamespace fly::coders {\n\n\n\n/**\n\n * Virtual interface to encode a string or file with a plaintext encoder. Coders for specific\n\n * algorithms should inherit from this class to perform encoding.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version July 7, 2019\n\n */\n", "file_path": "fly/coders/coder.hpp", "rank": 93, "score": 43384.16995281949 }, { "content": "class BitStreamReader;\n", "file_path": "fly/coders/coder.hpp", "rank": 94, "score": 43384.16995281949 }, { "content": "class BitStreamWriter;\n\n} // namespace fly\n\n\n\nnamespace fly::coders {\n\n\n", "file_path": "fly/coders/huffman/huffman_encoder.hpp", "rank": 95, "score": 40409.57370904152 }, { "content": "class BitStreamReader;\n\n} // namespace fly\n\n\n\nnamespace fly::coders {\n\n\n\n/**\n\n * Implementation of the Decoder interface for Huffman coding.\n\n *\n\n * @author Timothy Flynn ([email protected])\n\n * @version July 7, 2019\n\n */\n", "file_path": "fly/coders/huffman/huffman_decoder.hpp", "rank": 96, "score": 40409.57370904152 }, { "content": "var searchData=\n\n[\n\n ['literals_601',['literals',['../namespacefly_1_1literals.html',1,'fly']]]\n", "file_path": "docs/search/namespaces_0.js", "rank": 97, "score": 39227.8348215087 }, { "content": "// STL IO Streams\n\nclass StreamFormat : public StringBase\n\n{\n\npublic:\n\n void format_with_floats() override\n\n {\n\n std::stringstream stream;\n\n stream << std::setprecision(10) << std::fixed << 1.234 << ':'\n\n << std::resetiosflags(std::ios::floatfield) << std::setw(4) << std::setfill('0')\n\n << 42 << std::setfill(' ') << ':' << std::setiosflags(std::ios::showpos) << 3.13\n\n << std::resetiosflags(std::ios::showpos) << ':' << \"str\" << ':' << nullptr << ':'\n\n << 'X' << \":%\\n\";\n\n }\n\n\n\n void format_without_floats() override\n\n {\n\n std::stringstream stream;\n\n stream << std::setw(10) << 1234 << ':' << std::setw(4) << std::setfill('0') << 42\n\n << std::setfill(' ') << ':' << std::setiosflags(std::ios::showpos) << 313\n\n << std::resetiosflags(std::ios::showpos) << ':' << \"str\" << ':' << nullptr << ':'\n\n << 'X' << \":%\\n\";\n", "file_path": "bench/string/benchmark_string.cpp", "rank": 98, "score": 39075.77238515821 }, { "content": "class FailStreamSink : public QueueSink\n\n{\n\npublic:\n\n FailStreamSink(fly::ConcurrentQueue<fly::logger::Log> &logs) : QueueSink(logs)\n\n {\n\n }\n\n\n\n bool stream(fly::logger::Log &&log) override\n\n {\n\n return !QueueSink::stream(std::move(log));\n\n }\n\n};\n\n\n\n} // namespace\n\n\n\nCATCH_TEST_CASE(\"Logger\", \"[logger]\")\n\n{\n\n auto logger_config = std::make_shared<fly::logger::LoggerConfig>();\n\n fly::ConcurrentQueue<fly::logger::Log> received_logs;\n\n\n", "file_path": "test/logger/logger.cpp", "rank": 99, "score": 39070.16838841045 } ]
C++
hoomd/dem/DEMEvaluator.cc
schwendp/hoomd-blue
df7970121b19bc4f8674348ab3241055ac87153b
#ifndef __DEMEVALUATOR_CC__ #define __DEMEVALUATOR_CC__ #include "DEMEvaluator.h" #include "WCAPotential.h" #include <assert.h> template<typename Real> DEVICE inline Real clip(const Real &x) { return (x >= 0)*(x + (x > 1)*(1 - x)); } template<typename Real, typename Real4, typename Potential> template<typename Vec, typename Torque> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::comCOM( const Vec &rij, Real &potential, Vec &force_i, Torque &torque_i, Vec &force_j, Torque &torque_j) const { m_potential.evaluate(rij, Vec(), rij, potential, force_i, torque_i, force_j, torque_j); } template<typename Real, typename Real4, typename Potential> template<typename Vec, typename Torque> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::vertexVertex( const Vec &rij, const Vec &r0, const Vec &r1, Real &potential, Vec &force_i, Torque &torque_i, Vec &force_j, Torque &torque_j, float modFactor) const { m_potential.evaluate(rij, r0, r1, potential, force_i, torque_i, force_j, torque_j, modFactor); } template<typename Real, typename Real4, typename Potential> template<typename Vec, typename Torque> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::vertexEdge( const Vec &rij, const Vec &r0, const Vec &r1, const Vec &r2, Real &potential, Vec &force_i, Torque &torque_i, Vec &force_j, Torque &torque_j, float modFactor) const { const Vec r10(r0 - (r1 + rij)); const Vec r12(r2 - r1); Real lambda(dot(r10, r12)/dot(r12, r12)); lambda = clip(lambda); const Vec rPrime(r1 + rij + lambda*r12); m_potential.evaluate(rij, r0, rPrime, potential, force_i, torque_i, force_j, torque_j, modFactor); } template<typename Real, typename Real4, typename Potential> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::vertexFace( const vec3<Real> &rij, const vec3<Real> &r0, const quat<Real> quatj, const Real4 *verticesj, const unsigned int *realIndicesj, const unsigned int *facesj, const unsigned int vertex0Index, Real &potential, vec3<Real> &force_i, vec3<Real> &torque_i, vec3<Real> &force_j, vec3<Real> &torque_j) const { Real distsq(0); const vec3<Real> r0j(r0 - rij); vec3<Real> rPrime; const vec3<Real> vertex0(rotate(quatj, vec3<Real>(verticesj[realIndicesj[vertex0Index]]))); const vec3<Real> r0r0(r0j - vertex0); const vec3<Real> secondVertex(rotate(quatj, vec3<Real>(verticesj[realIndicesj[facesj[vertex0Index]]]))); const vec3<Real> rsec(secondVertex - vertex0); Real lambda(dot(r0r0, rsec)/dot(rsec, rsec)); lambda = clip(lambda); vec3<Real> closest(vertex0 + lambda*rsec); vec3<Real> closestr0(closest - r0j); Real closestDistsq(dot(closestr0, closestr0)); distsq = closestDistsq; rPrime = closest; vec3<Real> p1, p2(secondVertex), p01, p02(secondVertex - vertex0); unsigned int i(facesj[vertex0Index]); for(; facesj[i] != vertex0Index; i = facesj[i]) { Real alpha(0), beta(0); p1 = p2; p2 = rotate(quatj, vec3<Real>(verticesj[realIndicesj[facesj[i]]])); p01 = p02; p02 = p2 - vertex0; const vec3<Real> pc(cross(p01, p02)); Real magA(p01.x*(p02.y*pc.z - pc.y*p02.z) - p02.x*(p01.y*pc.z - pc.y*p01.z) + pc.x*(p01.y*p02.z - p02.y*p01.z)); alpha = ((p02.y*pc.z - pc.y*p02.z)*r0r0.x + (pc.x*p02.z - p02.x*pc.z)*r0r0.y + (p02.x*pc.y - pc.x*p02.y)*r0r0.z)/magA; beta = ((pc.y*p01.z - p01.y*pc.z)*r0r0.x + (p01.x*pc.z - pc.x*p01.z)*r0r0.y + (pc.x*p01.y - p01.x*pc.y)*r0r0.z)/magA; alpha = clip(alpha); beta = clip(beta); const Real k(alpha + beta); if(k > 1) { alpha /= k; beta /= k; } const vec3<Real> p12(p2 - p1); Real lambda(dot(r0j - p1, p12)/dot(p12, p12)); lambda = clip(lambda); vec3<Real> closest(p1 + lambda*p12); vec3<Real> closestr0(closest - r0j); Real closestDistsq(dot(closestr0, closestr0)); if(closestDistsq < distsq) { distsq = closestDistsq; rPrime = closest; } closest = vertex0 + alpha*p01 + beta*p02; closestr0 = closest - r0j; closestDistsq = dot(closestr0, closestr0); if(closestDistsq < distsq) { distsq = closestDistsq; rPrime = closest; } } const vec3<Real> rlast(p2 - vertex0); lambda = dot(r0r0, rlast)/dot(rlast, rlast); lambda = clip(lambda); closest = vertex0 + lambda*rlast; closestr0 = closest - r0j; closestDistsq = dot(closestr0, closestr0); if(closestDistsq < distsq) { distsq = closestDistsq; rPrime = closest; } if(distsq > 0) m_potential.evaluate(rij, r0, rPrime + rij, potential, force_i, torque_i, force_j, torque_j); } template<typename Real> DEVICE inline Real detp(const vec3<Real> &m, const vec3<Real> &n, const vec3<Real> o, const vec3<Real> p) { return dot(m - n, o - p); } template<typename Real, typename Real4, typename Potential> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::edgeEdge( const vec3<Real> &rij, const vec3<Real> &p00, const vec3<Real> &p01, const vec3<Real> &p10, const vec3<Real> &p11, Real &potential, vec3<Real> &force_i, vec3<Real> &torque_i, vec3<Real> &force_j, vec3<Real> &torque_j) const { Real denominator(detp(p01, p00, p01, p00)*detp(p11, p10, p11, p10) - detp(p11, p10, p01, p00)*detp(p11, p10, p01, p00)); Real lambda0((detp(p00, p10, p11, p10)*detp(p11, p10, p01, p00) - detp(p00, p10, p01, p00)*detp(p11, p10, p11, p10))/denominator); Real lambda1((detp(p00, p10, p11, p10) + lambda0*detp(p11, p10, p01, p00))/detp(p11, p10, p11, p10)); lambda0 = clip(lambda0); lambda1 = clip(lambda1); const vec3<Real> r0(p01 - p00); const Real r0sq(dot(r0, r0)); const vec3<Real> r1(p11 - p10); const Real r1sq(dot(r1, r1)); vec3<Real> closestI(p00 + lambda0*r0); vec3<Real> closestJ(p10 + lambda1*r1); vec3<Real> rContact(closestJ - closestI); Real closestDistsq(dot(rContact, rContact)); Real lambda(clip(dot(p10 - p00, r0)/r0sq)); vec3<Real> candidateI(p00 + lambda*r0); vec3<Real> candidateJ(p10); rContact = candidateJ - candidateI; Real distsq(dot(rContact, rContact)); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } lambda = clip(dot(p11 - p00, r0)/r0sq); candidateI = p00 + lambda*r0; candidateJ = p11; rContact = candidateJ - candidateI; distsq = dot(rContact, rContact); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } lambda = clip(dot(p00 - p10, r1)/r1sq); candidateI = p00; candidateJ = p10 + lambda*r1; rContact = candidateJ - candidateI; distsq = dot(rContact, rContact); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } lambda = clip(dot(p01 - p10, r1)/r1sq); candidateI = p01; candidateJ = p10 + lambda*r1; rContact = candidateJ - candidateI; distsq = dot(rContact, rContact); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } if(fabs(1 - dot(r0, r1)*dot(r0, r1)/r0sq/r1sq) < 1e-6) { const Real lambda00(clip(dot(p10 - p00, r0)/r0sq)); const Real lambda01(clip(dot(p11 - p00, r0)/r0sq)); const Real lambda10(clip(dot(p00 - p10, r1)/r1sq)); const Real lambda11(clip(dot(p01 - p10, r1)/r1sq)); lambda0 = Real(.5)*(lambda00 + lambda01); lambda1 = Real(.5)*(lambda10 + lambda11); closestI = p00 + lambda0*r0; closestJ = p10 + lambda1*r1; } m_potential.evaluate(rij, closestI, closestJ, potential, force_i, torque_i, force_j, torque_j); } #endif
#ifndef __DEMEVALUATOR_CC__ #define __DEMEVALUATOR_CC__ #include "DEMEvaluator.h" #include "WCAPotential.h" #include <assert.h> template<typename Real> DEVICE inline Real clip(const Real &x) { return (x >= 0)*(x + (x > 1)*(1 - x)); } template<typename Real, typename Real4, typename Potential> template<typename Vec, typename Torque> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::comCOM( const Vec &rij, Real &potential, Vec &force_i, Torque &torque_i, Vec &force_j, Torque &torque_j) const { m_potential.evaluate(rij, Vec(), rij, potential, force_i, torque_i, force_j, torque_j); } template<typename Real, typename Real4, typename Potential> template<typename Vec, typename Torque> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::vertexVertex( const Vec &rij, const Vec &r0, const Vec &r1, Real &potential, Vec &force_i, Torque &torque_i, Vec &force_j, Torque &torque_j, float modFactor) const { m_potential.evaluate(rij, r0, r1, potential, force_i, torque_i, force_j, torque_j, modFactor); } template<typename Real, typename Real4, typename Potential> template<typename Vec, typename Torque> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::vertexEdge( const Vec &rij, const Vec &r0, const Vec &r1, const Vec &r2, Real &potential, Vec &force_i, Torque &torque_i, Vec &force_j, Torque &torque_j, float modFactor) const { const Vec r10(r0 - (r1 + rij)); const Vec r12(r2 - r1); Real lambda(dot(r10, r12)/dot(r12, r12)); lambda = clip(lambda); const Vec rPrime(r1 + rij + lambda*r12); m_potential.evaluate(rij, r0, rPrime, potential, force_i, torque_i, force_j, torque_j, modFactor); } template<typename Real, typename Real4, typename Potential> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::vertexFace( const vec3<Real> &rij, const vec3<Real> &r0, const quat<Real> quatj, const Real4 *verticesj, const unsigned int *realIndicesj, const unsigned int *facesj, const unsigned int vertex0Index, Real &potential, vec3<Real> &force_i, vec3<Real> &torque_i, vec3<Real> &force_j, vec3<Real> &torque_j) const { Real distsq(0); const vec3<Real> r0j(r0 - rij); vec3<Real> rPrime; const vec3<Real> vertex0(rotate(quatj, vec3<Real>(verticesj[realIndicesj[vertex0Index]]))); const vec3<Real> r0r0(r0j - vertex0); const vec3<Real> secondVertex(rotate(quatj, vec3<Real>(verticesj[realIndicesj[facesj[vertex0Index]]]))); const vec3<Real> rsec(secondVertex - vertex0); Real lambda(dot(r0r0, rsec)/dot(rsec, rsec)); lambda = clip(lambda); vec3<Real> closest(vertex0 + lambda*rsec); vec3<Real> closestr0(closest - r0j); Real closestDistsq(dot(closestr0, closestr0)); distsq = closestDistsq; rPrime = closest; vec3<Real> p1, p2(secondVertex), p01, p02(secondVertex - vertex0); unsigned int i(facesj[vertex0Index]); for(; facesj[i] != vertex0Index; i = facesj[i]) { Real alpha(0), beta(0); p1 = p2; p2 = rotate(quatj, vec3<Real>(verticesj[realIndicesj[facesj[i]]])); p01 = p02; p02 = p2 - vertex0; const vec3<Real> pc(cross(p01, p02)); Real magA(p01.x*(p02.y*pc.z - pc.y*p02.z) - p02.x*(p01.y*pc.z - pc.y*p01.z) + pc.x*(p01.y*p02.z - p02.y*p01.z)); alpha = ((p02.y*pc.z - pc.y*p02.z)*r0r0.x + (pc.x*p02.z - p02.x*pc.z)*r0r0.y + (p02.x*pc.y - pc.x*p02.y)*r0r0.z)/magA; beta = ((pc.y*p01.z - p01.y*pc.z)*r0r0.x + (p01.x*pc.z - pc.x*p01.z)*r0r0.y + (pc.x*p01.y - p01.x*pc.y)*r0r0.z)/magA; alpha = clip(alpha); beta = clip(beta); const Real k(alpha + beta); if(k > 1) { alpha /= k; beta /= k; } const vec3<Real> p12(p2 - p1); Real lambda(dot(r0j - p1, p12)/dot(p12, p12)); lambda = clip(lambda); vec3<Real> closest(p1 + lambda*p12); vec3<Real> closestr0(closest - r0j); Real closestDistsq(dot(closestr0, closestr0)); if(closestDistsq < distsq) { distsq = closestDistsq; rPrime = closest; } closest = vertex0 + alpha*p01 + beta*p02; closestr0 = closest - r0j; closestDistsq = dot(closestr0, closestr0); if(closestDistsq < distsq) { distsq = closestDistsq; rPrime = closest; } } const vec3<Real> rlast(p2 - vertex0); lambda = dot(r0r0, rlast)/dot(rlast, rlast); lambda = clip(lambda); closest = vertex0 + lambda*rlast; closestr0 = closest - r0j; closestDistsq = dot(closestr0, closestr0); if(closestDistsq < distsq) { distsq = closestDistsq; rPrime = closest; } if(distsq > 0) m_potential.evaluate(rij, r0, rPrime + rij, potential, force_i, torque_i, force_j, torque_j); } template<typename Real> DEVICE inline Real detp(const vec3<Real> &m, const vec3<Real> &n, const vec3<Real> o, const vec3<Real> p) { return dot(m - n, o - p); } template<typename Real, typename Real4, typename Potential> DEVICE inline void DEMEvaluator<Real, Real4, Potential>::edgeEdge( const vec3<Real> &rij, const vec3<Real> &p00, const vec3<Real> &p01, const vec3<Real> &p10, const vec3<Real> &p11, Real &potential, vec3<Real> &force_i, vec3<Real> &torque_i, vec3<Real> &force_j, vec3<Real> &torque_j) const { Real denominator(detp(p01, p00, p01, p00)*detp(p11, p10, p11, p10) - detp(p11, p10, p01, p00)*detp(p11, p10, p01, p00)); Real lambda0((detp(p00, p10, p11, p10)*detp(p11, p10, p01, p00) - detp(p00, p10, p01, p00)*detp(p11, p10, p11, p10))/denominator); Real lambda1((detp(p00, p10, p11, p10) + lambda0*detp(p11, p10, p01, p00))/detp(p11, p10, p11, p10)); lambda0 = clip(lambda0); lambda1 = clip(lambda1); const vec3<Real> r0(p01 - p00); const Real r0sq(dot(r0, r0)); const vec3<Real> r1(p11 - p10); const Real r1sq(dot(r1, r1)); vec3<Real> closestI(p00 + lambda0*r0); vec3<Real> closestJ(p10 + lambda1*r1); vec3<Real> rContact(closestJ - closestI); Real closestDistsq(dot(rContact, rContact)); Real lambda(clip(dot(p10 - p00, r0)/r0sq)); vec3<Real> candidateI(p00 + lambda*r0); vec3<Real> candidateJ(p10); rContact = candidateJ - candidateI; Real distsq(dot(rContact, rContact));
lambda = clip(dot(p11 - p00, r0)/r0sq); candidateI = p00 + lambda*r0; candidateJ = p11; rContact = candidateJ - candidateI; distsq = dot(rContact, rContact); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } lambda = clip(dot(p00 - p10, r1)/r1sq); candidateI = p00; candidateJ = p10 + lambda*r1; rContact = candidateJ - candidateI; distsq = dot(rContact, rContact); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } lambda = clip(dot(p01 - p10, r1)/r1sq); candidateI = p01; candidateJ = p10 + lambda*r1; rContact = candidateJ - candidateI; distsq = dot(rContact, rContact); if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; } if(fabs(1 - dot(r0, r1)*dot(r0, r1)/r0sq/r1sq) < 1e-6) { const Real lambda00(clip(dot(p10 - p00, r0)/r0sq)); const Real lambda01(clip(dot(p11 - p00, r0)/r0sq)); const Real lambda10(clip(dot(p00 - p10, r1)/r1sq)); const Real lambda11(clip(dot(p01 - p10, r1)/r1sq)); lambda0 = Real(.5)*(lambda00 + lambda01); lambda1 = Real(.5)*(lambda10 + lambda11); closestI = p00 + lambda0*r0; closestJ = p10 + lambda1*r1; } m_potential.evaluate(rij, closestI, closestJ, potential, force_i, torque_i, force_j, torque_j); } #endif
if(distsq < closestDistsq) { closestI = candidateI; closestJ = candidateJ; closestDistsq = distsq; }
if_condition
[]
C++
src/multi_index_array/kennytm/vtmp.hpp
extragoya/LibNT
60372bf4e3c5d6665185358c4756da4fe547f093
#ifndef VTMP_HPP_KFLYEISDKHB #define VTMP_HPP_KFLYEISDKHB 1 #include <cstdlib> #include <type_traits> #include <utility> #include <array> #include "traits.hpp" namespace utils { namespace vtmp { template <size_t... ns> struct integers { template <size_t n> using push_back = integers<ns..., n>; }; namespace xx_impl { template <size_t n> struct iota_impl { typedef typename iota_impl<n-1>::type::template push_back<n-1> type; }; template <> struct iota_impl<0> { typedef integers<> type; }; } template <size_t n> using iota = typename xx_impl::iota_impl<n>::type; } namespace xx_impl { template <typename Source, typename Target> struct copy_cr { typedef Target type; }; template <typename Source, typename Target> struct copy_cr<Source&, Target> { typedef Target& type; }; template <typename Source, typename Target> struct copy_cr<Source&&, Target> { typedef Target&& type; }; template <typename Source, typename Target> struct copy_cr<const Source&, Target> { typedef const Target& type; }; template <typename Source, typename Target> struct copy_cr<const Source&&, Target> { typedef const Target&& type; }; template <typename... T, typename F, typename G, size_t... ns, typename Tuple> auto tuple_funcs(F&& reduce, G&& map, const vtmp::integers<ns...>&, Tuple&& tup) -> decltype(reduce(map(std::declval<typename copy_cr<Tuple, T>::type>())...)) { return reduce(map(std::get<ns>(tup))...); } struct no_op_func { template <typename T> T&& operator()(T&& value) const noexcept { return std::forward<T>(value); } }; struct make_tuple_func { template <typename... T> auto operator()(T&&... values) const -> decltype(std::make_tuple(std::declval<T>()...)) { return std::make_tuple(std::forward<T>(values)...); } }; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-braces" template <typename C> struct constructor_func { template <typename... T> C operator()(T&&... values) const { return C{std::forward<T>(values)...}; } }; #pragma GCC diagnostic pop } template <typename F, typename... T> auto tuple_apply(std::tuple<T...>& tup, F&& func) -> decltype(func(std::declval<T&>()...)) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(std::forward<F>(func), xx_impl::no_op_func(), instance, tup); } template <typename F, typename... T> auto tuple_apply(std::tuple<T...>&& tup, F&& func) -> decltype(func(std::declval<T&&>()...)) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(std::forward<F>(func), xx_impl::no_op_func(), instance, std::move(tup)); } template <typename F, typename... T> auto tuple_apply(const std::tuple<T...>& tup, F&& func) -> decltype(func(std::declval<const T&>()...)) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(std::forward<F>(func), xx_impl::no_op_func(), instance, tup); } template <typename F, typename... T> auto tuple_map(std::tuple<T...>&& tup, F&& func) -> std::tuple<decltype(func(std::declval<T>()))...> { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::make_tuple_func(), std::forward<F>(func), instance, std::move(tup)); } template <typename F, typename... T> auto tuple_map(const std::tuple<T...>& tup, F&& func) -> std::tuple<decltype(func(std::declval<T>()))...> { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::make_tuple_func(), std::forward<F>(func), instance, tup); } template <typename C, typename... T> C tuple_construct(std::tuple<T...>&& tup) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::constructor_func<C>(), xx_impl::no_op_func(), instance, std::move(tup)); } template <typename C, typename... T> C tuple_construct(const std::tuple<T...>& tup) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::constructor_func<C>(), xx_impl::no_op_func(), instance, tup); } } #endif
#ifndef VTMP_HPP_KFLYEISDKHB #define VTMP_HPP_KFLYEISDKHB 1 #include <cstdlib> #include <type_traits> #include <utility> #include <array> #include "traits.hpp" namespace utils { namespace vtmp { template <size_t... ns> struct integers { template <size_t n> using push_back = integers<ns..., n>; }; namespace xx_impl { template <size_t n> struct iota_impl { typedef typename iota_impl<n-1>::type::template push_back<n-1> type; }; template <> struct iota_impl<0> { typedef integers<> type; }; } template <size_t n> using iota = typename xx_impl::iota_impl<n>::type; } namespace xx_impl { template <typename Source, typename Target> struct copy_cr { typedef Target type; }; template <typename Source, typename Target> struct copy_cr<Source&, Target> { typedef Target& type; }; template <typename Source, typename Target> struct copy_cr<Source&&, Target> { typedef Target&& type; }; template <typename Source, typename Target> struct copy_cr<const Source&, Target> { typedef const Target& type; }; template <typename Source, typename Target> struct copy_cr<const Source&&, Target> { typedef const Target&& type; }; template <typename... T, typename F, typename G, size_t... ns, typename Tuple> auto tuple_funcs(F&& reduce, G&& map, const vtmp::integers<ns...>&, Tuple&& tup) -> decltype(reduce(map(std::declval<typename copy_cr<Tuple, T>::type>())...)) { return reduce(map(std::get<ns>(tup))...); } struct no_op_func { template <typename T> T&& operator()(T&& value) const noexcept { return std::forward<T>(value); } }; struct make_tuple_func { template <typename... T> auto operator()(T&&... values) const -> decltype(std::make_tuple(std::declval<T>()...)) { return std::make_tuple(std::forward<T>(values)...); } }; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-braces" template <typename C> struct constructor_func { template <typename... T> C operator()(T&&... values) const { return C{std::forward<T>(values)...}; } }; #pragma GCC diagnostic pop } template <typename F, typename... T> auto tuple_apply(std::tuple<T...>& tup, F&& func) -> decltype(func(std::declval<T&>()...)) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(std::forward<F>(func), xx_impl::no_op_func(), instance, tup); } template <typename F, typename... T> auto tuple_apply(std::tuple<T...>&& tup, F&& func) -> decltype(func(std::declval<T&&>()...)) { vtm
template <typename F, typename... T> auto tuple_apply(const std::tuple<T...>& tup, F&& func) -> decltype(func(std::declval<const T&>()...)) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(std::forward<F>(func), xx_impl::no_op_func(), instance, tup); } template <typename F, typename... T> auto tuple_map(std::tuple<T...>&& tup, F&& func) -> std::tuple<decltype(func(std::declval<T>()))...> { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::make_tuple_func(), std::forward<F>(func), instance, std::move(tup)); } template <typename F, typename... T> auto tuple_map(const std::tuple<T...>& tup, F&& func) -> std::tuple<decltype(func(std::declval<T>()))...> { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::make_tuple_func(), std::forward<F>(func), instance, tup); } template <typename C, typename... T> C tuple_construct(std::tuple<T...>&& tup) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::constructor_func<C>(), xx_impl::no_op_func(), instance, std::move(tup)); } template <typename C, typename... T> C tuple_construct(const std::tuple<T...>& tup) { vtmp::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(xx_impl::constructor_func<C>(), xx_impl::no_op_func(), instance, tup); } } #endif
p::template iota<sizeof...(T)> instance; return xx_impl::tuple_funcs<T...>(std::forward<F>(func), xx_impl::no_op_func(), instance, std::move(tup)); }
function_block-function_prefixed
[ { "content": "struct MIANonlinearFuncType<MIA,typename boost::enable_if<internal::is_DenseMIA<typename std::remove_const<MIA>::type>>::type>{\n\n typedef typename std::remove_const<MIA>::type MIA_type;\n\n typedef DenseMIA<typename internal::data_type<MIA_type>::type,internal::order<MIA_type>::value> type;\n\n};\n\n\n\ntemplate<typename MIA>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 0, "score": 323839.6106859348 }, { "content": "struct MIANonlinearFuncType<MIA,typename boost::enable_if<internal::is_SparseMIA<typename std::remove_const<MIA>::type>>::type>{\n\n typedef typename std::remove_const<MIA>::type MIA_type;\n\n typedef SparseMIA<typename internal::data_type<MIA_type>::type,internal::order<MIA_type>::value> type;\n\n\n\n};\n\n\n\n\n\ntemplate<typename MIA,size_t remaining_indices_size,class Enable = void>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 1, "score": 323839.6106859348 }, { "content": "struct MIAUnaryType<MIA,remaining_indices_size,typename boost::enable_if<internal::is_DenseMIA<typename std::remove_const<MIA>::type>>::type>\n\n{\n\n typedef DenseMIA<typename internal::data_type<typename std::remove_const<MIA>::type>::type,remaining_indices_size> type;\n\n};\n\n\n\ntemplate<typename MIA,size_t remaining_indices_size>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 2, "score": 281351.3440832955 }, { "content": "struct MIAUnaryType<MIA,remaining_indices_size,typename boost::enable_if<internal::is_SparseMIA<typename std::remove_const<MIA>::type>>::type>\n\n{\n\n typedef SparseMIA<typename internal::data_type<typename std::remove_const<MIA>::type>::type,remaining_indices_size> type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs,class Enable = void>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 3, "score": 281351.3440832955 }, { "content": "struct const_argument_qualifier<T,typename boost::enable_if<is_SparseLattice<T> >::type>\n\n{\n\n typedef T type;\n\n};\n\n\n\n\n\ntemplate<class T> struct incomplete;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//should be undefined\n\ntemplate<typename...Args>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 4, "score": 278887.21712371876 }, { "content": "struct const_argument_qualifier<T,typename boost::enable_if<is_SparseMIA<T> >::type>\n\n{\n\n typedef T type;\n\n};\n\n\n\ntemplate<class T>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 5, "score": 278887.21712371876 }, { "content": "struct function_traits<ReturnType(ClassType::*)(Args...) const>\n\n : public function_traits<ReturnType(Args...)>\n\n{\n\n typedef const ClassType& owner_type;\n\n};\n\n\n\ntemplate <typename ClassType, typename ReturnType, typename... Args>\n", "file_path": "src/multi_index_array/kennytm/traits.hpp", "rank": 6, "score": 269426.54908582784 }, { "content": "struct function_traits<ReturnType(ClassType::*)(Args...) const volatile>\n\n : public function_traits<ReturnType(Args...)>\n\n{\n\n typedef const volatile ClassType& owner_type;\n\n};\n\n\n\ntemplate <typename FunctionType>\n", "file_path": "src/multi_index_array/kennytm/traits.hpp", "rank": 7, "score": 263321.38676699623 }, { "content": "struct const_full_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 8, "score": 257028.4293973245 }, { "content": "struct const_full_iterator_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 9, "score": 252732.19332857936 }, { "content": "struct MIAProductReturnType\n\n{\n\n};\n\n\n\n\n\n\n\ntemplate<class L_MIA,class R_MIA, size_t order\n\n>\n", "file_path": "src/multi_index_array/Util.h", "rank": 10, "score": 252275.04780480417 }, { "content": "struct MIASolveReturnType\n\n{\n\n};\n\ntemplate<class L_MIA,class R_MIA, size_t order>\n", "file_path": "src/multi_index_array/Util.h", "rank": 11, "score": 252275.04780480417 }, { "content": "struct MIAMergeReturnType\n\n{\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 12, "score": 252275.04780480417 }, { "content": "struct SparseProductReturnType\n\n{\n\n\n\n typedef typename\n\n boost::enable_if<\n\n boost::mpl::and_<\n\n boost::is_same<\n\n typename internal::index_type<Lhs>::type,\n\n typename internal::index_type<Rhs>::type\n\n >,\n\n boost::is_same<\n\n typename internal::data_type<Lhs>::type,\n\n typename internal::data_type<Rhs>::type\n\n >\n\n >\n\n , SparseLattice<typename internal::data_type<Lhs>::type>\n\n >::type type;\n\n\n\n\n\n};\n\n\n\n//sparse sparse lattice product only enabled if LHS data type is floating point\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 13, "score": 252275.04780480417 }, { "content": "struct DenseProductReturnType\n\n{\n\n\n\n typedef\n\n typename boost::enable_if<\n\n boost::is_same<\n\n typename internal::data_type<Lhs>::type,\n\n typename internal::data_type<Rhs>::type\n\n >\n\n , DenseLattice<typename ScalarPromoteType<Lhs,Rhs>::type >\n\n >::type type;\n\n\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 14, "score": 252275.04780480417 }, { "content": "struct DenseMergeReturnType\n\n{\n\n\n\n typedef DenseLattice<typename ScalarPromoteType<Lhs,Rhs>::type> type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 15, "score": 252275.04780480417 }, { "content": "struct SparseMergeReturnType\n\n{\n\n\n\n typedef SparseLattice<typename ScalarPromoteType<Lhs,Rhs>::type> type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 16, "score": 252275.04780480417 }, { "content": "struct SparseSolveReturnType\n\n{\n\n\n\n typedef\n\n typename boost::enable_if<\n\n boost::is_floating_point<\n\n typename internal::data_type<Lhs>::type\n\n >, //floating point datatypes\n\n DenseLattice<typename internal::data_type<Lhs>::type> //return type\n\n >::type type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 17, "score": 252275.04780480417 }, { "content": "struct DenseSolveReturnType\n\n{\n\n\n\n typedef\n\n typename boost::enable_if<\n\n boost::is_floating_point<\n\n typename internal::data_type<Lhs>::type\n\n > //floating point datatypes\n\n , typename DenseProductReturnType<Lhs,Rhs>::type //return type\n\n >::type type;\n\n};\n\n\n\ntemplate<class L_MIA, class R_MIA, size_t order,class Enable = void>\n", "file_path": "src/multi_index_array/Util.h", "rank": 18, "score": 252275.04780480417 }, { "content": "struct const_data_type_ref;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 19, "score": 252165.54687784042 }, { "content": "struct const_full_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 20, "score": 248598.66529533075 }, { "content": "struct MIANoLatticeProductReturnType\n\n{\n\n};\n\n\n\n\n\n\n\ntemplate<class L_MIA,class R_MIA, size_t order\n\n>\n", "file_path": "src/multi_index_array/Util.h", "rank": 21, "score": 248150.17633149767 }, { "content": "struct const_full_iterator_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 22, "score": 244618.7739006598 }, { "content": "struct MIANonlinearFuncType{};\n\n\n\ntemplate<typename MIA>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 23, "score": 244313.3819946184 }, { "content": "struct MIASolveReturnType\n\n{\n\n};\n\ntemplate<class L_MIA,class R_MIA, size_t order>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 24, "score": 244178.6197462544 }, { "content": "struct SparseSolveReturnType\n\n{\n\n\n\n typedef\n\n typename boost::enable_if<\n\n boost::is_floating_point<\n\n typename internal::data_type<Lhs>::type\n\n >, //floating point datatypes\n\n DenseLattice<typename internal::data_type<Lhs>::type> //return type\n\n >::type type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 25, "score": 244178.6197462544 }, { "content": "struct DenseProductReturnType\n\n{\n\n\n\n typedef\n\n typename boost::enable_if<\n\n boost::is_same<\n\n typename internal::data_type<Lhs>::type,\n\n typename internal::data_type<Rhs>::type\n\n >\n\n , DenseLattice<typename ScalarPromoteType<Lhs,Rhs>::type >\n\n >::type type;\n\n\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 26, "score": 244178.6197462544 }, { "content": "struct DenseMergeReturnType\n\n{\n\n\n\n typedef DenseLattice<typename ScalarPromoteType<Lhs,Rhs>::type> type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 27, "score": 244178.6197462544 }, { "content": "struct SparseMergeReturnType\n\n{\n\n\n\n typedef SparseLattice<typename ScalarPromoteType<Lhs,Rhs>::type> type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 28, "score": 244178.6197462544 }, { "content": "struct SparseProductReturnType\n\n{\n\n\n\n typedef typename\n\n boost::enable_if<\n\n boost::is_same<\n\n typename internal::data_type<Lhs>::type,\n\n typename internal::data_type<Rhs>::type\n\n >,\n\n SparseLattice<typename internal::data_type<Lhs>::type>\n\n >::type type;\n\n\n\n\n\n};\n\n\n\n//sparse sparse lattice product only enabled if LHS data type is floating point\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 29, "score": 244178.6197462544 }, { "content": "struct DenseSolveReturnType\n\n{\n\n\n\n typedef\n\n typename boost::enable_if<\n\n boost::is_floating_point<\n\n typename internal::data_type<Lhs>::type\n\n > //floating point datatypes\n\n , typename DenseProductReturnType<Lhs,Rhs>::type //return type\n\n >::type type;\n\n};\n\n\n\ntemplate<class L_MIA, class R_MIA, size_t order,class Enable = void>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 30, "score": 244178.6197462544 }, { "content": "struct MIAProductReturnType\n\n{\n\n};\n\n\n\n\n\n\n\ntemplate<class L_MIA,class R_MIA, size_t order\n\n>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 31, "score": 244178.6197462544 }, { "content": "struct MIAMergeReturnType\n\n{\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 32, "score": 244178.6197462544 }, { "content": "struct const_data_type_ref;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 33, "score": 244073.1887939478 }, { "content": "struct function_traits<MEM_FN_SYMBOL_XX0SL7G4Z0J<R(C::*)(A...) const>>\n\n : public function_traits<R(const C*, A...)>\n\n{};\n\ntemplate <typename R, typename C, typename... A>\n", "file_path": "src/multi_index_array/kennytm/traits.hpp", "rank": 34, "score": 243971.99731480711 }, { "content": "struct const_full_tuple<MappedSparseLattice<T> >\n\n{\n\n\ttypedef boost::tuple< const T&, const typename index_type<MappedSparseLattice<T> >::type &> type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 35, "score": 242147.28511957283 }, { "content": "struct MIAUnaryType<MIA,remaining_indices_size,typename boost::enable_if<internal::is_DenseMIA<MIA>>::type>\n\n{\n\n typedef DenseMIA<typename internal::data_type<MIA>::type,remaining_indices_size> type;\n\n};\n\n\n\ntemplate<typename MIA,size_t remaining_indices_size>\n", "file_path": "src/multi_index_array/Util.h", "rank": 36, "score": 241602.9097237915 }, { "content": "struct MIAUnaryType<MIA,remaining_indices_size,typename boost::enable_if<internal::is_SparseMIA<MIA>>::type>\n\n{\n\n typedef SparseMIA<typename internal::data_type<MIA>::type,remaining_indices_size> type;\n\n};\n\n\n\ntemplate<typename Lhs, typename Rhs,class Enable = void>\n", "file_path": "src/multi_index_array/Util.h", "rank": 37, "score": 241602.9097237915 }, { "content": "struct MIAMergeReturnType<Lhs,Rhs,\n\n typename\n\n boost::enable_if<\n\n boost::mpl::and_<\n\n internal::is_SparseMIA<Lhs>,\n\n internal::is_SparseMIA<Rhs>\n\n >\n\n >::type\n\n >\n\n{\n\n\n\n typedef SparseMIA<typename ScalarPromoteType<Lhs,Rhs>::type,internal::order<Lhs>::value> type;\n\n};\n\n\n\n\n\n\n\n\n\n\n\n\n\n/*! @} */\n\n/*! @} */\n\n\n\n}\n\n\n\n\n\n#endif // SPARSEUTIL_H\n\n\n", "file_path": "src/multi_index_array/Util.h", "rank": 38, "score": 240433.60249074188 }, { "content": "struct MIANoLatticeProductReturnType\n\n{\n\n};\n\n\n\n\n\n\n\ntemplate<class L_MIA,class R_MIA, size_t order\n\n>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 39, "score": 240351.98629858397 }, { "content": "struct const_full_iterator_tuple<MappedSparseLattice<T> >\n\n{\n\n\ttypedef typename boost::tuple<typename const_data_iterator<MappedSparseLattice<T> >::type, typename const_index_iterator<MappedSparseLattice<T> >::type> type;\n\n\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 40, "score": 238822.1962550933 }, { "content": "struct const_data_type_ref<MappedSparseLattice<T> >\n\n{\n\n typedef const T & type;\n\n};\n\n\n\n\n\n\n\n\n\n} //namespace internal\n\n\n\n/*! @} */\n\n/*! @} */\n\n\n\n/** \\addtogroup lattice Lattice Classes\n\n * @{\n\n*/\n\n//Used to map existing set of data and indices to a sparse lattice. Destruction of data is left to the caller\n\ntemplate<class T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 41, "score": 238314.36193072633 }, { "content": "struct function_traits<MEM_FN_SYMBOL_XX0SL7G4Z0J<R(C::*)(A...) const volatile>>\n\n : public function_traits<R(const volatile C*, A...)>\n\n{};\n\n\n\n#undef MEM_FN_SYMBOL_XX0SL7G4Z0J\n\n#endif\n\n\n\ntemplate <typename T>\n", "file_path": "src/multi_index_array/kennytm/traits.hpp", "rank": 42, "score": 237333.94007315958 }, { "content": "struct MIAMergeReturnType<Lhs,Rhs,\n\n typename\n\n boost::enable_if<\n\n boost::mpl::and_<\n\n internal::is_SparseMIA<typename std::remove_const<Lhs>::type>,\n\n internal::is_SparseMIA<typename std::remove_const<Rhs>::type>\n\n >\n\n >::type\n\n >\n\n{\n\n\n\n typedef SparseMIA<typename ScalarPromoteType<Lhs,Rhs>::type,internal::order<typename std::remove_const<Lhs>::type>::value> type;\n\n};\n\n\n\n\n\n\n\n\n\n\n\n\n\n/*! @} */\n\n/*! @} */\n\n\n\n}\n\n\n\n\n\n#endif // LIBMIAUTIL_H\n\n\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 43, "score": 232917.46844309225 }, { "content": "struct MIASolveReturnType<L_MIA,R_MIA,order,\n\n typename boost::enable_if<\n\n boost::mpl::and_<\n\n internal::is_MIA<L_MIA>,\n\n internal::is_MIA<R_MIA>\n\n >\n\n >::type\n\n>\n\n{\n\n typedef DenseMIA<typename ScalarPromoteType<L_MIA,R_MIA>::type,order> type;\n\n\n\n};\n\n\n\n\n\ntemplate<typename MIA,size_t remaining_indices_size,class Enable = void>\n", "file_path": "src/multi_index_array/Util.h", "rank": 44, "score": 227774.99357132465 }, { "content": "struct MIAProductReturnType<L_MIA,R_MIA,order,\n\n typename boost::enable_if<\n\n boost::mpl::and_<\n\n internal::is_SparseMIA<L_MIA>,\n\n internal::is_SparseMIA<R_MIA>\n\n >\n\n >::type\n\n>\n\n{\n\n typedef SparseMIA<typename ScalarPromoteType<L_MIA,R_MIA>::type,order> type;\n\n\n\n};\n\n\n\n\n\ntemplate<class L_MIA, class R_MIA, size_t order,class Enable = void>\n", "file_path": "src/multi_index_array/Util.h", "rank": 45, "score": 227774.99357132465 }, { "content": "struct MIANoLatticeProductReturnType<L_MIA,R_MIA,order,\n\n typename boost::enable_if<\n\n boost::mpl::or_< //when no lattice mapping is required, dense * sparse is always a sparse\n\n internal::is_SparseMIA<L_MIA>,\n\n internal::is_SparseMIA<R_MIA>\n\n >\n\n >::type\n\n>\n\n{\n\n typedef SparseMIA<typename ScalarPromoteType<L_MIA,R_MIA>::type,order> type;\n\n\n\n};\n\n\n\ntemplate<class L_MIA, class R_MIA, size_t order,class Enable = void>\n", "file_path": "src/multi_index_array/Util.h", "rank": 46, "score": 224338.53444906726 }, { "content": "struct MIASolveReturnType<L_MIA,R_MIA,order,\n\n typename boost::enable_if<\n\n boost::mpl::and_<\n\n internal::is_MIA<typename std::remove_const<L_MIA>::type>,\n\n internal::is_MIA<typename std::remove_const<R_MIA>::type>\n\n >\n\n >::type\n\n>\n\n{\n\n typedef DenseMIA<typename ScalarPromoteType<L_MIA,R_MIA>::type,order> type;\n\n\n\n};\n\n\n\n//the datatype after application of a nonlinear function (copied).\n\ntemplate<typename MIA,class Enable=void>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 47, "score": 221018.9435165713 }, { "content": "struct MIAProductReturnType<L_MIA,R_MIA,order,\n\n typename boost::enable_if<\n\n boost::mpl::and_<\n\n internal::is_DenseMIA<typename std::remove_const<L_MIA>::type>,\n\n internal::is_DenseMIA<typename std::remove_const<R_MIA>::type>\n\n >\n\n >::type\n\n>\n\n{\n\n typedef DenseMIA<typename ScalarPromoteType<L_MIA,R_MIA>::type,order> type;\n\n\n\n};\n\n\n\n\n\ntemplate<class L_MIA, class R_MIA, size_t order,class Enable = void>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 48, "score": 221018.94351657134 }, { "content": "struct MIANoLatticeProductReturnType<L_MIA,R_MIA,order,\n\n typename boost::enable_if<\n\n boost::mpl::or_< //when no lattice mapping is required, dense * sparse is always a sparse\n\n internal::is_SparseMIA<typename std::remove_const<L_MIA>::type>,\n\n internal::is_SparseMIA<typename std::remove_const<R_MIA>::type>\n\n >\n\n >::type\n\n>\n\n{\n\n typedef SparseMIA<typename ScalarPromoteType<L_MIA,R_MIA>::type,order> type;\n\n\n\n};\n\n\n\ntemplate<class L_MIA, class R_MIA, size_t order,class Enable = void>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 49, "score": 217810.3587175753 }, { "content": "struct full_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 50, "score": 213522.21901433886 }, { "content": "struct data_type;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 51, "score": 212932.81985592534 }, { "content": "struct index_type;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 52, "score": 212932.81985592534 }, { "content": "struct function_type;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 53, "score": 212932.81985592534 }, { "content": "struct full_iterator_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 55, "score": 209997.693919999 }, { "content": "struct const_data_iterator;\n\n\n\n//only use for implicit MIAs\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 56, "score": 209830.92527086142 }, { "content": "struct const_storage_iterator;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 57, "score": 209830.92527086142 }, { "content": "struct const_index_iterator;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 58, "score": 209830.92527086142 }, { "content": "struct MIAUnaryType\n\n{\n\n\n\n};\n\n\n\n\n\ntemplate<typename MIA,size_t remaining_indices_size>\n", "file_path": "src/multi_index_array/Util.h", "rank": 59, "score": 209419.8950190916 }, { "content": "struct IndexPromoteType\n\n{\n\n typedef typename boost::numeric::conversion_traits<typename internal::index_type<Lhs>::type,typename internal::index_type<Rhs>::type>::supertype type;\n\n\n\n};\n\n\n\n\n\n\n\n\n\n\n\n//sparse sparse lattice product only enabled if operands share both data and index types\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 60, "score": 209419.8950190916 }, { "content": "struct ScalarPromoteType\n\n{\n\n typedef typename boost::numeric::conversion_traits<typename internal::data_type<Lhs>::type,typename internal::data_type<Rhs>::type>::supertype type;\n\n\n\n};\n\n\n\n//determines the super index type in Lhs and Rhs\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/Util.h", "rank": 61, "score": 209419.8950190916 }, { "content": "struct data_type_ref;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 62, "score": 209419.8950190916 }, { "content": "struct full_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 63, "score": 206609.22685699188 }, { "content": "struct function_type;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 64, "score": 206042.58040625288 }, { "content": "struct index_type;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 65, "score": 206042.58040625294 }, { "content": "struct data_type;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 66, "score": 206042.58040625294 }, { "content": "struct full_iterator_tuple;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 67, "score": 203349.08859397267 }, { "content": "struct const_data_iterator;\n\n\n\n//only use for implicit MIAs\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 68, "score": 203188.63584527664 }, { "content": "struct const_argument_qualifier\n\n{\n\n typedef const T type;\n\n};\n\n\n\n//SparseMIAs and Lattices could be modified (by a re-sort) even when the operation doesn't alter the underlying data. So in C++, even if the underlying data in 'const', the datatype will not be\n\ntemplate<class T>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 69, "score": 203188.63584527664 }, { "content": "struct const_index_iterator;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 70, "score": 203188.63584527664 }, { "content": "struct const_storage_iterator;\n\n\n\ntemplate<typename Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 71, "score": 203188.63584527664 }, { "content": "struct ScalarPromoteType\n\n{\n\n typedef typename boost::numeric::conversion_traits<typename internal::data_type<typename std::remove_const<Lhs>::type>::type,typename internal::data_type<typename std::remove_const<Rhs>::type >::type>::supertype type;\n\n\n\n};\n\n\n\n//determines the super index type in Lhs and Rhs\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 72, "score": 202793.17222525727 }, { "content": "struct IndexPromoteType\n\n{\n\n typedef typename boost::numeric::conversion_traits<typename internal::index_type<Lhs>::type,typename internal::index_type<Rhs>::type>::supertype type;\n\n\n\n};\n\n\n\n\n\n\n\n\n\n\n\n//sparse sparse lattice product only enabled if operands share both data and index types\n\ntemplate<typename Lhs, typename Rhs>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 73, "score": 202793.17222525727 }, { "content": "struct data_type_ref;\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 74, "score": 202793.17222525727 }, { "content": "struct MIAUnaryType\n\n{\n\n\n\n};\n\n\n\n\n\ntemplate<typename MIA,size_t remaining_indices_size>\n", "file_path": "src/multi_index_array/LibMIAUtil.h", "rank": 75, "score": 202793.17222525727 }, { "content": "struct full_tuple<MappedSparseLattice<T> >\n\n{\n\n\ttypedef boost::tuple<T&, typename index_type<MappedSparseLattice<T> >::type &> type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 76, "score": 202766.4981148259 }, { "content": "struct data_type<MappedSparseLattice<T> >\n\n{\n\n typedef T type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 77, "score": 202240.46482575324 }, { "content": "struct index_type<MappedDenseLattice<T> >\n\n{\n\n typedef typename Eigen::Matrix<typename data_type<MappedDenseLattice<T>>::type,Eigen::Dynamic,Eigen::Dynamic>::Index type;\n\n};\n\n\n\n\n\n}\n\n\n\n\n\n/** \\addtogroup lattice Lattice Classes\n\n * @{\n\n */\n\n\n\n//! Lattice class for dense data. Maps already allocated data to a denselattice.\n\n/*!\n\n Supports addition, multiplication, and solution of, possible over-determined, systems of\n\n linear equations. Class does not own internal scalar data - caller is responsible for\n\n freeing scalar data.\n\n\n\n \\tparam T the datatype of individual elements.\n\n*/\n\ntemplate <class T>\n", "file_path": "src/multi_index_array/MappedDenseLattice.h", "rank": 78, "score": 202240.46482575324 }, { "content": "struct index_type<MappedSparseLattice<T> >\n\n{\n\n typedef int64_t type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 79, "score": 202240.46482575324 }, { "content": "struct data_type<MappedDenseLattice<T> >\n\n{\n\n typedef T type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedDenseLattice.h", "rank": 80, "score": 202240.46482575324 }, { "content": "struct full_iterator_tuple<MappedSparseLattice<T> >\n\n{\n\n\ttypedef typename boost::tuple<typename data_iterator<MappedSparseLattice<T> >::type, typename index_iterator<MappedSparseLattice<T> >::type> type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 81, "score": 200083.78539221443 }, { "content": "struct const_index_iterator<MappedSparseLattice<T> >\n\n{\n\n typedef typename index_type<MappedSparseLattice<T> >::type const* type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 82, "score": 199934.63031402283 }, { "content": "struct const_storage_iterator<MappedDenseLattice<T> >\n\n{\n\n typedef typename Data<MappedDenseLattice<T> >::type::const_iterator type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedDenseLattice.h", "rank": 83, "score": 199934.63031402277 }, { "content": "struct const_storage_iterator<MappedSparseLattice<T> >\n\n{\n\n\ttypedef typename boost::zip_iterator<typename const_full_iterator_tuple<MappedSparseLattice<T> >::type > type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 84, "score": 199934.63031402283 }, { "content": "struct const_data_iterator<MappedDenseLattice<T> >\n\n{\n\n typedef const T* type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedDenseLattice.h", "rank": 85, "score": 199934.63031402283 }, { "content": "struct const_data_iterator<MappedSparseLattice<T> >\n\n{\n\n typedef typename data_type<MappedSparseLattice<T> >::type const* type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 86, "score": 199934.63031402283 }, { "content": "struct const_data_type_ref<MIA<Derived> >: public const_data_type_ref<Derived> {};\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/MIA.h", "rank": 87, "score": 199571.27137295163 }, { "content": "struct data_type_ref<MappedSparseLattice<T> >\n\n{\n\n typedef T & type;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/multi_index_array/MappedSparseLattice.h", "rank": 88, "score": 199567.01176186145 }, { "content": "struct function_traits<ReturnType(ClassType::*)(Args...)>\n\n : public function_traits<ReturnType(Args...)>\n\n{\n\n typedef ClassType& owner_type;\n\n};\n\n\n\ntemplate <typename ClassType, typename ReturnType, typename... Args>\n", "file_path": "src/multi_index_array/kennytm/traits.hpp", "rank": 89, "score": 197909.6247130008 }, { "content": "struct is_Lattice: public boost::false_type {};\n\n\n\ntemplate<class T>\n", "file_path": "src/multi_index_array/Util.h", "rank": 90, "score": 197465.28961649127 }, { "content": "struct is_MIA: public boost::false_type {};\n\n\n\ntemplate<class Derived>\n", "file_path": "src/multi_index_array/Util.h", "rank": 91, "score": 197465.28961649127 }, { "content": " }\n\n\n\npublic:\n\n static constexpr array_type make() noexcept\n\n {\n\n return make(utils::vtmp::iota<length>{});\n\n }\n\n};\n\n/*end of taken from KennyTM's answer to this question:\n\nhttp://stackoverflow.com/questions/10830406/copy-an-mplvector-c-to-a-static-array-at-compile-time*/\n\n\n\n\n\n\n\n//template <typename MPLVectorType>\n\n//class to_std_array\n\n//{\n\n//\t\n\n//\tstatic constexpr size_t length = boost::mpl::size<MPLVectorType>::value;\n\n//\ttypedef std::array<int, length> array_type;\n\n//\n", "file_path": "src/multi_index_array/MIA_Expr.h", "rank": 98, "score": 32.49664134979983 }, { "content": "#include \"boost/utility.hpp\"\n\n#include \"boost/type_traits.hpp\"\n\n#include \"boost/optional.hpp\" // for aligned_storage\n\n#include <boost/mpl/if.hpp>\n\n#include <boost/type_traits/is_const.hpp>\n\n#include <memory>\n\n\n\nnamespace iterators\n\n{\n\n namespace detail\n\n {\n\n\n\n template<typename TupleType>\n\n void preincrementTuple(TupleType& lhs)\n\n {\n\n\n\n ++(std::get<0>(lhs));\n\n ++(std::get<1>(lhs));\n\n }\n\n\n", "file_path": "src/multi_index_array/tupleit.hh", "rank": 99, "score": 31.813310773793017 } ]
C++
PROX/FOUNDATION/DIKUCL/DIKUCL/include/dikucl_context_manager.hpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
#ifndef DIKUCL_CONTEXT_MANAGER_HPP #define DIKUCL_CONTEXT_MANAGER_HPP #include <iostream> #include <map> #include <utility> #include <vector> #include <dikucl.hpp> #include <dikucl_device_manager.hpp> namespace dikucl { namespace details { inline void opencl_notify( const char * error_info , const void * , size_t , void * ) { std::cerr << "OpenCL Error Information: " << error_info << std::endl; } } class ContextHandle { public: DeviceHandle device_handle; cl::Context context; ContextHandle( DeviceHandle device_handle, cl::Context context) : device_handle(device_handle), context(context) { } friend bool operator<(const ContextHandle& ch1, const ContextHandle& ch2) { return ch1.device_handle < ch2.device_handle; } friend bool operator>(const ContextHandle& ch1, const ContextHandle& ch2) { return ch1.device_handle > ch2.device_handle; } friend bool operator==(const ContextHandle& ch1, const ContextHandle& ch2) { return ch1.device_handle == ch2.device_handle; } }; class ContextManager { private: std::map< DeviceHandle, ContextHandle > contexts; ContextManager() { } ContextManager(ContextManager const&); void operator=(ContextManager const&); public: static ContextManager& get_instance() { static ContextManager instance; return instance; } ContextHandle* get_context( cl_int *err = NULL, DeviceHandle *device_handle = DeviceManager::get_instance().get_device(), cl_context_properties *properties = NULL, void (CL_CALLBACK * notifyFptr)(const char*, const void*, size_t, void*) = details::opencl_notify, void* data = NULL) { cl_int error = CL_SUCCESS; if(device_handle == NULL) { return NULL; } if(contexts.count(*device_handle) == 0) { std::vector< cl::Device > device_vector(1, device_handle->device); cl::Context context(device_vector, properties, notifyFptr, data, &error); if(error == CL_SUCCESS) { contexts.insert(std::pair< DeviceHandle, ContextHandle >( *device_handle, ContextHandle(*device_handle, context))); } else { if(err != NULL) { *err = error; } return NULL; } } std::map< DeviceHandle, ContextHandle >::iterator it = contexts.find(*device_handle); if(it != contexts.end()) { return &(it->second); } return NULL; } void reset() { contexts.clear(); } }; } #endif
#ifndef DIKUCL_CONTEXT_MANAGER_HPP #define DIKUCL_CONTEXT_MANAGER_HPP #include <iostream> #include <map> #include <utility> #include <vector> #include <dikucl.hpp> #include <dikucl_device_manager.hpp> namespace dikucl { namespace details { inline void opencl_notify( const char * error_info , const void * , size_t , void * ) { std::cerr << "OpenCL Error Information: " << error_info << std::endl; } } class ContextHandle { public: DeviceHandle device_handle; cl::Context context; ContextHandle( DeviceHandle device_handle, cl::Context context) : device_handle(device_handle), context(context) { } friend bool operator<(const ContextHandle& ch1, const ContextHandle& ch2) { return ch1.device_handle < ch2.device_handle; } friend bool operator>(const ContextHandle& ch1, const ContextHandle& ch2) { return ch1.device_handle > ch2.device_handle; } friend bool
ager(ContextManager const&); void operator=(ContextManager const&); public: static ContextManager& get_instance() { static ContextManager instance; return instance; } ContextHandle* get_context( cl_int *err = NULL, DeviceHandle *device_handle = DeviceManager::get_instance().get_device(), cl_context_properties *properties = NULL, void (CL_CALLBACK * notifyFptr)(const char*, const void*, size_t, void*) = details::opencl_notify, void* data = NULL) { cl_int error = CL_SUCCESS; if(device_handle == NULL) { return NULL; } if(contexts.count(*device_handle) == 0) { std::vector< cl::Device > device_vector(1, device_handle->device); cl::Context context(device_vector, properties, notifyFptr, data, &error); if(error == CL_SUCCESS) { contexts.insert(std::pair< DeviceHandle, ContextHandle >( *device_handle, ContextHandle(*device_handle, context))); } else { if(err != NULL) { *err = error; } return NULL; } } std::map< DeviceHandle, ContextHandle >::iterator it = contexts.find(*device_handle); if(it != contexts.end()) { return &(it->second); } return NULL; } void reset() { contexts.clear(); } }; } #endif
operator==(const ContextHandle& ch1, const ContextHandle& ch2) { return ch1.device_handle == ch2.device_handle; } }; class ContextManager { private: std::map< DeviceHandle, ContextHandle > contexts; ContextManager() { } ContextMan
random
[ { "content": "class Context : public detail::Wrapper<cl_context>\n\n{\n\npublic:\n\n Context(\n\n const VECTOR_CLASS<Device>& devices,\n\n cl_context_properties* properties = NULL,\n\n void (CL_CALLBACK * notifyFptr)(\n\n const char *,\n\n const void *,\n\n ::size_t,\n\n void *) = NULL,\n\n void* data = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateContext(\n\n properties, (cl_uint) devices.size(),\n\n (cl_device_id*) &devices.front(),\n\n notifyFptr, data, &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 0, "score": 387858.10070442356 }, { "content": "class Context : public detail::Wrapper<cl_context>\n\n{\n\npublic:\n\n Context(\n\n const VECTOR_CLASS<Device>& devices,\n\n cl_context_properties* properties = NULL,\n\n void (CL_CALLBACK * notifyFptr)(\n\n const char *,\n\n const void *,\n\n ::size_t,\n\n void *) = NULL,\n\n void* data = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateContext(\n\n properties, (cl_uint) devices.size(),\n\n (cl_device_id*) &devices.front(),\n\n notifyFptr, data, &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 1, "score": 381724.4046418542 }, { "content": "class Error : public std::exception\n\n{\n\nprivate:\n\n cl_int err_;\n\n const char * errStr_;\n\npublic:\n\n /*! Create a new CL error exception for a given error code\n\n * and corresponding message.\n\n */\n\n Error(cl_int err, const char * errStr = NULL) : err_(err), errStr_(errStr)\n\n {}\n\n\n\n ~Error() throw() {}\n\n\n\n /*! \\brief Get error string associated with exception\n\n *\n\n * \\return A memory pointer to the error message string.\n\n */\n\n virtual const char * what() const throw ()\n\n {\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 2, "score": 324274.50909063715 }, { "content": "class Error : public std::exception\n\n{\n\nprivate:\n\n cl_int err_;\n\n const char * errStr_;\n\npublic:\n\n /*! Create a new CL error exception for a given error code\n\n * and corresponding message.\n\n */\n\n Error(cl_int err, const char * errStr = NULL) : err_(err), errStr_(errStr)\n\n {}\n\n\n\n ~Error() throw() {}\n\n\n\n /*! \\brief Get error string associated with exception\n\n *\n\n * \\return A memory pointer to the error message string.\n\n */\n\n virtual const char * what() const throw ()\n\n {\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 3, "score": 318608.61176957056 }, { "content": "class Event : public detail::Wrapper<cl_event>\n\n{\n\npublic:\n\n Event() : detail::Wrapper<cl_type>() { }\n\n\n\n Event(const Event& event) : detail::Wrapper<cl_type>(event) { }\n\n\n\n Event& operator = (const Event& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_event_info name, T* param) const\n\n {\n\n return detail::errHandler(\n\n detail::getInfo(&::clGetEventInfo, object_, name, param),\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 4, "score": 305378.6772898347 }, { "content": "class Sampler : public detail::Wrapper<cl_sampler>\n\n{\n\npublic:\n\n Sampler() { }\n\n\n\n Sampler(\n\n const Context& context,\n\n cl_bool normalized_coords,\n\n cl_addressing_mode addressing_mode,\n\n cl_filter_mode filter_mode,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateSampler(\n\n context(), \n\n normalized_coords,\n\n addressing_mode,\n\n filter_mode,\n\n &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 5, "score": 305378.67728983465 }, { "content": "class Program : public detail::Wrapper<cl_program>\n\n{\n\npublic:\n\n typedef VECTOR_CLASS<std::pair<const void*, ::size_t> > Binaries;\n\n typedef VECTOR_CLASS<std::pair<const char*, ::size_t> > Sources;\n\n\n\n Program(\n\n const Context& context,\n\n const Sources& sources,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n\n\n const ::size_t n = (::size_t)sources.size();\n\n ::size_t* lengths = (::size_t*) alloca(n * sizeof(::size_t));\n\n const char** strings = (const char**) alloca(n * sizeof(const char*));\n\n\n\n for (::size_t i = 0; i < n; ++i) {\n\n strings[i] = sources[(int)i].first;\n\n lengths[i] = sources[(int)i].second;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 6, "score": 305378.6772898347 }, { "content": "class Memory : public detail::Wrapper<cl_mem>\n\n{\n\npublic:\n\n Memory() : detail::Wrapper<cl_type>() { }\n\n\n\n Memory(const Memory& memory) : detail::Wrapper<cl_type>(memory) { }\n\n\n\n Memory& operator = (const Memory& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_mem_info name, T* param) const\n\n {\n\n return detail::errHandler(\n\n detail::getInfo(&::clGetMemObjectInfo, object_, name, param),\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 7, "score": 305378.67728983465 }, { "content": "class Kernel : public detail::Wrapper<cl_kernel>\n\n{\n\npublic:\n\n inline Kernel(const Program& program, const char* name, cl_int* err = NULL);\n\n\n\n Kernel() { }\n\n\n\n Kernel(const Kernel& kernel) : detail::Wrapper<cl_type>(kernel) { }\n\n\n\n Kernel& operator = (const Kernel& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_kernel_info name, T* param) const\n\n {\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 8, "score": 305378.67728983465 }, { "content": "class Program : public detail::Wrapper<cl_program>\n\n{\n\npublic:\n\n typedef VECTOR_CLASS<std::pair<const void*, ::size_t> > Binaries;\n\n typedef VECTOR_CLASS<std::pair<const char*, ::size_t> > Sources;\n\n\n\n Program(\n\n const Context& context,\n\n const Sources& sources,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n\n\n const ::size_t n = (::size_t)sources.size();\n\n ::size_t* lengths = (::size_t*) alloca(n * sizeof(::size_t));\n\n const char** strings = (const char**) alloca(n * sizeof(const char*));\n\n\n\n for (::size_t i = 0; i < n; ++i) {\n\n strings[i] = sources[(int)i].first;\n\n lengths[i] = sources[(int)i].second;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 9, "score": 300206.3054724772 }, { "content": "class Kernel : public detail::Wrapper<cl_kernel>\n\n{\n\npublic:\n\n inline Kernel(const Program& program, const char* name, cl_int* err = NULL);\n\n\n\n Kernel() { }\n\n\n\n Kernel(const Kernel& kernel) : detail::Wrapper<cl_type>(kernel) { }\n\n\n\n Kernel& operator = (const Kernel& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_kernel_info name, T* param) const\n\n {\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 10, "score": 300206.3054724773 }, { "content": "class Memory : public detail::Wrapper<cl_mem>\n\n{\n\npublic:\n\n Memory() : detail::Wrapper<cl_type>() { }\n\n\n\n Memory(const Memory& memory) : detail::Wrapper<cl_type>(memory) { }\n\n\n\n Memory& operator = (const Memory& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_mem_info name, T* param) const\n\n {\n\n return detail::errHandler(\n\n detail::getInfo(&::clGetMemObjectInfo, object_, name, param),\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 11, "score": 300206.3054724772 }, { "content": "class Event : public detail::Wrapper<cl_event>\n\n{\n\npublic:\n\n Event() : detail::Wrapper<cl_type>() { }\n\n\n\n Event(const Event& event) : detail::Wrapper<cl_type>(event) { }\n\n\n\n Event& operator = (const Event& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_event_info name, T* param) const\n\n {\n\n return detail::errHandler(\n\n detail::getInfo(&::clGetEventInfo, object_, name, param),\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 12, "score": 300206.3054724773 }, { "content": "class Device : public detail::Wrapper<cl_device_id>\n\n{\n\npublic:\n\n Device(cl_device_id device) { object_ = device; }\n\n\n\n Device() : detail::Wrapper<cl_type>() { }\n\n\n\n Device(const Device& device) : detail::Wrapper<cl_type>(device) { }\n\n\n\n Device& operator = (const Device& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_device_info name, T* param) const\n\n {\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 13, "score": 300206.3054724772 }, { "content": "class Sampler : public detail::Wrapper<cl_sampler>\n\n{\n\npublic:\n\n Sampler() { }\n\n\n\n Sampler(\n\n const Context& context,\n\n cl_bool normalized_coords,\n\n cl_addressing_mode addressing_mode,\n\n cl_filter_mode filter_mode,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateSampler(\n\n context(), \n\n normalized_coords,\n\n addressing_mode,\n\n filter_mode,\n\n &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 14, "score": 300206.3054724772 }, { "content": "class Platform : public detail::Wrapper<cl_platform_id>\n\n{\n\npublic:\n\n static const Platform null();\n\n\n\n Platform(cl_platform_id platform) { object_ = platform; }\n\n\n\n Platform() : detail::Wrapper<cl_type>() { }\n\n\n\n Platform(const Platform& platform) : detail::Wrapper<cl_type>(platform) { }\n\n\n\n Platform& operator = (const Platform& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n cl_int getInfo(cl_platform_info name, STRING_CLASS* param) const\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 15, "score": 300206.3054724773 }, { "content": "class CommandQueue : public detail::Wrapper<cl_command_queue>\n\n{\n\npublic:\n\n CommandQueue(\n\n const Context& context,\n\n const Device& device,\n\n cl_command_queue_properties properties = 0,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateCommandQueue(\n\n context(), device(), properties, &error);\n\n\n\n detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n\n }\n\n\n\n CommandQueue() { }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 16, "score": 295253.51531971496 }, { "content": "class Platform : public detail::Wrapper<cl_platform_id>\n\n{\n\npublic:\n\n static const Platform null();\n\n\n\n Platform(cl_platform_id platform) { object_ = platform; }\n\n\n\n Platform() : detail::Wrapper<cl_type>() { }\n\n\n\n Platform(const Platform& platform) : detail::Wrapper<cl_type>(platform) { }\n\n\n\n Platform& operator = (const Platform& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n cl_int getInfo(cl_platform_info name, STRING_CLASS* param) const\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 17, "score": 295253.51531971496 }, { "content": "class Device : public detail::Wrapper<cl_device_id>\n\n{\n\npublic:\n\n Device(cl_device_id device) { object_ = device; }\n\n\n\n Device() : detail::Wrapper<cl_type>() { }\n\n\n\n Device(const Device& device) : detail::Wrapper<cl_type>(device) { }\n\n\n\n Device& operator = (const Device& rhs)\n\n {\n\n if (this != &rhs) {\n\n detail::Wrapper<cl_type>::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n cl_int getInfo(cl_device_info name, T* param) const\n\n {\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 18, "score": 295253.5153197149 }, { "content": "class Context;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 19, "score": 294005.90657290834 }, { "content": "class vector\n\n{\n\nprivate:\n\n T data_[N];\n\n unsigned int size_;\n\n bool empty_;\n\npublic:\n\n vector() : \n\n size_(-1),\n\n empty_(true)\n\n {}\n\n\n\n ~vector() {}\n\n\n\n unsigned int size(void) const\n\n {\n\n return size_ + 1;\n\n }\n\n\n\n void clear()\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 20, "score": 293876.09684865444 }, { "content": "class CommandQueue : public detail::Wrapper<cl_command_queue>\n\n{\n\npublic:\n\n CommandQueue(\n\n const Context& context,\n\n const Device& device,\n\n cl_command_queue_properties properties = 0,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateCommandQueue(\n\n context(), device(), properties, &error);\n\n\n\n detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n\n }\n\n\n\n CommandQueue() { }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 21, "score": 290506.38224698685 }, { "content": "class Context;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 22, "score": 288835.55283393426 }, { "content": "class vector\n\n{\n\nprivate:\n\n T data_[N];\n\n unsigned int size_;\n\n bool empty_;\n\npublic:\n\n vector() : \n\n size_(-1),\n\n empty_(true)\n\n {}\n\n\n\n ~vector() {}\n\n\n\n unsigned int size(void) const\n\n {\n\n return size_ + 1;\n\n }\n\n\n\n void clear()\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 23, "score": 288709.0272265681 }, { "content": "struct size_t : public cl::vector< ::size_t, N> { };\n\n\n\nnamespace detail {\n\n\n\n// GetInfo help struct\n\ntemplate <typename Functor, typename T>\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 26, "score": 265439.86065528577 }, { "content": " class VectorMonitor\n\n {\n\n protected:\n\n\n\n std::vector< std::vector<float> > m_values;\n\n\n\n public:\n\n\n\n std::vector<float> const & get_values(size_t const & idx) const { return m_values[idx]; }\n\n size_t get_number_of_entries() const { return m_values.size(); }\n\n\n\n public:\n\n\n\n VectorMonitor()\n\n : m_values()\n\n {}\n\n\n\n public:\n\n\n\n void record( std::vector<float> const & values )\n", "file_path": "PROX/FOUNDATION/UTIL/UTIL/include/util_profiling.h", "rank": 27, "score": 264383.02678204956 }, { "content": "class Image : public Memory\n\n{\n\nprotected:\n\n Image() : Memory() { }\n\n\n\n Image(const Image& image) : Memory(image) { }\n\n\n\n Image& operator = (const Image& rhs)\n\n {\n\n if (this != &rhs) {\n\n Memory::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\npublic:\n\n template <typename T>\n\n cl_int getImageInfo(cl_image_info name, T* param) const\n\n {\n\n return detail::errHandler(\n\n detail::getInfo(&::clGetImageInfo, object_, name, param),\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 28, "score": 263598.9905986488 }, { "content": "class Buffer : public Memory\n\n{\n\npublic:\n\n Buffer(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ::size_t size,\n\n void* host_ptr = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateBuffer(context(), flags, size, host_ptr, &error);\n\n\n\n detail::errHandler(error, __CREATE_BUFFER_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n\n }\n\n\n\n Buffer() : Memory() { }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 29, "score": 263598.9905986488 }, { "content": "struct GetInfoHelper<Func, VECTOR_CLASS<char *> >\n\n{\n\n static cl_int\n\n get(Func f, cl_uint name, VECTOR_CLASS<char *>* param)\n\n {\n\n cl_uint err = f(name, param->size() * sizeof(char *), &(*param)[0], NULL);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n \n\n return CL_SUCCESS;\n\n }\n\n};\n\n\n\n// Specialized GetInfoHelper for STRING_CLASS params\n\ntemplate <typename Func>\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 30, "score": 262308.97887320677 }, { "content": "struct size_t : public cl::vector< ::size_t, N> { };\n\n\n\nnamespace detail {\n\n\n\n// GetInfo help struct\n\ntemplate <typename Functor, typename T>\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 31, "score": 261326.91142212023 }, { "content": "class Image3D : public Image\n\n{\n\npublic:\n\n Image3D(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ImageFormat format,\n\n ::size_t width,\n\n ::size_t height,\n\n ::size_t depth,\n\n ::size_t row_pitch = 0,\n\n ::size_t slice_pitch = 0,\n\n void* host_ptr = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateImage3D(\n\n context(), flags, &format, width, height, depth, row_pitch,\n\n slice_pitch, host_ptr, &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 32, "score": 258898.33120302897 }, { "content": "class UserEvent : public Event\n\n{\n\npublic:\n\n UserEvent(\n\n const Context& context,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateUserEvent(\n\n context(),\n\n &error);\n\n\n\n detail::errHandler(error, __CREATE_USER_EVENT_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n\n }\n\n\n\n UserEvent() : Event() { }\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 33, "score": 258898.33120302897 }, { "content": "class BufferGL : public Buffer\n\n{\n\npublic:\n\n BufferGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLuint bufobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLBuffer(\n\n context(),\n\n flags,\n\n bufobj,\n\n &error);\n\n\n\n detail::errHandler(error, __CREATE_GL_BUFFER_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 34, "score": 258898.33120302897 }, { "content": "class Image2D : public Image\n\n{\n\npublic:\n\n Image2D(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ImageFormat format,\n\n ::size_t width,\n\n ::size_t height,\n\n ::size_t row_pitch = 0,\n\n void* host_ptr = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateImage2D(\n\n context(), flags,&format, width, height, row_pitch, host_ptr, &error);\n\n\n\n detail::errHandler(error, __CREATE_IMAGE2D_ERR);\n\n if (err != NULL) {\n\n *err = error;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 35, "score": 258898.33120302897 }, { "content": "class Image : public Memory\n\n{\n\nprotected:\n\n Image() : Memory() { }\n\n\n\n Image(const Image& image) : Memory(image) { }\n\n\n\n Image& operator = (const Image& rhs)\n\n {\n\n if (this != &rhs) {\n\n Memory::operator=(rhs);\n\n }\n\n return *this;\n\n }\n\npublic:\n\n template <typename T>\n\n cl_int getImageInfo(cl_image_info name, T* param) const\n\n {\n\n return detail::errHandler(\n\n detail::getInfo(&::clGetImageInfo, object_, name, param),\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 36, "score": 258898.33120302897 }, { "content": "class Buffer : public Memory\n\n{\n\npublic:\n\n Buffer(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ::size_t size,\n\n void* host_ptr = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateBuffer(context(), flags, size, host_ptr, &error);\n\n\n\n detail::errHandler(error, __CREATE_BUFFER_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n\n }\n\n\n\n Buffer() : Memory() { }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 37, "score": 258898.33120302897 }, { "content": "struct GetInfoHelper<Func, VECTOR_CLASS<char *> >\n\n{\n\n static cl_int\n\n get(Func f, cl_uint name, VECTOR_CLASS<char *>* param)\n\n {\n\n cl_uint err = f(name, param->size() * sizeof(char *), &(*param)[0], NULL);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n \n\n return CL_SUCCESS;\n\n }\n\n};\n\n\n\n// Specialized GetInfoHelper for STRING_CLASS params\n\ntemplate <typename Func>\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 38, "score": 257351.82551655866 }, { "content": "#if defined (USE_DX_INTEROP)\n\nclass BufferD3D10 : public Buffer\n\n{\n\npublic:\n\n typedef CL_API_ENTRY cl_mem (CL_API_CALL *PFN_clCreateFromD3D10BufferKHR)(\n\n cl_context context, cl_mem_flags flags, ID3D10Buffer* buffer,\n\n cl_int* errcode_ret);\n\n\n\n BufferD3D10(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ID3D10Buffer* bufobj,\n\n cl_int * err = NULL)\n\n {\n\n static PFN_clCreateFromD3D10BufferKHR pfn_clCreateFromD3D10BufferKHR = NULL;\n\n __INIT_CL_EXT_FCN_PTR(clCreateFromD3D10BufferKHR);\n\n\n\n cl_int error;\n\n object_ = pfn_clCreateFromD3D10BufferKHR(\n\n context(),\n\n flags,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 39, "score": 254414.665047089 }, { "content": "class Image2DGL : public Image2D\n\n{\n\npublic:\n\n Image2DGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLenum target,\n\n GLint miplevel,\n\n GLuint texobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLTexture2D(\n\n context(),\n\n flags,\n\n target,\n\n miplevel,\n\n texobj,\n\n &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 40, "score": 254408.0669248858 }, { "content": "class Image2D : public Image\n\n{\n\npublic:\n\n Image2D(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ImageFormat format,\n\n ::size_t width,\n\n ::size_t height,\n\n ::size_t row_pitch = 0,\n\n void* host_ptr = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateImage2D(\n\n context(), flags,&format, width, height, row_pitch, host_ptr, &error);\n\n\n\n detail::errHandler(error, __CREATE_IMAGE2D_ERR);\n\n if (err != NULL) {\n\n *err = error;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 41, "score": 254408.0669248858 }, { "content": "class UserEvent : public Event\n\n{\n\npublic:\n\n UserEvent(\n\n const Context& context,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateUserEvent(\n\n context(),\n\n &error);\n\n\n\n detail::errHandler(error, __CREATE_USER_EVENT_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n\n }\n\n\n\n UserEvent() : Event() { }\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 42, "score": 254408.0669248858 }, { "content": "class Image3DGL : public Image3D\n\n{\n\npublic:\n\n Image3DGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLenum target,\n\n GLint miplevel,\n\n GLuint texobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLTexture3D(\n\n context(),\n\n flags,\n\n target,\n\n miplevel,\n\n texobj,\n\n &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 43, "score": 254408.0669248858 }, { "content": "class BufferRenderGL : public Buffer\n\n{\n\npublic:\n\n BufferRenderGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLuint bufobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLRenderbuffer(\n\n context(),\n\n flags,\n\n bufobj,\n\n &error);\n\n\n\n detail::errHandler(error, __CREATE_GL_BUFFER_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 44, "score": 254408.0669248858 }, { "content": "class Image3D : public Image\n\n{\n\npublic:\n\n Image3D(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ImageFormat format,\n\n ::size_t width,\n\n ::size_t height,\n\n ::size_t depth,\n\n ::size_t row_pitch = 0,\n\n ::size_t slice_pitch = 0,\n\n void* host_ptr = NULL,\n\n cl_int* err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateImage3D(\n\n context(), flags, &format, width, height, depth, row_pitch,\n\n slice_pitch, host_ptr, &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 45, "score": 254408.0669248858 }, { "content": "class BufferGL : public Buffer\n\n{\n\npublic:\n\n BufferGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLuint bufobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLBuffer(\n\n context(),\n\n flags,\n\n bufobj,\n\n &error);\n\n\n\n detail::errHandler(error, __CREATE_GL_BUFFER_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 46, "score": 254408.0669248858 }, { "content": "#if defined (USE_DX_INTEROP)\n\nclass BufferD3D10 : public Buffer\n\n{\n\npublic:\n\n typedef CL_API_ENTRY cl_mem (CL_API_CALL *PFN_clCreateFromD3D10BufferKHR)(\n\n cl_context context, cl_mem_flags flags, ID3D10Buffer* buffer,\n\n cl_int* errcode_ret);\n\n\n\n BufferD3D10(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n ID3D10Buffer* bufobj,\n\n cl_int * err = NULL)\n\n {\n\n static PFN_clCreateFromD3D10BufferKHR pfn_clCreateFromD3D10BufferKHR = NULL;\n\n __INIT_CL_EXT_FCN_PTR(clCreateFromD3D10BufferKHR);\n\n\n\n cl_int error;\n\n object_ = pfn_clCreateFromD3D10BufferKHR(\n\n context(),\n\n flags,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 47, "score": 250120.67268783215 }, { "content": "class BufferRenderGL : public Buffer\n\n{\n\npublic:\n\n BufferRenderGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLuint bufobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLRenderbuffer(\n\n context(),\n\n flags,\n\n bufobj,\n\n &error);\n\n\n\n detail::errHandler(error, __CREATE_GL_BUFFER_ERR);\n\n if (err != NULL) {\n\n *err = error;\n\n }\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 48, "score": 250114.07456562895 }, { "content": "class Image3DGL : public Image3D\n\n{\n\npublic:\n\n Image3DGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLenum target,\n\n GLint miplevel,\n\n GLuint texobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLTexture3D(\n\n context(),\n\n flags,\n\n target,\n\n miplevel,\n\n texobj,\n\n &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 49, "score": 250114.074565629 }, { "content": "class Image2DGL : public Image2D\n\n{\n\npublic:\n\n Image2DGL(\n\n const Context& context,\n\n cl_mem_flags flags,\n\n GLenum target,\n\n GLint miplevel,\n\n GLuint texobj,\n\n cl_int * err = NULL)\n\n {\n\n cl_int error;\n\n object_ = ::clCreateFromGLTexture2D(\n\n context(),\n\n flags,\n\n target,\n\n miplevel,\n\n texobj,\n\n &error);\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 50, "score": 250114.074565629 }, { "content": " class Vector \n\n : public detail::Container<1,N,T>\n\n {\n\n public:\n\n \n\n typedef detail::Container<1, N, T> \t\t\t base_class_type;\n\n typedef typename T::real_type \t\t real_type;\n\n typedef typename T::op_type \t\t op_type;\n\n typedef ValueTraits<real_type>\t\t value_traits;\n\n \n\n public:\n\n \n\n Vector () \n\n\t\t: base_class_type() \n\n\t\t{}\n\n \n\n ~Vector () {} \n\n \n\n Vector ( Vector const & v ) \n\n\t\t: base_class_type(v)\n", "file_path": "PROX/FOUNDATION/TINY/TINY/include/tiny_vector.h", "rank": 51, "score": 245708.0430684976 }, { "content": " class Vector\n\n {\n\n protected:\n\n \n\n typedef std::vector<B> data_container_type;\n\n \n\n public:\n\n \n\n typedef Vector<B> vector_type;\n\n typedef B block_type;\n\n typedef block_type& reference;\n\n typedef block_type const& const_reference;\n\n typedef block_type* pointer;\n\n typedef block_type const* const_pointer;\n\n typedef IndexIterator<false, vector_type> iterator;\n\n typedef IndexIterator<true, vector_type> const_iterator;\n\n \n\n typedef detail::VectorAccessor<vector_type> accessor;\n\n \n\n private:\n", "file_path": "PROX/FOUNDATION/SPARSE/SPARSE/include/sparse_vector.h", "rank": 52, "score": 245708.0430684976 }, { "content": " class A6, class A7, class A8>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6, \n\n const A7& a7, \n\n const A8& a8,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n\n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 53, "score": 217361.5061686384 }, { "content": " class A11, class A12, class A13>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11, \n\n const A12& a12, \n\n const A13& a13,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n\n \n\n kernel_.setArg(0,a1);\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 54, "score": 217361.5061686384 }, { "content": " class A5, class A6, class A7>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6, \n\n const A7& a7,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n\n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 55, "score": 217361.5061686384 }, { "content": " class A11, class A12, class A13>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11, \n\n const A12& a12, \n\n const A13& a13,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 56, "score": 217361.5061686384 }, { "content": " class A11, class A12, class A13, class A14>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 57, "score": 216985.25866485317 }, { "content": " class A6, class A7, class A8, class A9>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6, \n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 58, "score": 216985.25866485317 }, { "content": " class A11, class A12, class A13, class A14>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n\n \n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 59, "score": 216985.25866485317 }, { "content": " class Profiling\n\n {\n\n public:\n\n\n", "file_path": "PROX/FOUNDATION/UTIL/UTIL/include/util_profiling.h", "rank": 60, "score": 215811.19660952318 }, { "content": " class Log\n\n {\n\n public:\n\n\n\n static std::string tab() { return \"\\t\"; };\n\n static std::string newline() { return \"\\n\"; };\n\n\n\n void flush()\n\n {\n\n if(LogInfo::on())\n\n {\n\n if(LogInfo::console())\n\n {\n\n std::cout.flush();\n\n }\n\n else\n\n {\n\n LogInfo::stream().flush();\n\n }\n\n }\n", "file_path": "PROX/FOUNDATION/UTIL/UTIL/include/util_log.h", "rank": 61, "score": 215811.19660952318 }, { "content": " class Timer\n\n {\n\n protected:\n\n\n\n std::chrono::time_point<std::chrono::high_resolution_clock> m_start;\n\n std::chrono::time_point<std::chrono::high_resolution_clock> m_end;\n\n\n\n bool m_start_called;\n\n\n\n public:\n\n\n\n Timer()\n\n : m_start_called(false)\n\n {}\n\n\n\n public:\n\n\n\n void start()\n\n {\n\n m_end = m_start = std::chrono::high_resolution_clock::now();\n", "file_path": "PROX/FOUNDATION/UTIL/UTIL/include/util_timer.h", "rank": 62, "score": 215811.19660952318 }, { "content": " class Monitor\n\n {\n\n protected:\n\n\n\n float m_total;\n\n float m_min;\n\n float m_max;\n\n float m_avg;\n\n size_t m_N;\n\n std::vector<float> m_values;\n\n\n\n public:\n\n\n\n float get_avg() const { return m_avg; }\n\n float get_min() const { return m_min; }\n\n float get_max() const { return m_max; }\n\n float get_total() const { return m_total; }\n\n std::vector<float> const & get_values() const { return m_values; }\n\n size_t get_number_of_entries() const { return m_N; }\n\n\n", "file_path": "PROX/FOUNDATION/UTIL/UTIL/include/util_profiling.h", "rank": 63, "score": 215811.19660952318 }, { "content": " class A11, class A12, class A13, class A14, class A15>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5,\n\n const A6& a6, \n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14, \n\n const A15& a15,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 64, "score": 215591.71173993897 }, { "content": " class A6, class A7, class A8, class A9, class A10,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 65, "score": 215591.711739939 }, { "content": " class A6, class A7, class A8, class A9, class A10>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 66, "score": 215591.71173993897 }, { "content": " class A11, class A12, class A13, class A14, class A15>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14, \n\n const A15& a15,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n};\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 67, "score": 215591.71173993897 }, { "content": " class A6, class A7, class A8, class A9, class A10,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 68, "score": 215591.711739939 }, { "content": " class A11, class A12>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11, \n\n const A12& a12,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 69, "score": 215201.88854983446 }, { "content": " class A11, class A12>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11, \n\n const A12& a12,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n\n\n\n kernel_.setArg(0,a1);\n\n kernel_.setArg(1,a2);\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/CL/cl.hpp", "rank": 70, "score": 215201.88854983446 }, { "content": " class A11, class A12, class A13>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11, \n\n const A12& a12, \n\n const A13& a13,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n\n \n\n kernel_.setArg(0,a1);\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 71, "score": 214469.76054091204 }, { "content": " class A6, class A7, class A8>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6, \n\n const A7& a7, \n\n const A8& a8,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n\n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 72, "score": 214469.76054091204 }, { "content": " class A11, class A12, class A13>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11, \n\n const A12& a12, \n\n const A13& a13,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 73, "score": 214469.76054091204 }, { "content": " class A5, class A6, class A7>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6, \n\n const A7& a7,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n\n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 74, "score": 214469.76054091204 }, { "content": " class A11, class A12, class A13, class A14>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 75, "score": 214398.23717715777 }, { "content": " class A11, class A12, class A13, class A14>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n\n \n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 76, "score": 214398.23717715777 }, { "content": " class A6, class A7, class A8, class A9>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6, \n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 77, "score": 214398.23717715777 }, { "content": " class A11, class A12, class A13, class A14, class A15>\n\nEvent KernelFunctor::operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5,\n\n const A6& a6, \n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14, \n\n const A15& a15,\n\n const VECTOR_CLASS<Event>* events)\n\n{\n\n Event event;\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 78, "score": 213247.8198358634 }, { "content": " class A11, class A12, class A13, class A14, class A15>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10, \n\n const A11& a11,\n\n const A12& a12, \n\n const A13& a13, \n\n const A14& a14, \n\n const A15& a15,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n};\n\n\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 79, "score": 213247.8198358634 }, { "content": " class A6, class A7, class A8, class A9, class A10,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 80, "score": 213247.8198358634 }, { "content": " class A6, class A7, class A8, class A9, class A10,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 81, "score": 213247.8198358634 }, { "content": " class A6, class A7, class A8, class A9, class A10>\n\n inline Event operator()(\n\n const A1& a1, \n\n const A2& a2, \n\n const A3& a3, \n\n const A4& a4, \n\n const A5& a5, \n\n const A6& a6,\n\n const A7& a7, \n\n const A8& a8, \n\n const A9& a9, \n\n const A10& a10,\n\n const VECTOR_CLASS<Event>* events = NULL);\n\n \n\n template<class A1, class A2, class A3, class A4, class A5,\n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/OpenCL/cl.hpp", "rank": 82, "score": 213247.8198358634 }, { "content": " class LogInfo\n\n {\n\n public:\n\n\n\n static bool & console()\n\n {\n\n static bool value = true;\n\n return value;\n\n }\n\n\n\n static bool & on()\n\n {\n\n static bool value = true;\n\n return value;\n\n }\n\n\n\n static std::ofstream & stream()\n\n {\n\n static std::ofstream value;\n\n return value;\n", "file_path": "PROX/FOUNDATION/UTIL/UTIL/include/util_log.h", "rank": 83, "score": 212044.78899783062 }, { "content": "#ifndef DIKUCL_COMMAND_QUEUE_MANAGER_HPP\n\n#define DIKUCL_COMMAND_QUEUE_MANAGER_HPP\n\n\n\n#include <map>\n\n#include <utility>\n\n#include <vector>\n\n\n\n#include <dikucl.hpp>\n\n#include <dikucl_context_manager.hpp>\n\n\n\nnamespace dikucl {\n\n \n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/dikucl_command_queue_manager.hpp", "rank": 86, "score": 38.971246334672514 }, { "content": "#ifndef DIKUCL_KERNEL_MANAGER_HPP\n\n#define DIKUCL_KERNEL_MANAGER_HPP\n\n\n\n#include <fstream>\n\n#include <iostream>\n\n#include <map>\n\n#include <set>\n\n#include <sstream>\n\n#include <string>\n\n#include <utility>\n\n\n\n#include <dikucl.hpp>\n\n#include <dikucl_context_manager.hpp>\n\n\n\nnamespace dikucl {\n\n \n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/dikucl_kernel_manager.hpp", "rank": 87, "score": 37.82193333580645 }, { "content": "#ifndef DIKUCL_DEVICE_MANAGER_HPP\n\n#define DIKUCL_DEVICE_MANAGER_HPP\n\n\n\n#include <map>\n\n#include <utility>\n\n#include <vector>\n\n\n\n#include <dikucl.hpp>\n\n#include <dikucl_platform_manager.hpp>\n\n#include <util_get_environment.h>\n\n\n\nnamespace dikucl {\n\n \n", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/dikucl_device_manager.hpp", "rank": 88, "score": 35.389937581548 }, { "content": " traits::matrix_storage_const (a),\n\n traits::vector_storage_const (i),\n\n#endif \n\n traits::matrix_storage (b),\n\n traits::leading_dimension (b),\n\n &info);\n\n return info;\n\n }\n\n\n\n\n\n namespace detail {\n\n inline\n\n void sptri (char const uplo, integer_t const n,\n\n float* ap, integer_t* ipiv, float* work, integer_t* info)\n\n {\n\n LAPACK_SSPTRI (&uplo, &n, ap, ipiv, work, info);\n\n }\n\n\n\n inline\n\n void sptri (char const uplo, integer_t const n,\n", "file_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/spsv.hpp", "rank": 89, "score": 33.76631141167289 }, { "content": "#ifndef SPARSE_COMPRESSED_VECTOR_ITERATOR_H\n\n#define SPARSE_COMPRESSED_VECTOR_ITERATOR_H\n\n\n\n#include <sparse_if_then_else.h> \n\n#include <sparse_property_maps.h> // for col and row functions\n\n\n\n#include <iterator> // for iterator_traits\n\n\n\nnamespace sparse\n\n{\n\n /**\n\n * Compressed Vector Row Iterator Class.\n\n *\n\n * @tparam is_const Compile time boolean indicating it the iterator should const or non-const.\n\n * @tparam V The vector type the iterator should work on.\n\n */\n\n template <bool is_const, typename V>\n", "file_path": "PROX/FOUNDATION/SPARSE/SPARSE/include/sparse_compressed_vector_iterator.h", "rank": 90, "score": 32.97308480424404 }, { "content": " this->m_row_ptrs.resize(max_rows, max_rows); // TODO: Update old values\n\n }\n\n \n\n inline void reserve(size_t const nnz, size_t const max_rows)\n\n {\n\n this->resize(nnz, max_rows);\n\n }\n\n \n\n inline bool row_exists(size_t row_idx) const\n\n {\n\n return (row_idx < m_row_ptrs.size());\n\n }\n\n \n\n };\n\n \n\n }//end of namespace detail\n\n \n\n \n\n /** @class CompressedVector\n\n * Compressed Block Vector Class.\n", "file_path": "PROX/FOUNDATION/SPARSE/SPARSE/include/sparse_compressed_vector.h", "rank": 92, "score": 31.153360812287907 }, { "content": "#include <content_io_base.h>\n\n#include <content_channels.h>\n\n\n\n#include <tinyxml.h>\n\n\n\n#include <cassert>\n\n#include <stdexcept> // needed for std::runtime_error\n\n#include <sstream>\n\n#include <cmath> // needed for std::sqrt\n\n\n\nnamespace content\n\n{\n\n namespace details\n\n {\n\n /**\n\n * The Data Cache Class.\n\n * Used to pass information on when parsing XML document.\n\n */\n", "file_path": "PROX/SIMULATION/CONTENT/CONTENT/src/content_channels_reader.cpp", "rank": 93, "score": 30.6789359722858 }, { "content": " namespace detail {\n\n inline\n\n void gees (char const jobvs, char const sort, logical_t* select, integer_t const n,\n\n float* a, integer_t const lda, integer_t& sdim, traits::complex_f* w,\n\n float* vs, integer_t const ldvs, float* work, integer_t const lwork,\n\n bool* bwork, integer_t& info)\n\n {\n\n traits::detail::array<float> wr(n);\n\n traits::detail::array<float> wi(n);\n\n LAPACK_SGEES (&jobvs, &sort, select, &n, a, &lda, &sdim,\n\n traits::vector_storage(wr), traits::vector_storage(wi),\n\n vs, &ldvs, work, &lwork, bwork, &info);\n\n traits::detail::interlace(traits::vector_storage(wr),\n\n traits::vector_storage(wr)+n,\n\n traits::vector_storage(wi),\n\n w);\n\n }\n\n\n\n\n\n inline\n", "file_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gees.hpp", "rank": 94, "score": 30.296675426672945 }, { "content": " *err = error;\n\n }\n\n return NULL;\n\n }\n\n }\n\n \n\n std::map< ContextHandle, CommandQueueHandle >::iterator it = command_queues.find(*context_handle);\n\n if(it != command_queues.end()) {\n\n return &(it->second);\n\n }\n\n return NULL;\n\n }\n\n \n\n void reset() {\n\n command_queues.clear();\n\n }\n\n\n\n };\n\n\n\n} // namespace dikucl\n\n\n\n#endif // DIKUCL_COMMAND_QUEUE_MANAGER_HPP", "file_path": "PROX/FOUNDATION/DIKUCL/DIKUCL/include/dikucl_command_queue_manager.hpp", "rank": 95, "score": 30.186986251356846 }, { "content": "#ifndef GEOMETRY_GAUSS_MAP_OF_CONVEX_POLYHEDRA_H\n\n#define GEOMETRY_GAUSS_MAP_OF_CONVEX_POLYHEDRA_H\n\n\n\n#include <types/geometry_tetrahedron.h>\n\n\n\n#include <tiny.h>\n\n\n\n#include <cmath>\n\n#include <vector>\n\n#include <map>\n\n#include <cassert>\n\n\n\nnamespace geometry\n\n{\n\n namespace details\n\n {\n\n\n", "file_path": "PROX/FOUNDATION/GEOMETRY/GEOMETRY/include/types/geometry_gauss_map_of_convex_polyhedra.h", "rank": 96, "score": 29.68567292093688 }, { "content": "#include <min_map/big_compute_index_reordering.h>\n\n\n\n#include <big_return_codes.h>\n\n\n\n#include <cassert>\n\n\n\nnamespace big\n\n{\n\n void compute_index_reordering(\n\n ublas::vector<size_t> const & bitmask\n\n , ublas::vector<size_t> & old2new\n\n , ublas::vector<size_t> & new2old\n\n )\n\n {\n\n size_t const n = bitmask.size();\n\n \n\n old2new.resize(n);\n\n new2old.resize(n);\n\n \n\n size_t r = 0u;\n", "file_path": "PROX/FOUNDATION/BIG/BIG/src/big_compute_index_reordering.cpp", "rank": 97, "score": 29.684828246820246 }, { "content": "#include <min_map/big_compute_index_sets.h>\n\n\n\n#include <big_return_codes.h>\n\n\n\n#include <cassert>\n\n\n\nnamespace big\n\n{\n\n \n\n template < typename T>\n\n void compute_index_sets(\n\n ublas::vector<T> const & y\n\n , ublas::vector<T> const & x\n\n , ublas::vector<size_t> & bitmask\n\n , size_t & cnt_active\n\n , size_t & cnt_inactive\n\n )\n\n {\n\n size_t const n = x.size();\n\n \n", "file_path": "PROX/FOUNDATION/BIG/BIG/src/big_compute_index_sets.cpp", "rank": 98, "score": 29.44576589794275 }, { "content": "#include <boost/numeric/bindings/atlas/cblas1_overloads.hpp>\n\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_TYPE_CHECK\n\n# include <boost/type_traits/same_traits.hpp>\n\n# include <boost/static_assert.hpp>\n\n#endif \n\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n\n\n namespace atlas {\n\n\n\n // x_i <- alpha for all i\n\n template <typename T, typename Vct> \n\n inline \n\n void set (T const& alpha, Vct& x) {\n\n detail::set (traits::vector_size (x), alpha, \n\n traits::vector_storage (x), traits::vector_stride (x)); \n\n }\n\n\n\n // y <- x\n", "file_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/atlas/cblas1.hpp", "rank": 99, "score": 29.014618978998026 } ]
C++
vislib/src/sys/MemoryFile.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
#include "vislib/sys/MemoryFile.h" using namespace vislib::sys; MemoryFile::MemoryFile(void) : File(), accessMode(READ_ONLY), buffer(NULL), bufferLen(0), pos(0), storage(NULL) {} MemoryFile::~MemoryFile(void) { this->Close(); } void MemoryFile::Close(void) { this->accessMode = READ_ONLY; this->buffer = NULL; this->bufferLen = 0; this->pos = 0; this->storage = NULL; } void MemoryFile::Flush(void) { } File::FileSize MemoryFile::GetSize(void) const { return (this->storage != NULL) ? static_cast<File::FileSize>(this->storage->GetSize()) : ((this->buffer != NULL) ? this->bufferLen : 0); } bool MemoryFile::IsOpen(void) const { return (this->storage != NULL) || (this->buffer != NULL); } bool MemoryFile::Open(void* buffer, SIZE_T bufferLength, File::AccessMode accessMode) { if (buffer == NULL) return false; this->Close(); this->accessMode = accessMode; this->buffer = static_cast<unsigned char*>(buffer); this->bufferLen = bufferLength; this->pos = 0; this->storage = NULL; return true; } bool MemoryFile::Open(vislib::RawStorage& storage, File::AccessMode accessMode) { this->Close(); this->accessMode = accessMode; this->buffer = NULL; this->bufferLen = 0; this->pos = 0; this->storage = &storage; return true; } bool MemoryFile::Open(const char* filename, const File::AccessMode accessMode, const File::ShareMode shareMode, const File::CreationMode creationMode) { return false; } bool MemoryFile::Open(const wchar_t* filename, const File::AccessMode accessMode, const File::ShareMode shareMode, const File::CreationMode creationMode) { return false; } File::FileSize MemoryFile::Read(void* outBuf, const File::FileSize bufSize) { FileSize s = bufSize; FileSize l = this->GetSize(); if (this->accessMode == WRITE_ONLY) return 0; if (this->pos > l) { this->pos = l; } if (this->pos + s > l) { s = l - this->pos; } if (!this->IsOpen()) { s = 0; } if (s > 0) { ::memcpy(outBuf, (this->storage != NULL) ? this->storage->At(static_cast<SIZE_T>(this->pos)) : (this->buffer + this->pos), static_cast<SIZE_T>(s)); this->pos += s; } return s; } File::FileSize MemoryFile::Seek(const File::FileOffset offset, const File::SeekStartPoint from) { FileSize np = this->pos; switch (from) { case BEGIN: if (offset >= 0) { np = offset; } break; case CURRENT: if (offset < 0) { if (static_cast<FileSize>(-offset) > this->pos) { np = 0; } else { np = this->pos + offset; } } else { np = this->pos + offset; } break; case END: np = this->GetSize(); if (offset < 0) { if (static_cast<FileSize>(-offset) > np) { np = 0; } else { np += offset; } } break; } if (np > this->GetSize()) { np = this->GetSize(); } this->pos = np; return this->pos; } File::FileSize MemoryFile::Tell(void) const { return this->pos; } File::FileSize MemoryFile::Write(const void* buf, const File::FileSize bufSize) { FileSize s = 0; if (this->accessMode == READ_ONLY) return 0; if (this->buffer != NULL) { s = bufSize; if (this->pos + s > this->bufferLen) { if (this->pos > this->bufferLen) { this->pos = this->bufferLen; } s = this->bufferLen - this->pos; } ::memcpy(this->buffer + this->pos, buf, static_cast<SIZE_T>(s)); this->pos += s; } else if (this->storage != NULL) { s = bufSize; if (this->storage->GetSize() < this->pos + s) { this->storage->AssertSize(static_cast<SIZE_T>(this->pos + s), true); if (this->pos > this->storage->GetSize()) { this->pos = this->storage->GetSize(); } s = this->storage->GetSize() - this->pos; } ::memcpy(this->storage->At(static_cast<SIZE_T>(this->pos)), buf, static_cast<SIZE_T>(s)); this->pos += s; } else { s = 0; } return s; }
#include "vislib/sys/MemoryFile.h" using namespace vislib::sys; MemoryFile::MemoryFile(void) : File(), accessMode(READ_ONLY), buffer(NULL), bufferLen(0), pos(0), storage(NULL) {} MemoryFile::~MemoryFile(void) { this->Close(); } void MemoryFile::Close(void) { this->accessMode = READ_ONLY; this->buffer = NULL; this->bufferLen = 0; this->pos = 0; this->storage = NULL; } void MemoryFile::Flush(void) { } File::FileSize MemoryFile::GetSize(void) const { return (this->storage != NULL) ? static_cast<File::FileSize>(this->storage->GetSize()) : ((this->buffer != NULL) ? this->bufferLen : 0); } bool MemoryFile::IsOpen(void) const { return (this->storage != NULL) || (this->buffer != NULL); } bool MemoryFile::Open(void* buffer, SIZE_T bufferLength, File::AccessMode accessMode) { if (buffer == NULL) return false; this->Close(); this->accessMode = accessMode; this->buffer = static_cast<unsigned char*>(buffer); this->bufferLen = bufferLength; this->pos = 0; this->storage = NULL; return true; } bool MemoryFile::Open(vislib::RawStorage& storage, File::AccessMode accessMode) { this->Close(); this->accessMode = accessMode; this->buffer = NULL; this->bufferLen = 0; this->pos = 0; this->storage = &storage; return true; } bool MemoryFile::Open(const char* filename, const File::AccessMode accessMode, const File::ShareMode shareMode, const File::CreationMode creationMode) { return false; } bool MemoryFile::Open(const wchar_t* filename, const File::AccessMode accessMode, const File::ShareMode shareMode, const File::CreationMode creationMode) { return false; } File::FileSize MemoryFile::Read(void* outBuf, const File::FileSize bufSize) { FileSize s = bufSize; FileSize l = this->GetSize(); if (this->accessMode == WRITE_ONLY) return 0; if (this->pos > l) { this->pos = l; } if (this->pos + s > l) { s = l - this->pos; } if (!this->IsOpen()) { s = 0; } if (s > 0) {
; this->pos += s; } return s; } File::FileSize MemoryFile::Seek(const File::FileOffset offset, const File::SeekStartPoint from) { FileSize np = this->pos; switch (from) { case BEGIN: if (offset >= 0) { np = offset; } break; case CURRENT: if (offset < 0) { if (static_cast<FileSize>(-offset) > this->pos) { np = 0; } else { np = this->pos + offset; } } else { np = this->pos + offset; } break; case END: np = this->GetSize(); if (offset < 0) { if (static_cast<FileSize>(-offset) > np) { np = 0; } else { np += offset; } } break; } if (np > this->GetSize()) { np = this->GetSize(); } this->pos = np; return this->pos; } File::FileSize MemoryFile::Tell(void) const { return this->pos; } File::FileSize MemoryFile::Write(const void* buf, const File::FileSize bufSize) { FileSize s = 0; if (this->accessMode == READ_ONLY) return 0; if (this->buffer != NULL) { s = bufSize; if (this->pos + s > this->bufferLen) { if (this->pos > this->bufferLen) { this->pos = this->bufferLen; } s = this->bufferLen - this->pos; } ::memcpy(this->buffer + this->pos, buf, static_cast<SIZE_T>(s)); this->pos += s; } else if (this->storage != NULL) { s = bufSize; if (this->storage->GetSize() < this->pos + s) { this->storage->AssertSize(static_cast<SIZE_T>(this->pos + s), true); if (this->pos > this->storage->GetSize()) { this->pos = this->storage->GetSize(); } s = this->storage->GetSize() - this->pos; } ::memcpy(this->storage->At(static_cast<SIZE_T>(this->pos)), buf, static_cast<SIZE_T>(s)); this->pos += s; } else { s = 0; } return s; }
::memcpy(outBuf, (this->storage != NULL) ? this->storage->At(static_cast<SIZE_T>(this->pos)) : (this->buffer + this->pos), static_cast<SIZE_T>(s))
call_expression
[ { "content": "class BufferedFile : public File {\n\npublic:\n\n /**\n\n * Answers the default size used when creating new BufferedFile objects\n\n *\n\n * @return size in bytes used when creating new buffers\n\n */\n\n inline static File::FileSize GetDefaultBufferSize(void) {\n\n return BufferedFile::defaultBufferSize;\n\n }\n\n\n\n /**\n\n * Sets the default size used when creating new BufferedFile objects\n\n *\n\n * @param newSize The new size in bytes used when creating new buffers\n\n */\n\n inline static void SetDefaultBufferSize(File::FileSize newSize) {\n\n BufferedFile::defaultBufferSize = newSize;\n\n }\n\n\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 0, "score": 315607.32132099516 }, { "content": "class ASCIIFileBuffer {\n\npublic:\n\n /** Possible parsing elements */\n\n enum ParsingElement { PARSING_DEFAULT, PARSING_LINES, PARSING_WORDS };\n\n\n\n /**\n\n * Class storing all information about a single line\n\n */\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 1, "score": 262512.6534483937 }, { "content": "class File {\n\n\n\npublic:\n\n /** This type is used for offsets when seeking in files. */\n\n typedef INT64 FileOffset;\n\n\n\n /** This type is used for size information of files. */\n\n typedef UINT64 FileSize;\n\n\n\n /** Possible values for the access mode. */\n\n enum AccessMode { READ_WRITE = 1, READ_ONLY, WRITE_ONLY };\n\n\n\n /** Possible values for the share mode. */\n\n enum ShareMode { SHARE_EXCLUSIVE = 1, SHARE_READ, SHARE_WRITE, SHARE_READWRITE };\n\n\n\n /** Possible values for the CreationMode. */\n\n enum CreationMode {\n\n CREATE_ONLY = 0, // Fails, if file already exists.\n\n CREATE_OVERWRITE, // Overwrites existing files.\n\n OPEN_ONLY, // Fails, if file does not exist.\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 2, "score": 257904.07124891033 }, { "content": " * Answer the size of the current buffer in bytes.\n\n * The number of bytes of valid data in this buffer can differ.\n\n *\n\n * @return number of bytes of current buffer\n\n */\n\n inline File::FileSize GetBufferSize(void) const {\n\n return this->bufferSize;\n\n }\n\n\n\n /**\n\n * behaves like File::GetSize\n\n */\n\n virtual File::FileSize GetSize(void) const;\n\n\n\n /**\n\n * behaves like File::Open\n\n */\n\n virtual bool Open(const char* filename, const File::AccessMode accessMode, const File::ShareMode shareMode,\n\n const File::CreationMode creationMode);\n\n\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 3, "score": 245364.24675278144 }, { "content": " File::AccessMode fileMode;\n\n\n\n /** the number of bytes of the buffer which hold valid informations */\n\n File::FileSize validBufferSize;\n\n};\n\n\n\n} /* end namespace sys */\n\n} /* end namespace vislib */\n\n\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(pop)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n#endif /* VISLIB_BUFFERED_FILE_H_INCLUDED */\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 4, "score": 245360.38808965424 }, { "content": "\n\n /** the buffer for IO */\n\n unsigned char* buffer;\n\n\n\n /** the position inside the buffer */\n\n File::FileSize bufferOffset;\n\n\n\n /** the size of the buffer in bytes */\n\n File::FileSize bufferSize;\n\n\n\n /**\n\n * the starting position of the buffer inside the file in bytes from\n\n * the beginning of the file.\n\n */\n\n File::FileSize bufferStart;\n\n\n\n /** flag wether or not the buffer is dirty. */\n\n bool dirtyBuffer;\n\n\n\n /** the access mode the file has been opened with */\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 5, "score": 245360.1333344307 }, { "content": "/*\n\n * BufferedFile.h\n\n *\n\n * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.\n\n */\n\n\n\n#ifndef VISLIB_BUFFERED_FILE_H_INCLUDED\n\n#define VISLIB_BUFFERED_FILE_H_INCLUDED\n\n#if (defined(_MSC_VER) && (_MSC_VER > 1000))\n\n#pragma once\n\n#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(push, off)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n\n\n\n\n#include \"vislib/sys/File.h\"\n\n\n\n\n\nnamespace vislib {\n\nnamespace sys {\n\n\n\n/**\n\n * Instances of this class repsesent a file based on vislib::sys::File but\n\n * with buffered access for reading and writing.\n\n *\n\n * @author Sebastian Grottel ([email protected])\n\n */\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 6, "score": 245359.4595929888 }, { "content": " * Sets the size of the current buffer.\n\n * Calling this methode implictly flushes the buffer.\n\n *\n\n * @param newSize The number of bytes to be used for the new buffer.\n\n *\n\n * @throws IOException if the flush cannot be performed\n\n */\n\n void SetBufferSize(File::FileSize newSize);\n\n\n\n /**\n\n * behaves like File::Tell\n\n */\n\n virtual File::FileSize Tell(void) const;\n\n\n\n /**\n\n * behaves like File::Write\n\n * Performs an implicite flush if the buffer is not in write mode.\n\n * Ensures that the buffer is in write mode.\n\n *\n\n * throws IOException with ERROR_WRITE_FAULT if a buffer in write mode\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 7, "score": 245359.32252968496 }, { "content": " * @param rhs The right hand side operand.\n\n *\n\n * @return *this.\n\n *\n\n * @throws IllegalParamException If &'rhs' != this.\n\n */\n\n BufferedFile& operator=(const BufferedFile& rhs);\n\n\n\n /**\n\n * behaves like File::Flush\n\n *\n\n * @param fileFlush Flag whether or not to flush the file.\n\n *\n\n * throws IOException with ERROR_WRITE_FAULT if a buffer in write mode\n\n * could not be flushed to disk.\n\n */\n\n void flush(bool fileFlush);\n\n\n\n /** Resets the buffer. */\n\n void resetBuffer();\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 8, "score": 245358.3867236057 }, { "content": " /**\n\n * behaves like File::Open\n\n */\n\n virtual bool Open(const wchar_t* filename, const File::AccessMode accessMode, const File::ShareMode shareMode,\n\n const File::CreationMode creationMode);\n\n\n\n /**\n\n * behaves like File::Read\n\n * Performs an implicite flush if the buffer is not in read mode.\n\n * Ensures that the buffer is in read mode.\n\n */\n\n virtual File::FileSize Read(void* outBuf, const File::FileSize bufSize);\n\n\n\n /**\n\n * behaves like File::Seek\n\n * Performs an implicite flush if the buffer is in write mode.\n\n */\n\n virtual File::FileSize Seek(const File::FileOffset offset, const File::SeekStartPoint from = File::BEGIN);\n\n\n\n /**\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 9, "score": 245356.88051423163 }, { "content": " /** Ctor. */\n\n BufferedFile(void);\n\n\n\n /**\n\n * Dtor. If the file is still open, it is closed.\n\n */\n\n virtual ~BufferedFile(void);\n\n\n\n /** Close the file, if open. */\n\n virtual void Close(void);\n\n\n\n /**\n\n * behaves like File::Flush\n\n *\n\n * throws IOException with ERROR_WRITE_FAULT if a buffer in write mode\n\n * could not be flushed to disk.\n\n */\n\n virtual void Flush(void);\n\n\n\n /**\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 10, "score": 245355.61655815967 }, { "content": " * could not be flushed to disk.\n\n */\n\n virtual File::FileSize Write(const void* buf, const File::FileSize bufSize);\n\n\n\nprivate:\n\n /** the default buffer size when creating new buffers */\n\n static File::FileSize& defaultBufferSize;\n\n\n\n /**\n\n * Forbidden copy-ctor.\n\n *\n\n * @param rhs The object to be cloned.\n\n *\n\n * @throws UnsupportedOperationException Unconditionally.\n\n */\n\n BufferedFile(const BufferedFile& rhs);\n\n\n\n /**\n\n * Forbidden assignment.\n\n *\n", "file_path": "vislib/include/vislib/sys/BufferedFile.h", "rank": 11, "score": 245355.05389713947 }, { "content": "class MemoryFile : public File {\n\npublic:\n\n /** Ctor. */\n\n MemoryFile(void);\n\n\n\n /** Dtor. */\n\n virtual ~MemoryFile(void);\n\n\n\n /** Close the file, if open. */\n\n virtual void Close(void);\n\n\n\n /**\n\n * Forces all buffered data to be written.\n\n * This method has no effect.\n\n *\n\n * @throws IOException\n\n */\n\n virtual void Flush(void);\n\n\n\n /**\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 12, "score": 243810.88279629496 }, { "content": "class MemmappedFile : public File {\n\npublic:\n\n /** Ctor. */\n\n MemmappedFile(void);\n\n\n\n /**\n\n * Dtor. If the file is still open, it is closed.\n\n */\n\n virtual ~MemmappedFile(void);\n\n\n\n /** Close the file, if open. Flush, if necessary. */\n\n virtual void Close(void);\n\n\n\n /**\n\n * behaves like File::Flush, except that it flushes only dirty buffers.\n\n *\n\n * @throws IOException with ERROR_WRITE_FAULT (EFBIG on linux) if a buffer in write mode\n\n * could not be flushed to disk. GetLastError() will provide details (Windows).\n\n * @throws IOException with details (linux).\n\n */\n", "file_path": "core/include/mmcore/utility/sys/MemmappedFile.h", "rank": 13, "score": 240026.71129847495 }, { "content": " class LineBuffer {\n\n public:\n\n /**\n\n * Ctor\n\n */\n\n LineBuffer();\n\n\n\n /**\n\n * copy ctor\n\n *\n\n * @param src The object to clone from\n\n */\n\n LineBuffer(const LineBuffer& src);\n\n\n\n /** Dtor */\n\n ~LineBuffer(void);\n\n\n\n /**\n\n * Answer the number of word in this line. This value is zero if\n\n * the parsing element were lines and thus no tokens were\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 14, "score": 233691.51812690997 }, { "content": " * @param filename The path to the file to be loaded\n\n * @param elements The elements to be parsed.\n\n *\n\n * @return True on success, false on failure\n\n *\n\n * @throw vislib::Exception on any critical failure\n\n */\n\n inline bool LoadFile(const char* filename, ParsingElement elements = PARSING_DEFAULT) {\n\n MemmappedFile file;\n\n if (!file.Open(filename, File::READ_ONLY, File::SHARE_READ, File::OPEN_ONLY))\n\n return false;\n\n return this->LoadFile(file, elements);\n\n }\n\n\n\n /**\n\n * Loads the whole file as ASCII text into the buffer and builds up\n\n * the array of lines for accessing the data.\n\n *\n\n * @param filename The path to the file to be loaded\n\n * @param elements The elements to be parsed.\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 15, "score": 230033.87941143828 }, { "content": "#include \"vislib/String.h\"\n\n#include \"vislib/assert.h\"\n\n#include \"vislib/sys/File.h\"\n\n\n\n\n\nnamespace vislib {\n\nnamespace sys {\n\n\n\n\n\n/**\n\n * Buffer class loading a whole ASCII text file into memory and providing\n\n * a pointer array to access the lines.\n\n */\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 16, "score": 230033.62973743866 }, { "content": " *\n\n * @return True on success, false on failure\n\n *\n\n * @throw vislib::Exception on any critical failure\n\n */\n\n inline bool LoadFile(const vislib::StringW& filename, ParsingElement elements = PARSING_DEFAULT) {\n\n MemmappedFile file;\n\n if (!file.Open(filename, File::READ_ONLY, File::SHARE_READ, File::OPEN_ONLY))\n\n return false;\n\n return this->LoadFile(file, elements);\n\n }\n\n\n\n /**\n\n * Loads the whole file as ASCII text into the buffer and builds up\n\n * the array of lines for accessing the data.\n\n *\n\n * @param filename The path to the file to be loaded\n\n * @param elements The elements to be parsed.\n\n *\n\n * @return True on success, false on failure\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 17, "score": 230031.67231761065 }, { "content": "\n\n /**\n\n * Answer the pointer to the string of the line. Do not call when\n\n * the parsing elements were words and if 'Count' returns a value\n\n * larger than zero.\n\n *\n\n * @return The pointer to the string of the line\n\n */\n\n operator const char*(void) const {\n\n if (this->cnt > 0) {\n\n throw vislib::IllegalStateException(\"ASCIIFileBuffer was parsed for words. \"\n\n \"Requesting lines is thus illegal\",\n\n __FILE__, __LINE__);\n\n }\n\n return this->ptr.line;\n\n }\n\n\n\n private:\n\n /**\n\n * Ctor\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 18, "score": 230030.24386509904 }, { "content": " * the array of lines for accessing the data.\n\n *\n\n * @param filename The path to the file to be loaded\n\n * @param elements The elements to be parsed.\n\n *\n\n * @return True on success, false on failure\n\n *\n\n * @throw vislib::Exception on any critical failure\n\n */\n\n inline bool LoadFile(const vislib::StringA& filename, ParsingElement elements = PARSING_DEFAULT) {\n\n MemmappedFile file;\n\n if (!file.Open(filename, File::READ_ONLY, File::SHARE_READ, File::OPEN_ONLY))\n\n return false;\n\n return this->LoadFile(file, elements);\n\n }\n\n\n\n /**\n\n * Loads the whole file as ASCII text into the buffer and builds up\n\n * the array of lines for accessing the data.\n\n *\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 19, "score": 230030.07488664283 }, { "content": " * identified or if the line is empty (except for whitespaces).\n\n *\n\n * @return The number of words in this line\n\n */\n\n inline SIZE_T Count(void) const {\n\n return this->cnt;\n\n }\n\n\n\n /**\n\n * Answer the pointer to the string of the line. Do not call when\n\n * the parsing elements were words and if 'Count' returns a value\n\n * larger than zero.\n\n *\n\n * @return The pointer to the string of the line\n\n */\n\n inline const char* Pointer(void) const {\n\n if (this->cnt > 0) {\n\n throw vislib::IllegalStateException(\"ASCIIFileBuffer was parsed for words. \"\n\n \"Requesting lines is thus illegal\",\n\n __FILE__, __LINE__);\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 20, "score": 230029.56488833678 }, { "content": " *\n\n * @throw vislib::Exception on any critical failure\n\n */\n\n inline bool LoadFile(const wchar_t* filename, ParsingElement elements = PARSING_DEFAULT) {\n\n MemmappedFile file;\n\n if (!file.Open(filename, File::READ_ONLY, File::SHARE_READ, File::OPEN_ONLY))\n\n return false;\n\n return this->LoadFile(file, elements);\n\n }\n\n\n\n /**\n\n * Loads the whole file as ASCII text into the buffer and builds up\n\n * the array of lines for accessing the data. The current position in\n\n * 'file' is irrelevant. The file will not be closed, but the position\n\n * within will be undefined.\n\n *\n\n * @param file The file to be loaded\n\n * @param elements The elements to be parsed.\n\n *\n\n * @return True on success, false on failure\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 21, "score": 230029.44535596806 }, { "content": " *\n\n * @throw vislib::Exception on any critical failure\n\n */\n\n bool LoadFile(File& file, ParsingElement elements = PARSING_DEFAULT);\n\n\n\n /**\n\n * Sets the parsing element which will be parsed when no other element\n\n * is requested specifically.\n\n *\n\n * @param elements The new default parsing element\n\n */\n\n void SetParsingElements(ParsingElement elements);\n\n\n\n /**\n\n * Answer the idx-th line of the buffer\n\n *\n\n * @param idx The zero-based index of the line to return\n\n *\n\n * @return The requested line\n\n *\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 22, "score": 230027.9772122072 }, { "content": " /** Dtor. */\n\n ~ASCIIFileBuffer(void);\n\n\n\n /** Clears the buffer */\n\n void Clear(void);\n\n\n\n /**\n\n * Answer the number of lines stored in the buffer\n\n *\n\n * @return The number of lines stored in the buffer\n\n */\n\n inline SIZE_T Count(void) const {\n\n return this->lines.Count();\n\n }\n\n\n\n /**\n\n * Answer the parsing element which will be parsed when no other\n\n * element is requested specifically.\n\n *\n\n * @return The default parsing element\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 23, "score": 230027.3935135161 }, { "content": " * Array of the pointers to the beginnings of 'cnt' tokens, if\n\n * the 'cnt' is larger than zero\n\n */\n\n char** words;\n\n\n\n } ptr;\n\n\n\n /** Friend class for creation */\n\n friend class ASCIIFileBuffer;\n\n };\n\n\n\n /**\n\n * Ctor.\n\n *\n\n * @param elements The elements to be parsed. 'PARSING_DEFAULT' is not\n\n * a legal value and will be changed to\n\n * 'PARSING_LINES'\n\n */\n\n ASCIIFileBuffer(ParsingElement elements = PARSING_LINES);\n\n\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 24, "score": 230026.47901488718 }, { "content": "/*\n\n * ASCIIFileBuffer.h\n\n *\n\n * Copyright (C) 2006 - 2010 by Visualisierungsinstitut Universitaet Stuttgart.\n\n * Alle Rechte vorbehalten.\n\n */\n\n\n\n#ifndef VISLIB_ASCIIFILEBUFFER_H_INCLUDED\n\n#define VISLIB_ASCIIFILEBUFFER_H_INCLUDED\n\n#if (defined(_MSC_VER) && (_MSC_VER > 1000))\n\n#pragma once\n\n#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(push, off)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n\n\n#include \"mmcore/utility/sys/MemmappedFile.h\"\n\n#include \"vislib/Array.h\"\n\n#include \"vislib/IllegalStateException.h\"\n\n#include \"vislib/OutOfRangeException.h\"\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 25, "score": 230025.41012323604 }, { "content": " * @throw OutOfRangeException if a non-existing line is requested\n\n */\n\n inline const LineBuffer& operator[](SIZE_T idx) const {\n\n return this->lines[idx];\n\n }\n\n\n\nprivate:\n\n /** The buffer holding the whole file */\n\n char* buffer;\n\n\n\n /** Access to the lines in 'buffer' */\n\n vislib::Array<LineBuffer> lines;\n\n\n\n /** The default parsing elements */\n\n ParsingElement defElements;\n\n};\n\n\n\n} /* end namespace sys */\n\n} /* end namespace vislib */\n\n\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(pop)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n#endif /* VISLIB_ASCIIFILEBUFFER_H_INCLUDED */\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 26, "score": 230024.21325845912 }, { "content": "\n\n /**\n\n * Assignment operator\n\n *\n\n * @param rhs The right hand side operand\n\n *\n\n * @return A reference to 'this'\n\n */\n\n LineBuffer& operator=(const LineBuffer& rhs);\n\n\n\n /**\n\n * Test for equality\n\n *\n\n * @param rhs The right hand side operand\n\n *\n\n * @return True if this and rhs are equal\n\n */\n\n inline bool operator==(const LineBuffer& rhs) const {\n\n return (this->cnt == rhs.cnt) && (this->ptr.line == rhs.ptr.line);\n\n }\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 27, "score": 230018.23425617992 }, { "content": " *\n\n * @param line The line to set\n\n */\n\n LineBuffer(char* line);\n\n\n\n /**\n\n * Ctor\n\n *\n\n * @param words The words to set\n\n */\n\n LineBuffer(vislib::Array<char*>& words);\n\n\n\n /**\n\n * Assignment operator\n\n *\n\n * @param line The line to set\n\n *\n\n * @return A reference to 'this'\n\n */\n\n LineBuffer& operator=(char* line);\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 28, "score": 230016.24923954046 }, { "content": " }\n\n return this->ptr.line;\n\n }\n\n\n\n /**\n\n * Answer the idx-th word of the line\n\n *\n\n * @param idx The zero-based index of the word to return\n\n *\n\n * @return The requested word\n\n *\n\n * @throw OutOfRangeException if a non-existing line is requested\n\n */\n\n inline const char* Word(SIZE_T idx) const {\n\n if (idx >= this->cnt) {\n\n throw vislib::OutOfRangeException(\n\n static_cast<int>(idx), 0, static_cast<int>(this->cnt - 1), __FILE__, __LINE__);\n\n }\n\n return this->ptr.words[idx];\n\n }\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 29, "score": 230015.23882729938 }, { "content": "\n\n /**\n\n * Assignment operator\n\n *\n\n * @param words The words to set\n\n *\n\n * @return A reference to 'this'\n\n */\n\n LineBuffer& operator=(vislib::Array<char*>& words);\n\n\n\n /** The number of tokens, or Zero if only storing the line */\n\n SIZE_T cnt;\n\n\n\n /** The pointers */\n\n union _pointers_t {\n\n\n\n /** Pointer to the beginning of the line if 'cnt' is zero */\n\n char* line;\n\n\n\n /**\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 30, "score": 230013.00253708835 }, { "content": " */\n\n inline ParsingElement GetParsingElements(void) const {\n\n return this->defElements;\n\n }\n\n\n\n /**\n\n * Answer the idx-th line of the buffer\n\n *\n\n * @param idx The zero-based index of the line to return\n\n *\n\n * @return The requested line\n\n *\n\n * @throw OutOfRangeException if a non-existing line is requested\n\n */\n\n inline const LineBuffer& Line(SIZE_T idx) const {\n\n return this->lines[idx];\n\n }\n\n\n\n /**\n\n * Loads the whole file as ASCII text into the buffer and builds up\n", "file_path": "core/include/mmcore/utility/sys/ASCIIFileBuffer.h", "rank": 31, "score": 230012.82302772248 }, { "content": "class FileUtils {\n\npublic:\n\n /**\n\n * Check if file exists.\n\n *\n\n * @param path_str The file or directory path.\n\n */\n\n template<typename T>\n\n static bool FileExists(const T& path_str);\n\n\n\n /**\n\n * Check if any file exists and has specified file extension.\n\n *\n\n * @param path_str The file or directory path.\n\n * @param ext The extension the given file should have.\n\n */\n\n template<typename T>\n\n static bool FileWithExtensionExists(const T& path_str, const std::string& ext);\n\n\n\n /**\n", "file_path": "core/include/mmcore/utility/FileUtils.h", "rank": 32, "score": 205376.22592901872 }, { "content": "class TextFileReader {\n\npublic:\n\n /**\n\n * Ctor.\n\n *\n\n * @param file The file object to read from. The reader will not take\n\n * the ownership of the file object specified. The caller\n\n * must ensure that the file object remains valid as long\n\n * as it is used by this reader. The reader will also not\n\n * close or open the file!\n\n * @param bufferSize The size of the line buffer to be used in bytes.\n\n */\n\n TextFileReader(File* file = NULL, unsigned int bufferSize = 10240);\n\n\n\n /** Dtor. */\n\n ~TextFileReader(void);\n\n\n\n /**\n\n * Synchronises the reader position based on the position of the file\n\n * pointer. You must not call this method if no file object has been\n", "file_path": "vislib/include/vislib/sys/TextFileReader.h", "rank": 33, "score": 196307.04841050538 }, { "content": "class TmpFile : public File {\n\npublic:\n\n friend class vislib::sys::File;\n\n\n\n /** Close the file, if open. */\n\n virtual void Close(void) {\n\n if (this->hFile != NULL) {\n\n ::fclose(this->hFile);\n\n this->hFile = NULL;\n\n this->handle = -1;\n\n } else {\n\n File::Close();\n\n }\n\n }\n\n\n\nprivate:\n\n /** Ctor. */\n\n TmpFile(void) : File(), hFile(NULL) {\n\n // intentionally empty\n\n }\n", "file_path": "vislib/src/sys/File.cpp", "rank": 34, "score": 193381.89317931436 }, { "content": " *\n\n * @return true, if the specified file exists and is a normal file,\n\n * false otherwise.\n\n */\n\n static bool IsFile(const char* filename);\n\n\n\n /**\n\n * Answer whether a file with the specified name is a normal file (not\n\n * a directory or any other special file system element).\n\n *\n\n * @param filename Path to the file to be tested.\n\n *\n\n * @return true, if the specified file exists and is a normal file,\n\n * false otherwise.\n\n */\n\n static bool IsFile(const wchar_t* filename);\n\n\n\n /**\n\n * Rename the file 'oldName' to 'newName'.\n\n *\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 35, "score": 189820.26578254162 }, { "content": "\n\n /** Ctor. */\n\n File(void);\n\n\n\n /**\n\n * Dtor. If the file is still open, it is closed.\n\n */\n\n virtual ~File(void);\n\n\n\n /** Close the file, if open. */\n\n virtual void Close(void);\n\n\n\n /**\n\n * Forces all buffered data to be written.\n\n *\n\n * @throws IOException\n\n */\n\n virtual void Flush(void);\n\n\n\n /**\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 36, "score": 189818.7183485885 }, { "content": " return CreateTempFileName(s);\n\n }\n\n\n\n /**\n\n * Creates a file name for a temporary file\n\n *\n\n * @return the file name created\n\n */\n\n static inline vislib::StringW CreateTempFileNameW(void) {\n\n vislib::StringW s;\n\n return CreateTempFileName(s);\n\n }\n\n\n\n /**\n\n * Delete the file with the specified name.\n\n *\n\n * @param filename The name of the file to be deleted.\n\n *\n\n * @return true in case of success, false otherwise. Use\n\n * ::GetLastError() to retrieve further information on\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 37, "score": 189818.43112422567 }, { "content": "#endif /* _WIN32 */\n\n};\n\n\n\n} /* end namespace sys */\n\n} /* end namespace vislib */\n\n\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(pop)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n#endif /* VISLIB_FILE_H_INCLUDED */\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 38, "score": 189815.78748534905 }, { "content": " * Answer the size of the file in bytes.\n\n *\n\n * @return The size of the file in bytes.\n\n *\n\n * @throws IOException If the file size cannot be retrieve, e. g.\n\n * because the file has not been opened.\n\n */\n\n virtual FileSize GetSize(void) const;\n\n\n\n /**\n\n * Answer whether the file pointer is at the end of the file.\n\n *\n\n * @return true, if the eof flag is set, false otherwise.\n\n *\n\n * @throws IOException If the file is not open or the file pointer is at an\n\n * invalid position at the moment.\n\n */\n\n inline bool IsEOF(void) const {\n\n return (this->Tell() == this->GetSize());\n\n }\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 39, "score": 189815.3948256708 }, { "content": " * 'ShareMode' is 'SHARE_EXCLUSIVE'. The content of the temporary file\n\n * will be held in memory as long as the cache size is sufficient. The\n\n * file on secondary storage will be deleted when the file is closed.\n\n * This will also happen if 'Open' is called on the returned object.\n\n *\n\n * @return A pointer to the 'File' object of the created temporary\n\n * file. This object is placed on the heap and the caller must\n\n * delete it when it is no longer needed (best practice is to\n\n * assign the returned pointer to a 'SmartPtr' object). The\n\n * return value is 'NULL' if there was an unexpected error.\n\n *\n\n * @throws SystemException in most error cases.\n\n */\n\n static File* CreateTempFile(void);\n\n\n\n /**\n\n * Creates a file name for a temporary file\n\n *\n\n * @param outFn the string to receive the file name created\n\n *\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 40, "score": 189815.2681543974 }, { "content": " * Move the file pointer to the end of the file.\n\n *\n\n * @return The new offset of the file pointer from the beginning of the\n\n * file. This should be the size of the file.\n\n *\n\n * @throws IOException If the file pointer could not be moved.\n\n */\n\n inline FileSize SeekToEnd(void) {\n\n return this->Seek(0, END);\n\n }\n\n\n\n /**\n\n * Returns the position of the current file pointer\n\n *\n\n * @return Position of the file pointer in bytes from the beginning\n\n * of the file.\n\n *\n\n * @throws IOException\n\n */\n\n virtual FileSize Tell(void) const;\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 41, "score": 189814.64065050991 }, { "content": " * @param oldName The name of the file to be renamed.\n\n * @param newName The new name of the file.\n\n *\n\n * @return true in case of success, false otherwise. Use\n\n * ::GetLastError() to retrieve further information on\n\n * failure.\n\n */\n\n static bool Rename(const char* oldName, const char* newName);\n\n\n\n /**\n\n * Rename the file 'oldName' to 'newName'.\n\n *\n\n * @param oldName The name of the file to be renamed.\n\n * @param newName The new name of the file.\n\n *\n\n * @return true in case of success, false otherwise. Use\n\n * ::GetLastError() to retrieve further information on\n\n * failure.\n\n */\n\n static bool Rename(const wchar_t* oldName, const wchar_t* newName);\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 42, "score": 189812.557336049 }, { "content": "/*\n\n * File.h\n\n *\n\n * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.\n\n */\n\n\n\n#ifndef VISLIB_FILE_H_INCLUDED\n\n#define VISLIB_FILE_H_INCLUDED\n\n#if (defined(_MSC_VER) && (_MSC_VER > 1000))\n\n#pragma once\n\n#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(push, off)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n\n\n\n\n#ifndef _WIN32\n\n#include <unistd.h>\n\n#endif /* !_WIN32 */\n\n\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 43, "score": 189811.87462483675 }, { "content": " * failure.\n\n */\n\n static bool Delete(const char* filename);\n\n\n\n /**\n\n * Delete the file with the specified name.\n\n *\n\n * @param filename The name of the file to be deleted.\n\n *\n\n * @return true in case of success, false otherwise. Use\n\n * ::GetLastError() to retrieve further information on\n\n * failure.\n\n */\n\n static bool Delete(const wchar_t* filename);\n\n\n\n /**\n\n * Answer whether a file with the specified name exists.\n\n *\n\n * @param filename Path to the file to be tested.\n\n *\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 44, "score": 189811.14428174065 }, { "content": " *\n\n * @throws IOException If the file pointer could not be moved, e. g.\n\n * because the file was not open or the offset was\n\n * invalid.\n\n */\n\n virtual FileSize Seek(const FileOffset offset, const SeekStartPoint from = BEGIN);\n\n\n\n /**\n\n * Move the file pointer to the begin of the file.\n\n *\n\n * @return The new offset of the file pointer from the beginning of the\n\n * file. This should be zero ...\n\n *\n\n * @throws IOException If the file pointer could not be moved.\n\n */\n\n inline FileSize SeekToBegin(void) {\n\n return this->Seek(0, BEGIN);\n\n }\n\n\n\n /**\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 45, "score": 189809.31653299055 }, { "content": " * @return outFn\n\n */\n\n static vislib::StringA& CreateTempFileName(vislib::StringA& outFn);\n\n\n\n /**\n\n * Creates a file name for a temporary file\n\n *\n\n * @param outFn the string to receive the file name created\n\n *\n\n * @return outFn\n\n */\n\n static vislib::StringW& CreateTempFileName(vislib::StringW& outFn);\n\n\n\n /**\n\n * Creates a file name for a temporary file\n\n *\n\n * @return the file name created\n\n */\n\n static inline vislib::StringA CreateTempFileNameA(void) {\n\n vislib::StringA s;\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 46, "score": 189808.36716883606 }, { "content": " * @param accessMode The access mode for the file to be opened\n\n * @param shareMode The share mode\n\n * (Parameter is ignored on linux systems.)\n\n * @param creationMode Use your imagination on this one\n\n *\n\n * @return true, if the file has been successfully opened, false\n\n * otherwise. In case of an error you can receive additional\n\n * information using 'GetLastError'.\n\n *\n\n * @throws IllegalParamException\n\n */\n\n inline bool Open(const StringW& filename, const AccessMode accessMode, const ShareMode shareMode,\n\n const CreationMode creationMode) {\n\n return this->Open(filename.PeekBuffer(), accessMode, shareMode, creationMode);\n\n }\n\n\n\n /**\n\n * Read at most 'bufSize' bytes from the file into 'outBuf'.\n\n *\n\n * @param outBuf The buffer to receive the data.\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 47, "score": 189808.28786193853 }, { "content": " * @throws SystemException in most error cases.\n\n */\n\n static FileSize GetSize(const char* filename);\n\n\n\n /**\n\n * Answer the size of a file\n\n *\n\n * @param filename Path to the file\n\n *\n\n * @return The size of the file.\n\n *\n\n * @throws SystemException in most error cases.\n\n */\n\n static FileSize GetSize(const wchar_t* filename);\n\n\n\n /**\n\n * Answer whether a file with the specified name is a directory.\n\n *\n\n * @param filename Path to the file to be tested.\n\n *\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 48, "score": 189808.0403150607 }, { "content": " * @return true, if the specified file exists, false otherwise.\n\n */\n\n static bool Exists(const char* filename);\n\n\n\n /**\n\n * Answer whether a file with the specified name exists.\n\n *\n\n * @param filename Path to the file to be tested.\n\n *\n\n * @return true, if the specified file exists, false otherwise.\n\n */\n\n static bool Exists(const wchar_t* filename);\n\n\n\n /**\n\n * Answer the size of a file\n\n *\n\n * @param filename Path to the file\n\n *\n\n * @return The size of the file.\n\n *\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 49, "score": 189807.84212123434 }, { "content": "\n\n /**\n\n * Write 'bufSize' bytes from 'buf' to the file.\n\n *\n\n * @param buf Pointer to the data to be written.\n\n * @param bufSize The number of bytes to be written.\n\n *\n\n * @return The number of bytes acutally written.\n\n *\n\n * @throws IOException\n\n */\n\n virtual FileSize Write(const void* buf, const FileSize bufSize);\n\n\n\nprivate:\n\n /**\n\n * Forbidden copy-ctor.\n\n *\n\n * @param rhs The object to be cloned.\n\n *\n\n * @throws UnsupportedOperationException Unconditionally.\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 50, "score": 189807.82426335601 }, { "content": "\n\n /**\n\n * Answer whether this file is open.\n\n *\n\n * @return true, if the file is open, false otherwise.\n\n */\n\n virtual bool IsOpen(void) const;\n\n\n\n /**\n\n * Opens a file.\n\n *\n\n * If this object already holds an open file, this file is closed (like\n\n * calling Close) and the new file is opened.\n\n *\n\n * @param filename Path to the file to be opened\n\n * @param accessMode The access mode for the file to be opened\n\n * @param shareMode The share mode\n\n * (Parameter is ignored on linux systems.)\n\n * @param creationMode Use your imagination on this one\n\n *\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 51, "score": 189807.72494867438 }, { "content": "#ifdef _MSC_VER\n\n#pragma comment(lib, \"shlwapi\")\n\n#endif /* _MSC_VER */\n\n\n\n\n\n#include \"vislib/String.h\"\n\n#include \"vislib/types.h\"\n\n\n\n\n\nnamespace vislib {\n\nnamespace sys {\n\n\n\n/**\n\n * Instances of this class repsesent a file. The class provides unbuffered\n\n * read and write access to the file. The implementation uses 64 bit\n\n * operations on all platforms to allow access to very large files.\n\n *\n\n * @author Christoph Mueller ([email protected])\n\n */\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 52, "score": 189807.6537818094 }, { "content": " * @return true, if the file has been successfully opened, false\n\n * otherwise. In case of an error you can receive additional\n\n * information using 'GetLastError'.\n\n *\n\n * @throws IllegalParamException\n\n */\n\n virtual bool Open(\n\n const char* filename, const AccessMode accessMode, const ShareMode shareMode, const CreationMode creationMode);\n\n\n\n /**\n\n * Opens a file.\n\n *\n\n * If this object already holds an open file, this file is closed (like\n\n * calling Close) and the new file is opened.\n\n *\n\n * @param filename Path to the file to be opened\n\n * @param accessMode The access mode for the file to be opened\n\n * @param shareMode The share mode\n\n * (Parameter is ignored on linux systems.)\n\n * @param creationMode Use your imagination on this one\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 53, "score": 189806.83745746655 }, { "content": " * @return true, if the specified file exists and is a directory,\n\n * false otherwise.\n\n */\n\n static bool IsDirectory(const char* filename);\n\n\n\n /**\n\n * Answer whether a file with the specified name is a directory.\n\n *\n\n * @param filename Path to the file to be tested.\n\n *\n\n * @return true, if the specified file exists and is a directory,\n\n * false otherwise.\n\n */\n\n static bool IsDirectory(const wchar_t* filename);\n\n\n\n /**\n\n * Answer whether a file with the specified name is a normal file (not\n\n * a directory or any other special file system element).\n\n *\n\n * @param filename Path to the file to be tested.\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 54, "score": 189806.75942948106 }, { "content": " */\n\n File(const File& rhs);\n\n\n\n /**\n\n * Forbidden assignment.\n\n *\n\n * @param rhs The right hand side operand.\n\n *\n\n * @return *this.\n\n *\n\n * @throws IllegalParamException If &'rhs' != this.\n\n */\n\n File& operator=(const File& rhs);\n\n\n\nprotected:\n\n /** The file handle. */\n\n#ifdef _WIN32\n\n HANDLE handle;\n\n#else /* _WIN32 */\n\n int handle;\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 55, "score": 189806.35438629185 }, { "content": " * @param bufSize The size of 'outBuf' in bytes.\n\n *\n\n * @return The number of bytes actually read.\n\n *\n\n * @throws IOException\n\n */\n\n virtual FileSize Read(void* outBuf, const FileSize bufSize);\n\n\n\n /**\n\n * Move the file pointer.\n\n *\n\n * If the file pointer is seeked beyond the end of file, the behaviour is\n\n * undefined for Read, Write, Tell and isEoF\n\n *\n\n * @param offset The offset in bytes.\n\n * @param from The begin of the seek operation, which can be one of\n\n * BEGIN, CURRENT, or END.\n\n *\n\n * @return The new offset in bytes of the file pointer from the begin of\n\n * the file.\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 56, "score": 189806.3583705488 }, { "content": " *\n\n * @return true, if the file has been successfully opened, false\n\n * otherwise. In case of an error you can receive additional\n\n * information using 'GetLastError'.\n\n *\n\n * @throws IllegalParamException\n\n */\n\n inline bool Open(const StringA& filename, const AccessMode accessMode, const ShareMode shareMode,\n\n const CreationMode creationMode) {\n\n return this->Open(filename.PeekBuffer(), accessMode, shareMode, creationMode);\n\n }\n\n\n\n /**\n\n * Opens a file.\n\n *\n\n * If this object already holds an open file, this file is closed (like\n\n * calling Close) and the new file is opened.\n\n *\n\n * @param filename Path to the file to be opened\n\n * @param accessMode The access mode for the file to be opened\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 57, "score": 189805.62458040414 }, { "content": " OPEN_CREATE // Opens existing or creates new file as needed.\n\n };\n\n\n\n /** Possible starting points for seek operations. */\n\n enum SeekStartPoint {\n\n#ifdef _WIN32\n\n BEGIN = FILE_BEGIN,\n\n CURRENT = FILE_CURRENT,\n\n END = FILE_END\n\n#else /* _WIN32 */\n\n BEGIN = SEEK_SET,\n\n CURRENT = SEEK_CUR,\n\n END = SEEK_END\n\n#endif /* _WIN32 */\n\n };\n\n\n\n /**\n\n * Creates a temporary file. The file has 'AccessMode' 'READ_WRITE'.\n\n * Because the name of the file is highly OS configuration dependent\n\n * there is no way of opening the file a second time. Therefore the\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 58, "score": 189803.6311421724 }, { "content": " * @param shareMode The share mode\n\n * (Parameter is ignored on linux systems.)\n\n * @param creationMode Use your imagination on this one\n\n *\n\n * @return true, if the file has been successfully opened, false\n\n * otherwise. In case of an error you can receive additional\n\n * information using 'GetLastError'.\n\n *\n\n * @throws IllegalParamException\n\n */\n\n virtual bool Open(const wchar_t* filename, const AccessMode accessMode, const ShareMode shareMode,\n\n const CreationMode creationMode);\n\n\n\n /**\n\n * Opens a file.\n\n *\n\n * If this object already holds an open file, this file is closed (like\n\n * calling Close) and the new file is opened.\n\n *\n\n * @param filename Path to the file to be opened\n", "file_path": "vislib/include/vislib/sys/File.h", "rank": 59, "score": 189803.38382677195 }, { "content": "class FileTarget : public Log::Target {\n\npublic:\n\n /**\n\n * Opens a physical log file\n\n *\n\n * @param path The path to the physical log file\n\n * @param level The log level used for this target\n\n */\n\n FileTarget(std::string const& path, Log::UINT level = Log::LEVEL_ERROR);\n\n\n\n /** Dtor */\n\n virtual ~FileTarget(void);\n\n\n\n /** Flushes any buffer */\n\n void Flush(void) override;\n\n\n\n /**\n\n * Answer the path to the physical log file\n\n *\n\n * @return The path to the physical log file\n", "file_path": "core/include/mmcore/utility/log/FileTarget.h", "rank": 60, "score": 188033.72040686558 }, { "content": " : File()\n\n , buffer(NULL)\n\n , bufferOffset(0)\n\n , bufferSize(BufferedFile::defaultBufferSize)\n\n , bufferStart(0)\n\n , dirtyBuffer(false)\n\n , fileMode(File::READ_WRITE)\n\n , validBufferSize(0) {\n\n this->buffer = new unsigned char[static_cast<unsigned int>(this->bufferSize)];\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::~BufferedFile\n\n */\n\nvislib::sys::BufferedFile::~BufferedFile(void) {\n\n ARY_SAFE_DELETE(this->buffer);\n\n}\n\n\n\n\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 61, "score": 185560.16940967858 }, { "content": "/*\n\n * vislib::sys::BufferedFile::Close\n\n */\n\nvoid vislib::sys::BufferedFile::Close(void) {\n\n this->Flush(); // flushes if writeable and dirty.\n\n File::Close();\n\n this->fileMode = File::READ_WRITE;\n\n this->resetBuffer();\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::Flush\n\n */\n\nvoid vislib::sys::BufferedFile::Flush(void) {\n\n this->flush(true);\n\n}\n\n\n\n\n\n/*\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 62, "score": 185558.53802201457 }, { "content": " * vislib::sys::BufferedFile::GetSize\n\n */\n\nvislib::sys::File::FileSize vislib::sys::BufferedFile::GetSize(void) const {\n\n FileSize size = File::GetSize();\n\n if (this->bufferStart + this->validBufferSize > size) {\n\n size = this->bufferStart + this->validBufferSize;\n\n }\n\n return size;\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::Open\n\n */\n\nbool vislib::sys::BufferedFile::Open(const char* filename, const vislib::sys::File::AccessMode accessMode,\n\n const vislib::sys::File::ShareMode shareMode, const vislib::sys::File::CreationMode creationMode) {\n\n\n\n if (File::Open(filename, accessMode, shareMode, creationMode)) {\n\n\n\n this->fileMode = accessMode;\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 63, "score": 185556.69669991938 }, { "content": "\n\n/*\n\n * vislib::sys::BufferedFile::flush\n\n */\n\nvoid vislib::sys::BufferedFile::flush(bool fileFlush) {\n\n if (this->IsOpen() && ((this->fileMode == File::WRITE_ONLY) || (this->fileMode == File::READ_WRITE))) {\n\n\n\n if ((this->validBufferSize > 0) && this->dirtyBuffer) {\n\n\n\n File::Seek(this->bufferStart, File::BEGIN);\n\n File::FileSize w, r = 0;\n\n\n\n while (r < this->validBufferSize) {\n\n w = File::Write(this->buffer + r, this->validBufferSize + r);\n\n if (w == 0) {\n\n#ifdef _WIN32\n\n throw IOException(ERROR_WRITE_FAULT, __FILE__, __LINE__);\n\n#else /* _WIN32 */\n\n throw IOException(EIO, __FILE__, __LINE__);\n\n#endif /* _WIN32 */\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 64, "score": 185554.55988772804 }, { "content": " return retVal;\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::SetBufferSize\n\n */\n\nvoid vislib::sys::BufferedFile::SetBufferSize(vislib::sys::File::FileSize newSize) {\n\n\n\n if (newSize < 1) {\n\n throw vislib::IllegalParamException(\"newSize\", __FILE__, __LINE__);\n\n }\n\n\n\n this->Flush(); // writes buffer if dirty and file writeable\n\n this->resetBuffer();\n\n delete[] this->buffer;\n\n this->bufferSize = newSize;\n\n this->buffer = new unsigned char[static_cast<unsigned int>(this->bufferSize)];\n\n}\n\n\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 65, "score": 185553.40677324485 }, { "content": " this->resetBuffer();\n\n\n\n return true;\n\n\n\n } else {\n\n return false;\n\n }\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::Open\n\n */\n\nbool vislib::sys::BufferedFile::Open(const wchar_t* filename, const vislib::sys::File::AccessMode accessMode,\n\n const vislib::sys::File::ShareMode shareMode, const vislib::sys::File::CreationMode creationMode) {\n\n\n\n if (File::Open(filename, accessMode, shareMode, creationMode)) {\n\n\n\n this->fileMode = accessMode;\n\n this->resetBuffer();\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 66, "score": 185553.28593790293 }, { "content": "\n\n return true;\n\n\n\n } else {\n\n return false;\n\n }\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::Read\n\n */\n\nvislib::sys::File::FileSize vislib::sys::BufferedFile::Read(void* outBuf, const vislib::sys::File::FileSize bufSize) {\n\n // check for compatible file mode\n\n if ((this->fileMode != File::READ_WRITE) && (this->fileMode != File::READ_ONLY)) {\n\n throw IOException(\n\n#ifdef _WIN32\n\n E_ACCESSDENIED /* access denied: wrong access mode */\n\n#else /* _WIN32 */\n\n EINVAL /* invalid file: file not open for read */\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 67, "score": 185552.01691964836 }, { "content": "\n\n/*\n\n * vislib::sys::BufferedFile::Tell\n\n */\n\nvislib::sys::File::FileSize vislib::sys::BufferedFile::Tell(void) const {\n\n return this->bufferStart + this->bufferOffset;\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::Write\n\n */\n\nvislib::sys::File::FileSize vislib::sys::BufferedFile::Write(\n\n const void* buf, const vislib::sys::File::FileSize bufSize) {\n\n // check for compatible file mode\n\n if ((this->fileMode != File::READ_WRITE) && (this->fileMode != File::WRITE_ONLY)) {\n\n throw IOException(\n\n#ifdef _WIN32\n\n E_ACCESSDENIED /* access denied: wrong access mode */\n\n#else /* _WIN32 */\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 68, "score": 185551.30238591883 }, { "content": "#endif /* _WIN32 */\n\n ,\n\n __FILE__, __LINE__);\n\n }\n\n\n\n File::FileSize amount;\n\n unsigned char* outBuffer = static_cast<unsigned char*>(outBuf);\n\n File::FileSize outBufferSize = bufSize;\n\n\n\n // first copy from buffer\n\n amount = this->validBufferSize - this->bufferOffset;\n\n if (amount > outBufferSize) {\n\n amount = outBufferSize;\n\n }\n\n memcpy(outBuffer, this->buffer + this->bufferOffset, static_cast<unsigned int>(amount));\n\n this->bufferOffset += amount;\n\n outBufferSize -= amount;\n\n\n\n if (outBufferSize == 0) {\n\n return amount; // we are done!\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 69, "score": 185550.99931149854 }, { "content": "\n\n\n\n/*\n\n * vislib::sys::BufferedFile::defBufferSize\n\n */\n\nstatic vislib::sys::File::FileSize __vl_bufferedfile_defaultBufferSize\n\n // = vislib::sys::SystemInformation::PageSize();\n\n = 64 * 1024;\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::defBufferSize\n\n */\n\nvislib::sys::File::FileSize& vislib::sys::BufferedFile::defaultBufferSize(__vl_bufferedfile_defaultBufferSize);\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::BufferedFile\n\n */\n\nvislib::sys::BufferedFile::BufferedFile(void)\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 70, "score": 185550.9308920189 }, { "content": " EINVAL /* invalid file: file not open for writing */\n\n#endif /* _WIN32 */\n\n ,\n\n __FILE__, __LINE__);\n\n }\n\n\n\n const unsigned char* inBuffer = static_cast<const unsigned char*>(buf);\n\n File::FileSize inBufferSize = bufSize;\n\n File::FileSize amount;\n\n\n\n // store into buffer\n\n amount = this->bufferSize - this->bufferOffset;\n\n if (amount > inBufferSize) {\n\n amount = inBufferSize;\n\n }\n\n memcpy(this->buffer + this->bufferOffset, inBuffer, static_cast<unsigned int>(amount));\n\n inBufferSize -= amount;\n\n this->bufferOffset += amount;\n\n if (this->validBufferSize < this->bufferOffset) {\n\n this->validBufferSize = this->bufferOffset;\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 71, "score": 185550.3470676315 }, { "content": " }\n\n r += w;\n\n }\n\n }\n\n\n\n if (fileFlush) {\n\n File::Flush();\n\n }\n\n }\n\n this->dirtyBuffer = false;\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::resetBuffer\n\n */\n\nvoid vislib::sys::BufferedFile::resetBuffer() {\n\n this->bufferOffset = 0;\n\n this->bufferStart = 0;\n\n this->dirtyBuffer = false;\n\n this->validBufferSize = 0;\n\n}\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 72, "score": 185550.09992434527 }, { "content": " }\n\n this->dirtyBuffer = true;\n\n if (inBufferSize == 0) {\n\n return amount; // we are done.\n\n }\n\n\n\n inBuffer += amount;\n\n\n\n // buffer full need to refresh\n\n this->flush(false);\n\n this->bufferStart += this->bufferOffset;\n\n this->validBufferSize = 0;\n\n this->bufferOffset = 0;\n\n\n\n if (inBufferSize > this->bufferSize) {\n\n // requesting large amounts, so write directly\n\n File::Seek(this->bufferStart, File::BEGIN);\n\n File::FileSize written = amount;\n\n\n\n while (inBufferSize > 0) {\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 73, "score": 185549.44268133532 }, { "content": "/*\n\n * BufferedFile.cpp\n\n *\n\n * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.\n\n */\n\n\n\n#include \"vislib/sys/BufferedFile.h\"\n\n\n\n#include \"vislib/IllegalParamException.h\"\n\n#include \"vislib/UnsupportedOperationException.h\"\n\n#include \"vislib/assert.h\"\n\n#include \"vislib/memutils.h\"\n\n#include \"vislib/sys/IOException.h\"\n\n#include \"vislib/sys/error.h\"\n\n\n\n#ifdef _WIN32\n\n#include <WinError.h>\n\n#else /* _WIN32 */\n\n#include <errno.h>\n\n#endif /* _WIN32 */\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 74, "score": 185547.70108160804 }, { "content": "\n\n\n\n/*\n\n * vislib::sys::BufferedFile::BufferedFile copy ctor\n\n */\n\nvislib::sys::BufferedFile::BufferedFile(const vislib::sys::BufferedFile& rhs) {\n\n throw UnsupportedOperationException(\"vislib::sys::File::File\", __FILE__, __LINE__);\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::operator =\n\n */\n\nvislib::sys::BufferedFile& vislib::sys::BufferedFile::operator=(const vislib::sys::BufferedFile& rhs) {\n\n if (this != &rhs) {\n\n throw IllegalParamException(\"rhs\", __FILE__, __LINE__);\n\n }\n\n return *this;\n\n}\n\n\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 75, "score": 185546.67994402463 }, { "content": " }\n\n\n\n outBuffer += amount;\n\n\n\n // buffer depleted. Must be replaced.\n\n this->flush(false);\n\n this->bufferStart += this->bufferOffset;\n\n this->validBufferSize = 0;\n\n this->bufferOffset = 0;\n\n\n\n File::FileSize read = amount;\n\n if (outBufferSize >= this->bufferSize) {\n\n // requesting large amounts, so read directly\n\n File::Seek(this->bufferStart, File::BEGIN);\n\n\n\n while (outBufferSize > 0) {\n\n amount = File::Read(outBuffer, outBufferSize);\n\n if (amount == 0) {\n\n break;\n\n }\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 76, "score": 185545.15127609696 }, { "content": " pos = this->GetSize() + offset;\n\n break;\n\n default:\n\n throw vislib::IllegalParamException(\"from\", __FILE__, __LINE__);\n\n }\n\n\n\n if ((pos >= this->bufferStart) && (pos < this->bufferStart + this->validBufferSize)) {\n\n // we seek inside the buffer\n\n this->bufferOffset = pos - this->bufferStart;\n\n return pos;\n\n }\n\n\n\n // we cannot seek inside the buffer\n\n this->Flush();\n\n\n\n File::FileSize retVal = File::Seek(pos, File::BEGIN);\n\n this->validBufferSize = 0;\n\n this->bufferOffset = 0;\n\n this->bufferStart = retVal;\n\n\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 77, "score": 185544.65683459272 }, { "content": "\n\n return read + amount;\n\n}\n\n\n\n\n\n/*\n\n * vislib::sys::BufferedFile::Seek\n\n */\n\nvislib::sys::File::FileSize vislib::sys::BufferedFile::Seek(\n\n const vislib::sys::File::FileOffset offset, const vislib::sys::File::SeekStartPoint from) {\n\n\n\n File::FileSize pos; // absolute file position to seek to\n\n switch (from) {\n\n case File::BEGIN:\n\n pos = offset;\n\n break;\n\n case File::CURRENT:\n\n pos = this->Tell() + offset;\n\n break;\n\n case File::END:\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 78, "score": 185543.9573093867 }, { "content": " amount = File::Write(inBuffer, inBufferSize);\n\n if (amount == 0) {\n\n break;\n\n }\n\n inBuffer += amount;\n\n inBufferSize -= amount;\n\n written += amount;\n\n this->bufferStart += amount;\n\n }\n\n\n\n return written;\n\n }\n\n\n\n memcpy(this->buffer, inBuffer, static_cast<unsigned int>(inBufferSize));\n\n this->bufferOffset = inBufferSize;\n\n this->validBufferSize = inBufferSize;\n\n this->dirtyBuffer = true;\n\n\n\n return amount + inBufferSize;\n\n}\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 79, "score": 185543.75236911597 }, { "content": " outBuffer += amount;\n\n outBufferSize -= amount;\n\n read += amount;\n\n this->bufferStart += amount;\n\n }\n\n\n\n return read;\n\n }\n\n\n\n // refill the buffer\n\n File::Seek(this->bufferStart, File::BEGIN);\n\n this->validBufferSize = File::Read(this->buffer, this->bufferSize);\n\n\n\n // read remaining data from the buffer\n\n amount = outBufferSize; // amount to read to fulfill the request.\n\n if (amount > this->validBufferSize) {\n\n amount = this->validBufferSize;\n\n }\n\n memcpy(outBuffer, this->buffer, static_cast<unsigned int>(amount));\n\n this->bufferOffset = amount;\n", "file_path": "vislib/src/sys/BufferedFile.cpp", "rank": 80, "score": 185542.879069004 }, { "content": "class FilePathParam : public AbstractParam {\n\npublic:\n\n enum FilePathFlags_ : uint32_t {\n\n Flag_File = 1 << 0, // Only allows to hold an existing file\n\n Flag_Directory = 1 << 1, // Only allows to hold an existing directory\n\n Internal_NoExistenceCheck = 1 << 2, // Only used internally - do not use as flag\n\n Internal_RestrictExtension = 1 << 3, // Only used internally - do not use as flag\n\n Flag_Any = Flag_File | Flag_Directory, // Only allows to hold an existing file or directory\n\n Flag_Any_ToBeCreated = Flag_Any | Internal_NoExistenceCheck, // Allows to hold a non-existing file or directory\n\n Flag_File_ToBeCreated = Flag_File | Internal_NoExistenceCheck, // Allows to hold a non-existing file\n\n Flag_Directory_ToBeCreated = // Allows to hold a non-existing directory\n\n Flag_Directory | Internal_NoExistenceCheck,\n\n Flag_File_RestrictExtension = // Allows to hold an existing file having one of the given extensions\n\n Flag_File | Internal_RestrictExtension,\n\n Flag_File_ToBeCreatedWithRestrExts = // Allows to hold a non-existing file having one of the given extensions\n\n Flag_File | Internal_NoExistenceCheck | Internal_RestrictExtension\n\n };\n\n\n\n typedef uint32_t Flags_t;\n\n typedef std::vector<std::string> Extensions_t;\n", "file_path": "core/include/mmcore/param/FilePathParam.h", "rank": 81, "score": 184162.23452358946 }, { "content": "class FileStreamProvider : public AbstractStreamProvider {\n\npublic:\n\n /**\n\n * Answer the name of this module.\n\n *\n\n * @return The name of this module.\n\n */\n\n static const char* ClassName() {\n\n return \"FileStreamProvider\";\n\n }\n\n\n\n /**\n\n * Answer a human readable description of this module.\n\n *\n\n * @return A human readable description of this module.\n\n */\n\n static const char* Description() {\n\n return \"Provides a file stream\";\n\n }\n\n\n", "file_path": "core/include/mmcore/FileStreamProvider.h", "rank": 82, "score": 184162.23452358946 }, { "content": "class mmvtkmFileLoader : public core::Module {\n\npublic:\n\n /**\n\n * Answer the name of this module.\n\n *\n\n * @return The name of this module.\n\n */\n\n static const char* ClassName(void) {\n\n return \"vtkmFileLoader\";\n\n }\n\n\n\n /**\n\n * Answer a human readable description of this module.\n\n *\n\n * @return A human readable description of this module.\n\n */\n\n static const char* Description(void) {\n\n return \"File loader module for vtkm files.\";\n\n }\n\n\n", "file_path": "plugins/mmvtkm/include/mmvtkm/mmvtkmFileLoader.h", "rank": 83, "score": 184162.23452358946 }, { "content": " * @throws IllegalParamException If &'rhs' != this.\n\n */\n\n MemoryFile& operator=(const MemoryFile& rhs);\n\n\n\n /** The memory file access mode */\n\n AccessMode accessMode;\n\n\n\n /** The flat buffer */\n\n unsigned char* buffer;\n\n\n\n /** The length of the flat buffer */\n\n FileSize bufferLen;\n\n\n\n /** The current position */\n\n FileSize pos;\n\n\n\n /** The raw storage object used */\n\n RawStorage* storage;\n\n};\n\n\n\n} /* end namespace sys */\n\n} /* end namespace vislib */\n\n\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(pop)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n#endif /* VISLIB_MEMORYFILE_H_INCLUDED */\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 84, "score": 183517.14354915032 }, { "content": " * Answer the size of the file in bytes.\n\n *\n\n * @return The size of the file in bytes.\n\n */\n\n virtual FileSize GetSize(void) const;\n\n\n\n /**\n\n * Answer whether this file is open.\n\n *\n\n * @return true, if the file is open, false otherwise.\n\n */\n\n virtual bool IsOpen(void) const;\n\n\n\n /**\n\n * Opens a flat memory pointer as file. This object will not take\n\n * ownership of the memory 'buffer' points to. The caller is\n\n * responsible to keep the memory and the pointer valid as long as it\n\n * is used by this object.\n\n *\n\n * @param buffer The pointer to the memory. Must not be NULL\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 85, "score": 183508.60359077947 }, { "content": " * @param bufferlength The size of the memory 'buffer' points to in\n\n * bytes\n\n * @param accessMode The access mode for the memory file\n\n *\n\n * @return true on success, false on failure\n\n */\n\n virtual bool Open(void* buffer, SIZE_T bufferLength, AccessMode accessMode);\n\n\n\n /**\n\n * Opens a RawStorage as file. This object will not take ownership of\n\n * the RawStorage object. The caller is responsible to keep the object\n\n * alive and valid as long as it is used by this object. Resizing the\n\n * RawStorage object while it is used by this class may result in\n\n * undefined behaviour of any methods of this class.\n\n *\n\n * @param storage The RawStorage to be used as file\n\n * qparam accessMode The access mode for the memory file\n\n *\n\n * @return true on success, false on failure\n\n */\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 86, "score": 183506.59581893252 }, { "content": "/*\n\n * MemoryFile.h\n\n *\n\n * Copyright (C) 2006 - 2010 by Visualisierungsinstitut Universitaet Stuttgart.\n\n * Alle Rechte vorbehalten.\n\n */\n\n\n\n#ifndef VISLIB_MEMORYFILE_H_INCLUDED\n\n#define VISLIB_MEMORYFILE_H_INCLUDED\n\n#if (defined(_MSC_VER) && (_MSC_VER > 1000))\n\n#pragma once\n\n#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */\n\n#if defined(_WIN32) && defined(_MANAGED)\n\n#pragma managed(push, off)\n\n#endif /* defined(_WIN32) && defined(_MANAGED) */\n\n\n\n#include \"vislib/RawStorage.h\"\n\n#include \"vislib/sys/File.h\"\n\n\n\n\n\nnamespace vislib {\n\nnamespace sys {\n\n\n\n\n\n/**\n\n * File accessor to main memory\n\n */\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 87, "score": 183500.10569533377 }, { "content": " static bool LoadRawFile(const std::filesystem::path& filename, std::vector<char>& out_data);\n\n\n\nprivate:\n\n FileUtils() = default;\n\n ~FileUtils() = default;\n\n};\n\n\n\n\n\ntemplate<typename T>\n\nbool megamol::core::utility::FileUtils::FileExists(const T& path_str) {\n\n auto filepath = std::filesystem::u8path(path_str);\n\n try {\n\n if (std::filesystem::exists(filepath) && std::filesystem::is_regular_file(filepath)) {\n\n return true;\n\n }\n\n } catch (std::filesystem::filesystem_error const& e) {\n\n megamol::core::utility::log::Log::DefaultLog.WriteError(\n\n \"Filesystem Error: %s [%s, %s, line %d]\\n\", e.what(), __FILE__, __FUNCTION__, __LINE__);\n\n }\n\n return false;\n", "file_path": "core/include/mmcore/utility/FileUtils.h", "rank": 88, "score": 183498.13063493362 }, { "content": " /**\n\n * Returns the position of the current file pointer\n\n *\n\n * @return Position of the file pointer in bytes from the beginning\n\n * of the file.\n\n */\n\n virtual FileSize Tell(void) const;\n\n\n\n /**\n\n * Write 'bufSize' bytes from 'buf' to the file.\n\n * If the data to be written does not fit into the remaining memory\n\n * the behaviour depends on the used memory object. When using a\n\n * rawstorage object the memory is extended to fit all data. When\n\n * using a void pointer only as much data is written as fits into\n\n * the allocated memory.\n\n *\n\n * @param buf Pointer to the data to be written.\n\n * @param bufSize The number of bytes to be written.\n\n *\n\n * @return The number of bytes acutally written.\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 89, "score": 183493.78413315347 }, { "content": "/*\n\n * FileStreamProvider.h\n\n *\n\n * Copyright (C) 2019 by Universitaet Stuttgart (VIS).\n\n * Alle Rechte vorbehalten.\n\n */\n\n#pragma once\n\n\n\n#include \"mmcore/AbstractStreamProvider.h\"\n\n#include \"mmcore/param/ParamSlot.h\"\n\n\n\n#include <fstream>\n\n#include <iostream>\n\n\n\nnamespace megamol {\n\nnamespace core {\n\n\n\n/**\n\n * Provides a stream.\n\n *\n\n * @author Alexander Straub\n\n */\n", "file_path": "core/include/mmcore/FileStreamProvider.h", "rank": 90, "score": 183493.41705767633 }, { "content": " * @param silent Disable log output.\n\n *\n\n * @return True on success, false otherwise.\n\n */\n\n static bool WriteFile(const std::filesystem::path& filename, const std::string& in_content, bool silent = false);\n\n\n\n /**\n\n * Read content from file.\n\n *\n\n * @param filename The file name of the file.\n\n * @param out_content The content to read from file.\n\n * @param silent Disable log output.\n\n *\n\n * @return True on success, false otherwise.\n\n */\n\n static bool ReadFile(const std::filesystem::path& filename, std::string& out_content, bool silent = false);\n\n\n\n /**\n\n * Load raw data from file (e.g. texture data)\n\n */\n", "file_path": "core/include/mmcore/utility/FileUtils.h", "rank": 91, "score": 183492.69925186058 }, { "content": "#include <vector>\n\n\n\n\n\nnamespace megamol {\n\nnamespace core {\n\nnamespace utility {\n\n\n\n// #### Utility string conversion functions ############################ //\n\n\n\nstatic inline std::string WChar2Utf8String(const std::wstring& wstr) {\n\n return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wstr);\n\n}\n\n\n\n// ##################################################################### //\n\n/**\n\n * File utility functions.\n\n */\n", "file_path": "core/include/mmcore/utility/FileUtils.h", "rank": 92, "score": 183491.30213626364 }, { "content": " */\n\n FileStreamProvider();\n\n\n\nprotected:\n\n /**\n\n * Callback function providing the stream.\n\n *\n\n * @return Stream\n\n */\n\n virtual std::iostream& GetStream() override;\n\n\n\nprivate:\n\n /** File path parameter */\n\n core::param::ParamSlot filePath;\n\n\n\n /** File path parameter */\n\n core::param::ParamSlot append;\n\n\n\n /** File stream */\n\n std::fstream stream;\n\n};\n\n\n\n} // namespace core\n\n} // namespace megamol\n", "file_path": "core/include/mmcore/FileStreamProvider.h", "rank": 93, "score": 183490.41379681465 }, { "content": " *\n\n * @param filename Path to the file to be opened\n\n * @param accessMode The access mode for the file to be opened\n\n * @param shareMode The share mode\n\n * (Parameter is ignored on linux systems.)\n\n * @param creationMode Use your imagination on this one\n\n *\n\n * @return false\n\n */\n\n virtual bool Open(const wchar_t* filename, const AccessMode accessMode, const ShareMode shareMode,\n\n const CreationMode creationMode);\n\n\n\n /** redeclare remaining Open overloads from file */\n\n using File::Open;\n\n\n\n /**\n\n * Read at most 'bufSize' bytes from the file into 'outBuf'.\n\n *\n\n * @param outBuf The buffer to receive the data.\n\n * @param bufSize The size of 'outBuf' in bytes.\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 94, "score": 183489.6526822085 }, { "content": "}\n\n\n\n\n\ntemplate<typename T>\n\nbool megamol::core::utility::FileUtils::FileWithExtensionExists(const T& path_str, const std::string& ext) {\n\n try {\n\n if (FileUtils::FileExists<T>(path_str)) {\n\n auto filepath = std::filesystem::u8path(path_str);\n\n return (filepath.extension().generic_u8string() == std::string(\".\" + ext));\n\n }\n\n } catch (std::filesystem::filesystem_error const& e) {\n\n megamol::core::utility::log::Log::DefaultLog.WriteError(\n\n \"Filesystem Error: %s [%s, %s, line %d]\\n\", e.what(), __FILE__, __FUNCTION__, __LINE__);\n\n }\n\n return false;\n\n}\n\n\n\n\n\ntemplate<typename T>\n\nbool megamol::core::utility::FileUtils::FileHasExtension(const T& path_str, const std::string& ext) {\n", "file_path": "core/include/mmcore/utility/FileUtils.h", "rank": 95, "score": 183489.4352882347 }, { "content": " */\n\n virtual FileSize Write(const void* buf, const FileSize bufSize);\n\n\n\nprivate:\n\n /**\n\n * Forbidden copy-ctor.\n\n *\n\n * @param rhs The object to be cloned.\n\n *\n\n * @throws UnsupportedOperationException Unconditionally.\n\n */\n\n MemoryFile(const MemoryFile& rhs);\n\n\n\n /**\n\n * Forbidden assignment.\n\n *\n\n * @param rhs The right hand side operand.\n\n *\n\n * @return *this.\n\n *\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 96, "score": 183489.34235495506 }, { "content": " virtual bool Open(RawStorage& storage, AccessMode accessMode);\n\n\n\n /**\n\n * Opens a file.\n\n * This method has no effect and will always return false.\n\n *\n\n * @param filename Path to the file to be opened\n\n * @param accessMode The access mode for the file to be opened\n\n * @param shareMode The share mode\n\n * (Parameter is ignored on linux systems.)\n\n * @param creationMode Use your imagination on this one\n\n *\n\n * @return false\n\n */\n\n virtual bool Open(\n\n const char* filename, const AccessMode accessMode, const ShareMode shareMode, const CreationMode creationMode);\n\n\n\n /**\n\n * Opens a file.\n\n * This method has no effect and will always return false.\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 97, "score": 183487.32821345428 }, { "content": " *\n\n * @return The number of bytes actually read.\n\n */\n\n virtual FileSize Read(void* outBuf, const FileSize bufSize);\n\n\n\n /**\n\n * Move the file pointer.\n\n *\n\n * If the file pointer is seeked beyond the end of file, the behaviour is\n\n * undefined for Read, Write, Tell and isEoF\n\n *\n\n * @param offset The offset in bytes.\n\n * @param from The begin of the seek operation, which can be one of\n\n * BEGIN, CURRENT, or END.\n\n *\n\n * @return The new offset in bytes of the file pointer from the begin of\n\n * the file.\n\n */\n\n virtual FileSize Seek(const FileOffset offset, const SeekStartPoint from = BEGIN);\n\n\n", "file_path": "vislib/include/vislib/sys/MemoryFile.h", "rank": 98, "score": 183486.89889586193 }, { "content": "/*\n\n * FileUtils.h\n\n *\n\n * Copyright (C) 2019 by Universitaet Stuttgart (VIS).\n\n * Alle Rechte vorbehalten.\n\n */\n\n\n\n#ifndef MEGAMOL_GUI_FILEUTILS_INCLUDED\n\n#define MEGAMOL_GUI_FILEUTILS_INCLUDED\n\n\n\n\n\n#include \"mmcore/utility/log/Log.h\"\n\n#include \"vislib/UTF8Encoder.h\"\n\n#include <codecvt>\n\n#include <filesystem>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <istream>\n\n#include <locale>\n\n#include <string>\n", "file_path": "core/include/mmcore/utility/FileUtils.h", "rank": 99, "score": 183486.5689197097 } ]
C++
external/include/mapnik/rule.hpp
Wujingli/OpenWebGlobeDataProcessing
932eaa00c81fc0571122bc618ade010fa255735e
#ifndef MAPNIK_RULE_HPP #define MAPNIK_RULE_HPP #include <mapnik/building_symbolizer.hpp> #include <mapnik/line_symbolizer.hpp> #include <mapnik/line_pattern_symbolizer.hpp> #include <mapnik/polygon_symbolizer.hpp> #include <mapnik/polygon_pattern_symbolizer.hpp> #include <mapnik/point_symbolizer.hpp> #include <mapnik/raster_symbolizer.hpp> #include <mapnik/shield_symbolizer.hpp> #include <mapnik/text_symbolizer.hpp> #include <mapnik/markers_symbolizer.hpp> #include <mapnik/debug_symbolizer.hpp> #include <mapnik/feature.hpp> #include <mapnik/expression.hpp> #include <mapnik/expression_string.hpp> #include <mapnik/config.hpp> #include <boost/variant/variant_fwd.hpp> #include <string> #include <vector> #include <limits> namespace mapnik { inline bool operator==(point_symbolizer const& lhs, point_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_symbolizer const& lhs, line_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_pattern_symbolizer const& lhs, line_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_symbolizer const& lhs, polygon_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_pattern_symbolizer const& lhs, polygon_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(raster_symbolizer const& lhs, raster_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(text_symbolizer const& lhs, text_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(shield_symbolizer const& lhs, shield_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(building_symbolizer const& lhs, building_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(markers_symbolizer const& lhs, markers_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(debug_symbolizer const& lhs, debug_symbolizer const& rhs) { return (&lhs == &rhs); } typedef boost::variant<point_symbolizer, line_symbolizer, line_pattern_symbolizer, polygon_symbolizer, polygon_pattern_symbolizer, raster_symbolizer, shield_symbolizer, text_symbolizer, building_symbolizer, markers_symbolizer, debug_symbolizer> symbolizer; class MAPNIK_DECL rule { public: typedef std::vector<symbolizer> symbolizers; private: std::string name_; double min_scale_; double max_scale_; symbolizers syms_; expression_ptr filter_; bool else_filter_; bool also_filter_; public: rule(); rule(std::string const& name, double min_scale_denominator = 0, double max_scale_denominator = std::numeric_limits<double>::infinity()); rule(const rule& rhs, bool deep_copy = false); rule& operator=(rule const& rhs); bool operator==(rule const& other); void set_max_scale(double scale); double get_max_scale() const; void set_min_scale(double scale); double get_min_scale() const; void set_name(std::string const& name); std::string const& get_name() const; void append(symbolizer const& sym); void remove_at(size_t index); const symbolizers& get_symbolizers() const; symbolizers::const_iterator begin() const; symbolizers::const_iterator end() const; symbolizers::iterator begin(); symbolizers::iterator end(); void set_filter(expression_ptr const& filter); expression_ptr const& get_filter() const; void set_else(bool else_filter); bool has_else_filter() const; void set_also(bool also_filter); bool has_also_filter() const; bool active(double scale) const; private: void swap(rule& rhs) throw(); }; } #endif
#ifndef MAPNIK_RULE_HPP #define MAPNIK_RULE_HPP #include <mapnik/building_symbolizer.hpp> #include <mapnik/line_sy
hield_symbolizer.hpp> #include <mapnik/text_symbolizer.hpp> #include <mapnik/markers_symbolizer.hpp> #include <mapnik/debug_symbolizer.hpp> #include <mapnik/feature.hpp> #include <mapnik/expression.hpp> #include <mapnik/expression_string.hpp> #include <mapnik/config.hpp> #include <boost/variant/variant_fwd.hpp> #include <string> #include <vector> #include <limits> namespace mapnik { inline bool operator==(point_symbolizer const& lhs, point_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_symbolizer const& lhs, line_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_pattern_symbolizer const& lhs, line_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_symbolizer const& lhs, polygon_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_pattern_symbolizer const& lhs, polygon_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(raster_symbolizer const& lhs, raster_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(text_symbolizer const& lhs, text_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(shield_symbolizer const& lhs, shield_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(building_symbolizer const& lhs, building_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(markers_symbolizer const& lhs, markers_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(debug_symbolizer const& lhs, debug_symbolizer const& rhs) { return (&lhs == &rhs); } typedef boost::variant<point_symbolizer, line_symbolizer, line_pattern_symbolizer, polygon_symbolizer, polygon_pattern_symbolizer, raster_symbolizer, shield_symbolizer, text_symbolizer, building_symbolizer, markers_symbolizer, debug_symbolizer> symbolizer; class MAPNIK_DECL rule { public: typedef std::vector<symbolizer> symbolizers; private: std::string name_; double min_scale_; double max_scale_; symbolizers syms_; expression_ptr filter_; bool else_filter_; bool also_filter_; public: rule(); rule(std::string const& name, double min_scale_denominator = 0, double max_scale_denominator = std::numeric_limits<double>::infinity()); rule(const rule& rhs, bool deep_copy = false); rule& operator=(rule const& rhs); bool operator==(rule const& other); void set_max_scale(double scale); double get_max_scale() const; void set_min_scale(double scale); double get_min_scale() const; void set_name(std::string const& name); std::string const& get_name() const; void append(symbolizer const& sym); void remove_at(size_t index); const symbolizers& get_symbolizers() const; symbolizers::const_iterator begin() const; symbolizers::const_iterator end() const; symbolizers::iterator begin(); symbolizers::iterator end(); void set_filter(expression_ptr const& filter); expression_ptr const& get_filter() const; void set_else(bool else_filter); bool has_else_filter() const; void set_also(bool also_filter); bool has_also_filter() const; bool active(double scale) const; private: void swap(rule& rhs) throw(); }; } #endif
mbolizer.hpp> #include <mapnik/line_pattern_symbolizer.hpp> #include <mapnik/polygon_symbolizer.hpp> #include <mapnik/polygon_pattern_symbolizer.hpp> #include <mapnik/point_symbolizer.hpp> #include <mapnik/raster_symbolizer.hpp> #include <mapnik/s
random
[]
C++
include/ensmallen_bits/problems/logistic_regression_function_impl.hpp
kilasuelika/ensmallen-eigen
d9df7ca4d0e519974d56441c132fb9326da4ea3d
#ifndef ENSMALLEN_PROBLEMS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP #define ENSMALLEN_PROBLEMS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP #include "logistic_regression_function.hpp" namespace ens { namespace test { template<typename MatType> LogisticRegressionFunction<MatType>::LogisticRegressionFunction( MatType& predictors, arma::Row<size_t>& responses, const double lambda) : predictors(predictors), responses(responses), lambda(lambda) { initialPoint = arma::Row<typename MatType::Scalar>(predictors.n_rows + 1, arma::fill::zeros); if (responses.n_elem != predictors.n_cols) { std::ostringstream oss; oss << "LogisticRegressionFunction::LogisticRegressionFunction(): " << "predictors matrix has " << predictors.n_cols << " points, but " << "responses vector has " << responses.n_elem << " elements (should be" << " " << predictors.n_cols << ")!" << std::endl; throw std::logic_error(oss.str()); } } template<typename MatType> LogisticRegressionFunction<MatType>::LogisticRegressionFunction( MatType& predictors, arma::Row<size_t>& responses, MatType& initialPoint, const double lambda) : initialPoint(initialPoint), predictors(predictors), responses(responses), lambda(lambda) { if (initialPoint.n_rows != (predictors.n_rows + 1) || initialPoint.n_cols != 1) this->initialPoint = arma::Row<typename MatType::Scalar>( predictors.n_rows + 1, arma::fill::zeros); } template<typename MatType> void LogisticRegressionFunction<MatType>::Shuffle() { MatType newPredictors; arma::Row<size_t> newResponses; arma::uvec ordering = arma::shuffle(arma::linspace<arma::uvec>(0, predictors.n_cols - 1, predictors.n_cols)); newPredictors.set_size(predictors.n_rows, predictors.n_cols); for (size_t i = 0; i < predictors.n_cols; ++i) newPredictors.col(i) = predictors.col(ordering[i]); newResponses = responses.cols(ordering); predictors = std::move(newPredictors); responses = std::move(newResponses); } template<typename MatType> typename MatType::Scalar LogisticRegressionFunction<MatType>::Evaluate( const MatType& parameters) const { typedef typename MatType::Scalar ElemType; const ElemType regularization = 0.5 * lambda * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoid = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors))); const ElemType result = arma::accu(arma::log(1.0 - arma::conv_to<arma::Row<ElemType>>::from(responses) + sigmoid % (2 * arma::conv_to<arma::Row<ElemType>>::from(responses) - 1.0))); return regularization - result; } template<typename MatType> typename MatType::Scalar LogisticRegressionFunction<MatType>::Evaluate( const MatType& parameters, const size_t begin, const size_t batchSize) const { typedef typename MatType::Scalar ElemType; const ElemType regularization = lambda * (batchSize / (2.0 * predictors.n_cols)) * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoid = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors.cols(begin, begin + batchSize - 1)))); arma::Row<ElemType> respD = arma::conv_to<arma::Row<ElemType>>::from( responses.subvec(begin, begin + batchSize - 1)); const ElemType result = arma::accu(arma::log(1.0 - respD + sigmoid % (2 * respD - 1.0))); return regularization - result; } template<typename MatType> template<typename GradType> void LogisticRegressionFunction<MatType>::Gradient( const MatType& parameters, GradType& gradient) const { typedef typename MatType::Scalar ElemType; MatType regularization; regularization = lambda * parameters.tail_cols(parameters.n_elem - 1); const arma::Row<ElemType> sigmoids = (1 / (1 + arma::exp(-parameters(0, 0) - parameters.tail_cols(parameters.n_elem - 1) * predictors))); gradient.set_size(arma::size(parameters)); gradient[0] = -arma::accu(responses - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses) * predictors.t() + regularization; } template<typename MatType> template<typename GradType> void LogisticRegressionFunction<MatType>::Gradient( const MatType& parameters, const size_t begin, GradType& gradient, const size_t batchSize) const { typedef typename MatType::Scalar ElemType; MatType regularization; regularization = lambda * parameters.tail_cols(parameters.n_elem - 1) / predictors.n_cols * batchSize; const arma::Row<ElemType> exponents = parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors.cols(begin, begin + batchSize - 1); const arma::Row<ElemType> sigmoids = 1.0 / (1.0 + arma::exp(-exponents)); gradient.set_size(parameters.n_rows, parameters.n_cols); gradient[0] = -arma::accu(responses.subvec(begin, begin + batchSize - 1) - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses.subvec(begin, begin + batchSize - 1)) * predictors.cols(begin, begin + batchSize - 1).t() + regularization; } template <typename MatType> void LogisticRegressionFunction<MatType>::PartialGradient( const MatType& parameters, const size_t j, arma::sp_mat& gradient) const { const arma::Row<typename MatType::Scalar> diffs = responses - (1 / (1 + arma::exp(-parameters(0, 0) - parameters.tail_cols(parameters.n_elem - 1) * predictors))); gradient.set_size(arma::size(parameters)); if (j == 0) { gradient[j] = -arma::accu(diffs); } else { gradient[j] = arma::dot(-predictors.row(j - 1), diffs) + lambda * parameters(0, j); } } template<typename MatType> template<typename GradType> typename MatType::Scalar LogisticRegressionFunction<MatType>::EvaluateWithGradient( const MatType& parameters, GradType& gradient) const { typedef typename MatType::Scalar ElemType; MatType regularization = lambda * parameters.tail_cols(parameters.n_elem - 1); const ElemType objectiveRegularization = lambda / 2.0 * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoids = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors))); gradient.set_size(arma::size(parameters)); gradient[0] = -arma::accu(responses - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses) * predictors.t() + regularization; ElemType result = arma::accu(arma::log(1.0 - arma::conv_to<arma::Row<ElemType>>::from(responses) + sigmoids % (2 * arma::conv_to<arma::Row<ElemType>>::from(responses) - 1.0))); return objectiveRegularization - result; } template<typename MatType> template<typename GradType> typename MatType::Scalar LogisticRegressionFunction<MatType>::EvaluateWithGradient( const MatType& parameters, const size_t begin, GradType& gradient, const size_t batchSize) const { typedef typename MatType::Scalar ElemType; MatType regularization = lambda * parameters.tail_cols(parameters.n_elem - 1) / predictors.n_cols * batchSize; const ElemType objectiveRegularization = lambda * (batchSize / (2.0 * predictors.n_cols)) * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoids = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors.cols(begin, begin + batchSize - 1)))); gradient.set_size(parameters.n_rows, parameters.n_cols); gradient[0] = -arma::accu(responses.subvec(begin, begin + batchSize - 1) - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses.subvec(begin, begin + batchSize - 1)) * predictors.cols(begin, begin + batchSize - 1).t() + regularization; arma::Row<ElemType> respD = arma::conv_to<arma::Row<ElemType>>::from( responses.subvec(begin, begin + batchSize - 1)); const ElemType result = arma::accu(arma::log(1.0 - respD + sigmoids % (2 * respD - 1.0))); return objectiveRegularization - result; } template<typename MatType> void LogisticRegressionFunction<MatType>::Classify( const MatType& dataset, arma::Row<size_t>& labels, const MatType& parameters, const double decisionBoundary) const { labels = arma::conv_to<arma::Row<size_t>>::from((1.0 / (1.0 + arma::exp(-parameters(0) - parameters.tail_cols(parameters.n_elem - 1) * dataset))) + (1.0 - decisionBoundary)); } template<typename MatType> double LogisticRegressionFunction<MatType>::ComputeAccuracy( const MatType& predictors, const arma::Row<size_t>& responses, const MatType& parameters, const double decisionBoundary) const { arma::Row<size_t> tempResponses; Classify(predictors, tempResponses, parameters, decisionBoundary); size_t count = 0; for (size_t i = 0; i < responses.n_elem; i++) { if (responses(i) == tempResponses(i)) count++; } return (double) (count * 100) / responses.n_elem; } } } #endif
#ifndef ENSMALLEN_PROBLEMS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP #define ENSMALLEN_PROBLEMS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP #include "logistic_regression_function.hpp" namespace ens { namespace test { template<typename MatType> LogisticRegressionFunction<MatType>::LogisticRegressionFunction( MatType& predictors, arma::Row<size_t>& responses, const double lambda) : predictors(predictors), responses(responses), lambda(lambda) { initialPoint = arma::Row<typename MatType::Scalar>(predictors.n_rows + 1, arma::fill::zeros); if (responses.n_elem != predictors.n_cols) { std::ostringstream oss; oss << "LogisticRegressionFunction::LogisticRegressionFunction(): " << "predictors matrix has " << predictors.n_cols << " points, but " << "responses vector has " << responses.n_elem << " elements (should be" << " " << predictors.n_cols << ")!" << std::endl; throw std::logic_error(oss.str()); } } template<typename MatType> LogisticRegressionFunction<MatType>::LogisticRegressionFunction( MatType& predictors, arma::Row<size_t>& responses, MatType& initialPoint, const double lambda) : initialPoint(initialPoint), predictors(predictors), responses(responses), lambda(lambda) { if (initialPoint.n_rows != (predictors.n_rows + 1) || initialPoint.n_cols != 1) this->initialPoint = arma::Row<typename MatType::Scalar>( predictors.n_rows + 1, arma::fill::zeros); } template<typename MatType> void LogisticRegressionFunction<MatType>::Shuffle() { MatType newPredictors; arma::Row<size_t> newResponses; arma::uvec ordering = arma::shuffle(arma::linspace<arma::uvec>(0, predictors.n_cols - 1, predictors.n_cols)); newPredictors.set_size(predictors.n_rows, predictors.n_cols); for (size_t i = 0; i < predictors.n_cols; ++i) newPredictors.col(i) = predictors.col(ordering[i]); newResponses = responses.cols(ordering); predictors = std::move(newPredictors); responses = std::move(newResponses); } template<typename MatType> typename MatType::Scalar LogisticRegressionFunction<MatType>::Evaluate( const MatType& parameters) const { typedef typename MatType::Scalar ElemType; const ElemType regularization = 0.5 * lambda * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoid = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors))); const ElemType result = arma::accu(arma::log(1.0 - arma::conv_to<arma::Row<ElemType>>::from(responses) + sigmoid % (2 * arma::conv_to<arma::Row<ElemType>>::from(responses) - 1.0))); return regularization - result; } template<typename MatType> typename MatType::Scalar LogisticRegressionFunction<MatType>::Evaluate( const MatType& parameters, const size_t begin, const size_t batchSize) const { typedef typename MatType::Scalar ElemType; const ElemType regularization = lambda * (batchSize / (2.0 * predictors.n_cols)) * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoid = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors.cols(begin, begin + batchSize - 1)))); arma::Row<ElemType> respD = arma::conv_to<arma::Row<ElemType>>::from( responses.subvec(begin, begin + batchSize - 1)); const ElemType result = arma::accu(arma::log(1.0 - respD + sigmoid % (2 * respD - 1.0))); return regularization - result; } template<typename MatType> template<typename GradType> void LogisticRegressionFunction<MatType>::Gradient( const MatType& parameters, GradType& gradient) const { typedef typename MatType::Scalar ElemType; MatType regularization; regularization = lambda * parameters.tail_cols(parameters.n_elem - 1); const arma::Row<ElemType> sigmoids = (1 / (1 + arma::exp(-parameters(0, 0) - parameters.tail_cols(parameters.n_elem - 1) * predictors))); gradient.set_size(arma::size(parameters)); gradient[0] = -arma::accu(responses - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses) * predictors.t() + regularization; } template<typename MatType> template<typename GradType> void LogisticRegressionFunction<MatType>::Gradient( const MatType& parameters, const size_t begin, GradType& gradient, const size_t batchSize) const { typedef typename MatType::Scalar ElemType; MatType regularization; regularization = lambda * parameters.tail_cols(parameters.n_elem - 1) / predictors.n_cols * batchSize; const arma::Row<ElemType> exponents = parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors.cols(begin, begin + batchSize - 1); const arma::Row<ElemType> sigmoids = 1.0 / (1.0 + arma::exp(-exponents)); gradient.set_size(parameters.n_rows, parameters.n_cols); gradient[0] = -arma::accu(responses.subvec(begin, begin + batchSize - 1) - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses.subvec(begin, begin + batchSize - 1)) * predictors.cols(begin, begin + batchSize - 1).t() + regularization; } template <typename MatType> void LogisticRegressionFunction<MatType>::PartialGradient( const MatType& parameters, const size_t j, arma::sp_mat& gradient) const { const arma::Row<typename MatType::Scalar> diffs = responses - (1 / (1 + arma::exp(-parameters(0, 0) - parameters.tail_cols(parameters.n_elem - 1) * predictors))); gradient.set_size(arma::size(parameters)); if (j == 0) { gradient[j] = -arma::accu(diffs); } else { gradient[j] = arma::dot(-predictors.row(j - 1), diffs) + lambda * parameters(0, j); } } template<typename MatType> template<typename GradType> typename MatType::Scalar LogisticRegressionFunction<MatType>::EvaluateWithGradient( const MatType& parameters, GradType& gradient) const { typedef typename MatType::Scalar ElemType; MatType regularization = lambda * parameters.tail_cols(parameters.n_elem - 1); const ElemType objectiveRegularization = lambda / 2.0 * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoids = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors))); gradient.set_size(arma::size(parameters)); gradient[0] = -arma::accu(responses - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses) * predictors.t() + regularization; ElemType result =
; return objectiveRegularization - result; } template<typename MatType> template<typename GradType> typename MatType::Scalar LogisticRegressionFunction<MatType>::EvaluateWithGradient( const MatType& parameters, const size_t begin, GradType& gradient, const size_t batchSize) const { typedef typename MatType::Scalar ElemType; MatType regularization = lambda * parameters.tail_cols(parameters.n_elem - 1) / predictors.n_cols * batchSize; const ElemType objectiveRegularization = lambda * (batchSize / (2.0 * predictors.n_cols)) * arma::dot(parameters.tail_cols(parameters.n_elem - 1), parameters.tail_cols(parameters.n_elem - 1)); const arma::Row<ElemType> sigmoids = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + parameters.tail_cols(parameters.n_elem - 1) * predictors.cols(begin, begin + batchSize - 1)))); gradient.set_size(parameters.n_rows, parameters.n_cols); gradient[0] = -arma::accu(responses.subvec(begin, begin + batchSize - 1) - sigmoids); gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses.subvec(begin, begin + batchSize - 1)) * predictors.cols(begin, begin + batchSize - 1).t() + regularization; arma::Row<ElemType> respD = arma::conv_to<arma::Row<ElemType>>::from( responses.subvec(begin, begin + batchSize - 1)); const ElemType result = arma::accu(arma::log(1.0 - respD + sigmoids % (2 * respD - 1.0))); return objectiveRegularization - result; } template<typename MatType> void LogisticRegressionFunction<MatType>::Classify( const MatType& dataset, arma::Row<size_t>& labels, const MatType& parameters, const double decisionBoundary) const { labels = arma::conv_to<arma::Row<size_t>>::from((1.0 / (1.0 + arma::exp(-parameters(0) - parameters.tail_cols(parameters.n_elem - 1) * dataset))) + (1.0 - decisionBoundary)); } template<typename MatType> double LogisticRegressionFunction<MatType>::ComputeAccuracy( const MatType& predictors, const arma::Row<size_t>& responses, const MatType& parameters, const double decisionBoundary) const { arma::Row<size_t> tempResponses; Classify(predictors, tempResponses, parameters, decisionBoundary); size_t count = 0; for (size_t i = 0; i < responses.n_elem; i++) { if (responses(i) == tempResponses(i)) count++; } return (double) (count * 100) / responses.n_elem; } } } #endif
arma::accu(arma::log(1.0 - arma::conv_to<arma::Row<ElemType>>::from(responses) + sigmoids % (2 * arma::conv_to<arma::Row<ElemType>>::from(responses) - 1.0)))
call_expression
[ { "content": "//! Very, very simple test function which is the composite of three other\n\n//! functions. The gradient is not very steep far away from the optimum, so a\n\n//! larger step size may be required to optimize it in a reasonable number of\n\n//! iterations.\n\nclass GDTestFunction\n\n{\n\n public:\n\n //! Nothing to do for the constructor.\n\n GDTestFunction() { }\n\n\n\n //! Get the starting point.\n\n template<typename MatType>\n\n MatType GetInitialPoint() const { return MatType(\"1; 3; 2\"); }\n\n\n\n //! Evaluate a function.\n\n template<typename MatType>\n\n typename MatType::Scalar Evaluate(const MatType& coordinates) const;\n\n\n\n //! Evaluate the gradient of a function.\n\n template<typename MatType, typename GradType>\n\n void Gradient(const MatType& coordinates, GradType& gradient) const;\n\n};\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n#include \"gradient_descent_test_function_impl.hpp\"\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/gradient_descent_test_function.hpp", "rank": 0, "score": 118722.01830161925 }, { "content": "/**\n\n * @file gradient_descent_test_function.hpp\n\n * @author Sumedh Ghaisas\n\n *\n\n * Very simple test function for SGD.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_GRADIENT_DESCENT_TEST_FUNCTION_HPP\n\n#define ENSMALLEN_PROBLEMS_GRADIENT_DESCENT_TEST_FUNCTION_HPP\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n\n//! Very, very simple test function which is the composite of three other\n\n//! functions. The gradient is not very steep far away from the optimum, so a\n\n//! larger step size may be required to optimize it in a reasonable number of\n\n//! iterations.\n", "file_path": "include/ensmallen_bits/problems/gradient_descent_test_function.hpp", "rank": 1, "score": 115167.73619501542 }, { "content": "inline typename MatType::Scalar GDTestFunction::Evaluate(\n\n const MatType& coordinates) const\n\n{\n\n MatType temp = arma::trans(coordinates) * coordinates;\n\n return temp(0, 0);\n\n}\n\n\n\ntemplate<typename MatType, typename GradType>\n\ninline void GDTestFunction::Gradient(const MatType& coordinates,\n\n GradType& gradient) const\n\n{\n\n gradient = 2 * coordinates;\n\n}\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/gradient_descent_test_function_impl.hpp", "rank": 2, "score": 112215.72971246284 }, { "content": "/**\n\n * @file gradient_descent_test_function_impl.hpp\n\n * @author Sumedh Ghaisas\n\n *\n\n * Implementation of very simple test function for gradient descent.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_GRADIENT_DESCENT_TEST_FUNCTION_IMPL_HPP\n\n#define ENSMALLEN_PROBLEMS_GRADIENT_DESCENT_TEST_FUNCTION_IMPL_HPP\n\n\n\n#include \"gradient_descent_test_function.hpp\"\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n\ntemplate<typename MatType>\n", "file_path": "include/ensmallen_bits/problems/gradient_descent_test_function_impl.hpp", "rank": 3, "score": 112213.90492108045 }, { "content": "#include \"../../include/ensmallen_bits/problems/ackley_function.hpp\"\n\n\n\n\n\nusing namespace ens;\n\nusing namespace ens::test;\n\nusing namespace std;\n\nusing namespace Eigen;\n\n\n\nint main(){\n\n\tAckleyFunction f;\n\n\tauto init=f.GetInitialPoint();\n\n\t\n\n\tGradientDescent opt;\n\n\topt.Optimize(f,init);\n\n\tcout<<\"Solution:\"<<endl<<init<<endl;\n\n\tcout<<\"Objective value: \"<<f.Evaluate(init)<<endl;\n\n\tVectorXd g=init;\n\n\tf.Gradient(init,g);\n\n\tcout<<\"Gradien: \"<<g<<endl;\n\n\t\n\n\tVectorXd s(2);\n\n\ts<<0,0;\n\n\tcout<<\"Target solution:\"<<endl<<s<<endl;\n\n\tcout<<\"Objective value: \"<<f.Evaluate(s)<<endl;\n\n}", "file_path": "tests/gradient_descent_test/main.cpp", "rank": 4, "score": 101561.84577365202 }, { "content": "/**\n\n * @file main.cpp\n\n * @author Zhou Yao\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n\n\n#include<numeric>\n\n#include<Eigen/Core>\n\n\n\n\n\n#include<cmath>\n\n#include<iostream>\n\n\n\n#include \"../../include/ensmallen_bits/eigen_helper/Rand.hpp\"\n\n\n\n#include \"../../include/ensmallen_bits/gradient_descent/gradient_descent.hpp\"\n", "file_path": "tests/gradient_descent_test/main.cpp", "rank": 5, "score": 101541.52877161106 }, { "content": "#include \"../../include/ensmallen_bits/problems/ackley_function.hpp\"\n\n\n\n\n\nusing namespace ens;\n\nusing namespace ens::test;\n\nusing namespace std;\n\nusing namespace Eigen;\n\n\n\nint main(){\n\n\tAckleyFunction f;\n\n\tauto init=f.GetInitialPoint();\n\n\t\n\n\tGradientDescent opt;\n\n\topt.Optimize(f,init);\n\n\tcout<<\"Solution:\"<<endl<<init<<endl;\n\n\tcout<<\"Objective value: \"<<f.Evaluate(init)<<endl;\n\n\tVectorXd g=init;\n\n\tf.Gradient(init,g);\n\n\tcout<<\"Gradient: \"<<g<<endl;\n\n\t\n\n\tVectorXd s(2);\n\n\ts<<0,0;\n\n\tcout<<\"Target solution:\"<<endl<<s<<endl;\n\n\tcout<<\"Objective value: \"<<f.Evaluate(s)<<endl;\n\n}", "file_path": "tests/template/main.cpp", "rank": 6, "score": 96567.983879243 }, { "content": "/**\n\n * @file main.cpp\n\n * @author Zhou Yao\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n\n\n#include<numeric>\n\n#include<Eigen/Core>\n\n\n\n\n\n#include<cmath>\n\n#include<iostream>\n\n\n\n#include \"../../include/ensmallen_bits/eigen_helper/Rand.hpp\"\n\n\n\n#include \"../../include/ensmallen_bits/gradient_descent/gradient_descent.hpp\"\n", "file_path": "tests/template/main.cpp", "rank": 7, "score": 96547.08328693474 }, { "content": "class GradientDescent\n\n{\n\n public:\n\n /**\n\n * Construct the Gradient Descent optimizer with the given function and\n\n * parameters. The defaults here are not necessarily good for the given\n\n * problem, so it is suggested that the values used be tailored to the task\n\n * at hand.\n\n *\n\n * @param function Function to be optimized (minimized).\n\n * @param stepSize Step size for each iteration.\n\n * @param maxIterations Maximum number of iterations allowed (0 means no\n\n * limit).\n\n * @param tolerance Maximum absolute tolerance to terminate algorithm.\n\n */\n\n GradientDescent(const double stepSize = 0.01,\n\n const size_t maxIterations = 100000,\n\n const double tolerance = 1e-5);\n\n\n\n /**\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 8, "score": 89120.65546320021 }, { "content": " * Assert all dimensions are numeric and optimize the given function using\n\n * gradient descent. The given starting point will be modified to store the\n\n * finishing point of the algorithm, and the final objective value is\n\n * returned.\n\n *\n\n * This overload is intended to be used primarily by the hyper-parameter\n\n * tuning module.\n\n *\n\n * @tparam FunctionType Type of the function to optimize.\n\n * @tparam MatType Type of matrix to optimize with.\n\n * @tparam GradType Type of matrix to use to represent function gradients.\n\n * @tparam CallbackTypes Types of callback functions.\n\n * @param function Function to optimize.\n\n * @param iterate Starting point (will be modified).\n\n * @param categoricalDimensions A vector of dimension information. If a value\n\n * is true, then that dimension is a categorical dimension.\n\n * @param numCategories Number of categories in each categorical dimension.\n\n * @param callbacks Callback functions.\n\n * @return Objective value of the final point.\n\n */\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 9, "score": 86994.55278797398 }, { "content": " * Optimize the given function using gradient descent. The given starting\n\n * point will be modified to store the finishing point of the algorithm, and\n\n * the final objective value is returned.\n\n *\n\n * @tparam FunctionType Type of the function to optimize.\n\n * @tparam MatType Type of matrix to optimize with.\n\n * @tparam GradType Type of matrix to use to represent function gradients.\n\n * @tparam CallbackTypes Types of callback functions.\n\n * @param function Function to optimize.\n\n * @param iterate Starting point (will be modified).\n\n * @param callbacks Callback functions.\n\n * @return Objective value of the final point.\n\n */\n\n template<typename FunctionType,\n\n typename MatType>\n\n typename MatType::Scalar\n\n Optimize(FunctionType& function,\n\n MatType& iterate);\n\n\n\n /**\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 10, "score": 86992.11859719071 }, { "content": " //! Modify the tolerance for termination.\n\n double& Tolerance() { return tolerance; }\n\n\n\n private:\n\n //! The step size for each example.\n\n double stepSize;\n\n\n\n //! The maximum number of allowed iterations.\n\n size_t maxIterations;\n\n\n\n //! The tolerance for termination.\n\n double tolerance;\n\n};\n\n\n\n} // namespace ens\n\n\n\n#include \"gradient_descent_impl.hpp\"\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 11, "score": 86992.02109079485 }, { "content": "/**\n\n * @file gradient_descent.hpp\n\n * @author Sumedh Ghaisas\n\n *\n\n * Simple Gradient Descent.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_GRADIENT_DESCENT_GRADIENT_DESCENT_HPP\n\n#define ENSMALLEN_GRADIENT_DESCENT_GRADIENT_DESCENT_HPP\n\n\n\nnamespace ens {\n\n\n\n/**\n\n * Gradient Descent is a technique to minimize a function. To find a local\n\n * minimum of a function using gradient descent, one takes steps proportional\n\n * to the negative of the gradient of the function at the current point,\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 12, "score": 86990.89466140643 }, { "content": " * producing the following update scheme:\n\n *\n\n * \\f[\n\n * A_{j + 1} = A_j + \\alpha \\nabla F(A)\n\n * \\f]\n\n *\n\n * where \\f$ \\alpha \\f$ is a parameter which specifies the step size. \\f$ F \\f$\n\n * is the function being optimized. The algorithm continues until \\f$ j\n\n * \\f$ reaches the maximum number of iterations---or when an update produces\n\n * an improvement within a certain tolerance \\f$ \\epsilon \\f$. That is,\n\n *\n\n * \\f[\n\n * | F(A_{j + 1}) - F(A_j) | < \\epsilon.\n\n * \\f]\n\n *\n\n * The parameter \\f$\\epsilon\\f$ is specified by the tolerance parameter to the\n\n * constructor.\n\n *\n\n * GradientDescent can optimize differentiable functions. For more details, see\n\n * the documentation on function types included with this distribution or on the\n\n * ensmallen website.\n\n */\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 13, "score": 86987.90087920519 }, { "content": " template<typename FunctionType,\n\n typename MatType>\n\n typename MatType::Scalar::type\n\n Optimize(FunctionType& function,\n\n MatType& iterate,\n\n const std::vector<bool>& categoricalDimensions,\n\n const Eigen::VectorXi& numCategories);\n\n\n\n //! Get the step size.\n\n double StepSize() const { return stepSize; }\n\n //! Modify the step size.\n\n double& StepSize() { return stepSize; }\n\n\n\n //! Get the maximum number of iterations (0 indicates no limit).\n\n size_t MaxIterations() const { return maxIterations; }\n\n //! Modify the maximum number of iterations (0 indicates no limit).\n\n size_t& MaxIterations() { return maxIterations; }\n\n\n\n //! Get the tolerance for termination.\n\n double Tolerance() const { return tolerance; }\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent.hpp", "rank": 14, "score": 86982.97036794305 }, { "content": " }\n\n\n\n if (numCategories.rows() != iterate.rows())\n\n {\n\n std::ostringstream oss;\n\n oss << \"GradientDescent::Optimize(): expected numCategories to have length \"\n\n << \"equal to number of dimensions (\" << iterate.n_rows << \") but it has\"\n\n << \" length \" << numCategories.rows();\n\n throw std::invalid_argument(oss.str());\n\n }\n\n\n\n for (size_t i = 0; i < categoricalDimensions.size(); ++i)\n\n {\n\n if (categoricalDimensions[i])\n\n {\n\n std::ostringstream oss;\n\n oss << \"GradientDescent::Optimize(): the dimension \" << i\n\n << \"is not numeric\" << std::endl;\n\n throw std::invalid_argument(oss.str());\n\n }\n\n }\n\n\n\n return Optimize(function, iterate);\n\n}\n\n\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent_impl.hpp", "rank": 15, "score": 85218.2235066041 }, { "content": " << \") reached; \" << \"terminating optimization.\" << std::endl;\n\n\n\n return overallObjective;\n\n}\n\n\n\n template<typename FunctionType,\n\n typename MatType>\n\n typename MatType::Scalar::type\n\n GradientDescent::Optimize(FunctionType& function,\n\n MatType& iterate,\n\n const std::vector<bool>& categoricalDimensions,\n\n const Eigen::VectorXi& numCategories)\n\n{\n\n if (categoricalDimensions.size() != iterate.rows())\n\n {\n\n std::ostringstream oss;\n\n oss << \"GradientDescent::Optimize(): expected information about \"\n\n << iterate.n_rows << \" dimensions in categoricalDimensions, \"\n\n << \"but got \" << categoricalDimensions.size();\n\n throw std::invalid_argument(oss.str());\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent_impl.hpp", "rank": 16, "score": 85218.16659956479 }, { "content": "/**\n\n * @file gradient_descent_impl.hpp\n\n * @author Sumedh Ghaisas\n\n * @author Zhou Yao\n\n * Simple gradient descent implementation.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_GRADIENT_DESCENT_GRADIENT_DESCENT_IMPL_HPP\n\n#define ENSMALLEN_GRADIENT_DESCENT_GRADIENT_DESCENT_IMPL_HPP\n\n\n\n// In case it hasn't been included yet.\n\n#include \"gradient_descent.hpp\"\n\n\n\nnamespace ens {\n\n\n\n//! Constructor.\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent_impl.hpp", "rank": 17, "score": 85217.31509365865 }, { "content": "inline GradientDescent::GradientDescent(\n\n const double stepSize,\n\n const size_t maxIterations,\n\n const double tolerance) :\n\n stepSize(stepSize),\n\n maxIterations(maxIterations),\n\n tolerance(tolerance)\n\n{ /* Nothing to do. */ }\n\n\n\n//! Optimize the function (minimize).\n\n template<typename FunctionType,\n\n typename MatType>\n\n typename MatType::Scalar\n\n GradientDescent::Optimize(FunctionType& function,\n\n MatType& iterate)\n\n{\n\n // Convenience typedefs.\n\n typedef typename MatType::Scalar ElemType;\n\n\n\n // To keep track of where we are and how things are going.\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent_impl.hpp", "rank": 18, "score": 85208.81825884516 }, { "content": " ElemType overallObjective = std::numeric_limits<ElemType>::max();\n\n ElemType lastObjective = std::numeric_limits<ElemType>::max();\n\n\n\n MatType gradient(iterate.rows());\n\n\n\n for (size_t i = 1; i != maxIterations; ++i)\n\n {\n\n overallObjective = function.EvaluateWithGradient(iterate, gradient);\n\n\n\n\n\n // Output current objective function.\n\n std::cout << \"Gradient Descent: iteration \" << i << \", objective \"\n\n << overallObjective << \".\" << std::endl;\n\n\n\n if (std::isnan(overallObjective) || std::isinf(overallObjective))\n\n {\n\n std::cout << \"Gradient Descent: converged to \" << overallObjective\n\n << \"; terminating\" << \" with failure. Try a smaller step size?\"\n\n << std::endl;\n\n\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent_impl.hpp", "rank": 19, "score": 85205.86335453167 }, { "content": " return overallObjective;\n\n }\n\n\n\n if (std::abs(lastObjective - overallObjective) < tolerance)\n\n {\n\n std::cout << \"Gradient Descent: minimized within tolerance \"\n\n << tolerance << \"; \" << \"terminating optimization.\" << std::endl;\n\n\n\n return overallObjective;\n\n }\n\n\n\n // Reset the counter variables.\n\n lastObjective = overallObjective;\n\n\n\n // And update the iterate.\n\n iterate -= stepSize * gradient;\n\n\n\n }\n\n\n\n std::cout << \"Gradient Descent: maximum iterations (\" << maxIterations\n", "file_path": "include/ensmallen_bits/gradient_descent/gradient_descent_impl.hpp", "rank": 20, "score": 85205.67062592084 }, { "content": "\n\n# elif defined(__OS2__)\n\n# define PLATFORM_ID \"OS2\"\n\n\n\n# elif defined(__WINDOWS__)\n\n# define PLATFORM_ID \"Windows3x\"\n\n\n\n# else /* unknown platform */\n\n# define PLATFORM_ID\n\n# endif\n\n\n\n#elif defined(__INTEGRITY)\n\n# if defined(INT_178B)\n\n# define PLATFORM_ID \"Integrity178\"\n\n\n\n# else /* regular Integrity */\n\n# define PLATFORM_ID \"Integrity\"\n\n# endif\n\n\n\n#else /* unknown platform */\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 21, "score": 82946.42574559362 }, { "content": " require += info_platform[argc];\n\n#ifdef COMPILER_VERSION_MAJOR\n\n require += info_version[argc];\n\n#endif\n\n#ifdef COMPILER_VERSION_INTERNAL\n\n require += info_version_internal[argc];\n\n#endif\n\n#ifdef SIMULATE_ID\n\n require += info_simulate[argc];\n\n#endif\n\n#ifdef SIMULATE_VERSION_MAJOR\n\n require += info_simulate_version[argc];\n\n#endif\n\n#if defined(__CRAYXE) || defined(__CRAYXC)\n\n require += info_cray[argc];\n\n#endif\n\n require += info_language_dialect_default[argc];\n\n (void)argv;\n\n return require;\n\n}\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 22, "score": 82945.89861528043 }, { "content": "\n\n\n\n\n\n\n\n#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L\n\n# if defined(__INTEL_CXX11_MODE__)\n\n# if defined(__cpp_aggregate_nsdmi)\n\n# define CXX_STD 201402L\n\n# else\n\n# define CXX_STD 201103L\n\n# endif\n\n# else\n\n# define CXX_STD 199711L\n\n# endif\n\n#elif defined(_MSC_VER) && defined(_MSVC_LANG)\n\n# define CXX_STD _MSVC_LANG\n\n#else\n\n# define CXX_STD __cplusplus\n\n#endif\n\n\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 23, "score": 82942.26056377574 }, { "content": "\n\n/* Construct the string literal in pieces to prevent the source from\n\n getting matched. Store it in a pointer rather than an array\n\n because some compilers will just produce instructions to fill the\n\n array rather than assigning a pointer to a static array. */\n\nchar const* info_compiler = \"INFO\" \":\" \"compiler[\" COMPILER_ID \"]\";\n\n#ifdef SIMULATE_ID\n\nchar const* info_simulate = \"INFO\" \":\" \"simulate[\" SIMULATE_ID \"]\";\n\n#endif\n\n\n\n#ifdef __QNXNTO__\n\nchar const* qnxnto = \"INFO\" \":\" \"qnxnto[]\";\n\n#endif\n\n\n\n#if defined(__CRAYXE) || defined(__CRAYXC)\n\nchar const *info_cray = \"INFO\" \":\" \"compiler_wrapper[CrayPrgEnv]\";\n\n#endif\n\n\n\n#define STRINGIFY_HELPER(X) #X\n\n#define STRINGIFY(X) STRINGIFY_HELPER(X)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 24, "score": 82942.26056377574 }, { "content": "# endif\n\n\n\n#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)\n\n# define COMPILER_ID \"Embarcadero\"\n\n# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)\n\n# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)\n\n# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF)\n\n\n\n#elif defined(__BORLANDC__)\n\n# define COMPILER_ID \"Borland\"\n\n /* __BORLANDC__ = 0xVRR */\n\n# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)\n\n# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)\n\n\n\n#elif defined(__WATCOMC__) && __WATCOMC__ < 1200\n\n# define COMPILER_ID \"Watcom\"\n\n /* __WATCOMC__ = VVRR */\n\n# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)\n\n# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)\n\n# if (__WATCOMC__ % 10) > 0\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 25, "score": 82942.26056377574 }, { "content": "# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000)\n\n# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000)\n\n# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__)\n\n# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__))\n\n# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100)\n\n# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100))\n\n# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__)\n\n# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__)\n\n# endif\n\n\n\n\n\n/* These compilers are either not known or too old to define an\n\n identification macro. Try to identify the platform and guess that\n\n it is the native compiler. */\n\n#elif defined(__hpux) || defined(__hpua)\n\n# define COMPILER_ID \"HP\"\n\n\n\n#else /* unknown compiler */\n\n# define COMPILER_ID \"\"\n\n#endif\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 26, "score": 82942.26056377574 }, { "content": "\n\n#elif defined(__clang__)\n\n# define COMPILER_ID \"Clang\"\n\n# if defined(_MSC_VER)\n\n# define SIMULATE_ID \"MSVC\"\n\n# endif\n\n# define COMPILER_VERSION_MAJOR DEC(__clang_major__)\n\n# define COMPILER_VERSION_MINOR DEC(__clang_minor__)\n\n# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)\n\n# if defined(_MSC_VER)\n\n /* _MSC_VER = VVRR */\n\n# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)\n\n# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)\n\n# endif\n\n\n\n#elif defined(__GNUC__) || defined(__GNUG__)\n\n# define COMPILER_ID \"GNU\"\n\n# if defined(__GNUC__)\n\n# define COMPILER_VERSION_MAJOR DEC(__GNUC__)\n\n# else\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 27, "score": 82942.26056377574 }, { "content": "# else /* unknown architecture */\n\n# define ARCHITECTURE_ID \"\"\n\n# endif\n\n\n\n#elif defined(__ghs__)\n\n# if defined(__PPC64__)\n\n# define ARCHITECTURE_ID \"PPC64\"\n\n\n\n# elif defined(__ppc__)\n\n# define ARCHITECTURE_ID \"PPC\"\n\n\n\n# elif defined(__ARM__)\n\n# define ARCHITECTURE_ID \"ARM\"\n\n\n\n# elif defined(__x86_64__)\n\n# define ARCHITECTURE_ID \"x64\"\n\n\n\n# elif defined(__i386__)\n\n# define ARCHITECTURE_ID \"X86\"\n\n\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 28, "score": 82942.26056377574 }, { "content": "# define ARCHITECTURE_ID \"RH850\"\n\n\n\n# elif defined(__ICCRL78__)\n\n# define ARCHITECTURE_ID \"RL78\"\n\n\n\n# elif defined(__ICCRISCV__)\n\n# define ARCHITECTURE_ID \"RISCV\"\n\n\n\n# elif defined(__ICCAVR__)\n\n# define ARCHITECTURE_ID \"AVR\"\n\n\n\n# elif defined(__ICC430__)\n\n# define ARCHITECTURE_ID \"MSP430\"\n\n\n\n# elif defined(__ICCV850__)\n\n# define ARCHITECTURE_ID \"V850\"\n\n\n\n# elif defined(__ICC8051__)\n\n# define ARCHITECTURE_ID \"8051\"\n\n\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 29, "score": 82942.26056377574 }, { "content": "/* This source file must have a .cpp extension so that all C++ compilers\n\n recognize the extension without flags. Borland does not know .cxx for\n\n example. */\n\n#ifndef __cplusplus\n\n# error \"A C compiler has been selected for C++.\"\n\n#endif\n\n\n\n\n\n/* Version number components: V=Version, R=Revision, P=Patch\n\n Version date components: YYYY=Year, MM=Month, DD=Day */\n\n\n\n#if defined(__COMO__)\n\n# define COMPILER_ID \"Comeau\"\n\n /* __COMO_VERSION__ = VRR */\n\n# define COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100)\n\n# define COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100)\n\n\n\n#elif defined(__INTEL_COMPILER) || defined(__ICC)\n\n# define COMPILER_ID \"Intel\"\n\n# if defined(_MSC_VER)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 30, "score": 82942.26056377574 }, { "content": "# define COMPILER_ID \"AppleClang\"\n\n# if defined(_MSC_VER)\n\n# define SIMULATE_ID \"MSVC\"\n\n# endif\n\n# define COMPILER_VERSION_MAJOR DEC(__clang_major__)\n\n# define COMPILER_VERSION_MINOR DEC(__clang_minor__)\n\n# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)\n\n# if defined(_MSC_VER)\n\n /* _MSC_VER = VVRR */\n\n# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)\n\n# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)\n\n# endif\n\n# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__)\n\n\n\n#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION)\n\n# define COMPILER_ID \"ARMClang\"\n\n # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000)\n\n # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100)\n\n # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000)\n\n# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 31, "score": 82942.26056377574 }, { "content": "\n\n#elif defined(__SCO_VERSION__)\n\n# define COMPILER_ID \"SCO\"\n\n\n\n#elif defined(__ARMCC_VERSION) && !defined(__clang__)\n\n# define COMPILER_ID \"ARMCC\"\n\n#if __ARMCC_VERSION >= 1000000\n\n /* __ARMCC_VERSION = VRRPPPP */\n\n # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000)\n\n # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100)\n\n # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)\n\n#else\n\n /* __ARMCC_VERSION = VRPPPP */\n\n # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000)\n\n # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10)\n\n # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)\n\n#endif\n\n\n\n\n\n#elif defined(__clang__) && defined(__apple_build_version__)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 32, "score": 82942.26056377574 }, { "content": "# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)\n\n\n\n#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800\n\n# define COMPILER_ID \"VisualAge\"\n\n /* __IBMCPP__ = VRP */\n\n# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)\n\n# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)\n\n# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)\n\n\n\n#elif defined(__PGI)\n\n# define COMPILER_ID \"PGI\"\n\n# define COMPILER_VERSION_MAJOR DEC(__PGIC__)\n\n# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__)\n\n# if defined(__PGIC_PATCHLEVEL__)\n\n# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)\n\n# endif\n\n\n\n#elif defined(_CRAYC)\n\n# define COMPILER_ID \"Cray\"\n\n# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 33, "score": 82942.26056377574 }, { "content": "# define PLATFORM_ID\n\n\n\n#endif\n\n\n\n/* For windows compilers MSVC and Intel we can determine\n\n the architecture of the compiler being used. This is because\n\n the compilers do not have flags that can change the architecture,\n\n but rather depend on which compiler is being used\n\n*/\n\n#if defined(_WIN32) && defined(_MSC_VER)\n\n# if defined(_M_IA64)\n\n# define ARCHITECTURE_ID \"IA64\"\n\n\n\n# elif defined(_M_X64) || defined(_M_AMD64)\n\n# define ARCHITECTURE_ID \"x64\"\n\n\n\n# elif defined(_M_IX86)\n\n# define ARCHITECTURE_ID \"X86\"\n\n\n\n# elif defined(_M_ARM64)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 34, "score": 82942.26056377574 }, { "content": "# define ARCHITECTURE_ID \"ARM64\"\n\n\n\n# elif defined(_M_ARM)\n\n# if _M_ARM == 4\n\n# define ARCHITECTURE_ID \"ARMV4I\"\n\n# elif _M_ARM == 5\n\n# define ARCHITECTURE_ID \"ARMV5I\"\n\n# else\n\n# define ARCHITECTURE_ID \"ARMV\" STRINGIFY(_M_ARM)\n\n# endif\n\n\n\n# elif defined(_M_MIPS)\n\n# define ARCHITECTURE_ID \"MIPS\"\n\n\n\n# elif defined(_M_SH)\n\n# define ARCHITECTURE_ID \"SHx\"\n\n\n\n# else /* unknown architecture */\n\n# define ARCHITECTURE_ID \"\"\n\n# endif\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 35, "score": 82942.26056377574 }, { "content": "# else /* unknown architecture */\n\n# define ARCHITECTURE_ID \"\"\n\n# endif\n\n#else\n\n# define ARCHITECTURE_ID\n\n#endif\n\n\n\n/* Convert integer to decimal digit literals. */\n\n#define DEC(n) \\\n\n ('0' + (((n) / 10000000)%10)), \\\n\n ('0' + (((n) / 1000000)%10)), \\\n\n ('0' + (((n) / 100000)%10)), \\\n\n ('0' + (((n) / 10000)%10)), \\\n\n ('0' + (((n) / 1000)%10)), \\\n\n ('0' + (((n) / 100)%10)), \\\n\n ('0' + (((n) / 10)%10)), \\\n\n ('0' + ((n) % 10))\n\n\n\n/* Convert integer to hex digit literals. */\n\n#define HEX(n) \\\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 36, "score": 82942.26056377574 }, { "content": "# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)\n\n# endif\n\n\n\n#elif defined(__WATCOMC__)\n\n# define COMPILER_ID \"OpenWatcom\"\n\n /* __WATCOMC__ = VVRP + 1100 */\n\n# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100)\n\n# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)\n\n# if (__WATCOMC__ % 10) > 0\n\n# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)\n\n# endif\n\n\n\n#elif defined(__SUNPRO_CC)\n\n# define COMPILER_ID \"SunPro\"\n\n# if __SUNPRO_CC >= 0x5100\n\n /* __SUNPRO_CC = 0xVRRP */\n\n# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12)\n\n# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF)\n\n# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF)\n\n# else\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 37, "score": 82942.26056377574 }, { "content": "# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR)\n\n\n\n#elif defined(__TI_COMPILER_VERSION__)\n\n# define COMPILER_ID \"TI\"\n\n /* __TI_COMPILER_VERSION__ = VVVRRRPPP */\n\n# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000)\n\n# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000)\n\n# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000)\n\n\n\n#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version)\n\n# define COMPILER_ID \"Fujitsu\"\n\n\n\n#elif defined(__ghs__)\n\n# define COMPILER_ID \"GHS\"\n\n/* __GHS_VERSION_NUMBER = VVVVRP */\n\n# ifdef __GHS_VERSION_NUMBER\n\n# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100)\n\n# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10)\n\n# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10)\n\n# endif\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 38, "score": 82942.26056377574 }, { "content": "#elif defined(__IBMCPP__) && defined(__COMPILER_VER__)\n\n# define COMPILER_ID \"zOS\"\n\n /* __IBMCPP__ = VRP */\n\n# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)\n\n# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)\n\n# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)\n\n\n\n#elif defined(__ibmxl__) && defined(__clang__)\n\n# define COMPILER_ID \"XLClang\"\n\n# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__)\n\n# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__)\n\n# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__)\n\n# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__)\n\n\n\n\n\n#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800\n\n# define COMPILER_ID \"XL\"\n\n /* __IBMCPP__ = VRP */\n\n# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)\n\n# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 39, "score": 82942.26056377574 }, { "content": "# define SIMULATE_ID \"MSVC\"\n\n# endif\n\n# if defined(__GNUC__)\n\n# define SIMULATE_ID \"GNU\"\n\n# endif\n\n /* __INTEL_COMPILER = VRP */\n\n# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)\n\n# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)\n\n# if defined(__INTEL_COMPILER_UPDATE)\n\n# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)\n\n# else\n\n# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10)\n\n# endif\n\n# if defined(__INTEL_COMPILER_BUILD_DATE)\n\n /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */\n\n# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)\n\n# endif\n\n# if defined(_MSC_VER)\n\n /* _MSC_VER = VVRR */\n\n# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 40, "score": 82942.26056377574 }, { "content": "#elif defined(__NetBSD__) || defined(__NetBSD)\n\n# define PLATFORM_ID \"NetBSD\"\n\n\n\n#elif defined(__OpenBSD__) || defined(__OPENBSD)\n\n# define PLATFORM_ID \"OpenBSD\"\n\n\n\n#elif defined(__sun) || defined(sun)\n\n# define PLATFORM_ID \"SunOS\"\n\n\n\n#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__)\n\n# define PLATFORM_ID \"AIX\"\n\n\n\n#elif defined(__hpux) || defined(__hpux__)\n\n# define PLATFORM_ID \"HP-UX\"\n\n\n\n#elif defined(__HAIKU__)\n\n# define PLATFORM_ID \"Haiku\"\n\n\n\n#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS)\n\n# define PLATFORM_ID \"BeOS\"\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 41, "score": 82942.26056377574 }, { "content": "\n\n/* Identify known platforms by name. */\n\n#if defined(__linux) || defined(__linux__) || defined(linux)\n\n# define PLATFORM_ID \"Linux\"\n\n\n\n#elif defined(__CYGWIN__)\n\n# define PLATFORM_ID \"Cygwin\"\n\n\n\n#elif defined(__MINGW32__)\n\n# define PLATFORM_ID \"MinGW\"\n\n\n\n#elif defined(__APPLE__)\n\n# define PLATFORM_ID \"Darwin\"\n\n\n\n#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32)\n\n# define PLATFORM_ID \"Windows\"\n\n\n\n#elif defined(__FreeBSD__) || defined(__FreeBSD)\n\n# define PLATFORM_ID \"FreeBSD\"\n\n\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 42, "score": 82942.26056377574 }, { "content": " '.', COMPILER_VERSION_TWEAK,\n\n# endif\n\n# endif\n\n# endif\n\n ']','\\0'};\n\n#endif\n\n\n\n/* Construct a string literal encoding the internal version number. */\n\n#ifdef COMPILER_VERSION_INTERNAL\n\nchar const info_version_internal[] = {\n\n 'I', 'N', 'F', 'O', ':',\n\n 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_',\n\n 'i','n','t','e','r','n','a','l','[',\n\n COMPILER_VERSION_INTERNAL,']','\\0'};\n\n#endif\n\n\n\n/* Construct a string literal encoding the version number components. */\n\n#ifdef SIMULATE_VERSION_MAJOR\n\nchar const info_simulate_version[] = {\n\n 'I', 'N', 'F', 'O', ':',\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 43, "score": 82942.26056377574 }, { "content": "# define PLATFORM_ID \"MP-RAS\"\n\n\n\n#elif defined(__osf) || defined(__osf__)\n\n# define PLATFORM_ID \"OSF1\"\n\n\n\n#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv)\n\n# define PLATFORM_ID \"SCO_SV\"\n\n\n\n#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX)\n\n# define PLATFORM_ID \"ULTRIX\"\n\n\n\n#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX)\n\n# define PLATFORM_ID \"Xenix\"\n\n\n\n#elif defined(__WATCOMC__)\n\n# if defined(__LINUX__)\n\n# define PLATFORM_ID \"Linux\"\n\n\n\n# elif defined(__DOS__)\n\n# define PLATFORM_ID \"DOS\"\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 44, "score": 82942.26056377574 }, { "content": " /* __SUNPRO_CC = 0xVRP */\n\n# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8)\n\n# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF)\n\n# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF)\n\n# endif\n\n\n\n#elif defined(__HP_aCC)\n\n# define COMPILER_ID \"HP\"\n\n /* __HP_aCC = VVRRPP */\n\n# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000)\n\n# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100)\n\n# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100)\n\n\n\n#elif defined(__DECCXX)\n\n# define COMPILER_ID \"Compaq\"\n\n /* __DECCXX_VER = VVRRTPPPP */\n\n# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000)\n\n# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100)\n\n# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000)\n\n\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 45, "score": 82942.26056377574 }, { "content": "# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000)\n\n# endif\n\n# endif\n\n# if defined(_MSC_BUILD)\n\n# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD)\n\n# endif\n\n\n\n#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)\n\n# define COMPILER_ID \"ADSP\"\n\n#if defined(__VISUALDSPVERSION__)\n\n /* __VISUALDSPVERSION__ = 0xVVRRPP00 */\n\n# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24)\n\n# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF)\n\n# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF)\n\n#endif\n\n\n\n#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC)\n\n# define COMPILER_ID \"IAR\"\n\n# if defined(__VER__) && defined(__ICCARM__)\n\n# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 46, "score": 82942.26056377574 }, { "content": "\n\n#elif defined(__WATCOMC__)\n\n# if defined(_M_I86)\n\n# define ARCHITECTURE_ID \"I86\"\n\n\n\n# elif defined(_M_IX86)\n\n# define ARCHITECTURE_ID \"X86\"\n\n\n\n# else /* unknown architecture */\n\n# define ARCHITECTURE_ID \"\"\n\n# endif\n\n\n\n#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC)\n\n# if defined(__ICCARM__)\n\n# define ARCHITECTURE_ID \"ARM\"\n\n\n\n# elif defined(__ICCRX__)\n\n# define ARCHITECTURE_ID \"RX\"\n\n\n\n# elif defined(__ICCRH850__)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 47, "score": 82942.26056377574 }, { "content": " 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[',\n\n SIMULATE_VERSION_MAJOR,\n\n# ifdef SIMULATE_VERSION_MINOR\n\n '.', SIMULATE_VERSION_MINOR,\n\n# ifdef SIMULATE_VERSION_PATCH\n\n '.', SIMULATE_VERSION_PATCH,\n\n# ifdef SIMULATE_VERSION_TWEAK\n\n '.', SIMULATE_VERSION_TWEAK,\n\n# endif\n\n# endif\n\n# endif\n\n ']','\\0'};\n\n#endif\n\n\n\n/* Construct the string literal in pieces to prevent the source from\n\n getting matched. Store it in a pointer rather than an array\n\n because some compilers will just produce instructions to fill the\n\n array rather than assigning a pointer to a static array. */\n\nchar const* info_platform = \"INFO\" \":\" \"platform[\" PLATFORM_ID \"]\";\n\nchar const* info_arch = \"INFO\" \":\" \"arch[\" ARCHITECTURE_ID \"]\";\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 48, "score": 82942.26056377574 }, { "content": " ('0' + ((n)>>28 & 0xF)), \\\n\n ('0' + ((n)>>24 & 0xF)), \\\n\n ('0' + ((n)>>20 & 0xF)), \\\n\n ('0' + ((n)>>16 & 0xF)), \\\n\n ('0' + ((n)>>12 & 0xF)), \\\n\n ('0' + ((n)>>8 & 0xF)), \\\n\n ('0' + ((n)>>4 & 0xF)), \\\n\n ('0' + ((n) & 0xF))\n\n\n\n/* Construct a string literal encoding the version number components. */\n\n#ifdef COMPILER_VERSION_MAJOR\n\nchar const info_version[] = {\n\n 'I', 'N', 'F', 'O', ':',\n\n 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[',\n\n COMPILER_VERSION_MAJOR,\n\n# ifdef COMPILER_VERSION_MINOR\n\n '.', COMPILER_VERSION_MINOR,\n\n# ifdef COMPILER_VERSION_PATCH\n\n '.', COMPILER_VERSION_PATCH,\n\n# ifdef COMPILER_VERSION_TWEAK\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 49, "score": 82942.26056377574 }, { "content": "const char* info_language_dialect_default = \"INFO\" \":\" \"dialect_default[\"\n\n#if CXX_STD > 201703L\n\n \"20\"\n\n#elif CXX_STD >= 201703L\n\n \"17\"\n\n#elif CXX_STD >= 201402L\n\n \"14\"\n\n#elif CXX_STD >= 201103L\n\n \"11\"\n\n#else\n\n \"98\"\n\n#endif\n\n\"]\";\n\n\n\n/*--------------------------------------------------------------------------*/\n\n\n\nint main(int argc, char* argv[])\n\n{\n\n int require = 0;\n\n require += info_compiler[argc];\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 50, "score": 82942.26056377574 }, { "content": "\n\n#elif defined(__QNX__) || defined(__QNXNTO__)\n\n# define PLATFORM_ID \"QNX\"\n\n\n\n#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__)\n\n# define PLATFORM_ID \"Tru64\"\n\n\n\n#elif defined(__riscos) || defined(__riscos__)\n\n# define PLATFORM_ID \"RISCos\"\n\n\n\n#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__)\n\n# define PLATFORM_ID \"SINIX\"\n\n\n\n#elif defined(__UNIX_SV__)\n\n# define PLATFORM_ID \"UNIX_SV\"\n\n\n\n#elif defined(__bsdos__)\n\n# define PLATFORM_ID \"BSDOS\"\n\n\n\n#elif defined(_MPRAS) || defined(MPRAS)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 51, "score": 82942.26056377574 }, { "content": "# define COMPILER_VERSION_MAJOR DEC(__GNUG__)\n\n# endif\n\n# if defined(__GNUC_MINOR__)\n\n# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__)\n\n# endif\n\n# if defined(__GNUC_PATCHLEVEL__)\n\n# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)\n\n# endif\n\n\n\n#elif defined(_MSC_VER)\n\n# define COMPILER_ID \"MSVC\"\n\n /* _MSC_VER = VVRR */\n\n# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100)\n\n# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100)\n\n# if defined(_MSC_FULL_VER)\n\n# if _MSC_VER >= 1400\n\n /* _MSC_FULL_VER = VVRRPPPPP */\n\n# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000)\n\n# else\n\n /* _MSC_FULL_VER = VVRRPPPP */\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 52, "score": 82942.26056377574 }, { "content": "# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)\n\n# endif\n\n# if defined(__GNUC__)\n\n# define SIMULATE_VERSION_MAJOR DEC(__GNUC__)\n\n# elif defined(__GNUG__)\n\n# define SIMULATE_VERSION_MAJOR DEC(__GNUG__)\n\n# endif\n\n# if defined(__GNUC_MINOR__)\n\n# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__)\n\n# endif\n\n# if defined(__GNUC_PATCHLEVEL__)\n\n# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)\n\n# endif\n\n\n\n#elif defined(__PATHCC__)\n\n# define COMPILER_ID \"PathScale\"\n\n# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)\n\n# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)\n\n# if defined(__PATHCC_PATCHLEVEL__)\n\n# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdCXX/CMakeCXXCompilerId.cpp", "rank": 53, "score": 82942.26056377574 }, { "content": "class GradientClipping\n\n{\n\n public:\n\n /**\n\n * Constructor for creating a GradientClipping instance.\n\n *\n\n * @param minGradient Minimum possible value of gradient element.\n\n * @param maxGradient Maximum possible value of gradient element.\n\n * @param updatePolicy An instance of the UpdatePolicyType\n\n * used for actual optimization.\n\n */\n\n GradientClipping(const double minGradient,\n\n const double maxGradient,\n\n UpdatePolicyType& updatePolicy) :\n\n minGradient(minGradient),\n\n maxGradient(maxGradient),\n\n updatePolicy(updatePolicy)\n\n {\n\n // Nothing to do here.\n\n }\n", "file_path": "include/ensmallen_bits/sgd/update_policies/gradient_clipping.hpp", "rank": 54, "score": 81869.03064880394 }, { "content": "//! Very, very simple test function which is the composite of three other\n\n//! functions. The gradient is not very steep far away from the optimum, so a\n\n//! larger step size may be required to optimize it in a reasonable number of\n\n//! iterations.\n\nclass SGDTestFunction\n\n{\n\n private:\n\n arma::Col<size_t> visitationOrder;\n\n\n\n public:\n\n //! Initialize the SGDTestFunction.\n\n SGDTestFunction();\n\n\n\n /**\n\n * Shuffle the order of function visitation. This may be called by the\n\n * optimizer.\n\n */\n\n void Shuffle();\n\n\n\n //! Return 3 (the number of functions).\n\n size_t NumFunctions() const { return 3; }\n\n\n\n //! Get the starting point.\n\n template<typename MatType = arma::mat>\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function.hpp", "rank": 55, "score": 81363.65176472829 }, { "content": "// A simple test function. Each dimension has a parabola with a\n\n// distinct minimum. Each update is guaranteed to be sparse(only a single\n\n// dimension is updated in the decision variable by each thread). At the end of\n\n// a reasonable number of iterations, each value in the decision variable should\n\n// be at the vertex of the parabola in that dimension.\n\nclass SparseTestFunction\n\n{\n\n public:\n\n //! Set members in the default constructor.\n\n SparseTestFunction();\n\n\n\n //! Return 4 (the number of functions).\n\n size_t NumFunctions() const { return 4; }\n\n\n\n //! Return 4 (the number of features).\n\n size_t NumFeatures() const { return 4; }\n\n\n\n //! Get the starting point.\n\n template<typename MatType>\n\n MatType GetInitialPoint() const { return MatType(\"0 0 0 0;\"); }\n\n\n\n //! Evaluate a function.\n\n template<typename MatType>\n\n typename MatType::Scalar Evaluate(const MatType& coordinates,\n\n const size_t i,\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function.hpp", "rank": 56, "score": 81358.99090146378 }, { "content": "class TestFuncFW\n\n{\n\n public:\n\n TestFuncFW() {/* Nothing to do. */}\n\n\n\n /**\n\n * Evaluation of the function.\n\n *\n\n * @param coords input vector x.\n\n */\n\n typename MatType::Scalar Evaluate(const MatType& coords)\n\n {\n\n typename MatType::Scalar f = std::pow(coords[0] - 0.1, 2);\n\n f += std::pow(coords[1] - 0.2, 2);\n\n f += std::pow(coords[2] - 0.3, 2);\n\n return f;\n\n }\n\n\n\n /**\n\n * Gradient of the function.\n", "file_path": "include/ensmallen_bits/problems/fw_test_function.hpp", "rank": 57, "score": 81354.52784970842 }, { "content": "/**\n\n * @file ens_version.hpp\n\n * @author Conrad Sanderson\n\n * @author Ryan Curtin\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n\n\n\n\n// This follows the Semantic Versioning pattern defined in https://semver.org/.\n\n\n\n#define ENS_VERSION_MAJOR 2\n\n// The minor version is two digits so regular numerical comparisons of versions\n\n// work right. The first minor version of a release is always 10.\n\n#define ENS_VERSION_MINOR 12\n\n#define ENS_VERSION_PATCH 1\n\n// If this is a release candidate, it will be reflected in the version name\n\n// (i.e. the version name will be \"RC1\", \"RC2\", etc.). Otherwise the version\n\n// name will typically be a seemingly arbitrary set of words that does not\n\n// contain the capitalized string \"RC\".\n\n#define ENS_VERSION_NAME \"Stir Crazy\"\n\n\n\nnamespace ens {\n\n\n", "file_path": "include/ensmallen_bits/ens_version.hpp", "rank": 58, "score": 80145.39306824465 }, { "content": "class AugLagrangianTestFunction\n\n{\n\n public:\n\n AugLagrangianTestFunction();\n\n AugLagrangianTestFunction(const arma::mat& initial_point);\n\n\n\n double Evaluate(const arma::mat& coordinates);\n\n void Gradient(const arma::mat& coordinates, arma::mat& gradient);\n\n\n\n size_t NumConstraints() const { return 1; }\n\n\n\n double EvaluateConstraint(const size_t index, const arma::mat& coordinates);\n\n void GradientConstraint(const size_t index,\n\n const arma::mat& coordinates,\n\n arma::mat& gradient);\n\n\n\n const arma::mat& GetInitialPoint() const { return initialPoint; }\n\n\n\n private:\n\n arma::mat initialPoint;\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions.hpp", "rank": 59, "score": 78301.05957026574 }, { "content": "struct version\n\n{\n\n static const unsigned int major = ENS_VERSION_MAJOR;\n\n static const unsigned int minor = ENS_VERSION_MINOR;\n\n static const unsigned int patch = ENS_VERSION_PATCH;\n\n\n\n static inline std::string as_string()\n\n {\n\n const char* nickname = ENS_VERSION_NAME;\n\n\n\n std::stringstream ss;\n\n ss << version::major << '.' << version::minor << '.' << version::patch\n\n << \" (\" << nickname << ')';\n\n\n\n return ss.str();\n\n }\n\n};\n\n\n\n} // namespace ens\n", "file_path": "include/ensmallen_bits/ens_version.hpp", "rank": 60, "score": 77901.67772184193 }, { "content": "char const* qnxnto = \"INFO\" \":\" \"qnxnto[]\";\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 61, "score": 77341.55927362219 }, { "content": "void main() {}\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 62, "score": 77341.55927362219 }, { "content": "char const* info_platform = \"INFO\" \":\" \"platform[\" PLATFORM_ID \"]\";\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 63, "score": 76061.35869007473 }, { "content": "char const info_version[] = {\n\n 'I', 'N', 'F', 'O', ':',\n\n 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[',\n\n COMPILER_VERSION_MAJOR,\n\n# ifdef COMPILER_VERSION_MINOR\n\n '.', COMPILER_VERSION_MINOR,\n\n# ifdef COMPILER_VERSION_PATCH\n\n '.', COMPILER_VERSION_PATCH,\n\n# ifdef COMPILER_VERSION_TWEAK\n\n '.', COMPILER_VERSION_TWEAK,\n\n# endif\n\n# endif\n\n# endif\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 64, "score": 76061.35869007473 }, { "content": "char const* info_arch = \"INFO\" \":\" \"arch[\" ARCHITECTURE_ID \"]\";\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 65, "score": 76061.35869007473 }, { "content": "char const* info_compiler = \"INFO\" \":\" \"compiler[\" COMPILER_ID \"]\";\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 66, "score": 76061.35869007473 }, { "content": "char const* info_simulate = \"INFO\" \":\" \"simulate[\" SIMULATE_ID \"]\";\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 67, "score": 76061.35869007473 }, { "content": " MatType GetInitialPoint() const { return MatType(\"6; -45.6; 6.2\"); }\n\n\n\n //! Evaluate a function for a particular batch-size.\n\n template<typename MatType>\n\n typename MatType::Scalar Evaluate(const MatType& coordinates,\n\n const size_t begin,\n\n const size_t batchSize) const;\n\n\n\n //! Evaluate the gradient of a function for a particular batch-size\n\n template<typename MatType, typename GradType>\n\n void Gradient(const MatType& coordinates,\n\n const size_t begin,\n\n GradType& gradient,\n\n const size_t batchSize) const;\n\n};\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n// Include implementation.\n\n#include \"sgd_test_function_impl.hpp\"\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function.hpp", "rank": 68, "score": 75173.21551038681 }, { "content": "\n\n private:\n\n // Each quadratic polynomial is monic. The intercept and coefficient of the\n\n // first order term is stored.\n\n\n\n //! The vector storing the intercepts\n\n arma::vec intercepts;\n\n\n\n //! The vector having coefficients of the first order term\n\n arma::vec bi;\n\n};\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n// Include implementation.\n\n#include \"sparse_test_function_impl.hpp\"\n\n\n\n#endif // ENSMALLEN_PROBLEMS_SPARSE_TEST_FUNCTION_HPP\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function.hpp", "rank": 69, "score": 75165.46740968358 }, { "content": " *\n\n * @param coords input vector x.\n\n * @param gradient output gradient vector.\n\n */\n\n void Gradient(const MatType& coords, GradType& gradient)\n\n {\n\n gradient.set_size(3, 1);\n\n gradient[0] = coords[0] - 0.1;\n\n gradient[1] = coords[1] - 0.2;\n\n gradient[2] = coords[2] - 0.3;\n\n }\n\n};\n\n\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/fw_test_function.hpp", "rank": 70, "score": 75160.1442595225 }, { "content": "/**\n\n * @file sgd_test_function.hpp\n\n * @author Ryan Curtin\n\n *\n\n * Very simple test function for SGD.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_SGD_TEST_FUNCTION_HPP\n\n#define ENSMALLEN_PROBLEMS_SGD_TEST_FUNCTION_HPP\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n\n//! Very, very simple test function which is the composite of three other\n\n//! functions. The gradient is not very steep far away from the optimum, so a\n\n//! larger step size may be required to optimize it in a reasonable number of\n\n//! iterations.\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function.hpp", "rank": 71, "score": 75151.9420433675 }, { "content": " const size_t batchSize = 1) const;\n\n\n\n //! Evaluate all the functions.\n\n template<typename MatType>\n\n typename MatType::Scalar Evaluate(const MatType& coordinates) const;\n\n\n\n //! Evaluate the gradient of a function.\n\n template<typename MatType,\n\n typename GradType = arma::SpMat<typename MatType::Scalar>>\n\n void Gradient(const MatType& coordinates,\n\n const size_t i,\n\n GradType& gradient,\n\n const size_t batchSize = 1) const;\n\n\n\n //! Evaluate the gradient of a feature function.\n\n template<typename MatType,\n\n typename GradType = arma::SpMat<typename MatType::Scalar>>\n\n void PartialGradient(const MatType& coordinates,\n\n const size_t j,\n\n GradType& gradient) const;\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function.hpp", "rank": 72, "score": 75150.56462811821 }, { "content": "/**\n\n * @file fw_test_function.hpp\n\n * @author Chenzhe Diao\n\n *\n\n * Simple test function for classic Frank Wolfe Algorithm:\n\n *\n\n * \\f$ f(x) = (x1 - 0.1)^2 + (x2 - 0.2)^2 + (x3 - 0.3)^2 \\f$\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_FW_TEST_FUNCTION_HPP\n\n#define ENSMALLEN_PROBLEMS_FW_TEST_FUNCTION_HPP\n\n\n\nnamespace ens {\n\n\n\n/**\n\n * Simple test function for classic Frank Wolfe Algorithm:\n\n *\n\n * \\f$ f(x) = (x1 - 0.1)^2 + (x2 - 0.2)^2 + (x3 - 0.3)^2 \\f$.\n\n */\n\ntemplate<typename MatType = arma::mat, typename GradType = MatType>\n", "file_path": "include/ensmallen_bits/problems/fw_test_function.hpp", "rank": 73, "score": 75150.2839851353 }, { "content": "/**\n\n * @file sparse_test_function.hpp\n\n * @author Shikhar Bhardwaj\n\n *\n\n * Sparse test function for Parallel SGD.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_SPARSE_TEST_FUNCTION_HPP\n\n#define ENSMALLEN_PROBLEMS_SPARSE_TEST_FUNCTION_HPP\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n\n// A simple test function. Each dimension has a parabola with a\n\n// distinct minimum. Each update is guaranteed to be sparse(only a single\n\n// dimension is updated in the decision variable by each thread). At the end of\n\n// a reasonable number of iterations, each value in the decision variable should\n\n// be at the vertex of the parabola in that dimension.\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function.hpp", "rank": 74, "score": 75148.61338233495 }, { "content": "char const info_simulate_version[] = {\n\n 'I', 'N', 'F', 'O', ':',\n\n 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[',\n\n SIMULATE_VERSION_MAJOR,\n\n# ifdef SIMULATE_VERSION_MINOR\n\n '.', SIMULATE_VERSION_MINOR,\n\n# ifdef SIMULATE_VERSION_PATCH\n\n '.', SIMULATE_VERSION_PATCH,\n\n# ifdef SIMULATE_VERSION_TWEAK\n\n '.', SIMULATE_VERSION_TWEAK,\n\n# endif\n\n# endif\n\n# endif\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 75, "score": 74824.15182719137 }, { "content": "char const info_version_internal[] = {\n\n 'I', 'N', 'F', 'O', ':',\n\n 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_',\n\n 'i','n','t','e','r','n','a','l','[',\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 76, "score": 74824.15182719137 }, { "content": "const char* info_language_dialect_default =\n", "file_path": "tests/gradient_descent_test/CMakeFiles/3.16.0/CompilerIdC/CMakeCCompilerId.c", "rank": 77, "score": 73627.74661304562 }, { "content": " instPolicy.Update(iterate, stepSize, clippedGradient);\n\n }\n\n\n\n private:\n\n // The instantiated parent class.\n\n const GradientClipping<UpdatePolicyType>& parent;\n\n // The instantiated update policy we will use.\n\n typename UpdatePolicyType::template Policy<MatType, GradType> instPolicy;\n\n };\n\n\n\n private:\n\n //! Minimum possible value of gradient element.\n\n double minGradient;\n\n\n\n //! Maximum possible value of gradient element.\n\n double maxGradient;\n\n\n\n //! An instance of the UpdatePolicy used for actual optimization.\n\n UpdatePolicyType updatePolicy;\n\n};\n\n\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/sgd/update_policies/gradient_clipping.hpp", "rank": 78, "score": 73589.79597014989 }, { "content": " /**\n\n * Update step. First, the gradient is clipped, and then the actual update\n\n * policy does whatever update it needs to do.\n\n *\n\n * @param iterate Parameters that minimize the function.\n\n * @param stepSize Step size to be used for the given iteration.\n\n * @param gradient The gradient matrix.\n\n */\n\n void Update(MatType& iterate,\n\n const double stepSize,\n\n const GradType& gradient)\n\n {\n\n typedef typename GradType::Scalar GradElemType;\n\n\n\n // First, clip the gradient.\n\n GradType clippedGradient = arma::clamp(gradient,\n\n GradElemType(parent.minGradient),\n\n GradElemType(parent.maxGradient));\n\n\n\n // And only then do the update.\n", "file_path": "include/ensmallen_bits/sgd/update_policies/gradient_clipping.hpp", "rank": 79, "score": 73584.93559902195 }, { "content": "/**\n\n * @file gradient_clipping.hpp\n\n * @author Konstantin Sidorov\n\n *\n\n * Gradient clipping update wrapper.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_SGD_GRADIENT_CLIPPING_HPP\n\n#define ENSMALLEN_SGD_GRADIENT_CLIPPING_HPP\n\n\n\nnamespace ens {\n\n\n\n/**\n\n * Interface for wrapping around update policies (e.g., VanillaUpdate)\n\n * and feeding a clipped gradient to them instead of the normal one.\n\n * (Clipping here is implemented as\n\n * \\f$ g_{\\text{clipped}} = \\max(g_{\\text{min}}, \\min(g_{\\text{min}}, g))) \\f$.)\n\n *\n\n * @tparam UpdatePolicy A type of UpdatePolicy that sould be wrapped around.\n\n */\n\ntemplate<typename UpdatePolicyType>\n", "file_path": "include/ensmallen_bits/sgd/update_policies/gradient_clipping.hpp", "rank": 80, "score": 73583.24439486566 }, { "content": "\n\n //! Get the update policy.\n\n UpdatePolicyType& UpdatePolicy() const { return updatePolicy; }\n\n //! Modify the update policy.\n\n UpdatePolicyType& UpdatePolicy() { return updatePolicy; }\n\n\n\n //! Get the minimum gradient value.\n\n double MinGradient() const { return minGradient; }\n\n //! Modify the minimum gradient value.\n\n double& MinGradient() { return minGradient; }\n\n\n\n //! Get the maximum gradient value.\n\n double MaxGradient() const { return maxGradient; }\n\n //! Modify the maximum gradient value.\n\n double& MaxGradient() { return maxGradient; }\n\n\n\n /**\n\n * The UpdatePolicyType policy classes must contain an internal 'Policy'\n\n * template class with two template arguments: MatType and GradType. This is\n\n * instantiated at the start of the optimization, and holds parameters\n\n * specific to an individual optimization.\n\n */\n\n template<typename MatType, typename GradType>\n", "file_path": "include/ensmallen_bits/sgd/update_policies/gradient_clipping.hpp", "rank": 81, "score": 73582.92004444006 }, { "content": " double EvaluateConstraint(const size_t index, const arma::mat& coordinates);\n\n void GradientConstraint(const size_t index,\n\n const arma::mat& coordinates,\n\n arma::mat& gradient);\n\n\n\n const arma::mat& GetInitialPoint();\n\n\n\n const arma::mat& Edges() const { return edges; }\n\n arma::mat& Edges() { return edges; }\n\n\n\n private:\n\n arma::mat edges;\n\n size_t vertices;\n\n\n\n arma::mat initialPoint;\n\n};\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n// Include implementation.\n\n#include \"aug_lagrangian_test_functions_impl.hpp\"\n\n\n\n#endif // ENSMALLEN_AUG_LAGRANGIAN_TEST_FUNCTIONS_HPP\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions.hpp", "rank": 82, "score": 73183.36165753717 }, { "content": "inline void SparseTestFunction::Gradient(const MatType& coordinates,\n\n const size_t i,\n\n GradType& gradient,\n\n const size_t batchSize) const\n\n{\n\n gradient.zeros(arma::size(coordinates));\n\n for (size_t j = i; j < i + batchSize; ++j)\n\n gradient[j] = 2 * coordinates[j] + bi[j];\n\n}\n\n\n\n//! Evaluate the gradient of a feature function.\n\ntemplate<typename MatType, typename GradType>\n\ninline void SparseTestFunction::PartialGradient(const MatType& coordinates,\n\n const size_t j,\n\n GradType& gradient) const\n\n{\n\n gradient.zeros(arma::size(coordinates));\n\n gradient[j] = 2 * coordinates[j] + bi[j];\n\n}\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function_impl.hpp", "rank": 83, "score": 73179.82899931044 }, { "content": "}\n\n\n\ntemplate<typename MatType, typename GradType>\n\nvoid SGDTestFunction::Gradient(const MatType& coordinates,\n\n const size_t begin,\n\n GradType& gradient,\n\n const size_t batchSize) const\n\n{\n\n gradient.zeros(3);\n\n\n\n for (size_t i = begin; i < begin + batchSize; ++i)\n\n {\n\n switch (visitationOrder(i))\n\n {\n\n case 0:\n\n if (coordinates[0] >= 0)\n\n gradient[0] += std::exp(-coordinates[0]);\n\n else\n\n gradient[0] += -std::exp(coordinates[0]);\n\n break;\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function_impl.hpp", "rank": 84, "score": 73179.59552597126 }, { "content": "/**\n\n * @file sgd_test_function_impl.hpp\n\n * @author Ryan Curtin\n\n *\n\n * Implementation of very simple test function for stochastic gradient descent\n\n * (SGD).\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_SGD_TEST_FUNCTION_IMPL_HPP\n\n#define ENSMALLEN_PROBLEMS_SGD_TEST_FUNCTION_IMPL_HPP\n\n\n\n// In case it hasn't been included yet.\n\n#include \"sgd_test_function.hpp\"\n\n\n\nnamespace ens {\n\nnamespace test {\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function_impl.hpp", "rank": 85, "score": 73173.78309436292 }, { "content": "\n\ninline SGDTestFunction::SGDTestFunction() :\n\n visitationOrder(arma::linspace<arma::Col<size_t>>(0, NumFunctions() - 1,\n\n NumFunctions()))\n\n{ }\n\n\n\ninline void SGDTestFunction::Shuffle()\n\n{\n\n visitationOrder = arma::shuffle(arma::linspace<arma::Col<size_t> >(0,\n\n (NumFunctions() - 1), NumFunctions()));\n\n}\n\n\n\ntemplate<typename MatType>\n\ntypename MatType::Scalar SGDTestFunction::Evaluate(\n\n const MatType& coordinates,\n\n const size_t begin,\n\n const size_t batchSize) const\n\n{\n\n typename MatType::Scalar objective = 0;\n\n\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function_impl.hpp", "rank": 86, "score": 73173.32056437172 }, { "content": "\n\n case 1:\n\n gradient[1] += 2 * coordinates[1];\n\n break;\n\n\n\n case 2:\n\n gradient[2] += 4 * std::pow(coordinates[2], 3) + 6 * coordinates[2];\n\n break;\n\n }\n\n }\n\n}\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function_impl.hpp", "rank": 87, "score": 73173.29450857113 }, { "content": "/**\n\n * @file sparse_test_function_impl.hpp\n\n * @author Shikhar Bhardwaj\n\n *\n\n * Sparse test function for Parallel SGD.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_SPARSE_TEST_FUNCTION_IMPL_HPP\n\n#define ENSMALLEN_PROBLEMS_SPARSE_TEST_FUNCTION_IMPL_HPP\n\n\n\n// In case it hasn't been included yet.\n\n#include \"sparse_test_function.hpp\"\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function_impl.hpp", "rank": 88, "score": 73170.83498240645 }, { "content": " void GradientConstraint(const size_t index,\n\n const MatType& coordinates,\n\n GradType& gradient);\n\n\n\n template<typename MatType>\n\n MatType GetInitialPoint() const\n\n {\n\n return arma::conv_to<MatType>::from(initialPoint);\n\n }\n\n\n\n private:\n\n arma::mat initialPoint;\n\n};\n\n\n\n/**\n\n * This function is the Lovasz-Theta semidefinite program, as implemented in the\n\n * following paper:\n\n *\n\n * S. Burer, R. Monteiro\n\n * \"A nonlinear programming algorithm for solving semidefinite programs via\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions.hpp", "rank": 89, "score": 73170.15196171001 }, { "content": " return result;\n\n}\n\n\n\n//! Evaluate all the functions.\n\ntemplate<typename MatType>\n\ninline typename MatType::Scalar SparseTestFunction::Evaluate(\n\n const MatType& coordinates) const\n\n{\n\n typename MatType::Scalar objective = 0.0;\n\n for (size_t i = 0; i < NumFunctions(); ++i)\n\n {\n\n objective += coordinates[i] * coordinates[i] + bi[i] * coordinates[i] +\n\n intercepts[i];\n\n }\n\n\n\n return objective;\n\n}\n\n\n\n//! Evaluate the gradient of a function.\n\ntemplate<typename MatType, typename GradType>\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function_impl.hpp", "rank": 90, "score": 73169.05569295905 }, { "content": "/**\n\n * @file aug_lagrangian_test_functions.hpp\n\n * @author Ryan Curtin\n\n *\n\n * Define test functions for the augmented Lagrangian method.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_AUG_LAGRANGIAN_TEST_FUNCTIONS_HPP\n\n#define ENSMALLEN_AUG_LAGRANGIAN_TEST_FUNCTIONS_HPP\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n\n/**\n\n * This function is taken from \"Practical Mathematical Optimization\" (Snyman),\n\n * section 5.3.8 (\"Application of the Augmented Lagrangian Method\"). It has\n\n * only one constraint.\n\n *\n\n * The minimum that satisfies the constraint is x = [1, 4], with an objective\n\n * value of 70.\n\n */\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions.hpp", "rank": 91, "score": 73168.98549756716 }, { "content": "inline SparseTestFunction::SparseTestFunction()\n\n{\n\n intercepts = arma::vec(\"20 12 15 100\");\n\n bi = arma::vec(\"-4 -2 -3 -8\");\n\n}\n\n\n\n//! Evaluate a function.\n\ntemplate<typename MatType>\n\ninline typename MatType::Scalar SparseTestFunction::Evaluate(\n\n const MatType& coordinates,\n\n const size_t i,\n\n const size_t batchSize) const\n\n{\n\n typename MatType::Scalar result = 0.0;\n\n for (size_t j = i; j < i + batchSize; ++j)\n\n {\n\n result += coordinates[j] * coordinates[j] + bi[j] * coordinates[j] +\n\n intercepts[j];\n\n }\n\n\n", "file_path": "include/ensmallen_bits/problems/sparse_test_function_impl.hpp", "rank": 92, "score": 73166.77985491174 }, { "content": " for (size_t i = begin; i < begin + batchSize; i++)\n\n {\n\n switch (visitationOrder(i))\n\n {\n\n case 0:\n\n objective -= std::exp(-std::abs(coordinates[0]));\n\n break;\n\n\n\n case 1:\n\n objective += std::pow(coordinates[1], 2);\n\n break;\n\n\n\n case 2:\n\n objective += std::pow(coordinates[2], 4) + \\\n\n 3 * std::pow(coordinates[2], 2);\n\n break;\n\n }\n\n }\n\n\n\n return objective;\n", "file_path": "include/ensmallen_bits/problems/sgd_test_function_impl.hpp", "rank": 93, "score": 73162.17261032798 }, { "content": " * low-rank factorization.\"\n\n * Journal of Mathematical Programming, 2004\n\n *\n\n * Given a simple, undirected graph G = (V, E), the Lovasz-Theta SDP is defined\n\n * by:\n\n *\n\n * min_X{Tr(-(e e^T)^T X) : Tr(X) = 1, X_ij = 0 for all (i, j) in E, X >= 0}\n\n *\n\n * where e is the vector of all ones and X has dimension |V| x |V|.\n\n *\n\n * In the Monteiro-Burer formulation, we take X = R * R^T, where R is the\n\n * coordinates given to the Evaluate(), Gradient(), EvaluateConstraint(), and\n\n * GradientConstraint() functions.\n\n */\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions.hpp", "rank": 94, "score": 73160.87956131261 }, { "content": "};\n\n\n\n/**\n\n * This function is taken from M. Gockenbach's lectures on general nonlinear\n\n * programs, found at:\n\n * http://www.math.mtu.edu/~msgocken/ma5630spring2003/lectures/nlp/nlp.pdf\n\n *\n\n * The program we are using is example 2.5 from this document.\n\n * I have arbitrarily decided that this will be called the Gockenbach function.\n\n *\n\n * The minimum that satisfies the two constraints is given as\n\n * x = [0.12288, -1.1078, 0.015100], with an objective value of about 29.634.\n\n */\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions.hpp", "rank": 95, "score": 73152.50697571631 }, { "content": " class Policy\n\n {\n\n public:\n\n /**\n\n * This is called by the optimizer method before the start of the iteration\n\n * update process.\n\n *\n\n * @param parent Instantiated parent class.\n\n * @param rows Number of rows in the gradient matrix.\n\n * @param cols Number of columns in the gradient matrix.\n\n */\n\n Policy(const GradientClipping<UpdatePolicyType>& parent,\n\n const size_t rows,\n\n const size_t cols) :\n\n parent(parent),\n\n instPolicy(parent.UpdatePolicy(), rows, cols)\n\n {\n\n // Nothing to do.\n\n }\n\n\n", "file_path": "include/ensmallen_bits/sgd/update_policies/gradient_clipping.hpp", "rank": 96, "score": 71677.36144391587 }, { "content": " }\n\n }\n\n\n\n return initialPoint;\n\n}\n\n\n\n} // namespace test\n\n} // namespace ens\n\n\n\n#endif\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions_impl.hpp", "rank": 97, "score": 71293.06689791252 }, { "content": "{\n\n if (index == 0) // This is the constraint Tr(X) = 1.\n\n {\n\n gradient = 2 * coordinates; // d/dR (Tr(R R^T)) = 2 R.\n\n return;\n\n }\n\n\n\n size_t i = edges(0, index - 1);\n\n size_t j = edges(1, index - 1);\n\n\n\n // Since the constraint is (R^T R)_ij, the gradient for (x, y) will be (I\n\n // derived this for one of the MVU constraints):\n\n // 0 , y != i, y != j\n\n // 2 R_xj, y = i, y != j\n\n // 2 R_xi, y != i, y = j\n\n // 4 R_xy, y = i, y = j\n\n // This results in the gradient matrix having two nonzero rows; for row\n\n // i, the elements are R_nj, where n is the row; for column j, the elements\n\n // are R_ni.\n\n gradient.zeros(coordinates.n_rows, coordinates.n_cols);\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions_impl.hpp", "rank": 98, "score": 71289.20632262141 }, { "content": "/**\n\n * @file aug_lagrangian_test_functions_impl.hpp\n\n * @author Ryan Curtin\n\n *\n\n * Implementation of AugLagrangianTestFunction class.\n\n *\n\n * ensmallen is free software; you may redistribute it and/or modify it under\n\n * the terms of the 3-clause BSD license. You should have received a copy of\n\n * the 3-clause BSD license along with ensmallen. If not, see\n\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n\n */\n\n#ifndef ENSMALLEN_PROBLEMS_AUG_LAGRANGIAN_TEST_FUNCTIONS_IMPL_HPP\n\n#define ENSMALLEN_PROBLEMS_AUG_LAGRANGIAN_TEST_FUNCTIONS_IMPL_HPP\n\n\n\n#include \"aug_lagrangian_test_functions.hpp\"\n\n\n\nnamespace ens {\n\nnamespace test {\n\n\n\n//\n", "file_path": "include/ensmallen_bits/problems/aug_lagrangian_test_functions_impl.hpp", "rank": 99, "score": 71288.68959741143 } ]
C++
snake3d/wyShaderFunctions.cpp
wysaid/snake3d
54e167c3b1f73a3c9890f8f0e0678ec68e2ffd0c
 #include "wyShaderFunctions.h" #define GETUNIFORM(uniform, programID, name) \ GLint uniform = glGetUniformLocation(programID, name);\ if(uniform < 0) \ {\ LOG_ERROR("uniform name %s does not exist!\n", name);\ return ;\ }\ ShaderObject::ShaderObject() : m_shaderID(0) { m_shaderType = GL_FALSE; } ShaderObject::~ShaderObject() { clear(); } bool ShaderObject::init(GLenum shaderType) { LOG_INFO("Init %s \n", (shaderType == GL_VERTEX_SHADER) ? "VertexShader" : "FragmentShader"); m_shaderType = shaderType; if(m_shaderID != 0) glDeleteShader(m_shaderID); m_shaderID = glCreateShader(m_shaderType); if(m_shaderID == 0) return false; return true; } void ShaderObject::clear() { if(m_shaderID == 0) return; glDeleteShader(m_shaderID); LOG_INFO("%s Shader release\n", m_shaderType == GL_VERTEX_SHADER ? "Vertex" : "Fragment"); m_shaderID = 0; m_shaderType = GL_FALSE; } bool ShaderObject::loadShaderSourceFromString(const char* shaderString) { if(m_shaderID == 0) m_shaderID = glCreateShader(m_shaderType); if(m_shaderID == 0) { LOG_ERROR("glCreateShader Failed!"); return false; } glShaderSource(m_shaderID, 1, (const GLchar**)&shaderString, NULL); glCompileShader(m_shaderID); GLint compiled = 0; glGetShaderiv(m_shaderID, GL_COMPILE_STATUS, &compiled); if(compiled == GL_TRUE) return true; GLint logLen; glGetShaderiv(m_shaderID, GL_INFO_LOG_LENGTH, &logLen); if(logLen > 0) { char *buf = new char[logLen]; if(buf != NULL) { glGetShaderInfoLog(m_shaderID, logLen, &logLen, buf); LOG_ERROR("Shader %d compile faild: \n%s\n", m_shaderID, buf); delete [] buf; } glDeleteShader(m_shaderID); m_shaderID = 0; } return false; } ProgramObject::ProgramObject() { m_programID = glCreateProgram(); LOG_INFO("CREATE PROGRAM!!!! --> %d\n", m_programID); } ProgramObject::~ProgramObject() { GLuint attachedShaders[32]; int numAttachedShaders; glGetAttachedShaders(m_programID, 32, &numAttachedShaders, attachedShaders); for(int i = 0; i < numAttachedShaders; ++i) { glDetachShader(m_programID, attachedShaders[i]); } htCheckGLError("Detach Shaders in useProgram"); glDeleteProgram(m_programID); LOG_INFO("ProgramObject release\n"); } bool ProgramObject::initFragmentShaderSourceFromString(const char* fragShader) { return m_programID != 0 && m_fragObj.init(GL_FRAGMENT_SHADER) && m_fragObj.loadShaderSourceFromString(fragShader); } bool ProgramObject::initVertexShaderSourceFromString(const char* vertShader) { return m_programID != 0 && m_vertObj.init(GL_VERTEX_SHADER) && m_vertObj.loadShaderSourceFromString(vertShader); } bool ProgramObject::link() { LOG_INFO("COMPILE PROGRAM!!!!\n"); GLuint attachedShaders[32]; int numAttachedShaders, programStatus; glGetAttachedShaders(m_programID, 32, &numAttachedShaders, attachedShaders); for(int i = 0; i < numAttachedShaders; ++i) { glDetachShader(m_programID, attachedShaders[i]); } htCheckGLError("Detach Shaders in useProgram"); glAttachShader(m_programID, m_vertObj.getShaderID()); glAttachShader(m_programID, m_fragObj.getShaderID()); htCheckGLError("Attach Shaders in useProgram"); glLinkProgram(m_programID); glGetProgramiv(m_programID, GL_LINK_STATUS, &programStatus); m_vertObj.clear(); m_fragObj.clear(); if(programStatus != GL_TRUE) { GLint logLen = 0; glGetProgramiv(m_programID, GL_INFO_LOG_LENGTH, &logLen); if(logLen != 0) { char *buf = new char[logLen]; if(buf != NULL) { glGetProgramInfoLog(m_programID, logLen, &logLen, buf); LOG_ERROR("Failed to link the program!\n%s", buf); delete [] buf; } } LOG_INFO("LINK %d Failed\n", m_programID); return false; } LOG_INFO("LINK %d OK\n", m_programID); htCheckGLError("Link Program"); return true; } void ProgramObject::bind() { glUseProgram(m_programID); } void ProgramObject::sendUniformf(const char* name, GLfloat x) { GETUNIFORM(uniform, m_programID, name); glUniform1f(uniform, x); } void ProgramObject::sendUniformf(const char* name, GLfloat x, GLfloat y) { GETUNIFORM(uniform, m_programID, name); glUniform2f(uniform, x, y); } void ProgramObject::sendUniformf(const char* name, GLfloat x, GLfloat y, GLfloat z) { GETUNIFORM(uniform, m_programID, name); glUniform3f(uniform, x, y, z); } void ProgramObject::sendUniformf(const char* name, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { GETUNIFORM(uniform, m_programID, name); glUniform4f(uniform, x, y, z, w); } void ProgramObject::sendUniformi(const char* name, GLint x) { GETUNIFORM(uniform, m_programID, name); glUniform1i(uniform, x); } void ProgramObject::sendUniformi(const char* name, GLint x, GLint y) { GETUNIFORM(uniform, m_programID, name); glUniform2i(uniform, x, y); } void ProgramObject::sendUniformi(const char* name, GLint x, GLint y, GLint z) { GETUNIFORM(uniform, m_programID, name); glUniform3i(uniform, x, y, z); } void ProgramObject::sendUniformi(const char* name, GLint x, GLint y, GLint z, GLint w) { GETUNIFORM(uniform, m_programID, name); glUniform4i(uniform, x, y, z, w); } void ProgramObject::sendUniformMat2x2(const char* name, int count, GLboolean transpose, const GLfloat* matrix) { GETUNIFORM(uniform, m_programID, name); glUniformMatrix2fv(uniform, count, transpose, matrix); } void ProgramObject::sendUniformMat3x3(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix) { GETUNIFORM(uniform, m_programID, name); glUniformMatrix3fv(uniform, count, transpose, matrix); } void ProgramObject::sendUniformMat4x4(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix) { GETUNIFORM(uniform, m_programID, name); glUniformMatrix4fv(uniform, count, transpose, matrix); }
 #include "wyShaderFunctions.h" #define GETUNIFORM(uniform, programID, name) \ GLint uniform = glGetUniformLocation(programID, name);\ if(uniform < 0) \ {\ LOG_ERROR("uniform name %s does not exist!\n", name);\ return ;\ }\ ShaderObject::ShaderObject() : m_shaderID(0) { m_shaderType = GL_FALSE; } ShaderObject::~ShaderObject() { clear(); } bool ShaderObject::init(GLenum shaderType) { LOG_INFO("Init %s \n", (shaderType == GL_VERTEX_SHADER) ? "VertexShader" : "FragmentShader"); m_shaderType = shaderType; if(m_shaderID != 0) glDeleteShader(m_shaderID); m_shaderID = glCreateShader(m_shaderType); if(m_shaderID == 0) return false; return true; } void ShaderObject::clear() { if(m_shaderID == 0) return; glDeleteShader(m_shaderID); LOG_INFO("%s Shader release\n", m_shaderType == GL_VERTEX_SHADER ? "Vertex" : "Fragment"); m_shaderID = 0; m_shaderType = GL_FALSE; } bool ShaderObject::loadShaderSourceFromString(const char* shaderString) { if(m_shaderID == 0) m_shaderID = glCreateShader(m_shaderType); if(m_shaderID == 0) { LOG_ERROR("glCreateShader Failed!"); return false; } glShaderSource(m_shaderID, 1, (const GLchar**)&shaderString, NULL); glCompileShader(m_shaderID); GLint compiled = 0; glGetShaderiv(m_shaderID, GL_COMPILE_STATUS, &compiled); if(compiled == GL_TRUE) return true; GLint logLen; glGetShaderiv(m_shaderID, GL_INFO_LOG_LENGTH, &logLen); if(logLen > 0) { char *buf = new char[logLen]; if(buf != NULL) { glGetShaderInfoLog(m_shaderID, logLen, &logLen, buf); LOG_ERROR("Shader %d compile faild: \n%s\n", m_shaderID, buf); delete [] buf; } glDeleteShader(m_shaderID); m_shaderID = 0; } return false; } ProgramObject::ProgramObject() { m_programID = glCreateProgram(); LOG_INFO("CREATE PROGRAM!!!! --> %d\n", m_programID); } ProgramObject::~ProgramObject() { GLuint attachedShaders[32]; int numAttachedShaders; glGetAttachedShaders(m_programID, 32, &numAttachedShaders, attachedShaders); for(int i = 0; i < numAttachedShaders; ++i) { glDetachShader(m_programID, attachedShaders[i]); } htCheckGLError("Detach Shaders in useProgram"); glDeleteProgram(m_programID); LOG_INFO("ProgramObject release\n"); } bool ProgramObject::initFragmentShaderSourceFromString(const char* fragShader) { return m_programID != 0 && m_fragObj.init(GL_FRAGMENT_SHADER) && m_fragObj.loadShaderSourceFromString(fragShader); } bool ProgramObject::initVertexShaderSourceFromString(const char* vertShader) { return m_programID != 0 && m_vertObj.init(GL_VERTEX_SHADER) && m_vertObj.loadShaderSourceFromString(vertShader); } bool ProgramObject::link() { LOG_INFO("COMPILE PROGRAM!!!!\n"); GLuint attachedShaders[32]; int numAttachedShaders, programStatus; glGetAttachedShaders(m_programID, 32, &numAttachedShaders, attachedShaders); for(int i = 0; i < numAttachedShaders; ++i) { glDetachShader(m_programID, attachedShaders[i]); } htCheckGLError("Detach Shaders in useProgram"); glAttachShader(m_programID, m_vertObj.getShaderID()); glAttachShader(m_programID, m_fragObj.getShaderID()); htCheckGLError("Attach Shaders in useProgram"); glLinkProgram(m_programID); glGetProgramiv(m_programID, GL_LINK_STATUS, &programStatus); m_vertObj.clear(); m_fragObj.clear();
LOG_INFO("LINK %d OK\n", m_programID); htCheckGLError("Link Program"); return true; } void ProgramObject::bind() { glUseProgram(m_programID); } void ProgramObject::sendUniformf(const char* name, GLfloat x) { GETUNIFORM(uniform, m_programID, name); glUniform1f(uniform, x); } void ProgramObject::sendUniformf(const char* name, GLfloat x, GLfloat y) { GETUNIFORM(uniform, m_programID, name); glUniform2f(uniform, x, y); } void ProgramObject::sendUniformf(const char* name, GLfloat x, GLfloat y, GLfloat z) { GETUNIFORM(uniform, m_programID, name); glUniform3f(uniform, x, y, z); } void ProgramObject::sendUniformf(const char* name, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { GETUNIFORM(uniform, m_programID, name); glUniform4f(uniform, x, y, z, w); } void ProgramObject::sendUniformi(const char* name, GLint x) { GETUNIFORM(uniform, m_programID, name); glUniform1i(uniform, x); } void ProgramObject::sendUniformi(const char* name, GLint x, GLint y) { GETUNIFORM(uniform, m_programID, name); glUniform2i(uniform, x, y); } void ProgramObject::sendUniformi(const char* name, GLint x, GLint y, GLint z) { GETUNIFORM(uniform, m_programID, name); glUniform3i(uniform, x, y, z); } void ProgramObject::sendUniformi(const char* name, GLint x, GLint y, GLint z, GLint w) { GETUNIFORM(uniform, m_programID, name); glUniform4i(uniform, x, y, z, w); } void ProgramObject::sendUniformMat2x2(const char* name, int count, GLboolean transpose, const GLfloat* matrix) { GETUNIFORM(uniform, m_programID, name); glUniformMatrix2fv(uniform, count, transpose, matrix); } void ProgramObject::sendUniformMat3x3(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix) { GETUNIFORM(uniform, m_programID, name); glUniformMatrix3fv(uniform, count, transpose, matrix); } void ProgramObject::sendUniformMat4x4(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix) { GETUNIFORM(uniform, m_programID, name); glUniformMatrix4fv(uniform, count, transpose, matrix); }
if(programStatus != GL_TRUE) { GLint logLen = 0; glGetProgramiv(m_programID, GL_INFO_LOG_LENGTH, &logLen); if(logLen != 0) { char *buf = new char[logLen]; if(buf != NULL) { glGetProgramInfoLog(m_programID, logLen, &logLen, buf); LOG_ERROR("Failed to link the program!\n%s", buf); delete [] buf; } } LOG_INFO("LINK %d Failed\n", m_programID); return false; }
if_condition
[ { "content": "class ProgramObject\n\n{\n\npublic:\n\n\tProgramObject();\n\n\t~ProgramObject();\n\n\n\n\tbool initFragmentShaderSourceFromString(const char* fragShader);\n\n\tbool initVertexShaderSourceFromString(const char* vertShader);\n\n\n\n\tbool link();\n\n\tvoid bind();\n\n\n\n\t// For usage convenience, do not use template here.\n\n\tvoid sendUniformf(const char* name, GLfloat);\n\n\tvoid sendUniformf(const char* name, GLfloat, GLfloat);\n\n\tvoid sendUniformf(const char* name, GLfloat, GLfloat, GLfloat);\n\n\tvoid sendUniformf(const char* name, GLfloat, GLfloat, GLfloat, GLfloat);\n\n\n\n\tvoid sendUniformi(const char* name, GLint);\n\n\tvoid sendUniformi(const char* name, GLint, GLint);\n", "file_path": "snake3d/wyShaderFunctions.h", "rank": 0, "score": 52519.19651776959 }, { "content": "class ShaderObject\n\n{\n\npublic:\n\n\tShaderObject();\n\n\t~ShaderObject();\n\n\tbool init(GLenum shaderType);\n\n\tbool loadShaderSourceFromString(const char* shaderString);\n\n\tinline GLuint getShaderID() { return m_shaderID; }\n\n\tvoid clear();\n\nprivate:\n\n\tGLenum m_shaderType;\n\n\tGLuint m_shaderID;\n\n};\n\n\n", "file_path": "snake3d/wyShaderFunctions.h", "rank": 1, "score": 35453.444124830115 }, { "content": "\tvoid sendUniformi(const char* name, GLint, GLint, GLint);\n\n\tvoid sendUniformi(const char* name, GLint, GLint, GLint, GLint);\n\n\n\n\tvoid sendUniformMat2x2(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix);\n\n\tvoid sendUniformMat3x3(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix);\n\n\tvoid sendUniformMat4x4(const char* name, GLsizei count, GLboolean transpose, const GLfloat* matrix);\n\n\n\n\tinline GLuint programId() { return m_programID; }\n\n\tinline GLint attributeLocation(const char* name) { return glGetAttribLocation(m_programID, name); }\n\n\tinline GLint uniformLocation(const char* name) { return glGetUniformLocation(m_programID, name); } \n\n\tinline void bindAttributeLocation(const char* name, GLuint index) { return glBindAttribLocation(m_programID, index, name); }\n\nprivate:\n\n\tShaderObject m_vertObj, m_fragObj;\n\n\tGLuint m_programID;\n\n};\n\n\n\n\n\n#endif\n", "file_path": "snake3d/wyShaderFunctions.h", "rank": 2, "score": 29362.458325119598 }, { "content": "/*\n\n * htShaderFunctions.h\n\n *\n\n * Created on: 2013-12-6\n\n * Author: Wang Yang\n\n */\n\n\n\n#ifndef _HTSAHDERFUNCTIONS_H_\n\n#define _HTSAHDERFUNCTIONS_H_\n\n\n\n#include \"wyGLFunctions.h\"\n\n\n", "file_path": "snake3d/wyShaderFunctions.h", "rank": 3, "score": 29351.912947291374 }, { "content": "\t\n\n\thtCheckGLError(\"Ground::initPrograms\");\n\n\treturn true;\n\n}\n\n\n\nbool WYGround::initProgramsNoTexture()\n\n{\n\n\tclearGroundTexture();\n\n\n\n\tif(!(m_program.initVertexShaderSourceFromString(s_vshGroundNoTexture) &&\n\n\t\tm_program.initFragmentShaderSourceFromString(s_fshGroundNoTexture) &&\n\n\t\tm_program.link()))\n\n\t{\n\n\t\tLOG_ERROR(\"Ground : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\n\n\n\n\tif(!(m_programMesh.initVertexShaderSourceFromString(s_vshGroundNoTexture) &&\n\n\t\tm_programMesh.initFragmentShaderSourceFromString(s_fshGroundMesh) &&\n\n\t\tm_programMesh.link()))\n", "file_path": "snake3d/wyGround.cpp", "rank": 15, "score": 17.66316633459555 }, { "content": "\tglDeleteBuffers(1, &m_skyIndexVBO);\n\n\tm_skyVBO = m_skyIndexVBO = 0;\n\n}\n\n\n\nbool WYSky::initPrograms()\n\n{\n\n\tm_vertAttribLocation = 0;\n\n\n\n\tif(m_program.initVertexShaderSourceFromString(s_vshSky) &&\n\n\t\tm_program.initFragmentShaderSourceFromString(s_fshSky))\n\n\t{\n\n\t\tm_program.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\t}\n\n\n\n\n\n\tif(!(m_program.initVertexShaderSourceFromString(s_vshSky) &&\n\n\t\tm_program.initFragmentShaderSourceFromString(s_fshSky) &&\n\n\t\tm_program.link()))\n\n\t{\n\n\t\tLOG_ERROR(\"WYSky : Program link failed!\\n\");\n", "file_path": "snake3d/wySky.cpp", "rank": 16, "score": 17.564048054971224 }, { "content": "\n\nvoid WYSnake::clearSnakeTexture()\n\n{\n\n\tglDeleteTextures(1, &m_snakeTexture);\n\n\tm_snakeTexture = 0;\n\n}\n\n\n\nbool WYSnake::initPrograms()\n\n{\n\n\tm_vertAttribLocation = 0;\n\n\tm_dirAttribLocation = 1;\n\n\tm_relDataAttribLocation = 2;\n\n\n\n\tif(m_program.initVertexShaderSourceFromString(s_vshSnake) &&\n\n\t\tm_program.initFragmentShaderSourceFromString(s_fshSnake))\n\n\t{\n\n\t\tm_program.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\t\tm_program.bindAttributeLocation(paramSnakeDirName, m_dirAttribLocation);\n\n\t\tm_program.bindAttributeLocation(paramSnakeRelDataName, m_relDataAttribLocation);\n\n\t}\n", "file_path": "snake3d/wySnake.cpp", "rank": 17, "score": 16.658053051065025 }, { "content": "\t\treturn false;\n\n\t}\n\n\n\n\tif(m_programMesh.initVertexShaderSourceFromString(s_vshSkyNoTexture) &&\n\n\t\tm_programMesh.initFragmentShaderSourceFromString(s_fshSkyNoTexture))\n\n\t{\n\n\t\tm_programMesh.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\t}\n\n\n\n\tif(!m_programMesh.link())\n\n\t{\n\n\t\tLOG_ERROR(\"WYSky : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\n\n\n\n\thtCheckGLError(\"WYSky::initPrograms\");\n\n\treturn true;\n\n}\n", "file_path": "snake3d/wySky.cpp", "rank": 18, "score": 15.664189743218882 }, { "content": "\t\tm_program.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\t}\n\n\n\n\tif(!m_program.link())\n\n\t{\n\n\t\tLOG_ERROR(\"Ground : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\n\n\n\n\tif(m_programMesh.initVertexShaderSourceFromString(s_vshGroundNoTexture) &&\n\n\t\tm_programMesh.initFragmentShaderSourceFromString(s_fshGroundMesh))\n\n\t{\n\n\t\tm_programMesh.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\t}\n\n\n\n\tif(!m_programMesh.link())\n\n\t{\n\n\t\tLOG_ERROR(\"Ground : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\n", "file_path": "snake3d/wyGround.cpp", "rank": 19, "score": 15.534435415849726 }, { "content": "\tstatic const char* const paramModelviewMatrixName;\n\n\tstatic const char* const paramVertexPositionName;\n\n\tstatic const char* const paramSnakeTextureName;\n\n\tstatic const char* const paramSnakeDirName;\n\n\tstatic const char* const paramSnakeRelDataName;\n\n\n\n\tbool initSnakeTexture(const char* texName);\n\n\tvoid clearSnakeTexture();\n\n\tbool initPrograms();\n\n\tvoid initSnakeBuffers();\n\n\tvoid clearSnakeBuffers();\n\n\tGLuint genModelBySkeleton(); //根据骨骼生成模型\n\n//\tGLuint genFacesBySkeleton();\n\n\n\n\tenum SnakeTurning { Turn_None, Turn_Left, Turn_Right };\n\n\n\nprotected:\n\n\tGLuint m_snakeVBO, m_snakeDirVBO, m_snakeRelDataVBO, m_snakeIndexVBO;\n\n\tGLuint m_snakeVertIndexSize;\n\n\tstd::vector<SnakeBody> m_snakeSkeleton[2];\n\n\tProgramObject m_program, m_programMesh;\n\n\tGLuint m_vertAttribLocation, m_dirAttribLocation, m_relDataAttribLocation;\n\n\tGLuint m_snakeTexture;\n\n\tSnakeTurning m_nextTurn;\n\n\tint m_skeletonIndex;\n\n};\n\n\n\n\n\n#endif", "file_path": "snake3d/wySnake.h", "rank": 20, "score": 15.297165328611603 }, { "content": "\t}\n\n\tm_groundTexture = htGenTextureWithBuffer(image.bits(), image.width(), image.height(), GL_RGBA, GL_UNSIGNED_BYTE);\n\n\n\n\thtCheckGLError(\"initGroundTexture\");\n\n\treturn m_groundTexture != 0;\n\n}\n\n\n\nvoid WYGround::clearGroundTexture()\n\n{\n\n\tglDeleteTextures(1, &m_groundTexture);\n\n\tm_groundTexture = 0;\n\n}\n\n\n\nbool WYGround::initPrograms()\n\n{\n\n\tm_vertAttribLocation = 0;\n\n\n\n\tif(m_program.initVertexShaderSourceFromString(s_vshGround) &&\n\n\t\tm_program.initFragmentShaderSourceFromString(s_fshGround))\n\n\t{\n", "file_path": "snake3d/wyGround.cpp", "rank": 21, "score": 14.202896954009338 }, { "content": "\n\n\tif(!m_program.link())\n\n\t{\n\n\t\tLOG_ERROR(\"WYSnake : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\n\n\n\n\tif(m_programMesh.initVertexShaderSourceFromString(s_vshSnakeNoTexture) &&\n\n\t\tm_programMesh.initFragmentShaderSourceFromString(s_fshSnakeNotexture))\n\n\t{\n\n\t\tm_programMesh.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\t\n\n\t\tm_programMesh.bindAttributeLocation(paramSnakeDirName, m_dirAttribLocation);\n\n\t\tm_programMesh.bindAttributeLocation(paramSnakeRelDataName, m_relDataAttribLocation);\n\n\t}\n\n\n\n\tif(!m_programMesh.link())\n\n\t{\n\n\t\tLOG_ERROR(\"WYSnake : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\t\n", "file_path": "snake3d/wySnake.cpp", "rank": 22, "score": 14.064959615074395 }, { "content": "\t{\n\n\t\tLOG_ERROR(\"Ground : Program link failed!\\n\");\n\n\t\treturn false;\n\n\t}\n\n\n\n\tm_vertAttribLocation = 0;\n\n\n\n\tm_program.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\tm_programMesh.bindAttributeLocation(paramVertexPositionName, m_vertAttribLocation);\n\n\thtCheckGLError(\"Ground::initProgramsNoTexture\");\n\n\treturn true;\n\n}\n", "file_path": "snake3d/wyGround.cpp", "rank": 23, "score": 13.081843705020312 }, { "content": "void WYGround::clearGround()\n\n{\n\n\tglDeleteBuffers(1, &m_groundVBO);\n\n\tm_groundVBO = 0;\n\n\n\n\tglDeleteBuffers(1, &m_groundIndexVBO);\n\n\tm_groundIndexVBO = 0;\n\n\n\n\tglDeleteBuffers(1, &m_groundMeshIndexVBO);\n\n\tm_groundMeshIndexVBO = 0;\n\n\n\n}\n\n\n\nvoid WYGround::drawGround(const wy::Mat4& mvp)\n\n{\n\n\tm_program.bind();\n\n\tm_program.sendUniformMat4x4(paramModelviewMatrixName, 1, GL_FALSE, mvp[0]);\n\n\n\n\tif(m_groundTexture != 0)\n\n\t{\n", "file_path": "snake3d/wyGround.cpp", "rank": 24, "score": 12.894548387558714 }, { "content": "{\n\n\tclearSkyTexture();\n\n\tclearSkyBuffers();\n\n}\n\n\n\nbool WYSky::initSky(const char* texName)\n\n{\n\n\tclearSkyBuffers();\n\n\n\n\tconst float radiusStep = SKY_RADIUS / SKY_RADIUS_VERTEX_SIZE;\n\n\tconst float radianStep = (M_PI * 2.0f) / SKY_PERIMETER_CLIP_SIZE;\n\n\n\n\tstd::vector<wy::Vec3f> skyVertices;\n\n\tskyVertices.resize(SKY_RADIUS_VERTEX_SIZE * (SKY_PERIMETER_CLIP_SIZE + 1) + 1);\n\n\tint index = 0;\n\n\tfor(int i = 0; i < SKY_RADIUS_VERTEX_SIZE; ++i)\n\n\t{\n\n\t\tconst float z = i * radiusStep;\n\n\t\tconst float dis = sqrtf(SKY_RADIUS*SKY_RADIUS - z*z);\n\n\t\tfor(int j = 0; j <= SKY_PERIMETER_CLIP_SIZE; ++j)\n", "file_path": "snake3d/wySky.cpp", "rank": 25, "score": 12.075170931899436 }, { "content": "\tfor(int i = 0; i != sz; ++i)\n\n\t{\n\n\t\tindexData.push_back(dataIndex[i]);\n\n\t}\n\n}\n\n\n\nbool WYGround::initWithStage(const int *stage, int w, int h, const char* texName)\n\n{\n\n// \tm_groundSize[0] = w;\n\n// \tm_groundSize[1] = h;\n\n\n\n\tclearGround();\n\n\n\n\tconst float widthStep = 1.0f;\n\n\tconst float heightStep = 1.0f;\n\n\tconst float halfWidth = w / 2.0f;\n\n\tconst float halfHeight = h / 2.0f;\n\n\n\n\tm_groundVertices.resize((w + 1) * (h + 1));\n\n\tint index = 0;\n", "file_path": "snake3d/wyGround.cpp", "rank": 26, "score": 11.38930150286158 }, { "content": "void WYSky::drawSkyWithMesh(const wy::Mat4& mvp)\n\n{\n\n\tm_programMesh.bind();\n\n\tm_program.sendUniformMat4x4(paramModelviewMatrixName, 1, GL_FALSE, mvp[0]);\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_skyVBO);\n\n\tglEnableVertexAttribArray(m_vertAttribLocation);\n\n\tglVertexAttribPointer(m_vertAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_skyIndexVBO);\n\n\n\n\tglDrawElements(GL_LINE_STRIP, m_vertexIndexSize, GL_UNSIGNED_SHORT, 0);\n\n\thtCheckGLError(\"drawSkyWithMesh\");\n\n}\n\n\n\nbool WYSky::initSkyTexture(const char* texName)\n\n{\n\n\tclearSkyTexture();\n\n\tQImage image = QImage(texName).convertToFormat(QImage::Format_RGBA8888);\n\n\tif(image.width() < 1)\n", "file_path": "snake3d/wySky.cpp", "rank": 27, "score": 11.386357086548784 }, { "content": ");\n\n\n\nconst char* const WYSnake::paramModelviewMatrixName = \"m4MVP\";\n\nconst char* const WYSnake::paramVertexPositionName = \"v3Position\";\n\nconst char* const WYSnake::paramSnakeTextureName = \"snakeTexture\";\n\nconst char* const WYSnake::paramSnakeDirName = \"v3Norm\";\n\nconst char* const WYSnake::paramSnakeRelDataName = \"v2Relative\";\n\n\n\nWYSnake::WYSnake() : m_snakeVBO(0), m_snakeIndexVBO(0), m_snakeDirVBO(0), m_snakeRelDataVBO(0), m_vertAttribLocation(0), m_snakeTexture(0), m_nextTurn(Turn_None), m_skeletonIndex(0)\n\n{\n\n\n\n}\n\n\n\nWYSnake::~WYSnake()\n\n{\n\n\tclearSnakeTexture();\n\n\tclearSnakeBuffers();\n\n}\n\n\n\nbool WYSnake::init(float x, float y, const char* texName, float len, float xNorm, float yNorm)\n", "file_path": "snake3d/wySnake.cpp", "rank": 28, "score": 10.510945179418197 }, { "content": "\t{\n\n\t\tLOG_ERROR(\"Failed to open file %s!\\n\", texName);\n\n\t\treturn false;\n\n\t}\n\n\n\n\tm_skyTexture = htGenTextureWithBuffer(image.bits(), image.width(), image.height(), GL_RGBA, GL_UNSIGNED_BYTE);\n\n\n\n\thtCheckGLError(\"initSkyTexture\");\n\n\treturn m_skyTexture != 0;\n\n}\n\n\n\nvoid WYSky::clearSkyTexture()\n\n{\n\n\tglDeleteTextures(1, &m_skyTexture);\n\n\tm_skyTexture = 0;\n\n}\n\n\n\nvoid WYSky::clearSkyBuffers()\n\n{\n\n\tglDeleteBuffers(1, &m_skyVBO);\n", "file_path": "snake3d/wySky.cpp", "rank": 29, "score": 10.44397110772355 }, { "content": "/*\n\n * WYSceneWindow.cpp\n\n *\n\n * Created on: 2014-6-5\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n\n\n#include \"WYSceneWindow.h\"\n\n\n\nWYSceneWindow* g_sceneWindow = NULL;\n\n\n\nconst char* const s_vshScene = SHADER_STRING\n\n(\n\nattribute vec3 vPosition;\n\n\n\nvoid main()\n\n{\n\n\tgl_Position = vec4(vPosition, 1.0);\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 30, "score": 10.291554441399779 }, { "content": "\tgl_FragColor.rb *= fHeight;\n\n}\n\n);\n\n\n\nstatic const char* const s_fshGroundMesh = SHADER_STRING_PRECISION_L\n\n(\n\nvoid main()\n\n{\n\n\tgl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);\n\n}\n\n);\n\n\n\n\n\nconst char* const WYGround::paramModelviewMatrixName = \"m4MVP\";\n\nconst char* const WYGround::paramVertexPositionName = \"v3Position\";\n\nconst char* const WYGround::paramGroundTextureName = \"groundTexture\";\n\n//const char* const WYGround::paramGroundSizeName = \"v2GroundSize\";\n\n\n\nWYGround::WYGround() : m_groundVBO(0), m_groundIndexVBO(0), m_groundMeshIndexVBO(0), m_groundIndexSize(0), m_meshIndexSize(0), m_groundTexture(0)//, m_groundSize()\n\n{\n", "file_path": "snake3d/wyGround.cpp", "rank": 31, "score": 9.962438514555188 }, { "content": "uniform sampler2D skyTexture;\n\nvarying vec2 v2TexCoord;\n\n\n\n\n\nvoid main()\n\n{\n\n\tgl_FragColor = texture2D(skyTexture, v2TexCoord);\n\n}\n\n);\n\n\n\nconst char* const WYSky::paramModelviewMatrixName = \"m4MVP\";\n\nconst char* const WYSky::paramVertexPositionName = \"v3Position\";\n\nconst char* const WYSky::paramSkyTextureName = \"skyTexture\";\n\n\n\nWYSky::WYSky() : m_skyVBO(0), m_skyIndexVBO(0), m_skyTexture(0)\n\n{\n\n\tm_vertAttribLocation = 0;\n\n}\n\n\n\nWYSky::~WYSky()\n", "file_path": "snake3d/wySky.cpp", "rank": 32, "score": 9.829975961319064 }, { "content": "#if !defined(QT_OPENGL_ES_2) && !defined(Q_OS_MAC)\n\n g_glFunctions = context()->functions();\n\n#endif\n\n\n\n\tglClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n\n\n\n\tm_ground = new WYGround;\n\n\tif(!m_ground->initWithStage(g_stage1, g_stage1Width, g_stage1Height, g_stage1GroundTextureName))\n\n\t{\n\n\t\tLOG_ERROR(\"Init Stage Failed!\");\n\n\t}\n\n\n\n\tm_sky = new WYSky;\n\n\tif(!m_sky->initSky(g_skyTextureName))\n\n\t{\n\n\t\tLOG_ERROR(\"Init Sky Failed\\n!\");\n\n\t}\n\n\n\n\tm_snake = new WYSnake;\n\n\tif(!m_snake->init(0.0f, 0.0f, g_stage1SnakeTextureName, 10.0f))\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 33, "score": 9.780821978530486 }, { "content": "}\n\n);\n\n\n\nconst char* const s_fshSceneNormal = SHADER_STRING_PRECISION_M\n\n(\n\n\n\nvoid main()\n\n{\n\n\tgl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n}\n\n);\n\n\n\nconst char* const s_fshSceneMesh = SHADER_STRING_PRECISION_M\n\n(\n\n\n\nvoid main()\n\n{\n\n\tgl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n}\n\n);\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 34, "score": 9.626540430779801 }, { "content": "\n\n\thtCheckGLError(\"WYSnake::initPrograms\");\n\n\treturn true;\n\n}\n\n\n\nvoid WYSnake::initSnakeBuffers()\n\n{\n\n\tclearSnakeBuffers();\n\n\tglGenBuffers(1, &m_snakeVBO);\n\n\tglGenBuffers(1, &m_snakeIndexVBO);\n\n\tglGenBuffers(1, &m_snakeDirVBO);\n\n\tglGenBuffers(1, &m_snakeRelDataVBO);\n\n}\n\n\n\nvoid WYSnake::clearSnakeBuffers()\n\n{\n\n\tglDeleteBuffers(1, &m_snakeVBO);\n\n\tglDeleteBuffers(1, &m_snakeIndexVBO);\n\n\tglDeleteBuffers(1, &m_snakeDirVBO);\n\n\tglDeleteBuffers(1, &m_snakeRelDataVBO);\n\n\tm_snakeVBO = m_snakeDirVBO = m_snakeRelDataVBO = m_snakeIndexVBO = 0;\n\n}\n", "file_path": "snake3d/wySnake.cpp", "rank": 35, "score": 9.426588391443977 }, { "content": "/*\n\n * WYGround.cpp\n\n *\n\n * Created on: 2014-6-6\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n#include \"wyGround.h\"\n\n\n\n#define GROUND_TEXTURE_ID GL_TEXTURE1\n\n#define GROUND_TEXTURE_INDEX (GROUND_TEXTURE_ID - GL_TEXTURE0)\n\n\n\nstatic const char* const s_vshGroundNoTexture = SHADER_STRING\n\n(\n\nattribute vec3 v3Position;\n\nuniform mat4 m4MVP;\n\n\n\nvoid main()\n\n{\n", "file_path": "snake3d/wyGround.cpp", "rank": 36, "score": 9.009204772261691 }, { "content": "\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_groundVBO);\n\n\tglEnableVertexAttribArray(m_vertAttribLocation);\n\n\tglVertexAttribPointer(m_vertAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_groundMeshIndexVBO);\n\n\n\n\tglDrawElements(GL_LINES, m_meshIndexSize, GL_UNSIGNED_SHORT, 0);\n\n\thtCheckGLError(\"drawGroundWithMesh\");\n\n}\n\n\n\nbool WYGround::initGroundTexture(const char* texName)\n\n{\n\n\tclearGroundTexture();\n\n\n\n QImage image = QImage(texName).convertToFormat(QImage::Format_RGBA8888);\n\n\tif(image.width() < 1)\n\n\t{\n\n\t\tLOG_ERROR(\"Failed to open file %s!\\n\", texName);\n\n\t\treturn false;\n", "file_path": "snake3d/wyGround.cpp", "rank": 37, "score": 8.97331556327931 }, { "content": ");\n\n\n\nstatic const char* const s_vshSky = SHADER_STRING\n\n(\n\nattribute vec3 v3Position;\n\nuniform mat4 m4MVP;\n\nvarying vec2 v2TexCoord;\n\n\n\nconst float skyRadius = 10.0;\n\n\n\nvoid main()\n\n{\n\n\n\n\tgl_Position = m4MVP * vec4(v3Position, 1.0);\n\n\tv2TexCoord = (v3Position.xy / skyRadius + 1.0) / 2.0;\n\n}\n\n);\n\n\n\nstatic const char* const s_fshSky = SHADER_STRING_PRECISION_M\n\n(\n", "file_path": "snake3d/wySky.cpp", "rank": 38, "score": 8.880293227727604 }, { "content": ");\n\n\n\nstatic const char* const s_fshGroundNoTexture = SHADER_STRING_PRECISION_M\n\n(\n\nvoid main()\n\n{\n\n\tgl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);\n\n}\n\n);\n\n\n\nstatic const char* const s_fshGround = SHADER_STRING_PRECISION_M\n\n(\n\nuniform sampler2D groundTexture;\n\nvarying vec2 v2TexCoord;\n\nvarying float fHeight;\n\n\n\nvoid main()\n\n{\n\n\t//gl_FragColor = texture2D(groundTexture, fract(v2TexCoord));\n\n\tgl_FragColor = texture2D(groundTexture, v2TexCoord);\n", "file_path": "snake3d/wyGround.cpp", "rank": 39, "score": 8.74652336960834 }, { "content": "\t\t}\t\t\n\n\t}\n\n\tsnakeSkeletonRead = snakeSkeletonWrite;\n\n}\n\n\n\nbool WYSnake::initSnakeTexture(const char* texName)\n\n{\n\n\tclearSnakeTexture();\n\n\n\n\tQImage image = QImage(texName).convertToFormat(QImage::Format_RGBA8888);\n\n\tif(image.width() < 1)\n\n\t{\n\n\t\tLOG_ERROR(\"Failed to open file %s!\\n\", texName);\n\n\t\treturn false;\n\n\t}\n\n\tm_snakeTexture = htGenTextureWithBuffer(image.bits(), image.width(), image.height(), GL_RGBA, GL_UNSIGNED_BYTE);\n\n\n\n\thtCheckGLError(\"initGroundTexture\");\n\n\treturn m_snakeTexture != 0;\n\n}\n", "file_path": "snake3d/wySnake.cpp", "rank": 40, "score": 8.532787633608278 }, { "content": "\tbool initPrograms();\n\n\tbool initProgramsNoTexture();\n\n\n\n static void genCube(std::vector<wy::Vec3f>& vertexData, std::vector<unsigned short>& indexData, float x, float y, float width, float height);\n\n\n\nprotected:\n\n\tGLuint m_groundVBO, m_groundIndexVBO, m_groundMeshIndexVBO;\n\n std::vector<wy::Vec3f> m_groundVertices;\n\n//\twy::Vec2f m_groundSize;\n\n\tGLuint m_groundIndexSize, m_meshIndexSize;\n\n\tGLuint m_groundTexture;\n\n\tProgramObject m_program, m_programMesh;\n\n\tGLuint m_vertAttribLocation;\n\n};\n\n\n\n\n\n\n\n#endif\n", "file_path": "snake3d/wyGround.h", "rank": 41, "score": 8.3016437000786 }, { "content": "\t\tconst SnakeBody bd(coord[0], norm[0], coord[1], norm[1], SNAKE_DEFAULT_HEIGHT, SNAKE_DEFAULT_ZNORM);\n\n\t\tm_snakeSkeleton[0].push_back(bd);\n\n\t\tm_snakeSkeleton[1].push_back(bd);\n\n\t}\n\n\t\n\n\tinitSnakeBuffers();\n\n\treturn initPrograms() && initSnakeTexture(texName);\n\n}\n\n\n\nvoid WYSnake::drawSnake(const wy::Mat4& mvp)\n\n{\n\n\tGLuint indexSize = genModelBySkeleton();\n\n\tm_program.bind();\n\n\tm_program.sendUniformMat4x4(paramModelviewMatrixName, 1, GL_FALSE, mvp[0]);\n\n\tglActiveTexture(SNAKE_TEXTURE_ID);\n\n\tglBindTexture(GL_TEXTURE_2D, m_snakeTexture);\n\n\tm_program.sendUniformi(paramSnakeTextureName, SNAKE_TEXTURE_INDEX);\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_snakeVBO);\n\n\tglEnableVertexAttribArray(m_vertAttribLocation);\n", "file_path": "snake3d/wySnake.cpp", "rank": 42, "score": 8.16986597384039 }, { "content": "\t\t\n\n\t\tglActiveTexture(GROUND_TEXTURE_ID);\n\n\t\tglBindTexture(GL_TEXTURE_2D, m_groundTexture);\n\n\t\tm_program.sendUniformi(paramGroundTextureName, GROUND_TEXTURE_INDEX);\n\n\t}\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_groundVBO);\n\n\tglEnableVertexAttribArray(m_vertAttribLocation);\n\n\tglVertexAttribPointer(m_vertAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_groundIndexVBO);\n\n\t\n\n\tglDrawElements(GL_TRIANGLES, m_groundIndexSize, GL_UNSIGNED_SHORT, 0);\n\n\thtCheckGLError(\"drawGround\");\n\n}\n\n\n\nvoid WYGround::drawGroundWithMesh(const wy::Mat4& mvp)\n\n{\n\n\tm_programMesh.bind();\n\n\tm_programMesh.sendUniformMat4x4(paramModelviewMatrixName, 1, GL_FALSE, mvp[0]);\n", "file_path": "snake3d/wyGround.cpp", "rank": 43, "score": 7.947791753475041 }, { "content": "\n\n\tm_program.bind();\n\n\tm_program.sendUniformMat4x4(paramModelviewMatrixName, 1, GL_FALSE, mvp[0]);\n\n\n\n\tglActiveTexture(SKY_TEXTURE_ID);\n\n\tglBindTexture(GL_TEXTURE_2D, m_skyTexture);\n\n\tm_program.sendUniformi(paramSkyTextureName, SKY_TEXTURE_INDEX);\n\n\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_skyVBO);\n\n\tglEnableVertexAttribArray(m_vertAttribLocation);\n\n\tglVertexAttribPointer(m_vertAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_skyIndexVBO);\n\n\n\n\tglDrawElements(GL_TRIANGLES, m_vertexIndexSize, GL_UNSIGNED_SHORT, 0);\n\n\thtCheckGLError(\"drawSky\");\n\n\n\n}\n\n\n", "file_path": "snake3d/wySky.cpp", "rank": 44, "score": 7.904313311275178 }, { "content": "\n\n\tgl_Position = m4MVP * vec4(v3Position, 1.0);\n\n}\n\n);\n\n\n\nstatic const char* const s_vshGround = SHADER_STRING\n\n(\n\nattribute vec3 v3Position;\n\nuniform mat4 m4MVP;\n\nvarying vec2 v2TexCoord;\n\n//uniform vec2 v2GroundSize;\n\nvarying float fHeight;\n\n\n\nvoid main()\n\n{\n\n\n\n\tgl_Position = m4MVP * vec4(v3Position, 1.0);\n\n\tv2TexCoord = (v3Position.xy + 1.0) / 2.0;// / v2GroundSize;\n\n\tfHeight = v3Position.z * 5.0;\n\n}\n", "file_path": "snake3d/wyGround.cpp", "rank": 45, "score": 7.3473118769482415 }, { "content": "\tvoid keyPressEvent(QKeyEvent *);\n\n\tvoid keyReleaseEvent(QKeyEvent *);\n\n\n\n\tvoid wheelEvent(QWheelEvent *);\n\n\n\n\tvoid initOrtho(int w, int h);\n\n\tvoid initPerspective(int w, int h);\n\n\n\n\tvoid updateModelView();\n\n\n\n\tvoid goForward(float dis);\n\n\tvoid goBack(float dis);\n\n\tvoid goLeft(float dis);\n\n\tvoid goRight(float dis);\n\n\n\n\n\nprivate:\n\n\twy::Mat4 m_m4ModelView, m_m4Projection;\n\n\twy::Vec2f m_v2Direction, m_v2Position;\n\n\n", "file_path": "snake3d/WYSceneWindow.h", "rank": 46, "score": 7.318774158311696 }, { "content": "attribute vec3 v3Position;\n\nuniform mat4 m4MVP;\n\nvarying vec3 v3Color;\n\n\n\nconst float skyRadius = 10.0;\n\n\n\nvoid main()\n\n{\n\n\tv3Color = v3Position / skyRadius;\n\n\tgl_Position = m4MVP * vec4(v3Position, 1.0);\n\n}\n\n);\n\n\n\nstatic const char* const s_fshSkyNoTexture = SHADER_STRING_PRECISION_M\n\n(\n\nvarying vec3 v3Color;\n\nvoid main()\n\n{\n\n\tgl_FragColor = vec4(v3Color.yyy, 1.0);//vec4(1.0, v3Color.xy, 1.0);\n\n}\n", "file_path": "snake3d/wySky.cpp", "rank": 47, "score": 7.249674268496701 }, { "content": "/*\n\n * WYSky.cpp\n\n *\n\n * Created on: 2014-6-8\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n * Blog: http://blog.wysaid.org\n\n*/\n\n\n\n#include \"wySky.h\"\n\n\n\n#define SKY_TEXTURE_ID GL_TEXTURE2\n\n#define SKY_TEXTURE_INDEX (SKY_TEXTURE_ID - GL_TEXTURE0)\n\n\n\n#define SKY_RADIUS 10.0f\n\n#define SKY_RADIUS_VERTEX_SIZE 15\n\n#define SKY_PERIMETER_CLIP_SIZE (SKY_RADIUS_VERTEX_SIZE * 3)\n\n\n\nstatic const char* const s_vshSkyNoTexture = SHADER_STRING\n\n(\n", "file_path": "snake3d/wySky.cpp", "rank": 48, "score": 7.1461364621730254 }, { "content": "\t{\n\n\t\tLOG_ERROR(\"Init snake Failed!\\n\");\n\n\t}\n\n\n\n\tQTimer *timer = new QTimer(this);\n\n\tconnect(timer, SIGNAL(timeout()), SLOT(updateGL()));\n\n\ttimer->start(15);\n\n\n\n\tglEnable(GL_DEPTH_TEST);\n\n\t\n\n// \tglEnable(GL_BLEND);\n\n// \tglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n\n\n\n\thtCheckGLError(\"SceneWindow::initializeGL\");\n\n}\n\n\n\nvoid WYSceneWindow::resizeGL(int w, int h)\n\n{\n\n\tglViewport(0, 0, w, h);\n\n\tinitPerspective(w, h);\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 49, "score": 7.0980586909208405 }, { "content": "\tglVertexAttribPointer(m_vertAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_snakeDirVBO);\n\n\tglEnableVertexAttribArray(m_dirAttribLocation);\n\n\tglVertexAttribPointer(m_dirAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_snakeRelDataVBO);\n\n\tglEnableVertexAttribArray(m_relDataAttribLocation);\n\n\tglVertexAttribPointer(m_relDataAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_snakeIndexVBO);\n\n\tglDrawElements(GL_TRIANGLES, indexSize, GL_UNSIGNED_SHORT, 0);\n\n\thtCheckGLError(\"drawSnake\");\n\n}\n\n\n\nvoid WYSnake::drawSnakeWithMesh(const wy::Mat4& mvp)\n\n{\n\n\tGLuint indexSize = genModelBySkeleton();\n\n\tm_programMesh.bind();\n\n\tm_programMesh.sendUniformMat4x4(paramModelviewMatrixName, 1, GL_FALSE, mvp[0]);\n", "file_path": "snake3d/wySnake.cpp", "rank": 50, "score": 6.927761069840364 }, { "content": "\t\t\tv[2] *= len;\n\n\t\t\tv[3] *= len;\n\n\t\t\treturn v;\n\n\t\t}\n\n\n\n\t\tstatic inline void clamp(V& v, typename V::VecDataType low, typename V::VecDataType high)\n\n\t\t{\n\n\t\t\tHT_VEC_CLAMP(v[0], low, high);\n\n\t\t\tHT_VEC_CLAMP(v[1], low, high);\n\n\t\t\tHT_VEC_CLAMP(v[2], low, high);\n\n\t\t\tHT_VEC_CLAMP(v[3], low, high);\n\n\t\t}\n\n\n\n\t};\n\n\n\n}\n\n\n\nnamespace wy\n\n{\n\n\n\n\ttemplate<typename Type, int DIM>\n", "file_path": "snake3d/wyVec.h", "rank": 51, "score": 6.743251132490946 }, { "content": "\t\tmeshIndexes[index] = pos1;\n\n\t\tmeshIndexes[index + 1] = SNAKE_PERIMETER_VERTEX_SIZE - 1;\n\n\t\tmeshIndexes[index + 2] = 0;\n\n\t\tindex += 3;\n\n\t}\t\n\n\n\n\tfor(int i = 0; i < sz - 2; ++i)\n\n\t{\n\n\t\tconst int pos1 = i * SNAKE_PERIMETER_VERTEX_SIZE;\n\n\t\tconst int pos2 = (i + 1) * SNAKE_PERIMETER_VERTEX_SIZE;\n\n\n\n\t\tfor(int j = 0; j < SNAKE_PERIMETER_VERTEX_SIZE - 1; ++j)\n\n\t\t{\n\n\t\t\tmeshIndexes[index] = pos1 + j;\n\n\t\t\tmeshIndexes[index + 1] = pos1 + j + 1;\n\n\t\t\tmeshIndexes[index + 2] = pos2 + j;\n\n\t\t\tmeshIndexes[index + 3] = pos2 + j;\n\n\t\t\tmeshIndexes[index + 4] = pos1 + j + 1;\n\n\t\t\tmeshIndexes[index + 5] = pos2 + j + 1;\n\n\t\t\tindex += 6;\n", "file_path": "snake3d/wySnake.cpp", "rank": 52, "score": 6.63816357126972 }, { "content": "#define SNAKE_DEFAULT_ZNORM 0.0f\n\n\n\nstatic const char* const s_vshSnake = SHADER_STRING\n\n(\n\nvarying vec2 v2TexCoord;\n\nattribute vec3 v3Position;\n\nattribute vec3 v3Norm;\n\nattribute vec2 v2Relative;\n\nuniform mat4 m4MVP;\n\n\n\nconst float PI2 = 3.14159265 * 2.0;\n\n \n\nvoid main()\n\n{\n\n\tvec3 turn = normalize(v3Norm);\n\n\tfloat cosRad = -turn.y;\n\n\tfloat sinRad = sqrt(1.0 - cosRad * cosRad);\n\n\tif(v3Norm.x < 0.0)\n\n\t\tsinRad = -sinRad;\n\n\n", "file_path": "snake3d/wySnake.cpp", "rank": 53, "score": 6.261573270469313 }, { "content": "\n\n\tint snakeHeadIndex = index;\n\n\t\n\n\tstd::vector<unsigned short> meshIndexes;\n\n\tGLuint indexSize = (sz - 2) * (SNAKE_PERIMETER_VERTEX_SIZE - 1) * 6 + SNAKE_PERIMETER_VERTEX_SIZE * 3;\n\n\tmeshIndexes.resize(indexSize);\n\n\t\n\n\tindex = 0;\n\n\n\n\t//蛇头\n\n\t{\n\n\t\tconst int pos1 = snakeHeadIndex;\n\n\n\n\t\tfor(int j = 0; j < SNAKE_PERIMETER_VERTEX_SIZE - 1; ++j)\n\n\t\t{\n\n\t\t\tmeshIndexes[index] = pos1;\n\n\t\t\tmeshIndexes[index + 1] = j;\n\n\t\t\tmeshIndexes[index + 2] = j + 1;\n\n\t\t\tindex += 3;\n\n\t\t}\n", "file_path": "snake3d/wySnake.cpp", "rank": 54, "score": 6.224464758165304 }, { "content": "\n\nprotected:\n\n\tGLuint m_skyVBO, m_skyIndexVBO;\n\n\tGLuint m_skyTexture;\n\n\tProgramObject m_program, m_programMesh;\n\n\tGLuint m_vertAttribLocation;\n\n\tGLuint m_vertexIndexSize;\n\n};\n\n\n\n\n\n\n\n#endif", "file_path": "snake3d/wySky.h", "rank": 55, "score": 6.177251121277467 }, { "content": "\tgl_FragColor = texture2D(snakeTexture, v2TexCoord);\n\n}\n\n);\n\n\n\nstatic const char* const s_vshSnakeNoTexture = SHADER_STRING\n\n(\n\nattribute vec3 v3Position;\n\nattribute vec3 v3Norm;\n\nattribute vec2 v2Relative;\n\nvarying vec3 v3Color;\n\nuniform mat4 m4MVP;\n\n\n\nconst float PI2 = 3.14159265 * 2.0;\n\n\n\nvoid main()\n\n{\n\n\tvec3 turn = normalize(v3Norm);\n\n\tfloat cosRad = -turn.y;\n\n\tfloat sinRad = sqrt(1.0 - cosRad * cosRad);\n\n\tif(v3Norm.x < 0.0)\n", "file_path": "snake3d/wySnake.cpp", "rank": 56, "score": 6.130489823157346 }, { "content": "\tfloat angle = PI2 * v2Relative.x;\n\n\t//Points in xOz平面\n\n\tvec3 pos = v3Position + mat3(cosRad, sinRad, 0.0,\n\n\t\t-sinRad, cosRad, 0.0,\n\n\t\t0.0, 0.0, 1.0) * vec3(cos(angle), 0.0, sin(angle)) * 0.3;\n\n\n\n\tgl_Position = m4MVP * vec4(pos, 1.0);\n\n\n\n\tv2TexCoord = vec2(v2Relative.y, angle / PI2);\n\n}\n\n);\n\n\n\nstatic const char* const s_fshSnake = SHADER_STRING_PRECISION_M\n\n(\n\nuniform sampler2D snakeTexture;\n\nvarying vec2 v2TexCoord;\n\n\n\n\n\nvoid main()\n\n{\n", "file_path": "snake3d/wySnake.cpp", "rank": 57, "score": 6.066984912903893 }, { "content": "/*\n\n * WYSceneWindow.h\n\n *\n\n * Created on: 2014-6-5\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n#ifndef _SCENE_WINDOW_H_\n\n#define _SCENE_WINDOW_H_\n\n\n\n#include <QTimer>\n\n#include <vector>\n\n#include <QImage>\n\n\n\n#include \"wymainwindow.h\"\n\n#include \"wyPlatform_QT.h\"\n\n#include \"wyGLFunctions.h\"\n\n#include \"wyShaderFunctions.h\"\n\n\n\n#include \"wyStages.h\"\n\n#include \"wyGround.h\"\n\n#include \"wySky.h\"\n\n#include \"wySnake.h\"\n\n\n\nusing namespace Snake3D;\n\n\n", "file_path": "snake3d/WYSceneWindow.h", "rank": 58, "score": 6.058611982678672 }, { "content": "\t{\n\n\t\tmeshIndexes2[index] = pos + i;\n\n\t\tmeshIndexes2[index + 1] = pos + i + 1;\n\n\t\tindex += 2;\n\n\t}\n\n\n\n\tglGenBuffers(1, &m_groundMeshIndexVBO);\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_groundMeshIndexVBO);\n\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, meshIndexes2.size() * sizeof(meshIndexes2[0]), meshIndexes2.data(), GL_STATIC_DRAW);\n\n\n\n\thtCheckGLError(\"WYGround::initWithStage\");\n\n\n\n\tif(texName == NULL || !initGroundTexture(texName))\n\n\t{\n\n\t\treturn initProgramsNoTexture();\n\n\t}\n\n\n\n\treturn initPrograms();\n\n}\n\n\n", "file_path": "snake3d/wyGround.cpp", "rank": 59, "score": 5.94870588688519 }, { "content": "\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\n\treturn tex;\n\n}\n\n\n\nvoid WYSceneWindow::initOrtho(int w, int h)\n\n{\n\n m_m4Projection = wy::Mat4::makeOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, -1.0);\n\n}\n\n\n\nvoid WYSceneWindow::initPerspective(int w, int h)\n\n{\t\n\n\tfloat aspectRatio = w / float(h);\n\n\tfloat z = HT_MIN(width(), height());\n\n m_m4Projection = wy::Mat4::makePerspective(m_fovyRad, aspectRatio, .1f, 10000.0f);\n\n}\n\n\n\nvoid WYSceneWindow::updateModelView()\n\n{\n\n using namespace wy;\n\n\tconst Vec2f v2Dir = m_v2Position + m_v2Direction;\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 60, "score": 5.830281991313501 }, { "content": "/*\n\n * main.cpp\n\n *\n\n * Created on: 2014-6-5\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n#include \"wymainwindow.h\"\n\n#include <QtWidgets/QApplication>\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n\tQApplication a(argc, argv);\n\n\tWYMainWindow w;\n\n\tw.setWindowTitle(QString::fromLocal8Bit(\"Snake3D - by wysaid\"));\n\n\tw.show();\n\n\tLOG_INFO(\"GL_INFO %s = %s\\n\", \"Vendor: \", glGetString(GL_VENDOR));\n\n\tLOG_INFO(\"GL_INFO %s = %s\\n\", \"Version: \", glGetString(GL_VERSION));\n\n\tLOG_INFO(\"GL_INFO %s = %s\\n\", \"Renderer: \", glGetString(GL_RENDERER));\n\n\n\n\treturn a.exec();\n\n}", "file_path": "snake3d/main.cpp", "rank": 61, "score": 5.747076808900914 }, { "content": "\n\n\tint index = 0;\n\n\n\n\tfor(int i = 1; i < sz; ++i)\n\n\t{\n\n\t\tconst SnakeBody body = snakeSkeleton[i];\n\n\t\tconst Vec3f v3Pos(body.pos);\n\n\t\tconst Vec3f v3Norm = snakeSkeleton[i - 1].pos - snakeSkeleton[i + 1].pos;\n\n\t\tfor(int j = 0; j < SNAKE_PERIMETER_VERTEX_SIZE; ++j)\n\n\t\t{\n\n\t\t\tsnakeVertices[index] = v3Pos;\n\n\t\t\tsnakeDir[index] = v3Norm;\n\n\t\t\tsnakeRelData[index] = Vec2f(float(j) / (SNAKE_PERIMETER_VERTEX_SIZE - 1), i / float(SNAKE_VERTEX_PER_UNIT));\n\n\t\t\t++index;\n\n\t\t}\n\n\t}\n\n\n\n\tsnakeVertices[index] = snakeSkeleton[0].pos;\n\n\tsnakeDir[index] = snakeSkeleton[0].pos - snakeSkeleton[1].pos;\n\n\tsnakeRelData[index] = Vec2f(-1.0f / 4.0f, 0.0f);\n", "file_path": "snake3d/wySnake.cpp", "rank": 62, "score": 5.352616454716847 }, { "content": "/*\n\n * WYGround.h\n\n *\n\n * Created on: 2014-6-6\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n#ifndef _GROUND_H_\n\n#define _GROUND_H_\n\n\n\n#include \"wyShaderFunctions.h\"\n\n\n", "file_path": "snake3d/wyGround.h", "rank": 63, "score": 5.317589885743425 }, { "content": "}\n\n\n\nvoid WYSceneWindow::mousePressEvent(QMouseEvent *e)\n\n{\n\n\tm_bIsMouseDown = true;\n\n\tm_lastX = e->x();\n\n\tm_lastY = e->y();\n\n}\n\n\n\nvoid WYSceneWindow::mouseDoubleClickEvent(QMouseEvent *e)\n\n{\n\n\n\n}\n\n\n\nvoid WYSceneWindow::mouseMoveEvent(QMouseEvent *e)\n\n{\n\n\tif(!m_bIsMouseDown)\n\n\t\treturn;\n\n\t\n\n using namespace wy;\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 64, "score": 5.2534513158027805 }, { "content": "private:\n\n\tWYGround* m_ground;\n\n\tWYSky* m_sky;\n\n\tWYSnake* m_snake;\n\n\tint m_lastX, m_lastY;\n\n\tfloat m_farAway, m_headUp;\n\n\tfloat m_fovyRad;\n\n\tfloat m_zHeight;\n\n\tbool m_bIsMouseDown;\n\n\tbool m_bDrawWithMesh;\n\n\n\n};\n\n\n\nextern WYSceneWindow* g_sceneWindow;\n\n\n\n\n\n#endif\n", "file_path": "snake3d/WYSceneWindow.h", "rank": 65, "score": 5.181015441946744 }, { "content": "\t\t{\n\n\t\t\tconst float rad = radianStep * j;\n\n\t\t\tskyVertices[index++] = wy::Vec3f(cosf(rad) * dis, sinf(rad) * dis, z);\n\n\t\t}\n\n\t}\n\n\tskyVertices[index] = wy::Vec3f(0.0f, 0.0f, SKY_RADIUS);\n\n\n\n\tglGenBuffers(1, &m_skyVBO);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_skyVBO);\n\n\tglBufferData(GL_ARRAY_BUFFER, skyVertices.size() * sizeof(skyVertices[0]), skyVertices.data(), GL_STATIC_DRAW);\n\n\n\n\tindex = 0;\n\n\tstd::vector<unsigned short> meshIndexes;\n\n\tm_vertexIndexSize = SKY_RADIUS_VERTEX_SIZE * SKY_PERIMETER_CLIP_SIZE * 6;\n\n\tmeshIndexes.resize(m_vertexIndexSize);\n\n\n\n\tfor(int i = 0; i < SKY_RADIUS_VERTEX_SIZE - 1; ++i)\n\n\t{\n\n\t\tconst int pos1 = i * (SKY_PERIMETER_CLIP_SIZE + 1);\n\n\t\tconst int pos2 = (i + 1) * (SKY_PERIMETER_CLIP_SIZE + 1);\n", "file_path": "snake3d/wySky.cpp", "rank": 66, "score": 5.155155643639078 }, { "content": "//计算所需数据: \n\n\n\nGLuint WYSnake::genModelBySkeleton()\n\n{\n\n using namespace wy;\n\n\n\n\tconst float lengthStep = 1.0f / SNAKE_VERTEX_PER_UNIT;\n\n\tconst float radianStep = (M_PI * 2.0f) / (SNAKE_PERIMETER_VERTEX_SIZE - 1);\n\n\n\n\tstd::vector<Vec3f> snakeVertices;\n\n\tstd::vector<Vec3f> snakeDir;\n\n\tstd::vector<Vec2f> snakeRelData;\n\n\tstd::vector<SnakeBody>& snakeSkeleton = m_snakeSkeleton[m_skeletonIndex];\n\n\tint snakeDataSize = snakeSkeleton.size() * SNAKE_PERIMETER_VERTEX_SIZE + 1; //加蛇头\n\n\n\n \tsnakeVertices.resize(snakeDataSize);\n\n\tsnakeDir.resize(snakeDataSize);\n\n\tsnakeRelData.resize(snakeDataSize);\n\n\n\n\tconst int sz = (int)snakeSkeleton.size() - 1;\n", "file_path": "snake3d/wySnake.cpp", "rank": 67, "score": 4.932110712372689 }, { "content": "\n\n\t\tfor(int j = 0; j < SKY_PERIMETER_CLIP_SIZE; ++j)\n\n\t\t{\n\n\t\t\tmeshIndexes[index] = pos1 + j;\n\n\t\t\tmeshIndexes[index + 1] = pos1 + j + 1;\n\n\t\t\tmeshIndexes[index + 2] = pos2 + j;\n\n\t\t\tmeshIndexes[index + 3] = pos2 + j;\n\n\t\t\tmeshIndexes[index + 4] = pos1 + j + 1;\n\n\t\t\tmeshIndexes[index + 5] = pos2 + j + 1;\n\n\t\t\tindex += 6;\n\n\t\t}\n\n\t}\n\n\n\n\tconst int pos1 = (SKY_RADIUS_VERTEX_SIZE - 1) * (SKY_PERIMETER_CLIP_SIZE + 1);\n\n\tconst int pos2 = skyVertices.size() - 1;\n\n\n\n\tfor(int j = 0; j < SKY_PERIMETER_CLIP_SIZE; ++j)\n\n\t{\n\n\t\tmeshIndexes[index] = pos1 + j;\n\n\t\tmeshIndexes[index + 1] = pos1 + j + 1;\n", "file_path": "snake3d/wySky.cpp", "rank": 68, "score": 4.90644943369033 }, { "content": "\t\t{\n\n\t\t\tconst float len = 1.0f / _len(v);\n\n\t\t\tv[0] *= len;\n\n\t\t\tv[1] *= len;\n\n\t\t\treturn v;\n\n\t\t}\n\n\n\n\t\tstatic inline void clamp(V& v, typename V::VecDataType low, typename V::VecDataType high)\n\n\t\t{\n\n\t\t\tHT_VEC_CLAMP(v[0], low, high);\n\n\t\t\tHT_VEC_CLAMP(v[1], low, high);\n\n\t\t}\n\n\t};\n\n\n\n\t//////////////////////////////////////////////////////////////////////////\n\n\n\n\ttemplate<typename V>\n\n\tstruct VecAlgorithmHelp<V, 3>\n\n\t{\n\n\t\tstatic inline V _plus(const V& v1, const V& v2)\n", "file_path": "snake3d/wyVec.h", "rank": 69, "score": 4.899686371017015 }, { "content": "/*\n\n * WYSky.h\n\n *\n\n * Created on: 2014-6-8\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n * Blog: http://blog.wysaid.org\n\n*/\n\n\n\n#ifndef _SKY_H_\n\n#define _SKY_H_\n\n\n\n#include \"wyShaderFunctions.h\"\n\n\n", "file_path": "snake3d/wySky.h", "rank": 70, "score": 4.878378687653655 }, { "content": "\t\t{\n\n\t\t\treturn v[0]*v[0];\n\n\t\t}\n\n\n\n\t\tstatic inline float _len(const V& v)\n\n\t\t{\n\n\t\t\treturn sqrtf(v[0]*v[0]);\n\n\t\t}\n\n\n\n\t\tstatic inline V& _norm(V& v)\n\n\t\t{\n\n\t\t\tconst float len = 1.0f / _len(v);\n\n\t\t\tv[0] *= len;\n\n\t\t\treturn v;\n\n\t\t}\n\n\n\n\t\tstatic inline void clamp(V& v, typename V::VecDataType low, typename V::VecDataType high)\n\n\t\t{\n\n\t\t\tHT_VEC_CLAMP(v[0], low, high);\n\n\t\t}\n", "file_path": "snake3d/wyVec.h", "rank": 71, "score": 4.875600213745531 }, { "content": "/*\n\n * WYSnake.h\n\n *\n\n * Created on: 2014-6-17\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n * Description: First time to use skeleton animation, and I'll use my own method.\n\n*/\n\n\n\n#include \"wySnake.h\"\n\n\n\n#define SNAKE_TEXTURE_ID GL_TEXTURE2\n\n#define SNAKE_TEXTURE_INDEX (SNAKE_TEXTURE_ID - GL_TEXTURE0)\n\n\n\n#define SNAKE_VERTEX_PER_UNIT 5\n\n#define SNAKE_RADIUS 0.5f\n\n#define SNAKE_RADIUS_VERTEX_SIZE 10\n\n#define SNAKE_PERIMETER_VERTEX_SIZE (SNAKE_RADIUS_VERTEX_SIZE * 3)\n\n\n\n#define SNAKE_DEFAULT_HEIGHT 0.5f\n", "file_path": "snake3d/wySnake.cpp", "rank": 72, "score": 4.752306615272156 }, { "content": "\n\nWYSceneWindow::~WYSceneWindow() \n\n{\n\n makeCurrent();\n\n\tdelete m_ground;\n\n}\n\n\n\nvoid WYSceneWindow::paintGL()\n\n{\n\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\t\n\n wy::Mat4 qmat = m_m4Projection * m_m4ModelView;\n\n\t\n\n\tif(m_bDrawWithMesh)\n\n\t{\n\n\t\tm_sky->drawSkyWithMesh(qmat);\n\n\t\tglEnable(GL_DEPTH_TEST);\n\n\t\tm_ground->drawGround(qmat);\n\n\t\tglDisable(GL_DEPTH_TEST);\n\n\t\tm_ground->drawGroundWithMesh(qmat);\n", "file_path": "snake3d/wySceneWindow.cpp", "rank": 73, "score": 4.6723136252310375 }, { "content": "\n\n\t\tstatic inline V& _norm(V& v)\n\n\t\t{\n\n\t\t\tconst float len = 1.0f / _len(v);\n\n\t\t\tv[0] *= len;\n\n\t\t\tv[1] *= len;\n\n\t\t\tv[2] *= len;\t\t\t\n\n\t\t\treturn v;\n\n\t\t}\n\n\n\n\t\tstatic inline void clamp(V& v, typename V::VecDataType low, typename V::VecDataType high)\n\n\t\t{\n\n\t\t\tHT_VEC_CLAMP(v[0], low, high);\n\n\t\t\tHT_VEC_CLAMP(v[1], low, high);\n\n\t\t\tHT_VEC_CLAMP(v[2], low, high);\n\n\t\t}\n\n\t};\n\n\n\n\t//////////////////////////////////////////////////////////////////////////\n\n\n", "file_path": "snake3d/wyVec.h", "rank": 74, "score": 4.560050379214684 }, { "content": "\ttypedef Vec<unsigned char, 2> Vec2ub;\n\n\ttypedef Vec<short, 2> Vec2s;\n\n\ttypedef Vec<unsigned short, 2> Vec2us;\n\n\ttypedef Vec<int, 2> Vec2i;\n\n\ttypedef Vec<unsigned, 2> Vec2ui;\n\n\ttypedef Vec2ui Vec2u;\n\n\ttypedef Vec<long, 2> Vec2l;\n\n\ttypedef Vec<unsigned long, 2> Vec2ul;\n\n\ttypedef Vec<long long, 2> Vec2ll;\n\n\ttypedef Vec<unsigned long long, 2> Vec2ull;\n\n\ttypedef Vec<float, 2> Vec2f;\n\n\ttypedef Vec<double, 2> Vec2d;\n\n\ttypedef Vec<long double, 2> Vec2ld;\n\n\n\n\ttypedef Vec<char, 3> Vec3b;\n\n\ttypedef Vec<unsigned char, 3> Vec3ub;\n\n\ttypedef Vec<short, 3> Vec3s;\n\n\ttypedef Vec<unsigned short, 3> Vec3us;\n\n\ttypedef Vec<int, 3> Vec3i;\n\n\ttypedef Vec<unsigned, 3> Vec3ui;\n", "file_path": "snake3d/wyVec.h", "rank": 75, "score": 4.523426758739012 }, { "content": "WYMainWindow::~WYMainWindow()\n\n{\n\n\tdelete m_scene;\n\n}\n\n\n\n\n\nvoid WYMainWindow::resizeEvent(QResizeEvent *e)\n\n{\n\n\tui.centralWidget->setGeometry(0, 0, width(), height());\n\n\tm_scene->setGeometry(ui.centralWidget->geometry());\n\n}", "file_path": "snake3d/wymainwindow.cpp", "rank": 76, "score": 4.409748890414912 }, { "content": "\t//Only for class Vec.\n\n\ttemplate<typename V, int DIM>\n\n\tstruct VecAlgorithmHelp; //Check your code, when this is called.\n\n\n\n\ttemplate<typename V>\n\n\tstruct VecAlgorithmHelp<V, 1>\n\n\t{\n\n\t\tstatic inline V _plus(const V& v1, const V& v2)\n\n\t\t{\n\n\t\t\treturn V(v1[0] + v2[0]);\n\n\t\t}\n\n\n\n\t\tstatic inline V _minus(const V& v1, const V& v2)\n\n\t\t{\n\n\t\t\treturn V(v1[0] - v2[0]);\n\n\t\t}\n\n\n\n\t\tstatic inline V _oposite(const V& v)\n\n\t\t{\n\n\t\t\treturn V(-v[0]);\n", "file_path": "snake3d/wyVec.h", "rank": 77, "score": 4.400990007168803 }, { "content": "\t\tsinRad = -sinRad;\n\n\n\n\tfloat angle = PI2 * v2Relative.x;\n\n\t//Points in xOz平面\n\n\tvec3 pos = mat3(cosRad, sinRad, 0.0,\n\n\t\t-sinRad, cosRad, 0.0,\n\n\t\t0.0, 0.0, 1.0) * vec3(cos(angle), 0.0, sin(angle));\n\n\n\n\tgl_Position = m4MVP * vec4(v3Position + pos * 0.5, 1.0);\n\n\tv3Color = abs(pos);\n\n}\n\n);\n\n\n\nstatic const char* const s_fshSnakeNotexture = SHADER_STRING_PRECISION_M\n\n(\n\nvarying vec3 v3Color;\n\nvoid main()\n\n{\n\n\tgl_FragColor = vec4(v3Color.x, 1.0, v3Color.z, 1.0);\n\n}\n", "file_path": "snake3d/wySnake.cpp", "rank": 78, "score": 4.39426155815559 }, { "content": "{\n\n\tclearSnakeBuffers();\n\n using namespace wy;\n\n\tVec2f norm(xNorm, yNorm);\n\n\tVec2f pos(x, y);\n\n\tnorm.normalize();\n\n\tm_snakeSkeleton[0].clear();\n\n\tm_snakeSkeleton[1].clear();\n\n\tfloat snakeStride = 1.0f / SNAKE_VERTEX_PER_UNIT;\n\n\t\n\n// \tconst SnakeBody bd2(2.0, 2.0, 0.0, 0.0, SNAKE_DEFAULT_HEIGHT, SNAKE_DEFAULT_ZNORM);\n\n// \tm_snakeSkeleton.push_back(bd2);\n\n// \n\n// \tconst SnakeBody bd1(1.0, 1.0, 0.0, 0.0, SNAKE_DEFAULT_HEIGHT, SNAKE_DEFAULT_ZNORM);\n\n// \tm_snakeSkeleton.push_back(bd1);\n\n\t\n\n\tfor(float f = 0.0f; f < len; f += snakeStride)\n\n\t{\n\n\t\tconst Vec2f v(norm * f);\n\n\t\tconst Vec2f coord(pos - v);\n", "file_path": "snake3d/wySnake.cpp", "rank": 79, "score": 4.354779563108594 }, { "content": "/*\n\n * wymainwindow.h\n\n *\n\n * Created on: 2014-6-5\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n#ifndef WYMAINWINDOW_H\n\n#define WYMAINWINDOW_H\n\n\n\n#include <QtWidgets/QMainWindow>\n\n#include <QtOpenGL/QGLWidget>\n\n#include <QPainter>\n\n#include <QPaintEngine>\n\n#include <QString>\n\n#include <QtEvents>\n\n\n\n\n\n#include \"ui_wymainwindow.h\"\n\n#include \"WYSceneWindow.h\"\n\n\n", "file_path": "snake3d/wymainwindow.h", "rank": 80, "score": 4.3490645714193725 }, { "content": "/*\n\n * WYSnake.h\n\n *\n\n * Created on: 2014-6-17\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n * Description: First time to use skeleton animation, and I'll use my own method.\n\n*/\n\n\n\n#ifndef _WYSNAKE_H_\n\n#define _WYSNAKE_H_\n\n\n\n#include \"wyShaderFunctions.h\"\n\n\n\n//2014-6-28修正:将蛇神修正为结点管理方式。 每个结点不再自由运动,以避免出错。\n\n\n\n//本游戏中的蛇实际上依旧在二维平面上跑(xOy平面), 所以不需要太考虑z值\n\n//关于贪吃蛇拐弯原理: 蛇身每个节点都有自己前进的方向,\n\n//蛇身每个节点在向前运动时会与前一个节点之间坐标差与前进方向计算点积,若小于等于0,才转弯。(实现平滑移动)\n", "file_path": "snake3d/wySnake.h", "rank": 81, "score": 4.246970367331821 }, { "content": "/*\n\n * htPlatforms.h\n\n *\n\n * Created on: 2014-6-8\n\n * Author: Wang Yang\n\n * Description: be compatible with none-angle qt versions.\n\n */\n\n\n\n#include \"wyPlatform_QT.h\"\n\n\n\n#if !defined(QT_OPENGL_ES_2) && !defined(Q_OS_MAC)\n\n\n\nnamespace snake3D_OpenGLFunctions\n\n{\n\n\tQGLFunctions* g_glFunctions = NULL;\n\n}\n\n\n\n#endif\n", "file_path": "snake3d/wyPlatform_QT.cpp", "rank": 82, "score": 4.2365443459846155 }, { "content": "\n\n}\n\n\n\nWYGround::~WYGround()\n\n{\n\n\tclearGround();\n\n}\n\n\n\nvoid WYGround::genCube(std::vector<wy::Vec3f>& vertexData, std::vector<unsigned short>& indexData, float x, float y, float width, float height)\n\n{\n\n using wy::Vec3f;\n\n\tconst float widthStep = 1.0f;\n\n\tconst float heightStep = 1.0f;\n\n\tconst float halfBlockXWidth = widthStep / 2.0f;\n\n\tconst float halfBlockYWidth = heightStep / 2.0f;\n\n\tconst float halfWidth = width / 2.0f;\n\n\tconst float halfHeight = height / 2.0f;\n\n\n\n\tconst Vec3f v(x * widthStep - halfWidth, y * heightStep - halfHeight, 0.0f);\n\n\n", "file_path": "snake3d/wyGround.cpp", "rank": 83, "score": 4.198275842237418 }, { "content": "\tprivate:\n\n\t\tType m_data[DIM];\n\n\t};\n\n\n\n\ttypedef Vec<char, 1> Vec1b;\n\n\ttypedef Vec<unsigned char, 1> Vec1ub;\n\n\ttypedef Vec<short, 1> Vec1s;\n\n\ttypedef Vec<unsigned short, 1> Vec1us;\n\n\ttypedef Vec<int, 1> Vec1i;\n\n\ttypedef Vec<unsigned, 1> Vec1ui;\n\n\ttypedef Vec1ui Vec1u;\n\n\ttypedef Vec<long, 1> Vec1l;\n\n\ttypedef Vec<unsigned long, 1> Vec1ul;\n\n\ttypedef Vec<long long, 1> Vec1ll;\n\n\ttypedef Vec<unsigned long long, 1> Vec1ull;\n\n\ttypedef Vec<float, 1> Vec1f;\n\n\ttypedef Vec<double, 1> Vec1d;\n\n\ttypedef Vec<long double, 1> Vec1ld;\n\n\n\n\ttypedef Vec<char, 2> Vec2b;\n", "file_path": "snake3d/wyVec.h", "rank": 84, "score": 4.167169889482746 }, { "content": "\t{\n\n\t\tconst int pos1 = i * (w + 1);\n\n\t\tconst int pos2 = (i + 1) * (w + 1);\n\n\n\n\t\tfor(int j = 0; j < w; ++j)\n\n\t\t{\n\n\t\t\tmeshIndexes2[index] = pos1 + j;\n\n\t\t\tmeshIndexes2[index + 1] = pos1 + j + 1;\n\n\t\t\tmeshIndexes2[index + 2] = pos1 + j;\n\n\t\t\tmeshIndexes2[index + 3] = pos2 + j;\n\n\t\t\tindex += 4;\n\n\t\t}\n\n\t\tmeshIndexes2[index] = pos1 + w;\n\n\t\tmeshIndexes2[index + 1] = pos2 + w;\n\n\t\tindex += 2;\n\n\t}\n\n\n\n\tconst int pos = h * (w + 1);\n\n\n\n\tfor(int i = 0; i < w; ++i)\n", "file_path": "snake3d/wyGround.cpp", "rank": 85, "score": 4.100086473230104 }, { "content": "\tfor(int i = 0; i <= h; ++i)\n\n\t{\n\n\t\tconst float heightI = i * heightStep;\n\n\n\n\t\tfor(int j = 0; j <= w; ++j)\n\n\t\t{\n\n const wy::Vec3f v(j * widthStep - halfWidth, heightI - halfHeight, 0.0f);\n\n\t\t\tm_groundVertices[index++] = v;\n\n\t\t}\n\n\t}\n\n\n\n\tindex = 0;\n\n\tstd::vector<unsigned short> meshIndexes;\n\n\tm_groundIndexSize = w * h * 6;\n\n\tmeshIndexes.resize(m_groundIndexSize);\n\n\n\n\tfor(int i = 0; i < h; ++i)\n\n\t{\n\n\t\tconst int pos1 = i * (w + 1);\n\n\t\tconst int pos2 = (i + 1) * (w + 1);\n", "file_path": "snake3d/wyGround.cpp", "rank": 86, "score": 3.988596091805652 }, { "content": "/*\n\n * wymainwindow.cpp\n\n *\n\n * Created on: 2014-6-5\n\n * Author: Wang Yang\n\n * Mail: [email protected]\n\n*/\n\n\n\n#include \"wymainwindow.h\"\n\n\n\nWYMainWindow* g_mainwindow;\n\n\n\nWYMainWindow::WYMainWindow(QWidget *parent)\n\n\t: QMainWindow(parent)\n\n{\n\n\tg_mainwindow = this;\n\n\tui.setupUi(this);\n\n\tm_scene = new WYSceneWindow(ui.centralWidget);\n\n}\n\n\n", "file_path": "snake3d/wymainwindow.cpp", "rank": 87, "score": 3.905920340852364 }, { "content": "\n\n inline const Type& x() const { wyStaticAssert(DIM >= 1); return m_data[0]; }\n\n inline const Type& y() const { wyStaticAssert(DIM >= 2); return m_data[1]; }\n\n inline const Type& z() const { wyStaticAssert(DIM >= 3); return m_data[2]; }\n\n inline const Type& w() const { wyStaticAssert(DIM >= 4); return m_data[3]; }\n\n inline const Type& r() const { wyStaticAssert(DIM >= 1); return m_data[0]; }\n\n inline const Type& g() const { wyStaticAssert(DIM >= 2); return m_data[1]; }\n\n inline const Type& b() const { wyStaticAssert(DIM >= 3); return m_data[2]; }\n\n inline const Type& a() const { wyStaticAssert(DIM >= 4); return m_data[3]; }\n\n\n\n\t\tinline Type& get(int index) { return m_data[index]; }\n\n\t\tinline const Type& get(int index) const { return m_data[index]; }\n\n\n\n\t\tinline Vec<Type, 1> subvec(int fst) const { return Vec<Type, 1>(m_data[fst]); }\n\n\t\tinline Vec<Type, 2> subvec(int fst, int scd) const { return Vec<Type, 2>(m_data[fst], m_data[scd]); }\n\n\t\tinline Vec<Type, 3> subvec(int fst, int scd, int trd) const { return Vec<Type, 3>(m_data[fst], m_data[scd], m_data[trd]); }\n\n\t\tinline Vec<Type, 4> subvec(int fst, int scd, int trd, int fth) const { return Vec<Type, 4>(m_data[fst], m_data[scd], m_data[trd], m_data[fth]); }\n\n\n\n\n\n\t\n", "file_path": "snake3d/wyVec.h", "rank": 88, "score": 3.743292558823055 }, { "content": "\t\tmeshIndexes[index + 2] = pos2;\n\n\t\tmeshIndexes[index + 3] = pos2;\n\n\t\tmeshIndexes[index + 4] = pos1 + j + 1;\n\n\t\tmeshIndexes[index + 5] = pos2;\n\n\t\tindex += 6;\n\n\t}\n\n\n\n\tglGenBuffers(1, &m_skyIndexVBO);\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_skyIndexVBO);\n\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, meshIndexes.size() * sizeof(meshIndexes[0]), meshIndexes.data(), GL_STATIC_DRAW);\n\n\n\n\thtCheckGLError(\"WYSky::initSky\");\n\n\n\n\treturn initPrograms() && initSkyTexture(texName);\n\n}\n\n\n\nvoid WYSky::drawSky(const wy::Mat4& mvp)\n\n{\n\n\tif(m_skyTexture == 0)\n\n\t\treturn drawSkyWithMesh(mvp);\n", "file_path": "snake3d/wySky.cpp", "rank": 89, "score": 3.737970358844068 }, { "content": "\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_snakeVBO);\n\n\tglEnableVertexAttribArray(m_vertAttribLocation);\n\n\tglVertexAttribPointer(m_vertAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_snakeDirVBO);\n\n\tglEnableVertexAttribArray(m_dirAttribLocation);\n\n\tglVertexAttribPointer(m_dirAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ARRAY_BUFFER, m_snakeRelDataVBO);\n\n\tglEnableVertexAttribArray(m_relDataAttribLocation);\n\n\tglVertexAttribPointer(m_relDataAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);\n\n\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_snakeIndexVBO);\n\n\tglDrawElements(GL_LINE_STRIP, indexSize, GL_UNSIGNED_SHORT, 0);\n\n\thtCheckGLError(\"drawSnakeWithMesh\");\n\n}\n\n\n\n//Todo: 使用统一body,在shader中进行模型变换。\n\n//body 都在xOy平面内,绕Z轴旋转\n", "file_path": "snake3d/wySnake.cpp", "rank": 90, "score": 3.7158465051958056 }, { "content": "/*\n\n@Author: wysaid\n\n@Blog: blog.wysaid.org\n\n@Date: 2013-10-31\n\n@Description: Provide some cpu math algorithms like glsl shaders.\n\n*/\n\n\n\n#ifndef _HT_VEC_H_\n\n#define _HT_VEC_H_\n\n\n\n#include <cmath>\n\n#define wyStaticAssert(con) static_assert(con, \"Invalid Parameters!\")\n\n\n\n#define HT_VEC_CLAMP(n, low, high) do{\\\n\nif(n < low) n = low;\\\n\nelse if(n > high) n = high;\\\n\n}while(0)\\\n\n\n\nnamespace wy\n\n{\n", "file_path": "snake3d/wyVec.h", "rank": 91, "score": 3.5780401129043784 }, { "content": "\tconst std::vector<Vec3f>::size_type index = vertexData.size(), indexUp = index + 4;\n\n\n\n\tvertexData.push_back(v + Vec3f(-halfBlockXWidth, halfBlockYWidth, 0.0f));\n\n\tvertexData.push_back(v - Vec3f(halfBlockXWidth, halfBlockYWidth, 0.0f));\n\n\tvertexData.push_back(v + Vec3f(halfBlockXWidth, -halfBlockYWidth, 0.0f));\n\n\tvertexData.push_back(v + Vec3f(halfBlockXWidth, halfBlockYWidth, 0.0f));\n\n\n\n\tconst float z = 1.0f;\n\n\n\n\tvertexData.push_back(v + Vec3f(-halfBlockXWidth, halfBlockYWidth, z));\n\n\tvertexData.push_back(v - Vec3f(halfBlockXWidth, halfBlockYWidth, -z));\n\n\tvertexData.push_back(v + Vec3f(halfBlockXWidth, -halfBlockYWidth, z));\n\n\tvertexData.push_back(v + Vec3f(halfBlockXWidth, halfBlockYWidth, z));\n\n\n\n\t//////////////////////////////////////////////////////////////////////////\n\n\n\n\tconst std::vector<Vec3f>::size_type dataIndex[] = \n\n\t{\n\n\t\t//左面\n\n\t\tindex, index + 1u, indexUp,\n", "file_path": "snake3d/wyGround.cpp", "rank": 92, "score": 3.462919278850536 }, { "content": "\t\t}\n\n\n\n\t\tstatic inline V& _div(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] /= t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _assign(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] = t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline typename V::VecDataType _dot(const V& v1, const V& v2)\n\n\t\t{\n\n\t\t\treturn v1[0]*v2[0];\n\n\t\t}\n\n\n\n\t\tstatic inline typename V::VecDataType _dot(const V& v)\n", "file_path": "snake3d/wyVec.h", "rank": 93, "score": 3.461956585306604 }, { "content": "\t\t}\n\n\n\n\t\t//////////////////////////////////////////////////////////////////////////\n\n\n\n\t\tstatic inline V _plus(const V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\treturn V(v1[0] + t);\n\n\t\t}\n\n\n\n\t\tstatic inline V _minus(const V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\treturn V(v1[0] - t);\n\n\t\t}\n\n\n\n\t\tstatic inline V _times(const V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\treturn V(v1[0] * t);\n\n\t\t}\n\n\n\n\t\tstatic inline V _divide(const V& v1, typename V::VecDataType t)\n", "file_path": "snake3d/wyVec.h", "rank": 94, "score": 3.441293258264017 }, { "content": "\t\t{\n\n\t\t\treturn V(v1[0] / t);\n\n\t\t}\n\n\n\n\t\tstatic inline V& _inc(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] += t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _sub(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] -= t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _mul(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] *= t;\n\n\t\t\treturn v1;\n", "file_path": "snake3d/wyVec.h", "rank": 95, "score": 3.2957233193416857 }, { "content": "\t\t}\n\n\n\n\t\tstatic inline V& _mul(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] *= t;\n\n\t\t\tv1[1] *= t;\n\n\t\t\tv1[2] *= t;\t\t\t\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _div(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] /= t;\n\n\t\t\tv1[1] /= t;\n\n\t\t\tv1[2] /= t;\t\t\t\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _assign(V& v1, typename V::VecDataType t)\n\n\t\t{\n", "file_path": "snake3d/wyVec.h", "rank": 96, "score": 3.2957233193416857 }, { "content": "\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _mul(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] *= t;\n\n\t\t\tv1[1] *= t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _div(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] /= t;\n\n\t\t\tv1[1] /= t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _assign(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] = t;\n", "file_path": "snake3d/wyVec.h", "rank": 97, "score": 3.2957233193416857 }, { "content": "\tif(m_nextTurn != Turn_None)\n\n\t{\n\n\t\tVec3f& v = iterRead->pos;\n\n\t\tVec3f& dvR = iterRead->dPos;\n\n\t\tVec3f& dvW = iterWrite->dPos;\n\n\t\tif((fabsf(dvR[0]) > 0.1 && fabsf(v[0] - int(v[0]) < 0.02)) ||\n\n\t\t\t(fabsf(dvR[1]) > 0.1 && fabsf(v[1] - int(v[1]) < 0.02)))\n\n\t\t{\n\n// \t\t\tv[0] = int(v[0]);\n\n// \t\t\tv[1] = int(v[1]);\n\n\n\n\t\t\tswitch (m_nextTurn)\n\n\t\t\t{\n\n\t\t\tcase WYSnake::Turn_Left:\n\n\t\t\t\tdvW = Vec3f(-dvR[1], dvR[0], 0.0f);\n\n\t\t\t\tbreak;\n\n\t\t\tcase WYSnake::Turn_Right:\n\n\t\t\t\tdvW = Vec3f(dvR[1], -dvR[0], 0.0f);\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n", "file_path": "snake3d/wySnake.cpp", "rank": 98, "score": 3.2679227301687823 }, { "content": "\t\t{\n\n\t\t\treturn V(v1[0] * t, v1[1] * t);\n\n\t\t}\n\n\n\n\t\tstatic inline V _divide(const V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\treturn V(v1[0] / t, v1[1] / t);\n\n\t\t}\n\n\n\n\t\tstatic inline V& _inc(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] += t;\n\n\t\t\tv1[1] += t;\n\n\t\t\treturn v1;\n\n\t\t}\n\n\n\n\t\tstatic inline V& _sub(V& v1, typename V::VecDataType t)\n\n\t\t{\n\n\t\t\tv1[0] -= t;\n\n\t\t\tv1[1] -= t;\n", "file_path": "snake3d/wyVec.h", "rank": 99, "score": 3.22205170441274 } ]
C++
src/lookup/PerfectCount.cc
adigenova/discovarexp-51885
f827bab9bd0e328fee3dd57b7fefebfeebd92be4
#include "Basevector.h" #include "CoreTools.h" #include "PackAlign.h" #include "lookup/LookupTable.h" #include "lookup/PerfectCount.h" #include "random/RandomSampleFromStream.h" void GetBestKmers( const vecbasevector query, const AlignDir direction, const lookup_table& look, vec<int>& best_pos, vec<unsigned int>& best_index ) { unsigned int K = look.K( ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); best_pos.resize( nqueries * 2 ); best_index.resize( nqueries * 2 ); for ( int id = 0; id < nqueries; id++ ) { const basevector& s = query[id]; if ( s.size( ) < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); int pos = -1; unsigned int min_freq = 0, mindex = 0; int length = S.isize() - (int) K; unsigned int index = Index( S, 0, K ); unsigned int freq = look.Freq(index); if ( freq != 0 ) { mindex = index; pos = 0; if (freq != 1) { min_freq = freq; for ( int j = 1; j <= length; j++ ) { NextIndex( index, S, j, K ); freq = look.Freq(index); if ( freq == 1 ) { mindex = index; pos = j; break; } if ( freq == 0 ) { pos = -1; break; } if ( pos < 0 || freq < min_freq ) { min_freq = freq; mindex = index; pos = j; } } } } best_pos[ 2*id + pass ] = pos; best_index[ 2*id + pass ] = mindex; } } } int PerfectCount( const vecbasevector& query, const String& lookup_file, const AlignDir direction ) { vec<Bool> perfect; PerfectMark( query, lookup_file, direction, perfect ); return Sum(perfect); } void PerfectMark( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<Bool>& perfect ) { perfect.resize_and_set( query.size( ), False ); if ( query.empty( ) ) return; lookup_table look(lookup_file); unsigned int K = look.K( ); vec<int> best_pos; vec<unsigned int> best_index; GetBestKmers( query, direction, look, best_pos, best_index ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); const unsigned int max_query_size = 200 * 1000 * 1000; for ( unsigned int i = 0; i < look.NChunks( ); i++ ) { look.ReadChunk(i); for ( int id = 0; id < nqueries; id++ ) { if ( perfect[id] ) continue; const basevector& s = query[id]; unsigned int query_length = s.size(); if ( query_length < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { if ( perfect[id] ) break; int r = best_pos[ 2*id + pass ]; if ( r < 0 ) continue; static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); unsigned int index = best_index[ 2*id + pass ]; unsigned int start = look.StartLocs(index); unsigned int stop = look.StopLocs(index); for ( unsigned int l = start; l < stop; l++ ) { unsigned int offset = look.Locs(l) + ( max_query_size - r ); unsigned int tig, rpos; look.GetContigPos( look.Locs(l), tig, rpos ); unsigned int startx; unsigned int q_start; unsigned int t_start; unsigned int length = query_length; if ( offset < look.ContigStart(tig) + max_query_size) { q_start = r - rpos; t_start = 0; length -= q_start; startx = look.ContigStart(tig); } else { q_start = 0; t_start = rpos - r; startx = offset - max_query_size; } if (startx + length > look.ContigStop(tig) ) { length = look.ContigSize(tig) - t_start; } if ( length != query_length ) continue; if ( startx < look.BasesStart( ) ) continue; Bool mismatch = False; unsigned int start_of_kmer = r - q_start; for ( unsigned int y = 0; y < start_of_kmer; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; for ( unsigned int y = start_of_kmer + K; y < length; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; perfect[id] = True; break; } } } } } void PerfectPick( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<placement_mark>& places, vec< pair<placement_mark,int> >& places_plus, const int mode, vec<Bool> & queryHasPerfect) { if ( mode == 1 ) places.clear( ); else places_plus.clear( ); if ( query.empty( ) ) return; vec< RandomSampleFromStreamN1<placement_mark> > placesi( query.size( ) ); queryHasPerfect.resize(query.size(), false); lookup_table look(lookup_file); unsigned int K = look.K( ); vec<int> best_pos; vec<unsigned int> best_index; GetBestKmers( query, direction, look, best_pos, best_index ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); const unsigned int max_query_size = 200 * 1000 * 1000; for ( unsigned int i = 0; i < look.NChunks( ); i++ ) { look.ReadChunk(i); for ( int id = 0; id < nqueries; id++ ) { const basevector& s = query[id]; unsigned int query_length = s.size(); if ( query_length < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { int r = best_pos[ 2*id + pass ]; if ( r < 0 ) continue; static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); unsigned int index = best_index[ 2*id + pass ]; unsigned int start = look.StartLocs(index); unsigned int stop = look.StopLocs(index); for ( unsigned int l = start; l < stop; l++ ) { unsigned int offset = look.Locs(l) + ( max_query_size - r ); unsigned int tig, rpos; look.GetContigPos( look.Locs(l), tig, rpos ); unsigned int startx; unsigned int q_start; unsigned int t_start; unsigned int length = query_length; if ( offset < look.ContigStart(tig) + max_query_size) { q_start = r - rpos; t_start = 0; length -= q_start; startx = look.ContigStart(tig); } else { q_start = 0; t_start = rpos - r; startx = offset - max_query_size; } if (startx + length > look.ContigStop(tig) ) { length = look.ContigSize(tig) - t_start; } if ( length != query_length ) continue; if ( startx < look.BasesStart( ) ) continue; Bool mismatch = False; unsigned int start_of_kmer = r - q_start; for ( unsigned int y = 0; y < start_of_kmer; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; for ( unsigned int y = start_of_kmer + K; y < length; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; queryHasPerfect[id] = true; static placement_mark P; P.Set( tig, pass == 0, t_start ); placesi[id](P); } } } } int count = 0; for ( int id = 0; id < nqueries; id++ ) if ( placesi[id].Exists( ) ) ++count; if ( mode == 1 ) places.reserve(count); else places_plus.reserve(count); for ( int id = 0; id < nqueries; id++ ) { if ( placesi[id].Exists( ) ) { if ( mode == 1 ) places.push_back( placesi[id].Sample( ) ); else { places_plus.push_back( make_pair( placesi[id].Sample( ), id ) ); } } } } void PerfectPick( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<placement_mark>& places, vec<Bool> & queryHasPerfect) { vec< pair<placement_mark,int> > places_plus; PerfectPick( query, lookup_file, direction, places, places_plus, 1, queryHasPerfect ); } void PerfectPick( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec< pair<placement_mark,int> >& places_plus, vec<Bool> & queryHasPerfect ) { vec<placement_mark> places; PerfectPick( query, lookup_file, direction, places, places_plus, 2, queryHasPerfect ); } void PerfectCountPlaces( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<int>& places ) { places.resize_and_set( query.size( ), 0 ); if ( query.empty( ) ) return; lookup_table look(lookup_file); unsigned int K = look.K( ); vec<int> best_pos; vec<unsigned int> best_index; GetBestKmers( query, direction, look, best_pos, best_index ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); const unsigned int max_query_size = 200 * 1000 * 1000; for ( unsigned int i = 0; i < look.NChunks( ); i++ ) { look.ReadChunk(i); for ( int id = 0; id < nqueries; id++ ) { const basevector& s = query[id]; unsigned int query_length = s.size(); if ( query_length < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { int r = best_pos[ 2*id + pass ]; if ( r < 0 ) continue; static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); unsigned int index = best_index[ 2*id + pass ]; unsigned int start = look.StartLocs(index); unsigned int stop = look.StopLocs(index); for ( unsigned int l = start; l < stop; l++ ) { unsigned int offset = look.Locs(l) + ( max_query_size - r ); unsigned int tig, rpos; look.GetContigPos( look.Locs(l), tig, rpos ); unsigned int startx; unsigned int q_start; unsigned int t_start; unsigned int length = query_length; if ( offset < look.ContigStart(tig) + max_query_size) { q_start = r - rpos; t_start = 0; length -= q_start; startx = look.ContigStart(tig); } else { q_start = 0; t_start = rpos - r; startx = offset - max_query_size; } if (startx + length > look.ContigStop(tig) ) { length = look.ContigSize(tig) - t_start; } if ( length != query_length ) continue; if ( startx < look.BasesStart( ) ) continue; Bool mismatch = False; unsigned int start_of_kmer = r - q_start; for ( unsigned int y = 0; y < start_of_kmer; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; for ( unsigned int y = start_of_kmer + K; y < length; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; ++places[id]; } } } } }
#include "Basevector.h" #include "CoreTools.h" #include "PackAlign.h" #include "lookup/LookupTable.h" #include "lookup/PerfectCount.h" #include "random/RandomSampleFromStream.h" void GetBestKmers( const vecbasevector query, const AlignDir direction, const lookup_table& look, vec<int>& best_pos, vec<unsigned int>& best_index ) { unsigned int K = look.K( ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); best_pos.resize( nqueries * 2 ); best_index.resize( nqueries * 2 ); for ( int id = 0; id < nqueries; id++ ) { const basevector& s = query[id]; if ( s.size( ) < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); int pos = -1; unsigned int min_freq = 0, mindex = 0; int length = S.isize() - (int) K; unsigned int index = Index( S, 0, K ); unsigned int freq = look.Freq(index); if ( freq != 0 ) { mindex = index; pos = 0; if (freq != 1) { min_freq = freq; for ( int j = 1; j <= length; j++ ) { NextIndex( index, S, j, K ); freq = look.Freq(index); if ( freq == 1 ) { mindex = index; pos = j; break; } if ( freq == 0 ) { pos = -1; break; } if ( pos < 0 || freq < min_freq ) { min_freq = freq; mindex = index; pos = j; } } } } best_pos[ 2*id + pass ] = pos; best_index[ 2*id + pass ] = mindex; } } } int PerfectCount( const vecbasevector& query, const String& lookup_file, const AlignDir direction ) { vec<Bool> perfect; PerfectMark( query, lookup_file, direction, perfect ); return Sum(perfect); } void PerfectMark( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<Bool>& perfect ) { perfect.resize_and_set( query.size( ), False ); if ( query.empty( ) ) return; lookup_table look(lookup_file); unsigned int K = look.K( ); vec<int> best_pos; vec<unsigned int> best_index; GetBestKmers( query, direction, look, best_pos, best_index ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); const unsigned int max_query_size = 200 * 1000 * 1000; for ( unsigned int i = 0; i < look.NChunks( ); i++ ) { look.ReadChunk(i); for ( int id = 0; id < nqueries; id++ ) { if ( perfect[id] ) continue; const basevector& s = query[id]; unsigned int query_length = s.size(); if ( query_length < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { if ( perfect[id] ) break; int r = best_pos[ 2*id + pass ]; if ( r < 0 ) continue; static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); unsigned int index = best_index[ 2*id + pass ]; unsigned int start = look.StartLocs(index); unsigned int stop = look.StopLocs(index); for ( unsigned int l = start; l < stop; l++ ) { unsigned int offset = look.Locs(l) + ( max_query_size - r ); unsigned int tig, rpos; look.GetContigPos( look.Locs(l), tig, rpos ); unsigned int startx; unsigned int q_start; unsigned int t_start; unsigned int length = query_length; if ( offset < look.ContigStart(tig) + max_query_size) { q_start = r - rpos; t_start = 0; length -= q_start; startx = look.ContigStart(tig); } else { q_start = 0; t_start = rpos - r; startx = offset - max_query_size; } if (startx + length > look.ContigStop(tig) ) { length = look.ContigSize(tig) - t_start; } if ( length != query_length ) continue; if ( startx < look.BasesStart( ) ) continue; Bool mismatch = False; unsigned int start_of_kmer = r - q_start; for ( unsigned int y = 0; y < start_of_kmer; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; for ( unsigned int y = start_of_kmer + K; y < length; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; perfect[id] = True; break; } } } } } void PerfectPick( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<placement_mark>& places, vec< pair<placement_mark,int> >& places_plus, const int mode, vec<Bool> & queryHasPerfect) { if ( mode == 1 ) places.clear( ); else places_plus.clear( ); if ( query.empty( ) ) return; vec< RandomSampleFromStreamN1<placement_mark> > placesi( query.size( ) ); queryHasPerfect.resize(query.size(), false); lookup_table look(lookup_file); unsigned int K = look.K( ); vec<int> best_pos; vec<unsigned int> best_index; GetBestKmers( query, direction, look, best_pos, best_index ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); const unsigned int max_query_size = 200 * 1000 * 1000; for ( unsigned int i = 0; i < look.NChunks( ); i++ ) { look.ReadChunk(i); for ( int id = 0; id < nqueries; id++ ) { const basevector& s = query[id]; unsigned int query_length = s.size(); if ( query_length < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { int r = best_pos[ 2*id + pass ]; if ( r < 0 ) continue; static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); unsigned int index = best_index[ 2*id + pass ]; unsigned int start = look.StartLocs(index); unsigned int stop = look.StopLocs(index); for ( unsigned int l = start; l < stop; l++ ) { unsigned int offset = look.Locs(l) + ( max_query_size - r ); unsigned int tig, rpos; look.GetContigPos( look.Locs(l), tig, rpos ); unsigned int startx; unsigned int q_start; unsigned int t_start; unsigned int length = query_length; if ( offset < look.ContigStart(tig) + max_query_size) { q_start = r - rpos; t_start = 0; length -= q_start; startx = look.ContigStart(tig); } else { q_start = 0; t_start = rpos - r; startx = offset - max_query_size; } if (startx + length > look.ContigStop(tig) ) { length = look.ContigSize(tig) - t_start; } if ( length != query_length ) continue; if ( startx < look.BasesStart( ) ) continue; Bool mismatch = False; unsigned int start_of_kmer = r - q_start; for ( unsigned int y = 0; y < start_of_kmer; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; for ( unsigned int y = start_of_kmer + K; y < length; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; queryHasPerfect[id] = true; static placement_mark P; P.Set( tig, pass == 0, t_start ); placesi[id](P); } } } } int count = 0; for ( int id = 0; id < nqueries; id++ ) if ( placesi[id].Exists( ) ) ++count; if ( mode == 1 ) places.reserve(count); else places_plus.reserve(count); for ( int id = 0; id < nqueries; id++ ) { if ( placesi[id].Exists( ) ) { if ( mode == 1 ) places.push_back( placesi[id].Sample( ) ); else { places_plus.push_back( make_pair( placesi[id].Sample( ), id ) ); } } } } void PerfectPick( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<placement_mark>& places, vec<Bool> & queryHasPerfect) { vec< pair<placement_mark,int> > places_plus; PerfectPick( query, lookup_file, direction, places, places_plus, 1, queryHasPerfect ); } void PerfectPick( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec< pair<placement_mark,int> >& places_plus, vec<Bool> & queryHasPerfect ) { vec<placement_mark> places; PerfectPick( query, lookup_file, direction, places, places_plus, 2, queryHasPerfect ); }
void PerfectCountPlaces( const vecbasevector& query, const String& lookup_file, const AlignDir direction, vec<int>& places ) { places.resize_and_set( query.size( ), 0 ); if ( query.empty( ) ) return; lookup_table look(lookup_file); unsigned int K = look.K( ); vec<int> best_pos; vec<unsigned int> best_index; GetBestKmers( query, direction, look, best_pos, best_index ); const int npasses = ( direction == FW ? 1 : 2 ); const int nqueries = query.size( ); const unsigned int max_query_size = 200 * 1000 * 1000; for ( unsigned int i = 0; i < look.NChunks( ); i++ ) { look.ReadChunk(i); for ( int id = 0; id < nqueries; id++ ) { const basevector& s = query[id]; unsigned int query_length = s.size(); if ( query_length < K ) continue; for ( int pass = 0; pass < npasses; pass++ ) { int r = best_pos[ 2*id + pass ]; if ( r < 0 ) continue; static basevector src; if ( pass == 1 ) src.ReverseComplement(s); const basevector& S = ( pass == 0 ? s : src ); unsigned int index = best_index[ 2*id + pass ]; unsigned int start = look.StartLocs(index); unsigned int stop = look.StopLocs(index); for ( unsigned int l = start; l < stop; l++ ) { unsigned int offset = look.Locs(l) + ( max_query_size - r ); unsigned int tig, rpos; look.GetContigPos( look.Locs(l), tig, rpos ); unsigned int startx; unsigned int q_start; unsigned int t_start; unsigned int length = query_length; if ( offset < look.ContigStart(tig) + max_query_size) { q_start = r - rpos; t_start = 0; length -= q_start; startx = look.ContigStart(tig); } else { q_start = 0; t_start = rpos - r; startx = offset - max_query_size; } if (startx + length > look.ContigStop(tig) ) { length = look.ContigSize(tig) - t_start; } if ( length != query_length ) continue; if ( startx < look.BasesStart( ) ) continue; Bool mismatch = False; unsigned int start_of_kmer = r - q_start; for ( unsigned int y = 0; y < start_of_kmer; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; for ( unsigned int y = start_of_kmer + K; y < length; y++ ) { if ( S[q_start + y] != look.Base( startx + y ) ) { mismatch = True; break; } } if (mismatch) continue; ++places[id]; } } } } }
function_block-full_function
[ { "content": "/// Orders look aligns by 1) query id, then 2) complete position/structure of the target region(s)\n\n/// the query aligns to: first by target id, then start on target, then end on target, then number\n\n/// of gaps, then starts/ends of all blocks, and finally by number of mismatches.\n\nstruct order_lookalign_QueryIdFullTargetMutations : public binary_function<const look_align &, const look_align &, bool> {\n\n bool operator()(const look_align & a, const look_align & b) const {\n\n if ( a.QueryId() < b.QueryId() ) return true;\n\n if ( a.QueryId() > b.QueryId() ) return false;\n\n if ( a.TargetId() < b.TargetId() ) return true;\n\n if ( a.TargetId() > b.TargetId() ) return false;\n\n if ( a.StartOnTarget() < b.StartOnTarget() ) return true;\n\n if ( a.StartOnTarget() > b.StartOnTarget() ) return false;\n\n // for alignments with indels EndOnTraget requires some cycles to do the math; do it only once:\n\n longlong d = a.EndOnTarget() - b.EndOnTarget();\n\n if ( d < 0 ) return true;\n\n if ( d > 0 ) return false;\n\n // ok, these are alignments for the same read (query id) to the same contig\n\n // (target id) and their spans (Start,End) are exactly\n\n // the same; now let's try to order by number and positions of individual\n\n // continuous alignment blocks (if indels are present) and finally by the number\n\n // of mismatches:\n\n if ( a.indels < b.indels ) return true;\n\n if ( a.indels > b.indels ) return false;\n\n if ( a.a.Lengths(0) < b.a.Lengths(0) ) return true;\n", "file_path": "src/lookup/LookAlign.h", "rank": 0, "score": 302544.48900629114 }, { "content": "/// counterpart to order_lookalign_QueryIdFullTargetMutations\n\nstruct equal_lookalign_QueryIdFullTargetMutations : public binary_function<const look_align &, const look_align &, bool> {\n\n bool operator()(const look_align & a, const look_align & b) const {\n\n if ( a.QueryId() != b.QueryId() ) return false;\n\n if ( a.TargetId() != b.TargetId() ) return false;\n\n if ( a.mutations != b.mutations ) return false;\n\n if ( a.indels != b.indels ) return false;\n\n if ( a.StartOnTarget() != b.StartOnTarget() ) return false;\n\n if ( a.a.Lengths(0) != b.a.Lengths(0) ) return false;\n\n for ( unsigned int i = 1 ; i < static_cast<unsigned int>(a.a.Nblocks()) ; i++ ) {\n\n if ( a.a.Gaps(i) != b.a.Gaps(i) ) return false;\n\n if ( a.a.Lengths(i) != b.a.Lengths(i) ) return false;\n\n }\n\n return true;\n\n }\n\n};\n\n\n\n\n\n\n", "file_path": "src/lookup/LookAlign.h", "rank": 1, "score": 302525.5574701602 }, { "content": "QueryLookupTable K=12 SEQS=qlt_bug.fastb L=qlt_bug.lookup SMITH_WAT=True\n\n--------------------------------------------------------------------------------\n\n[...]\n\n0fw vs 0, 0 mismatches/0 indels (of 143), from 0-143 to 0-143\n\n0fw vs 1, 1 mismatches/1 indels (of 143), from 0-143 to 29-173\n\n0fw vs 2, 4 mismatches/0 indels (of 143), from 0-143 to 28-171\n\n\n\n1fw vs 1, 0 mismatches/0 indels (of 173), from 0-173 to 0-173\n\n\n\n2fw vs 2, 0 mismatches/0 indels (of 171), from 0-171 to 0-171\n\n\n\nNow all the k vs k alignments are found, but the 2 vs 1 and 2 vs 0 alignments have disappeared.\n\n\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 2, "score": 264928.58010076225 }, { "content": "QueryLookupTable K=12 SEQS=qlt_bug.fastb L=qlt_bug.lookup\n\n--------------------------------------------------------------------------------\n\n[...]\n\n0fw vs 0, 0 mismatches/0 indels (of 143), from 0-143 to 0-143\n\n0fw vs 1, 1 mismatches/1 indels (of 143), from 0-143 to 29-173\n\n0fw vs 2, 4 mismatches/0 indels (of 143), from 0-143 to 28-171\n\n\n\n1fw vs 1, 0 mismatches/0 indels (of 173), from 0-173 to 0-173\n\n\n\n2fw vs 1, 18 mismatches/2 indels (of 171), from 0-171 to 0-173\n\n2fw vs 0, 4 mismatches/0 indels (of 171), from 28-171 to 0-143\n\n\n\nAdding the SMITH_WAT parameter changes what is found. This demonstrates\n\nthat the lookup table contains enough hits to find the alignments, so\n\nthey are being lost in subsequent processing:\n\n\n\n--------------------------------------------------------------------------------\n\nFri Jan 12 14:28:43 2007 run, based on Tue Jan 9 02:22:27 EST 2007 make\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 3, "score": 229351.2896094889 }, { "content": "struct CompareRawHitsByQueryStartOffset {\n\n bool operator()(const RawHit &a, const RawHit &b) {\n\n return (a.QueryStartOnTarget() < b.QueryStartOnTarget());\n\n }\n\n};\n\n\n", "file_path": "src/lookup/Hit.h", "rank": 4, "score": 200178.43345294642 }, { "content": "struct RawHitsEqualByQueryStartOffset {\n\n bool operator()(const RawHit &a, const RawHit &b) {\n\n return (a.QueryStartOnTarget() == b.QueryStartOnTarget());\n\n }\n\n};\n\n\n", "file_path": "src/lookup/Hit.h", "rank": 5, "score": 200178.43345294645 }, { "content": "/// Sort by: target_id - if the same, sort by query_id, if same, sort by start,end on target\n\nstruct order_lookalign_TargetQueryStartEnd\n\n : public binary_function<const look_align&, const look_align&, bool>\n\n{\n\n public:\n\n bool operator() ( const look_align &left, const look_align &right ) const {\n\n if ( left.target_id < right.target_id )\n\n return true;\n\n if ( left.target_id > right.target_id )\n\n return false;\n\n if ( left.query_id < right.query_id )\n\n return true;\n\n if ( left.query_id > right.query_id )\n\n return false;\n\n if ( left.a.Pos1() < right.a.Pos1() )\n\n return true;\n\n if ( left.a.Pos1() > right.a.Pos1() )\n\n return false;\n\n if ( left.a.Pos2() < right.a.Pos2() )\n\n return true;\n\n if ( left.a.Pos2() > right.a.Pos2() )\n", "file_path": "src/lookup/LookAlign.h", "rank": 6, "score": 194018.78140762416 }, { "content": "struct equal_lookalign_TargetQueryStartEnd\n\n : public binary_function<const look_align&, const look_align&, bool>\n\n{\n\n public:\n\n bool operator() ( const look_align &left, const look_align &right ) const {\n\n if ( left.target_id == right.target_id &&\n\n\t left.query_id == right.query_id &&\n\n\t left.a.Pos2() == right.a.Pos2() &&\n\n\t left.a.Pos1() == right.a.Pos1() &&\n\n\t left.mutations == right.mutations &&\n\n\t left.indels == right.indels )\n\n return true;\n\n\n\n return false;\n\n }\n\n};\n\n\n\n\n\n\n\n/**\n", "file_path": "src/lookup/LookAlign.h", "rank": 7, "score": 193992.46979522772 }, { "content": "int PerfectCount( const vecbasevector& query, const String& lookup_file, \n", "file_path": "src/lookup/PerfectCount.h", "rank": 8, "score": 180058.10083668272 }, { "content": "void PerfectCountPlaces( const vecbasevector& query, const String& lookup_file, \n", "file_path": "src/lookup/PerfectCount.h", "rank": 9, "score": 177539.22073259437 }, { "content": "void PerfectPick( const vecbasevector& query, const String& lookup_file,\n\n\t\t const AlignDir direction, vec<placement_mark>& places,\n", "file_path": "src/lookup/PerfectCount.h", "rank": 10, "score": 164929.2519883878 }, { "content": "void PerfectMark( const vecbasevector& query, const String& lookup_file,\n", "file_path": "src/lookup/PerfectCount.h", "rank": 11, "score": 164928.6194999898 }, { "content": "/// Sort by: query_id\n\nstruct order_lookalign_Query\n\n : public binary_function<const look_align&, const look_align&, bool>\n\n{\n\n public:\n\n bool operator() ( const look_align &left,\n\n\t\t const look_align &right ) const {\n\n return ( left.query_id < right.query_id );\n\n }\n\n};\n\n\n", "file_path": "src/lookup/LookAlign.h", "rank": 12, "score": 161736.59388174178 }, { "content": "class Permutation : public vec<int> {\n\n\n\n public:\n\n\n\n Permutation(int); // construct the identity Permutation\n\n Permutation( ) { }\n\n\n\n};\n\n\n\n#endif\n", "file_path": "src/math/Permutation.h", "rank": 13, "score": 161057.01175745347 }, { "content": "class equivalence_relation : public vec<int> {\n\n public:\n\n equivalence_relation( ) { }\n\n // construct discrete ~ relation:\n\n explicit equivalence_relation(int n) : vec<int>(n) \n\n { for ( int i = 0; i < n; i++ )\n\n (*this)[i] = i; }\n\n bool equiv(int,int) const; // test for equivalence\n\n void join(int,int); // make two integers equivalent\n\n int size(int) const; // compute size of an equivalence class\n\n int orbit_count( ) const; // compute number of orbits\n\n vec<int> OrbitReps( ) const; // return a complete set of orbit representatives\n\n vec<int> orbit(int) const; // compute an orbit \n\n bool minimal(int x) // Is x the minimal element of its class?\n\n { int i = x;\n\n while ( (i = (*this)[i]) > x );\n\n return x <= i; }\n\n int min_in_class(int x)\n\n { int best = x;\n\n int i = x;\n", "file_path": "src/Equiv.h", "rank": 14, "score": 161057.01175745347 }, { "content": " friend void swap( vec& v1, vec& v2 )\n", "file_path": "src/Vec.h", "rank": 15, "score": 160461.91932066187 }, { "content": " typename BaseT::const_reference operator[](size_type i) const {\n\n AssertLt( i, BaseT::size() ); // Asserts index within bounds\n\n return BaseT::operator[](i); // ... and returns the element\n", "file_path": "src/Vec.h", "rank": 16, "score": 160437.08613433983 }, { "content": "class KmerParcelVecVec : public vec< KmerParcelVec<K> >\n\n{\n\npublic:\n\n\n\n KmerParcelVecVec(const size_t n_parcels,\n\n const size_t n_threads);\n\n\n\n void RunTasks(const size_t thread_ID,\n\n const BaseVecVec & bases, \n\n const vec<size_t> & read1_IDs,\n\n KmerParcelsStore & parcels_store,\n\n KmerFrequencyStatistics & stats);\n\n\n\n};\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// ----------------------------------------\n\n// ParcelProcessor<K>\n\n// ----------------------------------------\n\n\n\ntemplate<size_t K>\n", "file_path": "src/kmers/kmer_parcels/KmerParcelsBuilder.h", "rank": 17, "score": 157878.04624001816 }, { "content": "class istring : public vec<int> {\n\n\n\n public:\n\n\n\n istring( ) { }\n\n explicit istring( const vec<int>& v ) : vec<int>(v) { }\n\n\n\n int Length( const vec<int>& L ) const;\n\n\n\n void Append( const istring& x )\n\n { append(x); }\n\n\n\n private:\n\n enum display_mode { ONE_LINE, SPLIT };\n\n static display_mode s_displayMode;\n\n\n\n public:\n\n\n\n // By default, istrings are outputted in multi-line format (splitting so that\n\n // no one line is too long). You can override this with:\n\n // istring::UseOneLineOutput( );\n\n static void UseOneLineOutput() { s_displayMode = ONE_LINE; }\n\n static void UseSplitLineOutput() { s_displayMode = SPLIT; }\n\n\n\n friend ostream& operator<<( ostream& o, const istring& x );\n\n};\n\n\n\ntypedef istring pp_read;\n\n\n", "file_path": "src/paths/PairedPair.h", "rank": 18, "score": 157473.88690572802 }, { "content": "\t\t unsigned int length,\n\n\t\t int max_mismatches = 1000 * 1000,\n", "file_path": "src/BasevectorTools.h", "rank": 19, "score": 156792.71601423653 }, { "content": "\t\t unsigned int t_start,\n", "file_path": "src/BasevectorTools.h", "rank": 20, "score": 156789.44947465014 }, { "content": "\t\t unsigned int q_start,\n", "file_path": "src/BasevectorTools.h", "rank": 21, "score": 156789.44947465014 }, { "content": " typename V1::size_type count = 0;\n", "file_path": "src/VecUtilities.h", "rank": 22, "score": 156596.3430689399 }, { "content": "inline int MismatchCount(const basevector &query,\n\n\t\t const basevector &target,\n\n\t\t unsigned int q_start,\n\n\t\t unsigned int t_start,\n\n\t\t unsigned int length,\n\n\t\t int max_mismatches = 1000 * 1000,\n", "file_path": "src/BasevectorTools.h", "rank": 23, "score": 156548.91981604364 }, { "content": "struct CompareRawHitsByQueryStart {\n\n bool operator()(const RawHit &a, const RawHit &b) {\n\n RETURN_IF_UNEQUAL(a.QueryStartOnTarget(), b.QueryStartOnTarget());\n\n return a.Offset() < b.Offset();\n\n }\n\n};\n\n\n\n\n\n/// A ProcessedHit adds to a RawHit some additional information: how\n\n/// many times did this offset occur? What contig of target does it\n\n/// correspond to? What is the range of QueryStartOnTarget values\n\n/// being encoded by this object? Fits in 128 bits.\n\n\n", "file_path": "src/lookup/Hit.h", "rank": 24, "score": 156495.6250874037 }, { "content": "/// Sort by: query_id, number of errors (as from method Errors( )).\n\nstruct order_lookalign_QueryErrors :\n\n public binary_function<const look_align&, const look_align&, bool>\n\n{\n\npublic:\n\n bool operator() ( const look_align &left,\n\n\t\t const look_align &right ) const {\n\n if ( left.query_id == right.query_id )\n\n return ( left.Errors( ) < right.Errors( ) );\n\n return ( left.query_id < right.query_id );\n\n }\n\n};\n\n\n", "file_path": "src/lookup/LookAlign.h", "rank": 25, "score": 156455.05897211857 }, { "content": " const basevector::iterator query_end = query.End();\n", "file_path": "src/BasevectorTools.h", "rank": 26, "score": 156413.8386718521 }, { "content": " const bool unsigned_index = (std::numeric_limits<IDX>::is_signed == false);\n", "file_path": "src/VecUtilities.h", "rank": 27, "score": 156349.079157662 }, { "content": " typename V1::size_type count = 0;\n", "file_path": "src/ParallelVecUtilities.h", "rank": 28, "score": 153012.7920774297 }, { "content": "/// Sort by: query_id, number of indels, number of mutations.\n\nstruct order_lookalign_QueryIndelsMutations :\n\n public binary_function<const look_align&, const look_align&, bool>\n\n{\n\npublic:\n\n bool operator( ) ( const look_align &left,\n\n\t\t const look_align &right ) const {\n\n if ( left.query_id == right.query_id ) {\n\n if ( left.indels == right.indels ) {\n\n\treturn left.mutations < right.mutations; }\n\n return ( left.indels < right.indels ); }\n\n return ( left.query_id < right.query_id ); }\n\n};\n\n\n", "file_path": "src/lookup/LookAlign.h", "rank": 29, "score": 151508.25213878063 }, { "content": "// A row in a matrix\n\nclass Row : private vec<int> {\n\npublic:\n\n typedef vec<int>::allocator_type allocator_type;\n\n int lb, ub;\n\n //-------------------------\n\n Row(int N, int val) : vec<int>(N, val), lb(0), ub(N) {};\n\n Row(int lbi, int ubi, int val ) : vec<int>(ubi-lbi, val), lb(lbi), ub(ubi) { };\n\n void SetCol(int j, int val) { //ForceAssertLe( lb, j ); \n\n //ForceAssertLt( j, ub );\n\n vec<int>::operator[](j-lb) = Min(val, FastScorer::inf); }\n\n int GetCol(int j) const { if ( j < lb || j >= ub ) return FastScorer::inf; \n\n else return vec<int>::operator[]( j-lb ); }\n\n //int operator[](int j) const { return GetCol(j); }\n\n int back() const { return vec<int>::back(); }\n\n};\n\n\n\n#endif\n", "file_path": "src/paths/long/ultra/ConsensusScoreModel.h", "rank": 30, "score": 148003.30354300962 }, { "content": "struct CompareProcessedHitsByRcContigQueryStart {\n\n bool operator()(const ProcessedHit &a, const ProcessedHit &b) {\n\n RETURN_IF_UNEQUAL(a.IsRc(), b.IsRc());\n\n RETURN_IF_UNEQUAL(a.TargetContig(), b.TargetContig());\n\n return (a.QueryStartOnTarget() < b.QueryStartOnTarget());\n\n }\n\n};\n\n\n", "file_path": "src/lookup/Hit.h", "rank": 31, "score": 146901.596831232 }, { "content": "class index_seq_pos {\n\n\n\n public:\n\n\n\n unsigned int index;\n\n unsigned int seq;\n\n unsigned int pos;\n\n\n\n index_seq_pos( ) { }\n\n index_seq_pos( unsigned int index_arg,\n\n\t\t unsigned int seq_arg,\n\n\t\t unsigned int pos_arg )\n\n : index(index_arg),\n\n\t seq(seq_arg),\n\n\t pos(pos_arg)\n\n { }\n\n\n\n friend Bool operator<( const index_seq_pos& x1, const index_seq_pos& x2 )\n\n { if ( x1.index < x2.index ) return True;\n\n if ( x1.index > x2.index ) return False;\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 32, "score": 146849.71090950866 }, { "content": "struct Serializability< kmer_with_count<K> >\n\n{ typedef TriviallySerializable type; };\n\n\n\ntemplate < nbases_t K > inline\n\nostream& operator<< ( ostream& s, const kmer_with_count< K >& k ) {\n\n basevector b;\n\n k.GetBasevector( b );\n\n b.Print( s );\n\n return s;\n\n}\n\n\n\n#define KmerRecordType(KSHAPE,I) kmer_record_ ## KSHAPE ## _ ## I\n\n#define CreateKmerRecordType(KSHAPE,dummy) \\\n\n typedef kmer_record<KSHAPE::KSIZE,1> KmerRecordType(KSHAPE,1) ; \\\n\n typedef kmer_record<KSHAPE::KSIZE,2> KmerRecordType(KSHAPE,2)\n\n\n\nFOR_ALL_KSHAPES(CreateKmerRecordType,unused);\n\n\n\n#endif\n", "file_path": "src/kmers/KmerRecord.h", "rank": 33, "score": 135272.24453724577 }, { "content": "/// A feudal vector that has bits as values.\n\nclass BitVec : public FieldVec<1, MempoolAllocator<unsigned char> >\n\n{\n\npublic:\n\n typedef FieldVec<1, MempoolAllocator<unsigned char> > Base;\n\n typedef MempoolAllocator<unsigned char> Alloc;\n\n\n\n // Constructors\n\n BitVec() : Base() {}\n\n BitVec(Alloc const& alloc) : Base(alloc) {}\n\n BitVec(Base::size_type n, Base::value_type exemplar = 0,\n\n Base::size_type cap = 0, Alloc const& alloc = Alloc())\n\n : Base(n, exemplar, cap, alloc) {}\n\n\n\n BitVec& operator|=( BitVec const& bv );\n\n\n\n BitVec& operator&=( BitVec const& bv );\n\n\n\n BitVec& operator^=( BitVec const& bv );\n\n\n\n BitVec& invert();\n", "file_path": "src/feudal/BitVec.h", "rank": 34, "score": 134140.23945923432 }, { "content": "class BaseVec : public FieldVec<2, MempoolAllocator<unsigned char> >\n\n{\n\npublic:\n", "file_path": "src/feudal/BaseVec.h", "rank": 35, "score": 134140.23945923432 }, { "content": "class KmerParcelVec : public vec<KmerParcel<K> >, private LockedData\n\n{\n\nprivate:\n\n\n\n size_t _parcel0_ID; // id of the first parcel on the set\n\n size_t _parcel1_ID; // id of the parcel after the last one\n\n size_t _n_parcels; // total number of parcels \n\n\n\n // the read data is divided into blocks when\n\n // searching for the subset of parcel IDs\n\n // each read block is processed by its own thread \n\n size_t _n_blocks; \n\n size_t _n_blocks_started; \n\n size_t _n_blocks_done;\n\n\n\n // after the parcel IDs are computed, then each \n\n // thread sorts and writes each parcel.\n\n size_t _n_sub_parcels; // parcel_ID1 - parcel_ID0\n\n size_t _n_sub_parcels_started;\n\n size_t _n_sub_parcels_done;\n", "file_path": "src/kmers/kmer_parcels/KmerParcelsBuilder.h", "rank": 36, "score": 134105.9656685969 }, { "content": "struct less< vec<HoIntervalWithId> > : \n\n public binary_function< const vec<HoIntervalWithId> &, const vec<HoIntervalWithId> &, bool> {\n\n bool operator() (const vec<HoIntervalWithId> & a, const vec<HoIntervalWithId> & b) const {\n\n\n\n unsigned int min_size = min(a.size(),b.size());\n\n\n\n for ( unsigned int i = 0 ; i < min_size ; i++ ) {\n\n if (LessById(a[i],b[i])) return true;\n\n if (LessById(b[i],a[i])) return false;\n\n }\n\n // we have compared intervals up to min_size by now;\n\n // if we got here, all those intervals were the same\n\n\n\n // so now we check the sizes; the shorter vector is \"less\"\n\n if ( a.size() < b.size() ) return true;\n\n if ( a.size() > b.size() ) return false;\n\n\n\n // all the intervals up to min_size were the same, and the sizes\n\n // of a and b are equal, so that the vectors are exactly equal:\n\n return false;\n", "file_path": "src/math/HoInterval.h", "rank": 37, "score": 131728.51680830086 }, { "content": "void QueryLookupTableCore( int argc, char *argv[] );\n", "file_path": "src/lookup/QueryLookupTableCore.h", "rank": 38, "score": 122687.15430181003 }, { "content": "/// \\brief A Query encodes a kmer from the query sequence (as numeric index),\n\n/// position (offset) of this kmer in the query sequence (0-based), and the\n\n/// orientation of the query sequence (is this Kmer found at the specified\n\n/// offset in the original query sequence or in its reverse complement). \n\n///\n\n/// A query does not store any information about the identity of the original\n\n/// sequence it was generated from, so it is responsibility of the client\n\n/// to match sequences to the queries. Query fits\n\n/// in 64 bits and works for any reasonable query (length up to 2^31).\n\n///\n\nstruct Query {\n\n unsigned int k; ///< kmer index\n\n unsigned int query_pos; ///< offset of the kmer in the sequence (top bit==1 encodes rc queries)\n\n Query(unsigned int in_query_pos = 0, unsigned int k = 0, bool rc = false) :\n\n k(k),\n\n query_pos(rc ? (in_query_pos | TopBit32) : in_query_pos)\n\n {}\n\n /// Returns true if the query was generated from rc sequence\n\n bool IsRc() const { return (query_pos & TopBit32)!=0; }\n\n /// Returns Kmer index represented by this query\n\n unsigned int Kmer() const { return k; }\n\n /// Offset of this query's Kmer in the original sequence or in the\n\n /// reverse complement of the original sequence (if IsRc() is true)\n\n int QueryPos() const { return (query_pos & Bits31); }\n\n};\n\n\n\nTRIVIALLY_SERIALIZABLE(Query);\n\ntypedef SerfVec<Query> QueryVec;\n\ntypedef MasterVec<QueryVec> VecQueryVec;\n\nextern template class SmallVec< Query, MempoolAllocator<Query> >;\n\nextern template class OuterVec<QueryVec>;\n\n\n\ninline ostream & operator<<(ostream &out, const Query &h)\n\n{\n\n return out << h.QueryPos() << (h.IsRc() ? \"/\" : \"\\\\\") << h.Kmer();\n\n}\n\n\n\n#define RETURN_IF_UNEQUAL(expr1, expr2) \\\n\n{ if ((expr1)<(expr2)) return true; if ((expr2)<(expr1)) return false; }\n\n\n", "file_path": "src/lookup/Hit.h", "rank": 39, "score": 122267.81349492798 }, { "content": "///////////////////////////////////////////////////////////////////////////////\n\n// SOFTWARE COPYRIGHT NOTICE AGREEMENT //\n\n// This software and its documentation are copyright (2012) by the //\n\n// Broad Institute. All rights are reserved. This software is supplied //\n\n// without any warranty or guaranteed support whatsoever. The Broad //\n\n// Institute is not responsible for its use, misuse, or functionality. //\n\n///////////////////////////////////////////////////////////////////////////////\n\n/*\n\n * \\file VecString.cc\n\n * \\author tsharpe\n\n * \\date Feb 23, 2012\n\n *\n\n * \\brief\n\n */\n\n\n\n#include \"VecString.h\"\n\n#include \"feudal/OuterVecDefs.h\"\n\n\n\ntemplate class OuterVec<String>;\n", "file_path": "src/VecString.cc", "rank": 40, "score": 122073.06765294734 }, { "content": " typename vec<T,A>::size_type count = 0;\n", "file_path": "src/Vec.h", "rank": 41, "score": 120837.4607651693 }, { "content": "class KmerParcel : public vec< KmerRecord<K> >, private LockedData\n\n{\n\nprivate:\n\n NaifTimer _timer_sort;\n\n NaifTimer _timer_write;\n\n\n\npublic:\n\n KmerParcel() : _timer_sort(), _timer_write() {} \n\n ~KmerParcel() {}\n\n\n\n // ---- copy constructor\n\n // specified so that vec<> can be copied without copying LockedData\n\n KmerParcel(KmerParcel<K> const & that) \n\n : vec<KmerRecord<K> >(that), \n\n LockedData()\n\n { }\n\n\n\n // ---- = operator\n\n // specified so that vec<> can be copied without copying LockedData\n\n KmerParcel & operator=(KmerParcel<K> const & that) \n", "file_path": "src/kmers/kmer_parcels/KmerParcelsBuilder.h", "rank": 42, "score": 120338.4218729724 }, { "content": "inline String ToStringBool(bool value) { return (value ? \"True\" : \"False\"); }\n", "file_path": "src/feudal/CharString.h", "rank": 43, "score": 118092.36909037807 }, { "content": "The alternate approach using ShortQueryLookup yields the following alignments:\n\n--------------------------------------------------------------------------------\n\nFri Jan 12 14:47:19 2007 run, based on Thu Jan 11 12:11:05 EST 2007 make\n\nShortQueryLookup SEQS=qlt_bug.fastb REF=qlt_bug.fastb L=qlt_bug.lookup \\\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 44, "score": 118081.11530579929 }, { "content": "///////////////////////////////////////////////////////////////////////////////\n\n// SOFTWARE COPYRIGHT NOTICE AGREEMENT //\n\n// This software and its documentation are copyright (2012) by the //\n\n// Broad Institute. All rights are reserved. This software is supplied //\n\n// without any warranty or guaranteed support whatsoever. The Broad //\n\n// Institute is not responsible for its use, misuse, or functionality. //\n\n///////////////////////////////////////////////////////////////////////////////\n\n/*\n\n * \\file IntPairVec.cc\n\n * \\author tsharpe\n\n * \\date Jan 24, 2013\n\n *\n\n * \\brief\n\n */\n\n\n\n#include \"IntPairVec.h\"\n\n#include \"feudal/SmallVecDefs.h\"\n\n#include \"feudal/OuterVecDefs.h\"\n\n\n\ntemplate class SmallVec< IntPair, MempoolAllocator<IntPair> >;\n\ntemplate class OuterVec<IntPairVec>;\n", "file_path": "src/IntPairVec.cc", "rank": 66, "score": 117693.22805067657 }, { "content": "class ID\n\n{\n\npublic:\n\n ID() { memset(mVal,-1,N); }\n\n\n\n explicit ID( size_t val ) { setVal(val); }\n\n\n\n // compiler-generated copying and destructor are OK\n\n\n\n size_t val() const\n\n { size_t result; memcpy(&result,mVal,N); return result & MASK; }\n\n\n\n void setVal( size_t val )\n\n { AssertNot(val & ~MASK); memcpy(mVal,&val,N); }\n\n\n\n bool isNull() const { return *this == gNull; }\n\n\n\n static size_t nullVal() { return gNull.val(); }\n\n\n\n friend bool operator==( ID const& id1, ID const& id2 )\n", "file_path": "src/system/ID.h", "rank": 67, "score": 116795.59722579591 }, { "content": "/// Sort by: target_id - offset.\n\nstruct order_lookalign_TargetLookAlignOffset\n\n : public binary_function<const look_align&,\n\n\t\t\t const look_align&, bool>\n\n{\n\npublic:\n\n bool operator() ( const look_align &left,\n\n\t\t const look_align &right ) const {\n\n if ( left.target_id == right.target_id )\n\n return ( LookAlignOffset( left ) < LookAlignOffset( right ) );\n\n return ( left.target_id < right.target_id );\n\n }\n\n};\n\n\n", "file_path": "src/lookup/LookAlign.h", "rank": 68, "score": 115133.31904502197 }, { "content": "inline void AsciiBoolVecReadSubset( const String& filename,\n\n const vec<int>& ids,\n\n vec<Bool>& v )\n\n{ String ns;\n\n { Ifstream( in, filename );\n\n in >> ns; }\n\n ForceAssert( ns.IsInt() );\n\n longlong n = ns.Int();\n\n int k = ns.size()+1;\n\n FileReader fr(filename.c_str());\n\n v.resize( ids.size( ) );\n\n for ( int i = 0; i < ids.isize( ); i++ )\n\n { ForceAssertGe( ids[i], 0 );\n\n ForceAssertLt( ids[i], n );\n\n fr.seek( k + ids[i] );\n", "file_path": "src/Vec.h", "rank": 69, "score": 114894.82733186103 }, { "content": "///////////////////////////////////////////////////////////////////////////////\n\n// SOFTWARE COPYRIGHT NOTICE AGREEMENT //\n\n// This software and its documentation are copyright (2010) by the //\n\n// Broad Institute. All rights are reserved. This software is supplied //\n\n// without any warranty or guaranteed support whatsoever. The Broad //\n\n// Institute is not responsible for its use, misuse, or functionality. //\n\n///////////////////////////////////////////////////////////////////////////////\n\n\n\n#include \"MainTools.h\"\n\n#include \"lookup/QueryLookupTableCore.h\"\n\n\n\nint main( int argc, char *argv[] )\n\n{ \n\n // Define interrupt handling.\n\n\n\n Bool TRACEBACK_ON_INTERRUPT = False;\n\n for ( int i = 1; i < argc; i++ )\n\n { if ( String(argv[i]) == String(\"TRACEBACK_ON_INTERRUPT=True\") )\n\n TRACEBACK_ON_INTERRUPT = True; }\n\n RunTime(1,\n\n (TRACEBACK_ON_INTERRUPT\n\n ? &arachne_signal_handler_standard \n\n : &arachne_signal_handler_no_ctrlc_traceback));\n\n\n\n // Run QueryLookupTable.\n\n\n\n QueryLookupTableCore( argc, argv ); }\n", "file_path": "src/lookup/QueryLookupTable.cc", "rank": 70, "score": 113732.72448335601 }, { "content": "struct CompareQueriesByKmer {\n\n bool operator()(const Query &a, const Query &b) {\n\n return (a.Kmer() < b.Kmer());\n\n }\n\n};\n\n\n\n/// Transform a single basevector to queries. Each query in the resulting vector stores\n\n/// the Kmer (as numeric index) and the position, at which this Kmer occurs\n\n/// in the \\c bases sequence, incremented by constant amount <offset>. \n\n/// This method <em>does not</em> generate queries coming\n\n/// from the reverse complement of \\c bases.\n\nvoid BasesToQueries(const basevector &bases, vec<Query> &queries, unsigned int K, unsigned int offset = 0);\n\n\n\n\n\n\n\n/// Same as BasesToQueries(const basevector &bases, vec<Query> &queries, unsigned int K)\n\n/// but takes basevector iterator as its argument instead of basevector itself: this \n\n/// overload can be used, in particular, with adaptors\n\ntemplate <class ITER>\n\nvoid BasesToQueries(const ITER & bvec_iter, const ITER & bvec_iter_end, vec<Query> &queries, unsigned int K, unsigned int offset = 0)\n", "file_path": "src/lookup/Hit.h", "rank": 71, "score": 113694.54885579737 }, { "content": "struct CompareQueriesByPos {\n\n bool operator()(const Query &a, const Query &b) {\n\n return (a.QueryPos() < b.QueryPos());\n\n }\n\n};\n\n\n", "file_path": "src/lookup/Hit.h", "rank": 72, "score": 113694.54885579737 }, { "content": " class const_iterator\n\n : public ItrBase,\n\n public IteratorBase<const_iterator,size_type,difference_type>\n\n {\n\n public:\n\n const_iterator() : mpContainer(0) {}\n\n const_iterator( FieldVec const* pContainer, size_type pos )\n\n : IteratorBase<const_iterator,size_type,difference_type>(pos),\n\n mpContainer(pContainer) {}\n\n\n\n // compiler-supplied copying and destructor are OK\n\n\n\n value_type operator*() const { return (*mpContainer)[this->pos()]; }\n\n value_type operator[]( difference_type idx ) const\n\n { return (*mpContainer)[this->pos()+idx]; }\n\n\n\n private:\n\n FieldVec const* mpContainer;\n\n };\n\n\n", "file_path": "src/feudal/FieldVec.h", "rank": 73, "score": 113589.59329650167 }, { "content": "class kmer_shape_mid_gap<K,0> {\n\npublic:\n\n // Constant: KSIZE\n\n // The size of the kmer.\n\n static const int KSIZE = K;\n\n\n\n // Constant: KSPAN\n\n // The span from which the kmer is extracted\n\n static const int KSPAN = K;\n\n \n\n \n\n /// Return the kmer size.\n\n static int getKmerSize() { return K; }\n\n \n\n /// Return the offset of the i'th base of the shape.\n\n static unsigned int getShapeOffset(int posInShape) { return posInShape; }\n\n \n\n /// Return the number of inner gaps (where each position counts as a separate gap) in the shape.\n\n static unsigned int getNumGaps() { return 0; }\n\n \n", "file_path": "src/kmers/KmerShape.h", "rank": 74, "score": 112238.99370884175 }, { "content": "class BMG_node : public vec< mutmer_read_idY<I> >\n\n{\n\npublic:\n\n\n\n size_t SizeOf() const { return (*this).size() * sizeof(mutmer_read_idY<I>); }\n\n\n\n\n\n\n\n\n\n // ---- input from a stream\n\n friend std::istream& operator>>(std::istream & is, BMG_node & nodes) \n\n {\n\n uint32_t size; // stored as 32 bits on disk\n\n is.read(reinterpret_cast<char*>(&size), sizeof(uint32_t));\n\n nodes.resize(size);\n\n\n\n //static int nn = 0;\n\n //if (nn++ < 10) cout << size << endl;\n\n\n\n for (size_t i = 0; i != size; i++)\n", "file_path": "src/pairwise_aligners/BalancedMutmerGraph.h", "rank": 75, "score": 111820.46855500864 }, { "content": "class QualNibbleVec : private FieldVec<4, MempoolAllocator<unsigned char> >\n\n{\n\npublic:\n\n typedef allocator_type Alloc;\n\n typedef unsigned char value_type;\n\n typedef unsigned size_type;\n\n typedef FieldVec<4, MempoolAllocator<unsigned char> > BaseT;\n\n typedef std::ptrdiff_t difference_type;\n\n typedef std::iterator<std::random_access_iterator_tag,\n\n value_type,\n\n difference_type,\n\n void,\n\n value_type> ItrBase;\n\n struct QualMapper\n\n {\n\n value_type operator()( value_type val ) const\n\n { return deflate(val); }\n\n\n\n static value_type deflate( value_type val )\n\n { using std::min; return min(val/3,15); }\n\n static value_type inflate( value_type val )\n\n { return 3*val + 1; }\n\n };\n\n\n", "file_path": "src/feudal/QualNibbleVec.h", "rank": 76, "score": 110514.54188066504 }, { "content": "int BoolToInt( Bool b );\n", "file_path": "src/Misc.h", "rank": 77, "score": 109978.81590100349 }, { "content": " if ( isp[v].index != isp[u].index ) break;\n\n if ( isp[u].seq == 1 )\n\n { u = v - 1;\n\n continue; }\n\n for ( w = u + 1; w < v; w++ )\n\n if ( isp[w].seq != isp[u].seq ) break;\n\n for ( unsigned int x = u; x < w; x++ )\n\n { for ( unsigned int y = w; y < v; y++ )\n\n { unsigned int offset = isp[y].pos\n\n + ( max_query_size - isp[x].pos );\n\n if (strict)\n\n { if ( offset < min_offset ) continue;\n\n if ( offset > max_offset ) continue; }\n\n hitsp.push_back( make_pair( offset, isp[x].pos ) ); } }\n\n u = v - 1; }\n\n Sort(hitsp); }\n\n\n\nvoid ProcessCluster( int call, unsigned int K, int seq_id, Bool rc_seq, int h1,\n\n int h2, const vec< pair<unsigned int, unsigned int> >& hits, lookup_table& look,\n\n const basevector& s, int start_on_query, int stop_on_query,\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 78, "score": 109942.68848013895 }, { "content": " look.ContigStop(t), look.StartBaseInChunk(i),\n\n look.StopBaseInChunk(i) ) > 0 )\n\n { target_in_chunk = True;\n\n break; } }\n\n if ( !target_in_chunk ) continue; }\n\n\n\n static basevector s;\n\n s = seq[j];\n\n if ( s.size( ) < K ) continue;\n\n if ( s.size( ) < MIN_QUERY_LENGTH ) continue;\n\n if ( s.size( ) > MAX_QUERY_LENGTH ) continue;\n\n static qualvector q;\n\n if ( qual.size( ) ) q = qual[j];\n\n\n\n static vec< pair<int, int> > ints;\n\n ints.clear( );\n\n\n\n if ( seq_mask[j].size( ) == 0 )\n\n ints.push_back( make_pair( 0, s.size( ) ) );\n\n else\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 79, "score": 109934.74955143574 }, { "content": " const int SW_GAP_PENALTY, Bool SW_GAP_VERBOSE, ostream& out )\n\n{\n\n vec<unsigned int>& hits = *hits_ptr;\n\n vec< pair<unsigned int, unsigned int> >& hitsp = *hitsp_ptr;\n\n static vec<look_align> qualifiers;\n\n qualifiers.clear( );\n\n int min_hits = int(floor(\n\n MIN_COVERAGE * ((double) (stop_on_query-start_on_query) - (double) K) ) );\n\n min_hits = Min( min_hits, (int) MIN_HITS_TO_OVERRIDE );\n\n int winning_edge = int( floor( WINNING_EDGE * sqrtf(float(min_hits)) ) );\n\n winning_edge = Min( winning_edge, min_hits );\n\n int hfloor = min_hits - winning_edge;\n\n\n\n if ( start_on_query > 0 || stop_on_query < (int) s.size( ) )\n\n { static basevector t;\n\n t.SetToSubOf( s, start_on_query, stop_on_query - start_on_query );\n\n s = t; }\n\n\n\n for ( int pass = firstpass; pass <= npasses; pass++ )\n\n { if ( pass == 2 )\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 80, "score": 109931.10479664462 }, { "content": "\n\n // Do perfect extensions off the ends.\n\n\n\n Bool off_contig_end = False;\n\n if ( start != 0 )\n\n { for ( unsigned int y = start - 1; ; y-- )\n\n { if ( offset + y < max_query_size ) break;\n\n unsigned int bl = (offset + y) - max_query_size;\n\n if ( !look.BaseInMemory(bl) ||\n\n bl < look.ContigStart(current_contig) )\n\n { off_contig_end = True;\n\n break; }\n\n if ( s[y] != look.Base(bl) ) break;\n\n match[y] = True;\n\n --start;\n\n if ( y == 0 ) break; } }\n\n for ( unsigned int y = stop; y < s.size( ); y++ )\n\n { unsigned int bl = (offset + y) - max_query_size;\n\n if ( !look.BaseInMemory(bl) || bl >= look.ContigStop(current_contig) )\n\n { off_contig_end = True;\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 81, "score": 109930.94784356853 }, { "content": " static vec<umutmer> um;\n\n um.clear( );\n\n for ( int h = h1; h < h2; h++ )\n\n { int x;\n\n for ( x = h + 1; x < h2; x++ )\n\n if ( hits[x].first != hits[h].first ) break;\n\n\n\n // The hits between h and x all have the same offset.\n\n\n\n unsigned int offset = hits[h].first;\n\n unsigned int start = hits[h].second, stop = hits[x-1].second + K;\n\n\n\n // The bases on the sequence from start to stop all have the potential to\n\n // match at the given offset. First determine which ones actually match.\n\n\n\n static vec<Bool> match;\n\n match.resize_and_set( s.size( ), False );\n\n for ( unsigned int y = start; y < stop; y++ )\n\n { if ( s[y] == look.Base( (offset + y) - max_query_size ) )\n\n match[y] = True; }\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 82, "score": 109930.21876043765 }, { "content": " MIN_OVERLAP, END_STRETCH, mfreq, four_to_Kdiff, imperfect_extension,\n\n\t sync_aligns_to_TACG, SMITH_WAT, BW_ADD, SW_MISMATCH_PENALTY,\n\n SW_GAP_PENALTY, SW_GAP_VERBOSE, out ); } }\n\n\n\ntypedef std::pair<size_t,size_t> SummaryEntry;\n\n\n\nvoid ProcessQuerySequence( const int npasses, const Bool firstpass, \n\n lookup_table& look, int seq_id,\n\n basevector s, int start_on_query, int stop_on_query, int orig_query_length,\n\n qualvector q, int& n_all_qualifiers, unsigned int Kdiffbits,\n\n unsigned int four_to_Kdiff, unsigned int mfreq, const map_longlong_longlong& to_query_id,\n\n unsigned int K, double MIN_COVERAGE, unsigned int MIN_HITS_TO_OVERRIDE,\n\n double WINNING_EDGE, unsigned int MAX_OFFSET_DIFF, unsigned int MIN_OVERLAP,\n\n unsigned int END_STRETCH, double PROGRESSION_RATIO,\n\n unsigned int MIN_MUTMER_LENGTH, Bool SINGLETON_HITS, unsigned int KEEP_BEST,\n\n Bool SHOW_PREMUTMERS, Bool SHOW_MUTMERS, vec<unsigned int>* hits_ptr,\n\n vec< pair<unsigned int, unsigned int> >* hitsp_ptr, BinaryWriter& bwq,\n\n BinaryWriter& bwqs, Bool imperfect_extension,\n\n const vec<longlong>& targets_to_process, const Bool sync_aligns_to_TACG,\n\n Bool SMITH_WAT, int BW_ADD, const int SW_MISMATCH_PENALTY,\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 83, "score": 109928.5321114933 }, { "content": " unsigned int freq = 0, index2 = index;\n\n for ( unsigned int v = 0; v < four_to_Kdiff; v++ )\n\n freq += look.Freq(index2++);\n\n if ( freq > mfreq ) continue;\n\n for ( unsigned int v = 0; v < four_to_Kdiff; v++ )\n\n { unsigned int start = look.StartLocs(index);\n\n unsigned int stop = look.StopLocs(index);\n\n if ( targets_to_process.empty( ) )\n\n { if (SINGLETON_HITS)\n\n { for ( unsigned int l = start; l < stop; l++ )\n\n { unsigned int offset\n\n = look.Locs(l) + ( max_query_size - r );\n\n hits.push_back(offset); } }\n\n else\n\n { for ( unsigned int l = start; l < stop; l++ )\n\n { unsigned int offset\n\n = look.Locs(l) + ( max_query_size - r );\n\n hitsp.push_back(\n\n make_pair( offset, r ) ); } } }\n\n else\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 84, "score": 109928.30736053102 }, { "content": "\n\n const unsigned int UNDEFINED_CONTIG = 2000000000u;\n\n static unsigned int current_contig(UNDEFINED_CONTIG);\n\n { unsigned int start\n\n = ( hits[h1].first + hits[h1].second ) - max_query_size;\n\n if ( current_contig == UNDEFINED_CONTIG\n\n || start < look.ContigStart(current_contig)\n\n || start >= look.ContigStop(current_contig) )\n\n { unsigned int cpos;\n\n look.GetContigPos( start, current_contig, cpos ); }\n\n Bool off_contig = False;\n\n for ( int h = h1; h < h2; h++ )\n\n { unsigned int startx\n\n = ( hits[h].first + hits[h].second ) - max_query_size;\n\n if ( startx < look.ContigStart(current_contig)\n\n || startx + K > look.ContigStop(current_contig) )\n\n { off_contig = True; } }\n\n if (off_contig)\n\n { static vec< vec< pair<unsigned int, unsigned int> > > vhits;\n\n vhits.clear( );\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 85, "score": 109927.41907412258 }, { "content": "///Compare two ho_intervals by length.\n\nstruct SmallerLength: public binary_function<ho_interval, ho_interval, bool> {\n\n bool operator()(const ho_interval & l, const ho_interval & r) {\n\n return (l.Length() < r.Length());\n\n }\n\n};\n\n\n\ninline longlong Sum( const vec<ho_interval>& v )\n\n{ longlong sum = 0;\n\n for ( size_t i = 0; i < v.size(); i++ )\n\n sum += v[i].Length( );\n\n return sum; }\n\n\n\ninline Bool Member( const ho_interval& x, int k )\n\n{ return k >= x.Start( ) && k < x.Stop( ); }\n\n\n\ninline Bool Member( const vec<ho_interval>& v, int k )\n\n{ for ( size_t i = 0; i < v.size(); i++ )\n\n if ( Member( v[i], k ) ) return True;\n\n return False; }\n\n\n", "file_path": "src/math/HoInterval.h", "rank": 86, "score": 109925.92768358554 }, { "content": " if ( x1.seq < x2.seq ) return True;\n\n return False; }\n\n\n\n};\n\n\n\nvoid FetchHits( unsigned int min_offset, unsigned int max_offset,\n\n const basevector& s, unsigned int K, unsigned int mfreq,\n\n vec< pair<unsigned int, unsigned int> >& hitsp, lookup_table& look,\n\n unsigned int four_to_Kdiff, Bool strict )\n\n{\n\n hitsp.clear( );\n\n unsigned int min_on_genome = min_offset;\n\n unsigned int max_on_genome = max_offset + s.size( ) - K;\n\n if ( min_on_genome < max_query_size ) min_on_genome = 0;\n\n else min_on_genome -= max_query_size;\n\n unsigned int bases_start = look.BasesStart( );\n\n min_on_genome = Max( bases_start, min_on_genome );\n\n max_on_genome -= max_query_size;\n\n max_on_genome\n\n = Min( max_on_genome, look.BasesStart( ) + look.Bases( ).size( ) - K );\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 87, "score": 109925.73095830996 }, { "content": " static vec<int> contigs;\n\n contigs.clear( );\n\n static vec<Bool> used;\n\n used.resize_and_set( h2 - h1, False );\n\n while(1)\n\n { int h0;\n\n for ( h0 = h1; h0 < h2; h0++ )\n\n if ( !used[ h0 - h1 ] ) break;\n\n if ( h0 == h2 ) break;\n\n unsigned int cpos;\n\n unsigned int startx\n\n = ( hits[h0].first + hits[h0].second ) - max_query_size;\n\n look.GetContigPos( startx, current_contig, cpos );\n\n static vec< pair<unsigned int, unsigned int> > thits;\n\n thits.clear( );\n\n for ( int h = h0; h < h2; h++ )\n\n { if ( used[ h - h1 ] ) continue;\n\n startx = hits[h].first + hits[h].second - max_query_size;\n\n if ( startx >= look.ContigStart(current_contig)\n\n && startx < look.ContigStop(current_contig) )\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 88, "score": 109925.4391494335 }, { "content": " { static vec<ho_interval> covered;\n\n covered.clear( );\n\n for ( int u = 0; u < seq_mask[j].isize( ); u++ )\n\n covered.push_back( ho_interval(\n\n seq_mask[j][u].first, seq_mask[j][u].second ) );\n\n vec< pair<ho_interval, int> > condensed;\n\n CondenseIntervals( s.size( ), covered, condensed );\n\n for ( int u = 0; u < condensed.isize( ); u++ )\n\n { if ( condensed[u].second != 0 ) continue;\n\n const ho_interval& h = condensed[u].first;\n\n if ( h.Length( ) < (int) K ) continue;\n\n ints.push_back(\n\n make_pair( h.Start( ), h.Stop( ) ) ); } }\n\n for ( int u = 0; u < ints.isize( ); u++ )\n\n { const vec<longlong>& targets =\n\n ( SEQS_TARGETS_TO_PROCESS == \"undefString\"\n\n ? targets_to_process : targets_for_seq[j] );\n\n int npasses = ( FW_ONLY ? 1 : 2 );\n\n Bool firstpass = ( RC_ONLY ? 2 : 1 );\n\n ProcessQuerySequence( npasses, firstpass, look, j, s,\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 89, "score": 109922.88622762717 }, { "content": " { if (SINGLETON_HITS)\n\n { for ( unsigned int l = start; l < stop; l++ )\n\n { unsigned int loc = look.Locs(l);\n\n Bool in_targets = False;\n\n for ( int u = 0; u < targets_to_process.isize( );\n\n u++ )\n\n { int t = targets_to_process[u];\n\n if ( loc >= look.ContigStart(t)\n\n && loc <= look.ContigStop(t) )\n\n { in_targets = True; } }\n\n if ( !in_targets ) continue;\n\n unsigned int offset = loc + (max_query_size - r);\n\n hits.push_back(offset); } }\n\n else\n\n { for ( unsigned int l = start; l < stop; l++ )\n\n { unsigned int loc = look.Locs(l);\n\n Bool in_targets = False;\n\n for ( int u = 0; u < targets_to_process.isize( );\n\n u++ )\n\n { int t = targets_to_process[u];\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 90, "score": 109920.02245576723 }, { "content": " { if ( startx + K <= look.ContigStop(current_contig) )\n\n thits.push_back( hits[h] );\n\n used[ h - h1 ] = True; } }\n\n if ( thits.size( ) == 0 ) continue;\n\n contigs.push_back(current_contig);\n\n vhits.push_back(thits); }\n\n for ( int i = 0; i < vhits.isize( ); i++ )\n\n { ProcessCluster( call, K, seq_id, rc_seq, 0, vhits[i].size( ),\n\n vhits[i], look, s, start_on_query, stop_on_query,\n\n orig_query_length, qualifiers, actual_hits,\n\n SHOW_PREMUTMERS, SHOW_MUTMERS, have_spoken, to_query_id,\n\n PROGRESSION_RATIO, MIN_MUTMER_LENGTH, MAX_OFFSET_DIFF,\n\n MIN_OVERLAP, END_STRETCH, mfreq, four_to_Kdiff,\n\n imperfect_extension, sync_aligns_to_TACG, SMITH_WAT,\n\n BW_ADD, SW_MISMATCH_PENALTY, SW_GAP_PENALTY, \n\n SW_GAP_VERBOSE, out ); }\n\n return; } }\n\n\n\n // Create merged hits, which are presented as umutmers.\n\n\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 91, "score": 109919.65568670408 }, { "content": " // added the restriction that s.size( ) < 2000. I'm not sure what the right\n\n // solution is.\n\n\n\n if ( call == 0 && !found_full && ( max_pos1 > 0 || min_Pos1 < s.size( ) )\n\n && s.size( ) < 2000 )\n\n { int mfreq_mult = 600;\n\n unsigned int min_offset = hits[h1].first, max_offset = hits[h1].first;\n\n for ( int h = h1+1; h < h2; h++ )\n\n { min_offset = Min( min_offset, hits[h].first );\n\n max_offset = Max( max_offset, hits[h].first ); }\n\n if ( min_offset >= max_pos1 ) min_offset -= max_pos1;\n\n else min_offset = 0;\n\n max_offset += (int) s.size( ) - min_Pos1;\n\n static vec< pair<unsigned int, unsigned int> > hits2;\n\n FetchHits( min_offset, max_offset, s, K, mfreq_mult * mfreq, hits2, look,\n\n four_to_Kdiff, False );\n\n ProcessCluster( 1, K, seq_id, rc_seq, 0, hits2.size( ), hits2, look, s,\n\n start_on_query, stop_on_query, orig_query_length, qualifiers,\n\n actual_hits, SHOW_PREMUTMERS, SHOW_MUTMERS, have_spoken, to_query_id,\n\n PROGRESSION_RATIO, MIN_MUTMER_LENGTH, MAX_OFFSET_DIFF,\n", "file_path": "src/lookup/QueryLookupTableCore.cc", "rank": 92, "score": 109919.57863820356 }, { "content": "\n\n const unsigned int max_query_size = 200 * 1000 * 1000;\n\n for ( unsigned int i = 0; i < look.NChunks( ); i++ )\n\n { look.ReadChunk(i);\n\n // Go through the query sequences.\n\n\n\n for ( int id = 0; id < nqueries; id++ )\n\n { int query_id = range_start + id;\n\n const basevector& s = query[query_id];\n\n \t unsigned int query_length = s.size();\n\n\n\n // Go through the orientations.\n\n\n\n for ( int pass = 0; pass < npasses; pass++ )\n\n\t\t { int r = best_pos[ 2*id + pass ]; // r is low-freq kmer position in query\n\n if ( r < 0 ) continue;\n\n static basevector src;\n\n if ( pass == 1 ) src.ReverseComplement(s);\n\n const basevector& S = ( pass == 0 ? s : src );\n\n unsigned int index = best_index[ 2*id + pass ];\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 93, "score": 97.29308913530475 }, { "content": " // Go through the orientations.\n\n\n\n for ( int pass = 0; pass < npasses; pass++ )\n\n \t { // r is low-freq kmer position in query\n\n int r = best_pos[ 2*id + pass ]; \n\n if ( r < 0 ) continue;\n\n if ( pass == 1 ) src.ReverseComplement(s);\n\n const basevector& S = ( pass == 0 ? s : src );\n\n unsigned int index = best_index[ 2*id + pass ];\n\n unsigned int start = lookp->StartLocs(index);\n\n unsigned int stop = lookp->StopLocs(index);\n\n for ( unsigned int l = start; l < stop; l++ )\n\n\t\t { unsigned int offset = lookp->Locs(l) \n\n + ( max_query_size - r );\n\n // rpos is low-freq kmer position in target\n\n unsigned int tig, rpos; \n\n lookp->GetContigPos( lookp->Locs(l), tig, rpos );\n\n\t\t\t unsigned int startx;\n\n\t\t\t unsigned int q_start;\n\n\t\t\t unsigned int t_start;\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 94, "score": 93.06863279482562 }, { "content": " ForceAssertLt( static_cast<size_t>(range_end), query.size());\n\n ForceAssertLe( range_start, range_end);\n\n\n\n // For each query (or its rc), find a kmer in it that appears a minimal number \n\n // of times in the target.\n\n\n\n const int npasses = ( direction == FW ? 1 : 2 );\n\n const int nqueries = range_end - range_start + 1;\n\n\n\n vec<int> best_pos( nqueries * 2 );\n\n vec<unsigned int> best_index( nqueries * 2 );\n\n for ( int id = 0; id < nqueries; id++ )\n\n { int query_id = range_start + id;\n\n const basevector& s = query[query_id];\n\n if ( s.size() < K ) {\n\n for ( int pass = 0; pass < npasses; pass++ ) {\n\n best_pos[2*id+pass] = -1;\n\n best_index[2*id+pass] = 0;\n\n }\n\n continue;\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 95, "score": 92.79494334769528 }, { "content": "\t\t\t q_start = 0;\n\n\t\t\t t_start = rpos - r;\n\n\t\t\t startx = offset - max_query_size;\n\n\t\t\t }\n\n\n\n\t\t\t if (startx + length > look.ContigStop(tig) ) {\n\n\t\t\t length = look.ContigSize(tig) - t_start;\n\n\t\t\t }\n\n\n\n\t\t\t // Do we want subsumed alignments only?\n\n\t\t\t if (length != query_length && subsumed_only)\n\n\t\t\t continue;\n\n\n\n // Validate alignment, skipping portion covered by kmer.\n\n if ( startx < look.BasesStart( ) ) continue;\n\n Bool mismatch = False;\n\n\t\t\t unsigned int start_of_kmer = r - q_start;\n\n for ( unsigned int y = 0; y < start_of_kmer; y++ )\n\n\t\t\t { if ( S[q_start + y] != look.Base( startx + y ) )\n\n\t\t\t { mismatch = True;\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 96, "score": 87.95106076361351 }, { "content": " la.a.Setpos1(q_start);\n\n la.a.Setpos2(t_start);\n\n la.query_length = query_length;\n\n la.target_length = look.ContigSize(tig);\n\n la.rc1 = ( pass == 1 );\n\n la.a.SetLength( 0, length );\n\n aligns.push_back(la); } } } } }\n\n\n\n// ---------------------------------------------------------------------------------\n\n\n\nvoid ParallelPerfectLookup( const int max_threads, const unsigned int K, \n\n const vecbasevector& query, const String& lookup_file, vec<look_align>& aligns,\n\n const AlignDir direction, const Bool subsumed_only, \n\n const unsigned int target_seq_overlap )\n\n{ ParallelPerfectLookup( max_threads, K, query, lookup_file, aligns, direction, \n\n 0, query.size() - 1, subsumed_only, target_seq_overlap ); }\n\n\n\n// Communication for parallel threads:\n\n\n\nvec<int> best_pos;\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 97, "score": 87.64947012350204 }, { "content": " unsigned int start = look.StartLocs(index);\n\n unsigned int stop = look.StopLocs(index);\n\n for ( unsigned int l = start; l < stop; l++ )\n\n\t\t { unsigned int offset = look.Locs(l) + ( max_query_size - r );\n\n\n\n unsigned int tig, rpos; // rpos is low-freq kmer position in target\n\n look.GetContigPos( look.Locs(l), tig, rpos );\n\n\t\t\t \n\n\t\t\t unsigned int startx;\n\n\t\t\t unsigned int q_start;\n\n\t\t\t unsigned int t_start;\n\n\t\t\t unsigned int length = query_length;\n\n\n\n\t\t\t // Determine starting position in target and query\n\n\t\t\t if ( offset < look.ContigStart(tig) + max_query_size) {\n\n\t\t\t q_start = r - rpos;\n\n\t\t\t t_start = 0;\n\n\t\t\t length -= q_start;\n\n\t\t\t startx = look.ContigStart(tig);\n\n\t\t\t } else {\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 98, "score": 83.50921155950464 }, { "content": " }\n\n for ( int pass = 0; pass < npasses; pass++ )\n\n { static basevector src;\n\n\t if ( pass == 1 ) src.ReverseComplement(s);\n\n\t const basevector& S = ( pass == 0 ? s : src );\n\n int pos = -1;\n\n unsigned int min_freq = 0, mindex = 0;\n\n\t int length = S.isize() - (int) K;\n\n\t unsigned int index = Index( S, 0, K );\n\n\t unsigned int freq = look.Freq(index);\n\n\t if ( freq != 0 ) \n\n\t { mindex = index;\n\n\t\t pos = 0;\n\n\t\t if (freq != 1)\n\n\t\t { min_freq = freq;\n\n\t\t for ( int j = 1; j <= length; j++ )\n\n\t\t\t { NextIndex( index, S, j, K );\n\n\t\t\t freq = look.Freq(index);\n\n\t\t\t if ( freq == 1 )\n\n\t\t\t { mindex = index;\n", "file_path": "src/lookup/PerfectLookup.cc", "rank": 99, "score": 83.04360540346329 } ]
C++
silo-scripts/myscripts/replay-file-27.cpp
shenweihai1/rolis-eurosys2022
59b3fd58144496a9b13415e30b41617b34924323
#include <iostream> #include <string> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <fstream> #include <string.h> #include <chrono> #include <vector> #include <map> #include <cstring> #include <algorithm> #include <stdlib.h> using namespace std; std::map<long, std::string> table_map = {}; int OFFSET_CID = 0; int OFFSET_K = 8 ; int OFFSET_V = 16 ; int OFFSET_TABLE_ID = 24; int OFFSET_DELETE_TRUE = 26 ; long get_file_size(std::string filename) { struct stat *stat_buf=new struct stat(); int rc = stat(filename.c_str(), stat_buf); auto ans = rc == 0 ? stat_buf->st_size : -1; delete stat_buf; return ans; } inline std::vector<std::string> split_util2( std::string const& original, char separator) { std::vector<std::string> results; results.reserve(32); std::string::const_iterator start = original.begin(); std::string::const_iterator end = original.end(); std::string::const_iterator next = std::find( start, end, separator ); while ( next != end ) { results.emplace_back( start, next ); start = next + 1; next = std::find( start, end, separator ); } results.emplace_back( start, next ); return results; } bool fileToMap(const std::string &filename,std::map<long, std::string> &fileMap) { ifstream ifile; ifile.open(filename.c_str()); if(!ifile) { std::cout << "File " << filename << " Can't be read successfully " << '\n'; return false; } string line; string key; vector<string> v_str; while(ifile>>line) { v_str = split_util2(line,','); fileMap[stoul(v_str[1])] = v_str[0]; } return true; } namespace hopman_fast { struct itostr_helper { static unsigned out[10000]; itostr_helper() { for (int i = 0; i < 10000; i++) { unsigned v = i; char * o = (char*)(out + i); o[3] = v % 10 + '0'; o[2] = (v % 100) / 10 + '0'; o[1] = static_cast<char>((v % 1000) / 100) + '0'; o[0] = static_cast<char>((v % 10000) / 1000); if (o[0]) o[0] |= 0x30; else if (o[1] != '0') o[0] |= 0x20; else if (o[2] != '0') o[0] |= 0x10; else o[0] |= 0x00; } } }; unsigned itostr_helper::out[10000]; itostr_helper hlp_init; template <typename T> void itostr(T o, std::string& out) { typedef itostr_helper hlp; unsigned blocks[3], *b = blocks + 2; blocks[0] = o < 0 ? ~o + 1 : o; blocks[2] = blocks[0] % 10000; blocks[0] /= 10000; blocks[2] = hlp::out[blocks[2]]; if (blocks[0]) { blocks[1] = blocks[0] % 10000; blocks[0] /= 10000; blocks[1] = hlp::out[blocks[1]]; blocks[2] |= 0x30303030; b--; } if (blocks[0]) { blocks[0] = hlp::out[blocks[0] % 10000]; blocks[1] |= 0x30303030; b--; } char* f = ((char*)b); f += 3 - (*f >> 4); char* str = (char*)blocks; if (o < 0) *--f = '-'; out.assign(f, (str + 12) - f); } template <typename T> std::string itostr(T o) { std::string result; itostr(o,result); return result; } } void readOneFile(std::string file_name) { size_t sz = get_file_size(file_name); int fd = open (file_name.c_str (), O_RDONLY); size_t ret = 0; void *ptr = NULL; char *buffer; ptr = (void *) malloc (sz); buffer = (char *) ptr; ret = read (fd, buffer, sz); if (ret == -1 || ret == 0) { std::cout << "[mymain] file is empty " << ret << std::endl; } unsigned long long int *cid = 0; unsigned long long int *k = 0; unsigned long long int *v = 0; unsigned short int *table_id = 0; unsigned char *delete_true = 0; const unsigned char true_flag = 0x1; std::ofstream file(file_name + ".log"); size_t chunk = ret / 27 ; for (size_t i=0; i < chunk; ++i) { cid = reinterpret_cast<unsigned long long int *>(buffer + i * 27 + OFFSET_CID); k = reinterpret_cast<unsigned long long int *>(buffer + i * 27 + OFFSET_K); v = reinterpret_cast<unsigned long long int *>(buffer + i * 27 + OFFSET_V); table_id = reinterpret_cast<unsigned short int *>(buffer + i * 27 + OFFSET_TABLE_ID); delete_true = reinterpret_cast<unsigned char *>(buffer + i * 27 + OFFSET_DELETE_TRUE); bool isDeleted = false; if(*delete_true & true_flag) { isDeleted = true ; } if (*table_id == 0 || *table_id > 20000) { std::cout << "table_id " << *table_id << ":" << i << ":" << ret << std::endl; exit(1); } auto str_key = hopman_fast::itostr(*k); std::string row = to_string(*cid) + "," + str_key + "," + to_string(*v) + "," + to_string(*table_id) + "," + table_map[*table_id] + "," + to_string(isDeleted) + "\n"; file << row ; } } namespace so { std::string& itostr(int n, std::string& s) { if (n == 0) { s = "0"; return s; } int sign = -(n < 0); unsigned int val = (n ^ sign) - sign; int size; if (val >= 10000) { if (val >= 10000000) { if (val >= 1000000000) size = 10; else if (val >= 100000000) size = 9; else size = 8; } else { if (val >= 1000000) size = 7; else if (val >= 100000) size = 6; else size = 5; } } else { if (val >= 100) { if (val >= 1000) size = 4; else size = 3; } else { if (val>=10) size = 2; else size = 1; } } s.resize(-sign + size); char* c = &s[0]; if (sign) *c++='-'; char* d = c + size - 1; while(val > 0) { *d-- = '0' + (val % 10); val /= 10; } return s; } template <typename T> std::string itostr(T o) { std::string result; itostr(o,result); return result; } } namespace cppx { using std::numeric_limits; using std::reverse; typedef numeric_limits<long> Long_info; int const long_digits = Long_info::max_digits10; int const long_bufsize = long_digits + 2; inline void unsigned_to_decimal( unsigned long number, char* buffer ) { if( number == 0 ) { *buffer++ = '0'; } else { char* p_first = buffer; while( number != 0 ) { *buffer++ = '0' + number % 10; number /= 10; } reverse( p_first, buffer ); } *buffer = '\0'; } inline auto decimal_from_unsigned( unsigned long number, char* buffer ) -> char const* { unsigned_to_decimal( number, buffer ); return buffer; } inline void to_decimal( long number, char* buffer ) { if( number < 0 ) { buffer[0] = '-'; unsigned_to_decimal( -number, buffer + 1 ); } else { unsigned_to_decimal( number, buffer ); } } inline auto decimal_from( long number, char* buffer ) -> char const* { to_decimal( number, buffer ); return buffer; } } int main() { unsigned long long int k = 10232314212323; std::string s = hopman_fast::itostr(k) ; std::cout << s << " : " << std::to_string(k) << " : " << so::itostr(k) << std::endl; std::cout << sizeof(unsigned long long int) << " : " << sizeof(unsigned long) << " : " << sizeof(uint64_t) << " : " << sizeof(unsigned)<< std::endl; }
#include <iostream> #include <string> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <fstream> #include <string.h> #include <chrono> #include <vector> #include <map> #include <cstring> #include <algorithm> #include <stdlib.h> using namespace std; std::map<long, std::string> table_map = {}; int OFFSET_CID = 0; int OFFSET_K = 8 ; int OFFSET_V = 16 ; int OFFSET_TABLE_ID = 24; int OFFSET_DELETE_TRUE = 26 ; long get_file_size(std::string filename) { struct stat *stat_buf=new struct stat(); int rc = stat(filename.c_str(), stat_buf); auto ans = rc == 0 ? stat_buf->st_size : -1; delete stat_buf; return ans; } inline std::vector<std::string> split_util2( std::string const& original, char separator) { std::vector<std::string> results; results.reserve(32); std::string::const_iterator start = original.begin(); std::string::const_iterator end = original.end(); std::string::const_iterator next = std::find( start, end, separator ); while ( next != end ) { results.emplace_back( start, next ); start = next + 1; next = std::find( start, end, separator ); } results.emplace_back( start, next ); return results; } bool fileToMap(const std::string &filename,std::map<long, std::string> &fileMap) { ifstream ifile; ifile.open(filename.c_str()); if(!ifile) { std::cout << "File " << filename << " Can't be read successfully " << '\n'; return false; } string line; string key; vector<string> v_str; while(ifile>>line) { v_str = split_util2(line,','); fileMap[stoul(v_str[1])] = v_str[0]; } return true; } namespace hopman_fast { struct itostr_helper { static unsigned out[10000]; itostr_helper() { for (int i = 0; i < 10000; i++) { unsigned v = i; char * o = (char*)(out + i); o[3] = v % 10 + '0'; o[2] = (v % 100) / 10 + '0'; o[1] = static_cast<char>((v % 1000) / 100) + '0'; o[0] = static_cast<char>((v % 10000) / 1000); if (o[0]) o[0] |= 0x30; else if (o[1] != '0') o[0] |= 0x20; else if (o[2] != '0') o[0] |= 0x10; else o[0] |= 0x00; } } }; unsigned itostr_helper::out[10000]; itostr_helper hlp_init; template <typename T> void itostr(T o, std::string& out) { typedef itostr_helper hlp; unsigned blocks[3], *b = blocks + 2; blocks[0] = o < 0 ? ~o + 1 : o; blocks[2] = blocks[0] % 10000; blocks[0] /= 10000; blocks[2] = hlp::out[blocks[2]]; if (blocks[0]) { blocks[1] = blocks[0] % 10000; blocks[0] /= 10000; blocks[1] = hlp::out[blocks[1]]; blocks[2] |= 0x30303030; b--; } if (blocks[0]) { blocks[0] = hlp::out[blocks[0] % 10000]; blocks[1] |= 0x30303030; b--; } char* f = ((char*)b); f += 3 - (*f >> 4); char* str = (char*)blocks; if (o < 0) *--f = '-'; out.assign(f, (str + 12) - f); } template <typename T> std::string itostr(T o) { std::string result; itostr(o,result); return result; } } void readOneFile(std::string file_name) { size_t sz = get_file_size(file_name); int fd = open (file_name.c_str (), O_RDONLY); size_t ret = 0; void *ptr = NULL; char *buffer; ptr = (void *) malloc (sz); buffer = (char *) ptr; ret = read (fd, buffer, sz); if (ret == -1 || ret == 0) { std::cout << "[mymain] file is empty " << ret << std::endl; } unsigned long long int *cid = 0; unsigned long long int *k = 0; unsigned long long int *v = 0; unsigned short int *table_id = 0; unsigned char *delete_true = 0; const unsigned char true_flag = 0x1; std::ofstream file(file_name + ".log"); size_t chunk = ret / 27 ; for (size_t i=0; i < chunk; ++i) { cid = reinterpret_cast<unsigned long long int *>(buffer + i * 27 + OFFSET_CID); k = reinterpret_cast<unsigned long long int *>(buffer + i * 27 + OFFSET_K); v = reinterpret_cast<unsigned long long int *>(buffer + i * 27 + OFFSET_V); table_id = reinterpret_cast<unsigned short int *>(buffer + i * 27 + OFFSET_TABLE_ID); delete_true = reinterpret_cast<unsigned char *>(buffer + i * 27 + OFFSET_DELETE_TRUE); bool isDeleted = false; if(*delete_true & true_flag) { isDeleted = true ; } if (*table_id == 0 || *table_id > 20000) { std::cout << "table_id " << *table_id << ":" << i << ":" << ret << std::endl; exit(1); } auto str_key = hopman_fast::itostr(*k); std::string row = to_string(*cid) + "," + str_key + "," + to_string(*v) + "," + to_string(*table_id) + "," + table_map[*table_id] + "," + to_string(isDeleted) + "\n"; file << row ; } } namespace so { std::string& itostr(int n, std::string& s) { if (n == 0) { s = "0"; return s; } int sign = -(n < 0); unsigned int val = (n ^ sign) - sign; int size; if (val >= 10000) { if (val >= 10000000) { if (val >= 1000000000) size = 10; else if (val >= 100000000) size = 9; else size = 8; } else { if (val >= 1000000) size = 7; else if (val >= 100000) size = 6; else size = 5
unsigned long number, char* buffer ) { if( number == 0 ) { *buffer++ = '0'; } else { char* p_first = buffer; while( number != 0 ) { *buffer++ = '0' + number % 10; number /= 10; } reverse( p_first, buffer ); } *buffer = '\0'; } inline auto decimal_from_unsigned( unsigned long number, char* buffer ) -> char const* { unsigned_to_decimal( number, buffer ); return buffer; } inline void to_decimal( long number, char* buffer ) { if( number < 0 ) { buffer[0] = '-'; unsigned_to_decimal( -number, buffer + 1 ); } else { unsigned_to_decimal( number, buffer ); } } inline auto decimal_from( long number, char* buffer ) -> char const* { to_decimal( number, buffer ); return buffer; } } int main() { unsigned long long int k = 10232314212323; std::string s = hopman_fast::itostr(k) ; std::cout << s << " : " << std::to_string(k) << " : " << so::itostr(k) << std::endl; std::cout << sizeof(unsigned long long int) << " : " << sizeof(unsigned long) << " : " << sizeof(uint64_t) << " : " << sizeof(unsigned)<< std::endl; }
; } } else { if (val >= 100) { if (val >= 1000) size = 4; else size = 3; } else { if (val>=10) size = 2; else size = 1; } } s.resize(-sign + size); char* c = &s[0]; if (sign) *c++='-'; char* d = c + size - 1; while(val > 0) { *d-- = '0' + (val % 10); val /= 10; } return s; } template <typename T> std::string itostr(T o) { std::string result; itostr(o,result); return result; } } namespace cppx { using std::numeric_limits; using std::reverse; typedef numeric_limits<long> Long_info; int const long_digits = Long_info::max_digits10; int const long_bufsize = long_digits + 2; inline void unsigned_to_decimal(
random
[ { "content": "struct RemoveConstFromKey<std::pair<const K, V> > {\n\n typedef std::pair<K, V> type;\n\n};\n\n\n\n// Mapping from booleans to types. Similar to boost::bool_<kValue> and\n\n// std::integral_constant<bool, kValue>.\n\ntemplate <bool kValue>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 0, "score": 477890.58275111316 }, { "content": "struct convert<std::map<K, V>> {\n\n static Node encode(const std::map<K, V>& rhs) {\n\n Node node(NodeType::Map);\n\n for (typename std::map<K, V>::const_iterator it = rhs.begin();\n\n it != rhs.end(); ++it)\n\n node.force_insert(it->first, it->second);\n\n return node;\n\n }\n\n\n\n static bool decode(const Node& node, std::map<K, V>& rhs) {\n\n if (!node.IsMap())\n\n return false;\n\n\n\n rhs.clear();\n\n for (const_iterator it = node.begin(); it != node.end(); ++it)\n\n#if defined(__GNUC__) && __GNUC__ < 4\n\n // workaround for GCC 3:\n\n rhs[it->first.template as<K>()] = it->second.template as<V>();\n\n#else\n\n rhs[it->first.as<K>()] = it->second.as<V>();\n\n#endif\n\n return true;\n\n }\n\n};\n\n\n\n// std::vector\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 1, "score": 462534.98960546515 }, { "content": "struct serializer< inline_str_base<IntSizeType, N>, Compress > {\n\n typedef inline_str_base<IntSizeType, N> obj_type;\n\n static inline uint8_t *\n\n write(uint8_t *buf, const obj_type &obj)\n\n {\n\n buf = serializer<IntSizeType, Compress>::write(buf, &obj.sz);\n\n NDB_MEMCPY(buf, &obj.buf[0], obj.sz);\n\n return buf + obj.sz;\n\n }\n\n\n\n static const uint8_t *\n\n read(const uint8_t *buf, obj_type *obj)\n\n {\n\n buf = serializer<IntSizeType, Compress>::read(buf, &obj->sz);\n\n NDB_MEMCPY(&obj->buf[0], buf, obj->sz);\n\n return buf + obj->sz;\n\n }\n\n\n\n static const uint8_t *\n\n failsafe_read(const uint8_t *buf, size_t nbytes, obj_type *obj)\n", "file_path": "record/inline_str.h", "rank": 2, "score": 429197.05052728544 }, { "content": "struct convert<const char[N]> {\n\n static Node encode(const char(&rhs)[N]) { return Node(rhs); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 3, "score": 397275.53166593466 }, { "content": "struct convert<const char*> {\n\n static Node encode(const char*& rhs) { return Node(rhs); }\n\n};\n\n\n\ntemplate <std::size_t N>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 4, "score": 326221.38774523686 }, { "content": "struct convert<std::string> {\n\n static Node encode(const std::string& rhs) { return Node(rhs); }\n\n\n\n static bool decode(const Node& node, std::string& rhs) {\n\n if (!node.IsScalar())\n\n return false;\n\n rhs = node.Scalar();\n\n return true;\n\n }\n\n};\n\n\n\n// C-strings can only be encoded\n\ntemplate <>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 5, "score": 326107.7766279731 }, { "content": "struct RemoveConst<const T[N]> {\n\n typedef typename RemoveConst<T>::type type[N];\n\n};\n\n\n\n#if defined(_MSC_VER) && _MSC_VER < 1400\n\n// This is the only specialization that allows VC++ 7.1 to remove const in\n\n// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC\n\n// and thus needs to be conditionally compiled.\n\ntemplate <typename T, size_t N>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 6, "score": 312788.20938001346 }, { "content": "struct node_iterator_type<const V> {\n\n typedef node_seq::const_iterator seq;\n\n typedef node_map::const_iterator map;\n\n};\n\n\n\ntemplate <typename V>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h", "rank": 7, "score": 311068.7897880222 }, { "content": "struct convert<std::vector<T>> {\n\n static Node encode(const std::vector<T>& rhs) {\n\n Node node(NodeType::Sequence);\n\n for (typename std::vector<T>::const_iterator it = rhs.begin();\n\n it != rhs.end(); ++it)\n\n node.push_back(*it);\n\n return node;\n\n }\n\n\n\n static bool decode(const Node& node, std::vector<T>& rhs) {\n\n if (!node.IsSequence())\n\n return false;\n\n\n\n rhs.clear();\n\n for (const_iterator it = node.begin(); it != node.end(); ++it)\n\n#if defined(__GNUC__) && __GNUC__ < 4\n\n // workaround for GCC 3:\n\n rhs.push_back(it->template as<T>());\n\n#else\n\n rhs.push_back(it->as<T>());\n\n#endif\n\n return true;\n\n }\n\n};\n\n\n\n// std::list\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 8, "score": 310984.80845431495 }, { "content": "struct inline_string : public String_base<inline_string> {\n\n int len;\n\n char s[0];\n\n\n\n const char *data() const {\n\n return s;\n\n }\n\n int length() const {\n\n return len;\n\n }\n\n\n\n size_t size() const {\n\n return sizeof(inline_string) + len;\n\n }\n\n static size_t size(int len) {\n\n return sizeof(inline_string) + len;\n\n }\n\n};\n\n\n\n} // namespace lcdf\n\n\n\nLCDF_MAKE_STRING_HASH(lcdf::Str)\n\nLCDF_MAKE_STRING_HASH(lcdf::inline_string)\n\n#endif\n", "file_path": "masstree/str.hh", "rank": 9, "score": 304138.7638631001 }, { "content": "struct node_iterator_value : public std::pair<V*, V*> {\n\n typedef std::pair<V*, V*> kv;\n\n\n\n node_iterator_value() : kv(), pNode(0) {}\n\n explicit node_iterator_value(V& rhs) : kv(), pNode(&rhs) {}\n\n explicit node_iterator_value(V& key, V& value) : kv(&key, &value), pNode(0) {}\n\n\n\n V& operator*() const { return *pNode; }\n\n V& operator->() const { return *pNode; }\n\n\n\n V* pNode;\n\n};\n\n\n\ntypedef std::vector<node*> node_seq;\n\ntypedef std::vector<std::pair<node*, node*>> node_map;\n\n\n\ntemplate <typename V>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h", "rank": 10, "score": 304013.363853425 }, { "content": "// Tests that ResultOf(f, ...) compiles and works as expected when f is a\n\n// function object.\n\nstruct Functor : public ::std::unary_function<int, string> {\n\n result_type operator()(argument_type input) const {\n\n return IntToStringFunction(input);\n\n }\n\n};\n\n\n\nTEST(ResultOfTest, WorksForFunctors) {\n\n Matcher<int> matcher = ResultOf(Functor(), Eq(string(\"foo\")));\n\n\n\n EXPECT_TRUE(matcher.Matches(1));\n\n EXPECT_FALSE(matcher.Matches(2));\n\n}\n\n\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/test/gmock-matchers_test.cc", "rank": 11, "score": 300780.7234815721 }, { "content": "struct convert<std::array<T, N>> {\n\n static Node encode(const std::array<T, N>& rhs) {\n\n Node node(NodeType::Sequence);\n\n for (const auto& element : rhs) {\n\n node.push_back(element);\n\n }\n\n return node;\n\n }\n\n\n\n static bool decode(const Node& node, std::array<T, N>& rhs) {\n\n if (!isNodeValid(node)) {\n\n return false;\n\n }\n\n\n\n for (auto i = 0u; i < node.size(); ++i) {\n\n#if defined(__GNUC__) && __GNUC__ < 4\n\n // workaround for GCC 3:\n\n rhs[i] = node[i].template as<T>();\n\n#else\n\n rhs[i] = node[i].as<T>();\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 12, "score": 298092.6963721942 }, { "content": "struct inline_string : public String_base<inline_string> {\n\n int len;\n\n char s[0];\n\n\n\n const char *data() const {\n\n return s;\n\n }\n\n int length() const {\n\n return len;\n\n }\n\n\n\n size_t size() const {\n\n return sizeof(inline_string) + len;\n\n }\n\n static size_t size(int len) {\n\n return sizeof(inline_string) + len;\n\n }\n\n};\n\n\n\n} // namespace lcdf\n\n\n\nLCDF_MAKE_STRING_HASH(lcdf::Str)\n\nLCDF_MAKE_STRING_HASH(lcdf::inline_string)\n\n#endif\n", "file_path": "benchmarks/sto/masstree-beta/str.hh", "rank": 13, "score": 292522.89918225014 }, { "content": "struct Packer<std::string, false> {\n\n template <typename... Args>\n\n static void* pack(TransactionBuffer& buf, Args&&... args) {\n\n return buf.template allocate<std::string>(std::forward<Args>(args)...);\n\n }\n\n static void* pack(TransactionBuffer&, const StringWrapper& wrapper) {\n\n return wrapper.value();\n\n }\n\n static void* pack(TransactionBuffer&, StringWrapper&& wrapper) {\n\n return wrapper.value();\n\n }\n\n static void* pack_unique(TransactionBuffer& buf, const std::string& x) {\n\n if (const void* ptr = buf.find<UniqueKey<std::string> >(x))\n\n return const_cast<void*>(ptr);\n\n else\n\n return buf.allocate<UniqueKey<std::string> >(x);\n\n }\n\n template <typename... Args>\n\n static void* repack(TransactionBuffer& buf, void*, Args&&... args) {\n\n return pack(buf, std::forward<Args>(args)...);\n\n }\n\n static std::string& unpack(void* x) {\n\n return *(std::string*) x;\n\n }\n\n};\n", "file_path": "benchmarks/sto/StringWrapper.hh", "rank": 14, "score": 292470.85272272973 }, { "content": "// Helper for suppressing false warning from Clang on a const char*\n\n// variable declared in a conditional expression always being NULL in\n\n// the else branch.\n\nstruct GTEST_API_ ConstCharPtr {\n\n ConstCharPtr(const char* str) : value(str) {}\n\n operator bool() const { return true; }\n\n const char* value;\n\n};\n\n\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 15, "score": 289167.55133548216 }, { "content": "struct Str : public String_base<Str> {\n\n typedef Str substring_type;\n\n typedef Str argument_type;\n\n\n\n const char *s;\n\n int len;\n\n\n\n Str()\n\n : s(0), len(0) {\n\n }\n\n template <typename T>\n\n Str(const String_base<T>& x)\n\n : s(x.data()), len(x.length()) {\n\n }\n\n Str(const char* s_)\n\n : s(s_), len(strlen(s_)) {\n\n }\n\n Str(const char* s_, int len_)\n\n : s(s_), len(len_) {\n\n }\n", "file_path": "masstree/str.hh", "rank": 16, "score": 284515.63005285227 }, { "content": "struct RemoveConst<const T> { typedef T type; }; // NOLINT\n\n\n\n// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above\n\n// definition to fail to remove the const in 'const int[3]' and 'const\n\n// char[3][4]'. The following specialization works around the bug.\n\ntemplate <typename T, size_t N>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 17, "score": 280311.6226198684 }, { "content": "struct ByRef { typedef const T& type; }; // NOLINT\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 18, "score": 276430.2336091646 }, { "content": "struct Str : public String_base<Str> {\n\n typedef Str substring_type;\n\n typedef Str argument_type;\n\n\n\n const char *s;\n\n int len;\n\n\n\n Str()\n\n : s(0), len(0) {\n\n }\n\n template <typename T>\n\n Str(const String_base<T>& x)\n\n : s(x.data()), len(x.length()) {\n\n }\n\n Str(const char* s_)\n\n : s(s_), len(strlen(s_)) {\n\n }\n\n Str(const char* s_, int len_)\n\n : s(s_), len(len_) {\n\n }\n", "file_path": "benchmarks/sto/masstree-beta/str.hh", "rank": 19, "score": 274961.45135645533 }, { "content": "struct RemoveConst<T[N]> {\n\n typedef typename RemoveConst<T>::type type[N];\n\n};\n\n#endif\n\n\n\n// A handy wrapper around RemoveConst that works when the argument\n\n// T depends on template parameters.\n\n#define GTEST_REMOVE_CONST_(T) \\\n\n typename ::testing::internal::RemoveConst<T>::type\n\n\n\n// Turns const U&, U&, const U, and U all into U.\n\n#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \\\n\n GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T))\n\n\n\n// Adds reference to a type if it is not a reference type,\n\n// otherwise leaves it unchanged. This is the same as\n\n// tr1::add_reference, which is not widely available yet.\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 20, "score": 274607.52321631945 }, { "content": "struct keystore decode(const string& s){\n\n\tstruct keystore obj{};\n\n\tmemcpy (&obj, s.data(),sizeof (struct keystore));\n\n\treturn obj;\n\n}\n\n\n\n#ifndef MASS_DIRECT\n\nvoid nontrans_get(new_ds &h, std::string& k,unsigned long long int& table_id,std::string &v, bool &exists) {\n\n {\n\n TransactionGuard guard;\n\n exists = h[table_id].transGet(k, v);\n\n }\n\n}\n\n#endif\n\n\n\nbool cmpFunc(const std::string& newValue,const std::string& oldValue)\n\n{\n\n auto retrieved_value_1 = decode(newValue);\n\n auto retrieved_value_2 = decode(oldValue);\n\n \n", "file_path": "benchmarks/sto/ThreadPool.cc", "rank": 21, "score": 268837.47665485204 }, { "content": "struct signed_aware_trfm<true, T> {\n\n typedef T signed_type;\n\n typedef\n\n typename std::enable_if<std::is_signed<T>::value, typename std::make_unsigned<T>::type>::type\n\n unsigned_type;\n\n inline ALWAYS_INLINE unsigned_type\n\n operator()(signed_type s) const\n\n {\n\n const unsigned_type offset = -std::numeric_limits<signed_type>::min();\n\n const unsigned_type converted = static_cast<unsigned_type>(s) + offset;\n\n return converted;\n\n }\n\n};\n\n\n\ntemplate <typename T,\n\n typename EncodingTrfm = signed_aware_trfm<std::is_signed<T>::value, T>,\n\n typename ByteTrfm = util::big_endian_trfm<T> >\n", "file_path": "varkey.h", "rank": 22, "score": 264722.44124282233 }, { "content": "struct IntStr {\n\n char s_[16];\n\n lcdf::Str str_;\n\n IntStr(int i) {\n\n int n = snprintf(s_, sizeof(s_), \"%d\", i);\n\n str_.assign(s_, n);\n\n }\n\n lcdf::Str& str() {\n\n return str_;\n\n }\n\n operator lcdf::Str&() {\n\n return str_;\n\n }\n\n};\n", "file_path": "benchmarks/sto/IntStr.hh", "rank": 23, "score": 262614.7425306073 }, { "content": "class TestingVector : public std::vector<int> {\n\n};\n\n\n\n::std::ostream& operator<<(::std::ostream& os,\n\n const TestingVector& vector) {\n\n os << \"{ \";\n\n for (size_t i = 0; i < vector.size(); i++) {\n\n os << vector[i] << \" \";\n\n }\n\n os << \"}\";\n\n return os;\n\n}\n\n\n\n// This line tests that we can define tests in an unnamed namespace.\n\nnamespace {\n\n\n\nTEST(GetRandomSeedFromFlagTest, HandlesZero) {\n\n const int seed = GetRandomSeedFromFlag(0);\n\n EXPECT_LE(1, seed);\n\n EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/test/gtest_unittest.cc", "rank": 24, "score": 254789.8292225282 }, { "content": "struct RemoveConst { typedef T type; }; // NOLINT\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 25, "score": 254303.12866959994 }, { "content": "class snapshot_range: public Enumerator<std::pair<const Key&, const Value&>> {\n\n Snapshot snapshot_;\n\n Iterator begin_, end_, next_;\n\n bool cached_;\n\n std::pair<const Key*, const Value*> cached_next_;\n\n int count_;\n\n\n\n bool prefetch_next() {\n\n assert(cached_ == false);\n\n while (cached_ == false && next_ != end_) {\n\n if (next_->second.valid_at(snapshot_.version())) {\n\n cached_next_.first = &(next_->first);\n\n cached_next_.second = &(next_->second.val);\n\n cached_ = true;\n\n }\n\n ++next_;\n\n }\n\n return cached_;\n\n }\n\n\n", "file_path": "third-party/paxos/src/memdb/snapshot.h", "rank": 26, "score": 251488.16006450713 }, { "content": "struct RemoveConstFromKey {\n\n typedef T type;\n\n};\n\n\n\n// Partially specialized to remove constness from std::pair<const K, V>.\n\ntemplate <typename K, typename V>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 27, "score": 248805.59189666226 }, { "content": "struct convert<bool> {\n\n static Node encode(bool rhs) { return rhs ? Node(\"true\") : Node(\"false\"); }\n\n\n\n YAML_CPP_API static bool decode(const Node& node, bool& rhs);\n\n};\n\n\n\n// std::map\n\ntemplate <typename K, typename V>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 28, "score": 247749.74731450307 }, { "content": "class inline_str_16 : public inline_str_base<uint16_t, N> {\n\n typedef inline_str_base<uint16_t, N> super_type;\n\npublic:\n\n inline_str_16() : super_type() {}\n\n inline_str_16(const char *s) : super_type(s) {}\n\n inline_str_16(const char *s, size_t n) : super_type(s, n) {}\n\n inline_str_16(const std::string &s) : super_type(s) {}\n\n} PACKED;\n\n\n\n// equiavlent to CHAR(N)\n\ntemplate <unsigned int N, char FillChar = ' '>\n", "file_path": "record/inline_str.h", "rank": 29, "score": 246965.14056228564 }, { "content": "class inline_str_8 : public inline_str_base<uint8_t, N> {\n\n typedef inline_str_base<uint8_t, N> super_type;\n\npublic:\n\n inline_str_8() : super_type() {}\n\n inline_str_8(const char *s) : super_type(s) {}\n\n inline_str_8(const char *s, size_t n) : super_type(s, n) {}\n\n inline_str_8(const std::string &s) : super_type(s) {}\n\n} PACKED;\n\n\n\ntemplate <unsigned int N>\n", "file_path": "record/inline_str.h", "rank": 30, "score": 246965.14056228564 }, { "content": "struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>\n\n : public true_type {}; // NOLINT\n\n\n\n// Converting bool to any integer type is lossless.\n\ntemplate <typename To>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 31, "score": 243386.4603229643 }, { "content": "struct SameSizeTuplePrefixComparator<k, k> {\n\n template <class Tuple1, class Tuple2>\n\n static bool Eq(const Tuple1& t1, const Tuple2& t2) {\n\n return SameSizeTuplePrefixComparator<k - 1, k - 1>::Eq(t1, t2) &&\n\n ::std::tr1::get<k - 1>(t1) == ::std::tr1::get<k - 1>(t2);\n\n }\n\n};\n\n\n\n} // namespace gtest_internal\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>\n\ninline bool operator==(const GTEST_10_TUPLE_(T)& t,\n\n const GTEST_10_TUPLE_(U)& u) {\n\n return gtest_internal::SameSizeTuplePrefixComparator<\n\n tuple_size<GTEST_10_TUPLE_(T) >::value,\n\n tuple_size<GTEST_10_TUPLE_(U) >::value>::Eq(t, u);\n\n}\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>\n\ninline bool operator!=(const GTEST_10_TUPLE_(T)& t,\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 32, "score": 238903.9055473033 }, { "content": "struct SameSizeTuplePrefixComparator<0, 0> {\n\n template <class Tuple1, class Tuple2>\n\n static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {\n\n return true;\n\n }\n\n};\n\n\n\ntemplate <int k>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 33, "score": 238901.96851876046 }, { "content": "struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > {\n\n typedef T7 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 34, "score": 235015.1011406334 }, { "content": "struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > {\n\n typedef T5 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 35, "score": 235015.1011406334 }, { "content": "struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > {\n\n typedef T9 type;\n\n};\n\n\n\n} // namespace gtest_internal\n\n\n\ntemplate <>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 36, "score": 235015.1011406334 }, { "content": "struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > {\n\n typedef T6 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 37, "score": 235014.54058114212 }, { "content": "struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > {\n\n typedef T4 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 38, "score": 235013.98334552662 }, { "content": "struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {\n\n typedef T0 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 39, "score": 235013.98334552662 }, { "content": "struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > {\n\n typedef T2 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 40, "score": 235012.32080485875 }, { "content": "struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > {\n\n typedef T3 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 41, "score": 235010.66386555595 }, { "content": "struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {\n\n typedef T1 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 42, "score": 235004.045075118 }, { "content": "struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > {\n\n typedef T8 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 43, "score": 235002.94164111844 }, { "content": "struct LOGGING_CONST {\n\n static std::string WHOLE_LOG_STRING;\n\n static std::string WHOLE_INFO_STRING;\n\n \n\n static void setlog(int threads, int runTime){\n\n\tstd::string SUFFIX_STRING = \"GenLogThd\"+std::to_string(threads)+\".Time.\"+std::to_string(runTime)+\"/\";\n\n\tWHOLE_LOG_STRING = LOG_FOLDER + SUFFIX_STRING;\n\n\tWHOLE_INFO_STRING = LOG_FOLDER + SUFFIX_STRING + \"info/\";\n\n }\n\n};\n\n\n\nbool util_mkpath( const std::string& path );\n\n\n\n/**\n\n* Singleton Logger Class.\n\n*/\n", "file_path": "benchmarks/sto/OutputDataSerializer.h", "rank": 44, "score": 234714.18202313955 }, { "content": "struct vector {\n\n T _buf[128];\n\n uint _cnt;\n\n\n\n vector() : _cnt(0) {}\n\n void insert_front(T e) {\n\n assert(_cnt < sizeof(_buf) / sizeof(T));\n\n memmove(&_buf[1], &_buf[0], _cnt * sizeof(T));\n\n _buf[0] = e;\n\n _cnt++;\n\n }\n\n void push_back(T e) {\n\n assert(_cnt < sizeof(_buf) / sizeof(T));\n\n _buf[_cnt] = e;\n\n _cnt++;\n\n }\n\n};\n\n\n\ntemplate<class T>\n", "file_path": "scopedperf.hh", "rank": 45, "score": 231088.69101333688 }, { "content": "struct row_delta_marker : public row_marker {\n\n kvtimestamp_t prev_ts_;\n\n R *prev_;\n\n char s_[0];\n\n};\n\n\n\ntemplate <typename R>\n\ninline bool row_is_delta_marker(const R* row) {\n\n if (row_is_marker(row)) {\n\n const row_marker* m =\n\n reinterpret_cast<const row_marker *>(row->col(0).s);\n\n return m->marker_type_ == m->mt_delta;\n\n } else\n\n return false;\n\n}\n\n\n\ntemplate <typename R>\n\ninline row_delta_marker<R>* row_get_delta_marker(const R* row, bool force = false) {\n\n (void) force;\n\n assert(force || row_is_delta_marker(row));\n\n return reinterpret_cast<row_delta_marker<R>*>\n\n (const_cast<char*>(row->col(0).s));\n\n}\n\n\n\n#endif\n", "file_path": "masstree/log.hh", "rank": 46, "score": 230801.38728299324 }, { "content": "struct stat {\n\n /** @brief An initialization call from main function\n\n */\n\n static void initmain(bool pinthreads);\n\n#if GCSTATS\n\n int gc_nfree;\n\n#endif\n\n void initialize(int cid) {\n\n this->cid = cid;\n\n }\n\n static void print(const stat **s, int n);\n\n int cid; // core index\n\n};\n\n}\n\n#endif\n", "file_path": "masstree/perfstat.hh", "rank": 47, "score": 227989.49491615372 }, { "content": "struct convert<std::list<T>> {\n\n static Node encode(const std::list<T>& rhs) {\n\n Node node(NodeType::Sequence);\n\n for (typename std::list<T>::const_iterator it = rhs.begin();\n\n it != rhs.end(); ++it)\n\n node.push_back(*it);\n\n return node;\n\n }\n\n\n\n static bool decode(const Node& node, std::list<T>& rhs) {\n\n if (!node.IsSequence())\n\n return false;\n\n\n\n rhs.clear();\n\n for (const_iterator it = node.begin(); it != node.end(); ++it)\n\n#if defined(__GNUC__) && __GNUC__ < 4\n\n // workaround for GCC 3:\n\n rhs.push_back(it->template as<T>());\n\n#else\n\n rhs.push_back(it->as<T>());\n\n#endif\n\n return true;\n\n }\n\n};\n\n\n\n// std::array\n\ntemplate <typename T, std::size_t N>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 48, "score": 224814.57841776422 }, { "content": "class UniversalTersePrinter<const char*> {\n\n public:\n\n static void Print(const char* str, ::std::ostream* os) {\n\n if (str == NULL) {\n\n *os << \"NULL\";\n\n } else {\n\n UniversalPrint(string(str), os);\n\n }\n\n }\n\n};\n\ntemplate <>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/gtest-printers.h", "rank": 49, "score": 224434.23496368347 }, { "content": " class iterator_ : public std::iterator<std::bidirectional_iterator_tag, ObjType> {\n\n friend class static_vector;\n\n public:\n\n inline iterator_() : p(0) {}\n\n\n\n template <typename O>\n\n inline iterator_(const iterator_<O> &other)\n\n : p(other.p)\n\n {}\n\n\n\n inline ObjType &\n\n operator*() const\n\n {\n\n return *p;\n\n }\n\n\n\n inline ObjType *\n\n operator->() const\n\n {\n\n return p;\n", "file_path": "static_vector.h", "rank": 50, "score": 223976.15357822547 }, { "content": "struct IteratorTraits<const T*> {\n\n typedef T value_type;\n\n};\n\n\n\n#if GTEST_OS_WINDOWS\n\n# define GTEST_PATH_SEP_ \"\\\\\"\n\n# define GTEST_HAS_ALT_PATH_SEP_ 1\n\n// The biggest signed integer type the compiler supports.\n\ntypedef __int64 BiggestInt;\n\n#else\n\n# define GTEST_PATH_SEP_ \"/\"\n\n# define GTEST_HAS_ALT_PATH_SEP_ 0\n\ntypedef long long BiggestInt; // NOLINT\n\n#endif // GTEST_OS_WINDOWS\n\n\n\n// Utilities for char.\n\n\n\n// isspace(int ch) and friends accept an unsigned char or EOF. char\n\n// may be signed, depending on the compiler (or compiler flags).\n\n// Therefore we need to cast a char to unsigned char before calling\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-port.h", "rank": 51, "score": 223896.722697708 }, { "content": "class iterator_base : public std::iterator<std::forward_iterator_tag, V,\n\n std::ptrdiff_t, V*, V> {\n\n\n\n private:\n\n template <typename>\n\n friend class iterator_base;\n\n struct enabler {};\n\n typedef node_iterator base_type;\n\n\n\n struct proxy {\n\n explicit proxy(const V& x) : m_ref(x) {}\n\n V* operator->() { return std::addressof(m_ref); }\n\n operator V*() { return std::addressof(m_ref); }\n\n\n\n V m_ref;\n\n };\n\n\n\n public:\n\n typedef typename iterator_base::value_type value_type;\n\n\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/detail/iterator.h", "rank": 52, "score": 222166.97482654618 }, { "content": "struct result {\n\n uint64_t ngt;\n\n int final_value;\n\n};\n\n\n", "file_path": "benchmarks/sto/ex-counter.cc", "rank": 53, "score": 222021.1433368132 }, { "content": "struct row_delta_marker : public row_marker {\n\n kvtimestamp_t prev_ts_;\n\n R *prev_;\n\n char s_[0];\n\n};\n\n\n\ntemplate <typename R>\n\ninline bool row_is_delta_marker(const R* row) {\n\n if (row_is_marker(row)) {\n\n const row_marker* m =\n\n reinterpret_cast<const row_marker *>(row->col(0).s);\n\n return m->marker_type_ == m->mt_delta;\n\n } else\n\n return false;\n\n}\n\n\n\ntemplate <typename R>\n\ninline row_delta_marker<R>* row_get_delta_marker(const R* row, bool force = false) {\n\n (void) force;\n\n assert(force || row_is_delta_marker(row));\n\n return reinterpret_cast<row_delta_marker<R>*>\n\n (const_cast<char*>(row->col(0).s));\n\n}\n\n\n\n#endif\n", "file_path": "benchmarks/sto/masstree-beta/log.hh", "rank": 54, "score": 221012.54605431546 }, { "content": " class iterator_ : public std::iterator<std::forward_iterator_tag, ValueType> {\n\n friend class static_unordered_map;\n\n public:\n\n inline iterator_() : b(0) {}\n\n\n\n template <typename B, typename V>\n\n inline iterator_(const iterator_<B, V> &other)\n\n : b(other.b)\n\n {}\n\n\n\n inline ValueType &\n\n operator*() const\n\n {\n\n return reinterpret_cast<ValueType &>(b->ref());\n\n }\n\n\n\n inline ValueType *\n\n operator->() const\n\n {\n\n return reinterpret_cast<ValueType *>(b->ptr());\n", "file_path": "static_unordered_map.h", "rank": 55, "score": 220987.02245904435 }, { "content": "struct versioned_value_struct<T, typename std::enable_if<!__has_trivial_copy(T)>::type> {\n\npublic:\n\n typedef T value_type;\n\n typedef TransactionTid::type version_type;\n\n\n\n static versioned_value_struct* make(const value_type& val, version_type version) {\n\n return new versioned_value_struct(val, version);\n\n }\n\n\n\n versioned_value_struct() : version_(), valueptr_() {}\n\n\n\n bool needsResize(const value_type&) {\n\n return false;\n\n }\n\n versioned_value_struct* resizeIfNeeded(const value_type&) {\n\n return this;\n\n }\n\n\n\n void set_value(const value_type& v) {\n\n //auto *old = valueptr_;\n", "file_path": "benchmarks/sto/versioned_value.hh", "rank": 56, "score": 219548.21222693502 }, { "content": "struct stat {\n\n /** @brief An initialization call from main function\n\n */\n\n static void initmain(bool pinthreads);\n\n#if GCSTATS\n\n int gc_nfree;\n\n#endif\n\n void initialize(int cid) {\n\n this->cid = cid;\n\n }\n\n static void print(const stat **s, int n);\n\n int cid; // core index\n\n};\n\n}\n\n#endif\n", "file_path": "benchmarks/sto/masstree-beta/perfstat.hh", "rank": 57, "score": 219315.763487119 }, { "content": "struct _Null;\n\n} // namespace YAML\n\n\n\nnamespace YAML {\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/emitter.h", "rank": 58, "score": 219197.57974600312 }, { "content": "struct YAML_CPP_API _Null {};\n\ninline bool operator==(const _Null&, const _Null&) { return true; }\n\ninline bool operator!=(const _Null&, const _Null&) { return false; }\n\n\n\nYAML_CPP_API bool IsNull(const Node& node); // old API only\n\nYAML_CPP_API bool IsNullString(const std::string& str);\n\n\n\nextern YAML_CPP_API _Null Null;\n\n}\n\n\n\n#endif // NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/null.h", "rank": 59, "score": 219158.68147115444 }, { "content": "struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>\n\n : public false_type {}; // NOLINT\n\n\n\n// Converting an integer to another non-bool integer is lossless iff\n\n// the target type's range encloses the source type's range.\n\ntemplate <typename From, typename To>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 60, "score": 217180.00238177058 }, { "content": "struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>\n\n : public true_type {}; // NOLINT\n\n\n\n// Converting bool to any floating-point type is lossless.\n\ntemplate <typename To>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 61, "score": 217180.00238177058 }, { "content": "struct TuplePolicy< ::std::tuple<Types...> > {\n\n typedef ::std::tuple<Types...> Tuple;\n\n static const size_t tuple_size = ::std::tuple_size<Tuple>::value;\n\n\n\n template <size_t I>\n\n struct tuple_element : ::std::tuple_element<I, Tuple> {};\n\n\n\n template <size_t I>\n\n static const typename ::std::tuple_element<I, Tuple>::type& get(\n\n const Tuple& tuple) {\n\n return ::std::get<I>(tuple);\n\n }\n\n};\n\ntemplate <typename... Types>\n\nconst size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;\n\n#endif // GTEST_HAS_STD_TUPLE_\n\n\n\n#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_\n\n// This helper template allows PrintTo() for tuples and\n\n// UniversalTersePrintTupleFieldsToStrings() to be defined by\n\n// induction on the number of tuple fields. The idea is that\n\n// TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N\n\n// fields in tuple t, and can be defined in terms of\n\n// TuplePrefixPrinter<N - 1>.\n\n//\n\n// The inductive case.\n\ntemplate <size_t N>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/gtest-printers.h", "rank": 62, "score": 216456.07741139532 }, { "content": "RESULTS = [({'scale_factor': 1, 'db': 'ndb-proto2', 'par_load': False, 'threads': 1, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '4G', 'persist': True}, [(28037.0, 28037.0, 0.0355513, 80.7772, 0.0), (28591.2, 28591.2, 0.0348332, 83.3726, 0.0), (28174.9, 28174.9, 0.0353661, 80.9923, 0.0)]), ({'scale_factor': 4, 'db': 'ndb-proto2', 'par_load': False, 'threads': 4, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '16G', 'persist': True}, [(101575.0, 101575.0, 0.0392489, 100.616, 4.06351), (104315.0, 104315.0, 0.0382123, 92.747, 4.44552), (103600.0, 103600.0, 0.0384777, 104.11, 4.54582)]), ({'scale_factor': 8, 'db': 'ndb-proto2', 'par_load': False, 'threads': 8, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '32G', 'persist': True}, [(198630.0, 198630.0, 0.0401546, 114.32, 8.11104), (201243.0, 201243.0, 0.039627, 156.711, 7.31041), (199076.0, 199076.0, 0.0400534, 119.783, 8.10939)]), ({'scale_factor': 12, 'db': 'ndb-proto2', 'par_load': False, 'threads': 12, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '48G', 'persist': True}, [(298566.0, 298566.0, 0.0400453, 133.356, 12.1187), (298133.0, 298133.0, 0.040098, 99.2246, 13.4485), (296903.0, 296903.0, 0.0402781, 124.433, 12.3886)]), ({'scale_factor': 16, 'db': 'ndb-proto2', 'par_load': False, 'threads': 16, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '64G', 'persist': True}, [(391792.0, 391792.0, 0.0407065, 118.188, 17.0175), (391965.0, 391965.0, 0.0406917, 111.37, 16.8899), (390145.0, 390145.0, 0.0408607, 110.049, 15.7134)]), ({'scale_factor': 20, 'db': 'ndb-proto2', 'par_load': False, 'threads': 20, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '80G', 'persist': True}, [(490782.0, 490782.0, 0.0406097, 118.621, 19.6794), (491448.0, 491448.0, 0.0405582, 117.648, 19.7812), (490189.0, 490189.0, 0.0406614, 146.335, 19.8124)]), ({'scale_factor': 24, 'db': 'ndb-proto2', 'par_load': False, 'threads': 24, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '96G', 'persist': True}, [(579773.0, 579773.0, 0.0412569, 163.993, 23.5593), (582446.0, 582446.0, 0.0410567, 105.998, 25.318), (576929.0, 576929.0, 0.0414494, 104.131, 23.6849)]), ({'scale_factor': 28, 'db': 'ndb-proto2', 'par_load': False, 'threads': 28, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '112G', 'persist': True}, [(670070.0, 670070.0, 0.041655, 103.69, 27.1961), (669347.0, 669347.0, 0.0416867, 141.835, 27.8873), (669634.0, 669634.0, 0.0416696, 102.389, 26.9551)]), ({'scale_factor': 32, 'db': 'ndb-proto2', 'par_load': False, 'threads': 32, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '128G', 'persist': True}, [(712434.0, 712434.0, 0.0447644, 214.95, 29.8936), (700382.0, 700382.0, 0.0455139, 240.664, 27.8856), (712480.0, 712480.0, 0.0447631, 234.26, 28.4791)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 1, 'name': 'scale_tpcc', 'numa_memory': '4G', 'persist': False, 'threads': 1, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(30286.9, 30286.9, 0.0329245, 0.0, 0.0), (30753.4, 30753.4, 0.0324305, 0.0, 0.0), (31151.2, 31151.2, 0.0320159, 0.0, 0.0)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 4, 'name': 'scale_tpcc', 'numa_memory': '16G', 'persist': False, 'threads': 4, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(112481.0, 112481.0, 0.0354717, 0.0, 5.06663), (111014.0, 111014.0, 0.0359431, 0.0, 5.14995), (112559.0, 112559.0, 0.035451, 0.0, 4.39996)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 8, 'name': 'scale_tpcc', 'numa_memory': '32G', 'persist': False, 'threads': 8, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(209400.0, 209400.0, 0.0381135, 0.0, 9.3166), (209405.0, 209405.0, 0.0381132, 0.0, 9.03321), (214395.0, 214395.0, 0.0372271, 0.0, 9.49995)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 12, 'name': 'scale_tpcc', 'numa_memory': '48G', 'persist': False, 'threads': 12, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(317759.0, 317759.0, 0.0376752, 0.0, 13.5665), (319487.0, 319487.0, 0.0374694, 0.0, 13.5165), (323316.0, 323316.0, 0.0370279, 0.0, 13.9331)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 16, 'name': 'scale_tpcc', 'numa_memory': '64G', 'persist': False, 'threads': 16, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(420957.0, 420957.0, 0.0379212, 0.0, 18.2664), (419207.0, 419207.0, 0.0380766, 0.0, 18.8332), (421561.0, 421561.0, 0.0378607, 0.0, 17.6499)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 20, 'name': 'scale_tpcc', 'numa_memory': '80G', 'persist': False, 'threads': 20, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(526460.0, 526460.0, 0.0378989, 0.0, 22.0331), (529197.0, 529197.0, 0.0377043, 0.0, 23.7497), (533214.0, 533214.0, 0.0374174, 0.0, 22.3831)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 24, 'name': 'scale_tpcc', 'numa_memory': '96G', 'persist': False, 'threads': 24, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(625632.0, 625632.0, 0.0382689, 0.0, 26.5161), (631692.0, 631692.0, 0.0378988, 0.0, 26.8828), (622284.0, 622284.0, 0.038478, 0.0, 26.9162)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 28, 'name': 'scale_tpcc', 'numa_memory': '112G', 'persist': False, 'threads': 28, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(728676.0, 728676.0, 0.0383326, 0.0, 30.5828), (731237.0, 731237.0, 0.0382001, 0.0, 32.2995), (724542.0, 724542.0, 0.0385532, 0.0, 32.4161)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 32, 'name': 'scale_tpcc', 'numa_memory': '128G', 'persist': False, 'threads': 32, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(783983.0, 783983.0, 0.0407091, 0.0, 35.0656), (782308.0, 782308.0, 0.040797, 0.0, 33.7652), (715915.0, 715915.0, 0.0445905, 0.0, 31.1658)])]\n", "file_path": "benchmarks/results/istc3-8-1-13_log_reduce_size.py", "rank": 63, "score": 216401.2587046349 }, { "content": "struct convert<std::pair<T, U>> {\n\n static Node encode(const std::pair<T, U>& rhs) {\n\n Node node(NodeType::Sequence);\n\n node.push_back(rhs.first);\n\n node.push_back(rhs.second);\n\n return node;\n\n }\n\n\n\n static bool decode(const Node& node, std::pair<T, U>& rhs) {\n\n if (!node.IsSequence())\n\n return false;\n\n if (node.size() != 2)\n\n return false;\n\n\n\n#if defined(__GNUC__) && __GNUC__ < 4\n\n // workaround for GCC 3:\n\n rhs.first = node[0].template as<T>();\n\n#else\n\n rhs.first = node[0].as<T>();\n\n#endif\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 64, "score": 215874.05649382048 }, { "content": "struct _Null;\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 65, "score": 215838.13667062332 }, { "content": "struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>\n\n : public false_type {}; // NOLINT\n\n\n\n// Converting a floating-point to an integer is lossy.\n\ntemplate <typename From, typename To>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 66, "score": 214972.89384609478 }, { "content": "struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>\n\n : public true_type {}; // NOLINT\n\n\n\n// Converting an integer to bool is lossy.\n\ntemplate <typename From>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 67, "score": 214972.89384609478 }, { "content": "RESULTS = [({'scale_factor': 28, 'db': 'ndb-proto2', 'par_load': False, 'threads': 28, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '112G', 'persist': True}, [(670070.0, 670070.0, 0.041655, 103.69, 27.1961), (669347.0, 669347.0, 0.0416867, 141.835, 27.8873), (669634.0, 669634.0, 0.0416696, 102.389, 26.9551)]), ({'scale_factor': 32, 'db': 'ndb-proto2', 'par_load': False, 'threads': 32, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '128G', 'persist': True}, [(712434.0, 712434.0, 0.0447644, 214.95, 29.8936), (700382.0, 700382.0, 0.0455139, 240.664, 27.8856), (712480.0, 712480.0, 0.0447631, 234.26, 28.4791)])]\n", "file_path": "benchmarks/results/istc3-8-1-13_log_reduce_size_1.py", "rank": 68, "score": 213654.88157723573 }, { "content": "RESULTS = [({'scale_factor': 1, 'db': 'ndb-proto2', 'par_load': False, 'threads': 1, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '4G', 'persist': True}, [(27871.4, 27871.4, 0.0357607, 81.8997, 0.0), (29390.7, 29390.7, 0.0338998, 82.0619, 0.0), (28280.2, 28280.2, 0.0352519, 82.0879, 0.0)]), ({'scale_factor': 4, 'db': 'ndb-proto2', 'par_load': False, 'threads': 4, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '16G', 'persist': True}, [(107300.0, 107300.0, 0.0371596, 96.2916, 4.61302), (106620.0, 106620.0, 0.037399, 95.1791, 4.31287), (104450.0, 104450.0, 0.0381691, 94.9936, 4.39564)]), ({'scale_factor': 8, 'db': 'ndb-proto2', 'par_load': False, 'threads': 8, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '32G', 'persist': True}, [(198942.0, 198942.0, 0.0400843, 110.726, 8.97438), (199131.0, 199131.0, 0.0400565, 105.12, 8.5101), (200443.0, 200443.0, 0.0397906, 103.181, 7.71011)]), ({'scale_factor': 12, 'db': 'ndb-proto2', 'par_load': False, 'threads': 12, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '48G', 'persist': True}, [(299454.0, 299454.0, 0.0399389, 109.416, 12.6518), (299527.0, 299527.0, 0.0399373, 115.718, 12.2231), (300443.0, 300443.0, 0.0398378, 106.138, 12.145)]), ({'scale_factor': 16, 'db': 'ndb-proto2', 'par_load': False, 'threads': 16, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '64G', 'persist': True}, [(391388.0, 391388.0, 0.0407652, 124.563, 15.2232), (394657.0, 394657.0, 0.0404256, 130.43, 15.0728), (396611.0, 396611.0, 0.0402169, 136.605, 16.1692)]), ({'scale_factor': 20, 'db': 'ndb-proto2', 'par_load': False, 'threads': 20, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '80G', 'persist': True}, [(498099.0, 498099.0, 0.0400256, 134.432, 21.216), (488264.0, 488264.0, 0.0408347, 133.72, 20.5144), (495505.0, 495505.0, 0.0402241, 150.323, 21.0244)]), ({'scale_factor': 24, 'db': 'ndb-proto2', 'par_load': False, 'threads': 24, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '96G', 'persist': True}, [(584701.0, 584701.0, 0.0409133, 102.95, 23.1438), (586412.0, 586412.0, 0.0407895, 99.3766, 22.822), (589676.0, 589676.0, 0.0405919, 99.7467, 22.6878)]), ({'scale_factor': 28, 'db': 'ndb-proto2', 'par_load': False, 'threads': 28, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '112G', 'persist': True}, [(675436.0, 675436.0, 0.0413229, 105.453, 28.0404), (660534.0, 660534.0, 0.0422653, 103.337, 27.3102), (679870.0, 679870.0, 0.0410626, 101.341, 28.1444)]), ({'scale_factor': 32, 'db': 'ndb-proto2', 'par_load': False, 'threads': 32, 'bench_opts': '', 'log_fake_writes': False, 'retry': False, 'log_nofsync': True, 'name': 'scale_tpcc', 'bench': 'tpcc', 'numa_memory': '128G', 'persist': True}, [(711674.0, 711674.0, 0.0448229, 216.884, 28.8772), (715904.0, 715904.0, 0.0445292, 279.838, 29.7625), (725241.0, 725241.0, 0.0439786, 315.067, 29.7777)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 1, 'name': 'scale_tpcc', 'numa_memory': '4G', 'persist': False, 'threads': 1, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(30286.9, 30286.9, 0.0329245, 0.0, 0.0), (30753.4, 30753.4, 0.0324305, 0.0, 0.0), (31151.2, 31151.2, 0.0320159, 0.0, 0.0)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 4, 'name': 'scale_tpcc', 'numa_memory': '16G', 'persist': False, 'threads': 4, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(112481.0, 112481.0, 0.0354717, 0.0, 5.06663), (111014.0, 111014.0, 0.0359431, 0.0, 5.14995), (112559.0, 112559.0, 0.035451, 0.0, 4.39996)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 8, 'name': 'scale_tpcc', 'numa_memory': '32G', 'persist': False, 'threads': 8, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(209400.0, 209400.0, 0.0381135, 0.0, 9.3166), (209405.0, 209405.0, 0.0381132, 0.0, 9.03321), (214395.0, 214395.0, 0.0372271, 0.0, 9.49995)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 12, 'name': 'scale_tpcc', 'numa_memory': '48G', 'persist': False, 'threads': 12, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(317759.0, 317759.0, 0.0376752, 0.0, 13.5665), (319487.0, 319487.0, 0.0374694, 0.0, 13.5165), (323316.0, 323316.0, 0.0370279, 0.0, 13.9331)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 16, 'name': 'scale_tpcc', 'numa_memory': '64G', 'persist': False, 'threads': 16, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(420957.0, 420957.0, 0.0379212, 0.0, 18.2664), (419207.0, 419207.0, 0.0380766, 0.0, 18.8332), (421561.0, 421561.0, 0.0378607, 0.0, 17.6499)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 20, 'name': 'scale_tpcc', 'numa_memory': '80G', 'persist': False, 'threads': 20, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(526460.0, 526460.0, 0.0378989, 0.0, 22.0331), (529197.0, 529197.0, 0.0377043, 0.0, 23.7497), (533214.0, 533214.0, 0.0374174, 0.0, 22.3831)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 24, 'name': 'scale_tpcc', 'numa_memory': '96G', 'persist': False, 'threads': 24, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(625632.0, 625632.0, 0.0382689, 0.0, 26.5161), (631692.0, 631692.0, 0.0378988, 0.0, 26.8828), (622284.0, 622284.0, 0.038478, 0.0, 26.9162)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 28, 'name': 'scale_tpcc', 'numa_memory': '112G', 'persist': False, 'threads': 28, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(728676.0, 728676.0, 0.0383326, 0.0, 30.5828), (731237.0, 731237.0, 0.0382001, 0.0, 32.2995), (724542.0, 724542.0, 0.0385532, 0.0, 32.4161)]), ({'par_load': False, 'bench_opts': '', 'retry': False, 'scale_factor': 32, 'name': 'scale_tpcc', 'numa_memory': '128G', 'persist': False, 'threads': 32, 'db': 'ndb-proto2', 'bench': 'tpcc'}, [(783983.0, 783983.0, 0.0407091, 0.0, 35.0656), (782308.0, 782308.0, 0.040797, 0.0, 33.7652), (715915.0, 715915.0, 0.0445905, 0.0, 31.1658)])]\n", "file_path": "benchmarks/results/istc3-8-1-13_log_reduce_size_nofsync.py", "rank": 69, "score": 213027.788030428 }, { "content": "class TVector<T, W>::const_iterator : public std::iterator<std::random_access_iterator_tag, T> {\n\npublic:\n\n typedef TVector<T, W> vector_type;\n\n typedef typename vector_type::size_type size_type;\n\n typedef typename vector_type::difference_type difference_type;\n\n typedef typename vector_type::pred_type pred_type;\n\n typedef typename vector_type::difference_proxy difference_proxy;\n\n\n\n const_iterator()\n\n : a_() {\n\n }\n\n const_iterator(const TVector<T, W>* a, size_type i, TransItem* eitem)\n\n : a_(const_cast<vector_type*>(a)), i_(i), eitem_(eitem) {\n\n }\n\n\n\n typename vector_type::const_proxy_type operator*() const {\n\n return vector_type::const_proxy_type(a_, i_);\n\n }\n\n\n\n bool operator==(const const_iterator& x) const {\n", "file_path": "benchmarks/sto/TVector.hh", "rank": 70, "score": 212663.15282501298 }, { "content": "class SetArgumentPointeeAction<N, Proto, true> {\n\n public:\n\n // Constructs an action that sets the variable pointed to by the\n\n // N-th function argument to 'proto'. Both ProtocolMessage and\n\n // proto2::Message have the CopyFrom() method, so the same\n\n // implementation works for both.\n\n explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {\n\n proto_->CopyFrom(proto);\n\n }\n\n\n\n template <typename Result, typename ArgumentTuple>\n\n void Perform(const ArgumentTuple& args) const {\n\n CompileAssertTypesEqual<void, Result>();\n\n ::testing::get<N>(args)->CopyFrom(*proto_);\n\n }\n\n\n\n private:\n\n const internal::linked_ptr<Proto> proto_;\n\n\n\n GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);\n\n};\n\n\n\n// Implements the InvokeWithoutArgs(f) action. The template argument\n\n// FunctionImpl is the implementation type of f, which can be either a\n\n// function pointer or a functor. InvokeWithoutArgs(f) can be used as an\n\n// Action<F> as long as f's type is compatible with F (i.e. f can be\n\n// assigned to a tr1::function<F>).\n\ntemplate <typename FunctionImpl>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/gmock-actions.h", "rank": 71, "score": 211870.60366922006 }, { "content": "class TArray<T, N, W>::const_iterator : public std::iterator<std::random_access_iterator_tag, T> {\n\npublic:\n\n typedef TArray<T, N, W> array_type;\n\n typedef typename array_type::size_type size_type;\n\n typedef typename array_type::difference_type difference_type;\n\n\n\n const_iterator(const TArray<T, N, W>* a, size_type i)\n\n : a_(const_cast<array_type*>(a)), i_(i) {\n\n }\n\n\n\n typename array_type::const_proxy_type operator*() const {\n\n return array_type::const_proxy_type(a_, i_);\n\n }\n\n\n\n bool operator==(const const_iterator& x) const {\n\n return a_ == x.a_ && i_ == x.i_;\n\n }\n\n bool operator!=(const const_iterator& x) const {\n\n return !(*this == x);\n\n }\n", "file_path": "benchmarks/sto/TArray.hh", "rank": 72, "score": 211371.29180909455 }, { "content": "class TVector_nopred<T, W>::const_iterator : public std::iterator<std::random_access_iterator_tag, T> {\n\npublic:\n\n typedef TVector_nopred<T, W> vector_type;\n\n typedef typename vector_type::size_type size_type;\n\n typedef typename vector_type::difference_type difference_type;\n\n\n\n const_iterator()\n\n : a_() {\n\n }\n\n const_iterator(const TVector_nopred<T, W>* a, size_type i)\n\n : a_(const_cast<vector_type*>(a)), i_(i) {\n\n }\n\n\n\n typename vector_type::const_proxy_type operator*() const {\n\n return vector_type::const_proxy_type(a_, i_);\n\n }\n\n\n\n bool operator==(const const_iterator& x) const {\n\n return a_ == x.a_ && i_ == x.i_;\n\n }\n", "file_path": "benchmarks/sto/TVector_nopred.hh", "rank": 73, "score": 208184.4642275847 }, { "content": "class GTEST_API_ Matcher<const internal::string&>\n\n : public internal::MatcherBase<const internal::string&> {\n\n public:\n\n Matcher() {}\n\n\n\n explicit Matcher(const MatcherInterface<const internal::string&>* impl)\n\n : internal::MatcherBase<const internal::string&>(impl) {}\n\n\n\n // Allows the user to write str instead of Eq(str) sometimes, where\n\n // str is a string object.\n\n Matcher(const internal::string& s); // NOLINT\n\n\n\n // Allows the user to write \"foo\" instead of Eq(\"foo\") sometimes.\n\n Matcher(const char* s); // NOLINT\n\n};\n\n\n\ntemplate <>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/gmock-matchers.h", "rank": 74, "score": 208174.47509488993 }, { "content": "struct record_version<true> {\n\n // [ locked | size | version ]\n\n // [ 0..1 | 1..17 | 17..32 ]\n\n\n\n static const uint32_t HDR_LOCKED_MASK = 0x1;\n\n\n\n static const uint32_t HDR_SIZE_SHIFT = 1;\n\n static const uint32_t HDR_SIZE_MASK = std::numeric_limits<uint16_t>::max() << HDR_SIZE_SHIFT;\n\n\n\n static const uint32_t HDR_VERSION_SHIFT = 17;\n\n static const uint32_t HDR_VERSION_MASK = ((uint32_t)-1) << HDR_VERSION_SHIFT;\n\n\n\n record_version<true>() : hdr(0) {}\n\n\n\n volatile uint32_t hdr;\n\n\n\n static inline bool\n\n IsLocked(uint32_t v)\n\n {\n\n return v & HDR_LOCKED_MASK;\n", "file_path": "benchmarks/kvdb_wrapper_impl.h", "rank": 75, "score": 207188.35887086234 }, { "content": "typedef void (*unspecified_bool_type)(unspecified_bool::NOT_ALLOWED*);\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h", "rank": 76, "score": 207017.28646227054 }, { "content": "struct convert<_Null> {\n\n static Node encode(const _Null& /* rhs */) { return Node(); }\n\n\n\n static bool decode(const Node& node, _Null& /* rhs */) {\n\n return node.IsNull();\n\n }\n\n};\n\n\n\n#define YAML_DEFINE_CONVERT_STREAMABLE(type, negative_op) \\\n\n template <> \\\n\n struct convert<type> { \\\n\n static Node encode(const type& rhs) { \\\n\n std::stringstream stream; \\\n\n stream.precision(std::numeric_limits<type>::digits10 + 1); \\\n\n stream << rhs; \\\n\n return Node(stream.str()); \\\n\n } \\\n\n \\\n\n static bool decode(const Node& node, type& rhs) { \\\n\n if (node.Type() != NodeType::Scalar) \\\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/include/yaml-cpp/node/convert.h", "rank": 77, "score": 206574.1854483143 }, { "content": "struct RemoveReference { typedef T type; }; // NOLINT\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 78, "score": 205329.2943850557 }, { "content": "struct AddRef { typedef T& type; }; // NOLINT\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 79, "score": 205329.2943850557 }, { "content": "struct AddReference { typedef T& type; }; // NOLINT\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 80, "score": 205329.2943850557 }, { "content": "struct bool_constant {\n\n typedef bool_constant<bool_value> type;\n\n static const bool value = bool_value;\n\n};\n\ntemplate <bool bool_value> const bool bool_constant<bool_value>::value;\n\n\n\ntypedef bool_constant<false> false_type;\n\ntypedef bool_constant<true> true_type;\n\n\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-port.h", "rank": 81, "score": 203615.99403464733 }, { "content": "struct ByRef<T&> { typedef T& type; }; // NOLINT\n\n\n\n// A handy wrapper for ByRef.\n\n#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef<T>::type\n\n\n\n// AddRef<T>::type is T if T is a reference; otherwise it's T&. This\n\n// is the same as tr1::add_reference<T>::type.\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 82, "score": 200303.93864634997 }, { "content": "// A user-defined data type.\n\nstruct Bool {\n\n explicit Bool(int val) : value(val != 0) {}\n\n\n\n bool operator>(int n) const { return value > Bool(n).value; }\n\n\n\n Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }\n\n\n\n bool operator==(const Bool& rhs) const { return value == rhs.value; }\n\n\n\n bool value;\n\n};\n\n\n\n// Enables Bool to be used in assertions.\n\nstd::ostream& operator<<(std::ostream& os, const Bool& x) {\n\n return os << (x.value ? \"true\" : \"false\");\n\n}\n\n\n\n// Sample functions/functors for testing unary predicate assertions.\n\n\n\n// A unary predicate function.\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/test/gtest_pred_impl_unittest.cc", "rank": 83, "score": 198946.85496184469 }, { "content": "struct SameSizeTuplePrefixComparator;\n\n\n\ntemplate <>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 84, "score": 198137.31306706494 }, { "content": "struct LinkedPtrLessThan {\n\n bool operator()(const ::testing::internal::linked_ptr<T>& lhs,\n\n const ::testing::internal::linked_ptr<T>& rhs) const {\n\n return lhs.get() < rhs.get();\n\n }\n\n};\n\n\n\n// Symbian compilation can be done with wchar_t being either a native\n\n// type or a typedef. Using Google Mock with OpenC without wchar_t\n\n// should require the definition of _STLP_NO_WCHAR_T.\n\n//\n\n// MSVC treats wchar_t as a native type usually, but treats it as the\n\n// same as unsigned short when the compiler option /Zc:wchar_t- is\n\n// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t\n\n// is a native type.\n\n#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \\\n\n (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))\n\n// wchar_t is a typedef.\n\n#else\n\n# define GMOCK_WCHAR_T_IS_NATIVE_ 1\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 85, "score": 198135.96611822708 }, { "content": "struct RemoveReference<T&> { typedef T type; }; // NOLINT\n\n\n\n// A handy wrapper around RemoveReference that works when the argument\n\n// T depends on template parameters.\n\n#define GTEST_REMOVE_REFERENCE_(T) \\\n\n typename ::testing::internal::RemoveReference<T>::type\n\n\n\n// Removes const from a type if it is a const type, otherwise leaves\n\n// it unchanged. This is the same as tr1::remove_const, which is not\n\n// widely available yet.\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 86, "score": 197879.33408393175 }, { "content": "struct PointeeOf<T*> { typedef T type; }; // NOLINT\n\n\n\n// GetRawPointer(p) returns the raw pointer underlying p when p is a\n\n// smart pointer, or returns p itself when p is already a raw pointer.\n\n// The following default implementation is for the smart pointer case.\n\ntemplate <typename Pointer>\n\ninline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {\n\n return p.get();\n\n}\n\n// This overloaded version is for the raw pointer case.\n\ntemplate <typename Element>\n\ninline Element* GetRawPointer(Element* p) { return p; }\n\n\n\n// This comparator allows linked_ptr to be stored in sets.\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h", "rank": 87, "score": 197879.33408393175 }, { "content": "struct AddRef<T&> { typedef T& type; }; // NOLINT\n\n\n\n// A handy wrapper for AddRef.\n\n#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef<T>::type\n\n\n\n// A helper for implementing get<k>().\n\ntemplate <int k> class Get;\n\n\n\n// A helper for implementing tuple_element<k, T>. kIndexValid is true\n\n// iff k < the number of fields in tuple type T.\n\ntemplate <bool kIndexValid, int kIndex, class Tuple>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 88, "score": 197879.33408393175 }, { "content": "struct AddReference<T&> { typedef T& type; }; // NOLINT\n\n\n\n// A handy wrapper around AddReference that works when the argument T\n\n// depends on template parameters.\n\n#define GTEST_ADD_REFERENCE_(T) \\\n\n typename ::testing::internal::AddReference<T>::type\n\n\n\n// Adds a reference to const on top of T as necessary. For example,\n\n// it transforms\n\n//\n\n// char ==> const char&\n\n// const char ==> const char&\n\n// char& ==> const char&\n\n// const char& ==> const char&\n\n//\n\n// The argument T must depend on some template parameters.\n\n#define GTEST_REFERENCE_TO_CONST_(T) \\\n\n GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T))\n\n\n\n// ImplicitlyConvertible<From, To>::value is a compile-time bool\n\n// constant that's true iff type From can be implicitly converted to\n\n// type To.\n\ntemplate <typename From, typename To>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-internal.h", "rank": 89, "score": 197879.33408393175 }, { "content": "class FooTest : public ::testing::TestWithParam<const char*> {\n\n // You can implement all the usual class fixture members here.\n\n};\n\n\n\n// Then, use the TEST_P macro to define as many parameterized tests\n\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n\n// or \"pattern\", whichever you prefer to think.\n\n\n\nTEST_P(FooTest, DoesBlah) {\n\n // Inside a test, access the test parameter with the GetParam() method\n\n // of the TestWithParam<T> class:\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n ...\n\n}\n\n\n\nTEST_P(FooTest, HasBlahBlah) {\n\n ...\n\n}\n\n\n\n// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/gtest-param-test.h", "rank": 90, "score": 195939.43391343814 }, { "content": "struct StaticAssertTypeEqHelper;\n\n\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-port.h", "rank": 91, "score": 195539.80652251324 }, { "content": "// A builtin parameterized test name generator which returns the result of\n\n// testing::PrintToString.\n\nstruct PrintToStringParamName {\n\n template <class ParamType>\n\n std::string operator()(const TestParamInfo<ParamType>& info) const {\n\n return PrintToString(info.param);\n\n }\n\n};\n\n\n\nnamespace internal {\n\n\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n\n//\n\n// Outputs a message explaining invalid registration of different\n\n// fixture class for the same test case. This may happen when\n\n// TEST_P macro is used to define two tests with the same name\n\n// but in different namespaces.\n\nGTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name,\n\n CodeLocation code_location);\n\n\n\ntemplate <typename> class ParamGeneratorInterface;\n\ntemplate <typename> class ParamGenerator;\n\n\n\n// Interface for iterating over elements provided by an implementation\n\n// of ParamGeneratorInterface<T>.\n\ntemplate <typename T>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-param-util.h", "rank": 92, "score": 195468.75187707887 }, { "content": "struct bufrec { char buf[256]; };\n\n\n\ntemplate <template <typename> class TxnType, typename Traits>\n\nstatic void\n\ntest2()\n\n{\n\n for (size_t txn_flags_idx = 0;\n\n txn_flags_idx < ARRAY_NELEMS(TxnFlags);\n\n txn_flags_idx++) {\n\n const uint64_t txn_flags = TxnFlags[txn_flags_idx];\n\n txn_btree<TxnType> btr(sizeof(bufrec));\n\n typename Traits::StringAllocator arena;\n\n bufrec r;\n\n NDB_MEMSET(r.buf, 'a', ARRAY_NELEMS(r.buf));\n\n for (size_t i = 0; i < 100; i++) {\n\n TxnType<Traits> t(txn_flags, arena);\n\n btr.insert_object(t, u64_varkey(i), r);\n\n AssertSuccessfulCommit(t);\n\n }\n\n for (size_t i = 0; i < 100; i++) {\n", "file_path": "txn_btree.cc", "rank": 93, "score": 193163.07425110877 }, { "content": "class ActionResultHolder<void> : public UntypedActionResultHolderBase {\n\n public:\n\n void Unwrap() { }\n\n\n\n virtual void PrintAsActionResult(::std::ostream* /* os */) const {}\n\n\n\n // Performs the given mock function's default action and returns ownership\n\n // of an empty ActionResultHolder*.\n\n template <typename F>\n\n static ActionResultHolder* PerformDefaultAction(\n\n const FunctionMockerBase<F>* func_mocker,\n\n const typename Function<F>::ArgumentTuple& args,\n\n const string& call_description) {\n\n func_mocker->PerformDefaultAction(args, call_description);\n\n return new ActionResultHolder;\n\n }\n\n\n\n // Performs the given action and returns ownership of an empty\n\n // ActionResultHolder*.\n\n template <typename F>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/gmock-spec-builders.h", "rank": 94, "score": 186580.55278498345 }, { "content": "struct TuplePrefixPrinter<0> {\n\n template <typename Tuple>\n\n static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}\n\n\n\n template <typename Tuple>\n\n static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}\n\n};\n\n\n\n// Helper function for printing a tuple.\n\n// Tuple must be either std::tr1::tuple or std::tuple type.\n\ntemplate <typename Tuple>\n\nvoid PrintTupleTo(const Tuple& t, ::std::ostream* os) {\n\n *os << \"(\";\n\n TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os);\n\n *os << \")\";\n\n}\n\n\n\n// Prints the fields of a tuple tersely to a string vector, one\n\n// element for each field. See the comment before\n\n// UniversalTersePrint() for how we define \"tersely\".\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/gtest-printers.h", "rank": 95, "score": 186228.91215139185 }, { "content": "struct tuple_size<GTEST_3_TUPLE_(T) > {\n\n static const int value = 3;\n\n};\n\n\n\ntemplate <GTEST_4_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 96, "score": 184854.50514619844 }, { "content": "struct tuple_size<GTEST_1_TUPLE_(T) > {\n\n static const int value = 1;\n\n};\n\n\n\ntemplate <GTEST_2_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 97, "score": 184854.50514619844 }, { "content": "struct tuple_size<GTEST_2_TUPLE_(T) > {\n\n static const int value = 2;\n\n};\n\n\n\ntemplate <GTEST_3_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 98, "score": 184854.50514619844 }, { "content": "struct tuple_size<GTEST_0_TUPLE_(T) > {\n\n static const int value = 0;\n\n};\n\n\n\ntemplate <GTEST_1_TYPENAMES_(T)>\n", "file_path": "third-party/paxos/dependencies/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-tuple.h", "rank": 99, "score": 184854.50514619844 } ]
C++
stereo_egomotion/base/evaluator.cc
bartn8/stereo-vision
1180045fe560478e5c441e75202cc899fe90ec3d
#include "evaluator.h" #include <iostream> #include <fstream> #include <stdio.h> #include <math.h> #include <tuple> #include <limits> #include <algorithm> #include <iomanip> #include <dirent.h> #include <sys/stat.h> namespace egomotion { typedef std::tuple<std::string,double,double> ResultTuple; using namespace std; using namespace libviso; namespace { float lengths[] = {100,200,300,400,500,600,700,800}; int32_t num_lengths = 8; struct errors { int32_t first_frame; float r_err; float t_err; float len; float speed; errors (int32_t first_frame,float r_err,float t_err,float len,float speed) : first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {} }; vector<Matrix> loadPoses(string file_name) { vector<Matrix> poses; FILE *fp = fopen(file_name.c_str(),"r"); if (!fp) return poses; while (!feof(fp)) { Matrix P = Matrix::eye(4); if (fscanf(fp, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3], &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3], &P.val[2][0], &P.val[2][1], &P.val[2][2], &P.val[2][3] )==12) { poses.push_back(P); } } fclose(fp); return poses; } vector<float> trajectoryDistances(const std::vector<Matrix>& poses) { vector<float> dist; dist.push_back(0); for (int32_t i=1; i<poses.size(); i++) { Matrix P1 = poses[i-1]; Matrix P2 = poses[i]; float dx = P1.val[0][3]-P2.val[0][3]; float dy = P1.val[1][3]-P2.val[1][3]; float dz = P1.val[2][3]-P2.val[2][3]; dist.push_back(dist[i-1]+sqrt(dx*dx+dy*dy+dz*dz)); } return dist; } int32_t lastFrameFromSegmentLength(vector<float> &dist,int32_t first_frame,float len) { for (int32_t i=first_frame; i<dist.size(); i++) if (dist[i]>dist[first_frame]+len) return i; return -1; } inline float rotationError(const Matrix& pose_error) { float a = pose_error.val[0][0]; float b = pose_error.val[1][1]; float c = pose_error.val[2][2]; float d = 0.5*(a+b+c-1.0); return acos(max(min(d,1.0f),-1.0f)); } inline float translationError(const Matrix& pose_error) { float dx = pose_error.val[0][3]; float dy = pose_error.val[1][3]; float dz = pose_error.val[2][3]; return sqrt(dx*dx+dy*dy+dz*dz); } std::vector<errors> CalcSequenceErrors(const std::vector<Matrix>& poses_gt, const std::vector<Matrix>& poses_result) { std::vector<errors> err; int32_t step_size = 10; vector<float> dist = trajectoryDistances(poses_gt); for (int32_t first_frame=0; first_frame<poses_gt.size(); first_frame+=step_size) { for (int32_t i=0; i<num_lengths; i++) { float len = lengths[i]; int32_t last_frame = lastFrameFromSegmentLength(dist,first_frame,len); if (last_frame==-1) continue; Matrix pose_delta_gt = Matrix::inv(poses_gt[first_frame])*poses_gt[last_frame]; Matrix pose_delta_result = Matrix::inv(poses_result[first_frame])*poses_result[last_frame]; Matrix pose_error = Matrix::inv(pose_delta_result)*pose_delta_gt; float r_err = rotationError(pose_error); float t_err = translationError(pose_error); float num_frames = (float)(last_frame-first_frame+1); float speed = len/(0.1*num_frames); err.push_back(errors(first_frame,r_err/len,t_err/len,len,speed)); } } return err; } void GetStats(std::vector<errors> errors, double& t_error, double& r_error) { double t_err = 0; double r_err = 0; for (const auto& e : errors) { t_err += e.t_err; r_err += e.r_err; } double num = errors.size(); t_error = 100.0 * t_err / num; r_error = 100.0 * r_err / num; } } void Evaluator::Eval(const std::string& gt_fname, const std::vector<libviso::Matrix>& egomotion_poses, double& trans_error, double& rot_error) { std::vector<Matrix> poses_gt = loadPoses(gt_fname); if(poses_gt.size() == 0 || egomotion_poses.size() != poses_gt.size()) throw 1; std::vector<errors> errors = CalcSequenceErrors(poses_gt, egomotion_poses); if(errors.size() > 0) GetStats(errors, trans_error, rot_error); else throw 1; } libviso::Matrix Evaluator::EigenMatrixToLibvisoMatrix(const Eigen::Matrix4d& mat1) { libviso::Matrix mat2 = libviso::Matrix(mat1.rows(), mat1.cols()); for (int i = 0; i < mat1.rows(); i++) for (int j = 0; j < mat1.cols(); j++) mat2.val[i][j] = mat1(i,j); return mat2; } void Evaluator::EigenVectorToLibvisoVector(const std::vector<Eigen::Matrix4d>& vec1, std::vector<libviso::Matrix>& vec2) { vec2.clear(); for (const auto& rt : vec1) vec2.push_back(EigenMatrixToLibvisoMatrix(rt)); } void Evaluator::Eval(const std::string& gt_fname, const std::vector<Eigen::Matrix4d>& egomotion_poses, double& trans_error, double& rot_error) { std::vector<libviso::Matrix> libviso_poses; EigenVectorToLibvisoVector(egomotion_poses, libviso_poses); Eval(gt_fname, libviso_poses, trans_error, rot_error); } }
#include "evaluator.h" #include <iostream> #include <fstream> #include <stdio.h> #include <math.h> #include <tuple> #include <limits> #include <algorithm> #include <iomanip> #include <dirent.h> #include <sys/stat.h> namespace egomotion { typedef std::tuple<std::string,double,double> ResultTuple; using namespace std; using namespace libviso; namespace { float lengths[] = {100,200,300,400,500,600,700,800}; int32_t num_lengths = 8; struct errors { int32_t first_frame; float r_err; float t_err; float len; float speed; errors (int32_t first_frame,float r_err,float t_err,float len,float speed) : first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {} }; vector<Matrix> loadPoses(string file_name) { vector<Matrix> poses; FILE *fp = fopen(file_name.c_str(),"r"); if (!fp) return poses; while (!feof(fp)) { Matrix P = Matrix::eye(4); if (fscanf(fp, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3], &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3], &P.val[2][0], &P.val[2][1], &P.val[2][2], &P.val[2][3] )==12) { poses.push_back(P); } } fclose(fp); return poses; } vector<float> trajectoryDistances(const std::vector<Matrix>& poses) { vector<float> dist; dist.push_back(0); for (int32_t i=1; i<poses.size(); i++) { Matrix P1 = poses[i-1]; Matrix P2 = poses[i]; float dx = P1.val[0][3]-P2.val[0][3]; float dy = P1.val[1][3]-P2.val[1][3]; float dz = P1.val[2][3]-P2.val[2][3]; dist.push_back(dist[i-1]+sqrt(dx*dx+dy*dy+dz*dz)); } return dist; } int32_t lastFrameFromSegmentLength(vector<float> &dist,int32_t first_frame,float len) { for (int32_t i=first_frame; i<dist.size(); i++) if (dist[i]>dist[first_frame]+len) return i; return -1; } inline float rotationError(const Matrix& pose_error) { float a = pose_error.val[0][0]; float b = pose_error.val[1][1]; float c = pose_error.val[2][2]; float d = 0.5*(a+b+c-1.0); return acos(max(min(d,1.0f),-1.0f)); } inline float translationError(const Matrix& pose_error) { float dx = pose_error.val[0][3]; float dy = pose_error.val[1][3]; float dz = pose_error.val[2][3]; return sqrt(dx*dx+dy*dy+dz*dz); } std::vector<errors> CalcSequenceErrors(const std::vector<Matrix>& poses_gt, const std::vector<Matrix>& poses_result) { std::vector<errors> err; int32_t step_size = 10; vector<float> dist = trajectoryDistances(poses_gt); for (int32_t first_frame=0; first_frame<poses_gt.size(); first_frame+=step_size) { for (int32_t i=0; i<num_lengths; i++) { float len = lengths[i]; int32_t last_frame = lastFrameFromSegmentLength(dist,first_frame,len); if (last_frame==-1) continue; Matrix pose_delta_gt = Matrix::inv(poses_gt[first_frame])*poses_gt[last_frame]; Matrix pose_delta_result = Matrix::inv(poses_result[first_frame])*poses_result[last_frame]; Matrix pose_error = Matrix::inv(pose_delta_result)*pose_delta_gt; float r_err = rotationError(pose_error); float t_err = translationError(pose_error); float num_frames = (float)(last_frame-first_frame+1); float speed = len/(0.1*num_frames); err.push_back(errors(first_frame,r_err/len,t_err/len,len,speed)); } } return err; } void GetStats(std::vector<errors> errors, double& t_error, double& r_error) { double t_err = 0; double r_err = 0; for (const auto& e : errors) { t_err += e.t_err; r_err += e.r_err; } double num = errors.size(); t_error = 100.0 * t_err / num; r_error = 100.0 * r_err / num; } } void Evaluator::Eval(const std::string& gt_fname, const std::vector<libviso::Matrix>& egomotion_poses, double& trans_error, double& rot_error) { std::vector<Matrix> poses_gt = loadPoses(gt_fname); if(poses_gt.size() == 0 || egomotion_poses.size() != poses_gt.size()) throw 1; std::vector<errors> errors = CalcSequenceErrors(poses_gt, egomotion_poses); if(errors.size() > 0) GetStats(errors, trans_error, rot_error); else throw 1; } libviso::Matrix Evaluator::EigenMatrixToLibvisoMatrix(const Eigen::Matrix4d& mat1) { libviso::Matrix mat2 = libviso::Matrix(mat1.rows(), mat1.cols()); for (int i = 0; i < mat1.rows(); i++) for (int j = 0; j < mat1.cols(); j++) mat2.val[i][j] = mat1(i,j); return mat2; }
void Evaluator::Eval(const std::string& gt_fname, const std::vector<Eigen::Matrix4d>& egomotion_poses, double& trans_error, double& rot_error) { std::vector<libviso::Matrix> libviso_poses; EigenVectorToLibvisoVector(egomotion_poses, libviso_poses); Eval(gt_fname, libviso_poses, trans_error, rot_error); } }
void Evaluator::EigenVectorToLibvisoVector(const std::vector<Eigen::Matrix4d>& vec1, std::vector<libviso::Matrix>& vec2) { vec2.clear(); for (const auto& rt : vec1) vec2.push_back(EigenMatrixToLibvisoMatrix(rt)); }
function_block-full_function
[ { "content": "struct greaterThanPtr : public std::binary_function<const float*, const float*, bool>\n\n{\n\n bool operator () (const float* a, const float* b) const\n\n { return *a > *b; }\n\n};\n\n\n\n}\n\n\n\nnamespace track {\n\n\n\nFeatureDetectorHarrisCV::FeatureDetectorHarrisCV(int block_size, int ksize, double k, double eig_thr, \n\n int margin_size, int max_corners) {\n\n block_size_ = block_size;\n\n ksize_ = ksize;\n\n k_ = k;\n\n eig_thr_ = eig_thr;\n\n margin_size_ = margin_size;\n\n max_corners_ = max_corners;\n\n}\n\n\n", "file_path": "tracker/detector/feature_detector_harris_cv.cc", "rank": 0, "score": 258642.9719367451 }, { "content": "struct errors {\n\n int32_t first_frame;\n\n float r_err;\n\n float t_err;\n\n float len;\n\n float speed;\n\n errors (int32_t first_frame,float r_err,float t_err,float len,float speed) :\n\n first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {}\n\n};\n\n\n\nvector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n", "file_path": "stereo_egomotion/evaluation/evaluate_odometry.cpp", "rank": 2, "score": 183967.6538316746 }, { "content": "struct errors {\n\n int32_t frame;\n\n float r_err;\n\n float t_err;\n\n errors(int32_t frame, float r_err, float t_err) :\n\n frame(frame), r_err(r_err), t_err(t_err) {}\n\n};\n\n\n\nstd::vector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n\n &P.val[2][0], &P.val[2][1], &P.val[2][2], &P.val[2][3] )==12) {\n\n poses.push_back(P);\n", "file_path": "stereo_egomotion/evaluation/evaluate_odometry_independent.cpp", "rank": 3, "score": 179757.77885924146 }, { "content": "struct errors {\n\n int32_t first_frame;\n\n float r_err;\n\n float t_err;\n\n float len;\n\n errors (int32_t first_frame,float r_err,float t_err,float len) :\n\n first_frame(first_frame),r_err(r_err),t_err(t_err),len(len) {}\n\n};\n\n\n\nvector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n\n &P.val[2][0], &P.val[2][1], &P.val[2][2], &P.val[2][3] )==12) {\n", "file_path": "stereo_egomotion/evaluation/evaluate_odometry_dense.cpp", "rank": 4, "score": 179757.77885924146 }, { "content": "struct errors {\n\n int32_t first_frame;\n\n float r_err;\n\n float t_err;\n\n float len;\n\n float speed;\n\n errors (int32_t first_frame,float r_err,float t_err,float len,float speed) :\n\n first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {}\n\n};\n\n\n\nvector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n", "file_path": "stereo_egomotion/evaluation/evaluate_odometry_batch.cpp", "rank": 5, "score": 179757.77885924146 }, { "content": "struct errors {\n\n int32_t first_frame;\n\n float r_err;\n\n float t_err;\n\n float len;\n\n float speed;\n\n errors (int32_t first_frame,float r_err,float t_err,float len,float speed) :\n\n first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {}\n\n};\n\n\n\nvector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n", "file_path": "stereo_egomotion/evaluation/evaluate_odometry_tsukuba.cpp", "rank": 6, "score": 179757.77885924146 }, { "content": "struct errors {\n\n int32_t first_frame;\n\n float r_err;\n\n float t_err;\n\n float len;\n\n float speed;\n\n errors (int32_t first_frame,float r_err,float t_err,float len,float speed) :\n\n first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {}\n\n};\n\n\n\nvector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n", "file_path": "stereo_egomotion/main/legacy/vo_eval/evaluate_odometry.cc", "rank": 7, "score": 172008.74017745757 }, { "content": "struct errors {\n\n int32_t first_frame;\n\n float r_err;\n\n float t_err;\n\n float len;\n\n float speed;\n\n errors (int32_t first_frame,float r_err,float t_err,float len,float speed) :\n\n first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {}\n\n};\n\n\n\nvector<Matrix> loadPoses(string file_name) {\n\n vector<Matrix> poses;\n\n FILE *fp = fopen(file_name.c_str(),\"r\");\n\n if (!fp)\n\n return poses;\n\n while (!feof(fp)) {\n\n Matrix P = Matrix::eye(4);\n\n if (fscanf(fp, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n\n &P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],\n\n &P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],\n", "file_path": "stereo_egomotion/main/legacy/vo_eval/evaluate_odometry_batch.cc", "rank": 8, "score": 168434.8788766425 }, { "content": "class Matrix {\n\n\n\npublic:\n\n\n\n // constructor / deconstructor\n\n Matrix (); // init empty 0x0 matrix\n\n Matrix (const int32_t m,const int32_t n); // init empty mxn matrix\n\n Matrix (const int32_t m,const int32_t n,const FLOAT* val_); // init mxn matrix with values from array 'val'\n\n Matrix (const Matrix &M); // creates deepcopy of M\n\n ~Matrix ();\n\n\n\n // assignment operator, copies contents of M\n\n Matrix& operator= (const Matrix &M);\n\n\n\n // copies submatrix of M into array 'val', default values copy whole row/column/matrix\n\n void getData(FLOAT* val_,int32_t i1=0,int32_t j1=0,int32_t i2=-1,int32_t j2=-1);\n\n\n\n // set or get submatrices of current matrix\n\n Matrix getMat(int32_t i1,int32_t j1,int32_t i2=-1,int32_t j2=-1);\n\n void setMat(const Matrix &M,const int32_t i,const int32_t j);\n", "file_path": "stereo_egomotion/base/matrix.h", "rank": 9, "score": 151427.47680762847 }, { "content": "class Matrix {\n\n\n\npublic:\n\n\n\n // constructor / deconstructor\n\n Matrix (); // init empty 0x0 matrix\n\n Matrix (const int32_t m,const int32_t n); // init empty mxn matrix\n\n Matrix (const int32_t m,const int32_t n,const FLOAT* val_); // init mxn matrix with values from array 'val'\n\n Matrix (const Matrix &M); // creates deepcopy of M\n\n ~Matrix ();\n\n\n\n // assignment operator, copies contents of M\n\n Matrix& operator= (const Matrix &M);\n\n\n\n // copies submatrix of M into array 'val', default values copy whole row/column/matrix\n\n void getData(FLOAT* val_,int32_t i1=0,int32_t j1=0,int32_t i2=-1,int32_t j2=-1);\n\n\n\n // set or get submatrices of current matrix\n\n Matrix getMat(int32_t i1,int32_t j1,int32_t i2=-1,int32_t j2=-1);\n\n void setMat(const Matrix &M,const int32_t i,const int32_t j);\n", "file_path": "stereo_egomotion/evaluation/matrix.h", "rank": 10, "score": 151427.47680762847 }, { "content": "class Matrix {\n\n\n\npublic:\n\n\n\n // constructor / deconstructor\n\n Matrix (); // init empty 0x0 matrix\n\n Matrix (const int32_t m,const int32_t n); // init empty mxn matrix\n\n Matrix (const int32_t m,const int32_t n,const FLOAT* val_); // init mxn matrix with values from array 'val'\n\n Matrix (const Matrix &M); // creates deepcopy of M\n\n ~Matrix ();\n\n\n\n // assignment operator, copies contents of M\n\n Matrix& operator= (const Matrix &M);\n\n\n\n // copies submatrix of M into array 'val', default values copy whole row/column/matrix\n\n void getData(FLOAT* val_,int32_t i1=0,int32_t j1=0,int32_t i2=-1,int32_t j2=-1);\n\n\n\n // set or get submatrices of current matrix\n\n Matrix getMat(int32_t i1,int32_t j1,int32_t i2=-1,int32_t j2=-1);\n\n void setMat(const Matrix &M,const int32_t i,const int32_t j);\n", "file_path": "stereo_egomotion/extern/libviso2/src/matrix.h", "rank": 11, "score": 146073.25835194805 }, { "content": "class Matrix {\n\n\n\npublic:\n\n\n\n // constructor / deconstructor\n\n Matrix (); // init empty 0x0 matrix\n\n Matrix (const int32_t m,const int32_t n); // init empty mxn matrix\n\n Matrix (const int32_t m,const int32_t n,const FLOAT* val_); // init mxn matrix with values from array 'val'\n\n Matrix (const Matrix &M); // creates deepcopy of M\n\n ~Matrix ();\n\n\n\n // assignment operator, copies contents of M\n\n Matrix& operator= (const Matrix &M);\n\n\n\n // copies submatrix of M into array 'val', default values copy whole row/column/matrix\n\n void getData(FLOAT* val_,int32_t i1=0,int32_t j1=0,int32_t i2=-1,int32_t j2=-1);\n\n\n\n // set or get submatrices of current matrix\n\n Matrix getMat(int32_t i1,int32_t j1,int32_t i2=-1,int32_t j2=-1);\n\n void setMat(const Matrix &M,const int32_t i,const int32_t j);\n", "file_path": "deformation_field/stereo_egomotion/base/matrix.h", "rank": 12, "score": 146073.25835194805 }, { "content": "class Matrix {\n\n\n\npublic:\n\n\n\n // constructor / deconstructor\n\n Matrix (); // init empty 0x0 matrix\n\n Matrix (const int32_t m,const int32_t n); // init empty mxn matrix\n\n Matrix (const int32_t m,const int32_t n,const FLOAT* val_); // init mxn matrix with values from array 'val'\n\n Matrix (const Matrix &M); // creates deepcopy of M\n\n ~Matrix ();\n\n\n\n // assignment operator, copies contents of M\n\n Matrix& operator= (const Matrix &M);\n\n\n\n // copies submatrix of M into array 'val', default values copy whole row/column/matrix\n\n void getData(FLOAT* val_,int32_t i1=0,int32_t j1=0,int32_t i2=-1,int32_t j2=-1);\n\n\n\n // set or get submatrices of current matrix\n\n Matrix getMat(int32_t i1,int32_t j1,int32_t i2=-1,int32_t j2=-1);\n\n void setMat(const Matrix &M,const int32_t i,const int32_t j);\n", "file_path": "stereo_egomotion/main/legacy/vo_eval/matrix.h", "rank": 13, "score": 143584.6793609005 }, { "content": "struct KeyHash : public std::unary_function<TrackKey, std::size_t>\n\n{\n\n std::size_t operator()(const TrackKey& k) const\n\n {\n\n return std::get<0>(k) ^ std::get<1>(k);\n\n }\n\n};\n\n\n", "file_path": "optimization/bundle_adjustment/bundle_adjuster.h", "rank": 14, "score": 140127.2996143071 }, { "content": "enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,\n\n struct otri *searchtri,\n\n vertex searchpoint)\n\n{\n\n struct otri checktri;\n\n vertex startvertex;\n\n vertex leftvertex, rightvertex;\n\n float leftccw, rightccw;\n\n int leftflag, rightflag;\n\n triangle ptr; /* Temporary variable used by onext() and oprev(). */\n\n\n\n org(*searchtri, startvertex);\n\n dest(*searchtri, rightvertex);\n\n apex(*searchtri, leftvertex);\n\n /* Is `searchpoint' to the left? */\n\n leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);\n\n leftflag = leftccw > 0.0;\n\n /* Is `searchpoint' to the right? */\n\n rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);\n\n rightflag = rightccw > 0.0;\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 15, "score": 138724.00721156102 }, { "content": "enum locateresult locate(struct mesh *m, struct behavior *b,\n\n vertex searchpoint, struct otri *searchtri)\n\n{\n\n int **sampleblock;\n\n char *firsttri;\n\n struct otri sampletri;\n\n vertex torg, tdest;\n\n unsigned long long alignptr;\n\n float searchdist, dist;\n\n float ahead;\n\n long samplesperblock, totalsamplesleft, samplesleft;\n\n long population, totalpopulation;\n\n triangle ptr; /* Temporary variable used by sym(). */\n\n\n\n if (b->verbose > 2) {\n\n printf(\" Randomly sampling for a triangle near point (%.12g, %.12g).\\n\",\n\n searchpoint[0], searchpoint[1]);\n\n }\n\n /* Record the distance from the suggested starting triangle to the */\n\n /* point we seek. */\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 16, "score": 138724.00721156102 }, { "content": "enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,\n\n vertex newvertex, struct otri *searchtri,\n\n struct osub *splitseg,\n\n int segmentflaws, int triflaws)\n\n{\n\n struct otri horiz;\n\n struct otri top;\n\n struct otri botleft, botright;\n\n struct otri topleft, topright;\n\n struct otri newbotleft, newbotright;\n\n struct otri newtopright;\n\n struct otri botlcasing, botrcasing;\n\n struct otri toplcasing, toprcasing;\n\n struct otri testtri;\n\n struct osub botlsubseg, botrsubseg;\n\n struct osub toplsubseg, toprsubseg;\n\n struct osub brokensubseg;\n\n struct osub checksubseg;\n\n struct osub rightsubseg;\n\n struct osub newsubseg;\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 17, "score": 138724.00721156102 }, { "content": "enum locateresult preciselocate(struct mesh *m, struct behavior *b,\n\n vertex searchpoint, struct otri *searchtri,\n\n int stopatsubsegment)\n\n{\n\n struct otri backtracktri;\n\n struct osub checkedge;\n\n vertex forg, fdest, fapex;\n\n float orgorient, destorient;\n\n int moveleft;\n\n triangle ptr; /* Temporary variable used by sym(). */\n\n subseg sptr; /* Temporary variable used by tspivot(). */\n\n\n\n if (b->verbose > 2) {\n\n printf(\" Searching for point (%.12g, %.12g).\\n\",\n\n searchpoint[0], searchpoint[1]);\n\n }\n\n /* Where are we? */\n\n org(*searchtri, forg);\n\n dest(*searchtri, fdest);\n\n apex(*searchtri, fapex);\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 18, "score": 138724.00721156102 }, { "content": "struct Errors {\n\n double out_noc;\n\n double out_all;\n\n double avg_noc;\n\n double avg_all;\n\n double density;\n\n};\n\n\n\nvector<float> disparityErrorsOutlier (DisparityImage &D_gt,DisparityImage &D_orig,DisparityImage &D_ipol) {\n\n\n\n // check file size\n\n if (D_gt.width()!=D_orig.width() || D_gt.height()!=D_orig.height()) {\n\n cout << \"ERROR: Wrong file size!\" << endl;\n\n throw 1;\n\n }\n\n\n\n // extract width and height\n\n int32_t width = D_gt.width();\n\n int32_t height = D_gt.height();\n\n\n", "file_path": "reconstruction/evaluation/evaluate_stereo.cc", "rank": 19, "score": 138562.54342216323 }, { "content": "struct Errors {\n\n double out_noc;\n\n double out_all;\n\n double avg_noc;\n\n double avg_all;\n\n double density;\n\n std::string name;\n\n};\n\n\n\nvector<float> disparityErrorsOutlier (DisparityImage &D_gt,DisparityImage &D_orig,DisparityImage &D_ipol) {\n\n\n\n // check file size\n\n if (D_gt.width()!=D_orig.width() || D_gt.height()!=D_orig.height()) {\n\n cout << \"ERROR: Wrong file size!\" << endl;\n\n throw 1;\n\n }\n\n\n\n // extract width and height\n\n int32_t width = D_gt.width();\n\n int32_t height = D_gt.height();\n", "file_path": "reconstruction/evaluation/evaluate_stereo_batch.cc", "rank": 20, "score": 135541.2076362285 }, { "content": "struct ReprojectionErrorResidual {\n\n ReprojectionErrorResidual(int frame_id, int track_id,\n\n const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const std::array<double,3>& wmotion_trans,\n\n const std::array<double,4>& wmotion_rot) :\n\n wmotion_rot_(wmotion_rot), wmotion_trans_(wmotion_trans) {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n frame_id_ = frame_id;\n\n track_id_ = track_id;\n\n }\n\n\n\n template <typename T>\n\n bool operator()(\n\n const T* const f1,\n\n const T* const pp1,\n\n const T* const k1,\n", "file_path": "optimization/calibration_from_motion/cfm_solver.h", "rank": 21, "score": 132689.32235389075 }, { "content": "namespace libviso {\n\n\n\nstruct triangulateio {\n\n float *pointlist; /* In / out */\n\n float *pointattributelist; /* In / out */\n\n int *pointmarkerlist; /* In / out */\n\n int numberofpoints; /* In / out */\n\n int numberofpointattributes; /* In / out */\n\n\n\n int *trianglelist; /* In / out */\n\n float *triangleattributelist; /* In / out */\n\n float *trianglearealist; /* In only */\n\n int *neighborlist; /* Out only */\n\n int numberoftriangles; /* In / out */\n\n int numberofcorners; /* In / out */\n\n int numberoftriangleattributes; /* In / out */\n\n\n\n int *segmentlist; /* In / out */\n\n int *segmentmarkerlist; /* In / out */\n\n int numberofsegments; /* In / out */\n\n\n\n float *holelist; /* In / pointer to array copied out */\n\n int numberofholes; /* In / copied out */\n\n\n\n float *regionlist; /* In / pointer to array copied out */\n\n int numberofregions; /* In / copied out */\n\n\n\n int *edgelist; /* Out only */\n\n int *edgemarkerlist; /* Not used with Voronoi diagram; out only */\n\n float *normlist; /* Used only with Voronoi diagram; out only */\n\n int numberofedges; /* Out only */\n\n};\n\n\n\nvoid triangulate(char *,triangulateio *,triangulateio *,triangulateio *);\n\nvoid trifree(int *memptr);\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.h", "rank": 22, "score": 130543.51337785933 }, { "content": "namespace libviso {\n\n\n\n// fast filters: implements 3x3 and 5x5 sobel filters and \n\n// 5x5 blob and corner filters based on SSE2/3 instructions\n\nnamespace filter {\n\n \n\n // private namespace, public user functions at the bottom of this file\n\n namespace detail {\n\n void integral_image( const uint8_t* in, int32_t* out, int w, int h );\n\n void unpack_8bit_to_16bit( const __m128i a, __m128i& b0, __m128i& b1 );\n\n void pack_16bit_to_8bit_saturate( const __m128i a0, const __m128i a1, __m128i& b );\n\n \n\n // convolve image with a (1,4,6,4,1) row vector. Result is accumulated into output.\n\n // output is scaled by 1/128, then clamped to [-128,128], and finally shifted to [0,255].\n\n void convolve_14641_row_5x5_16bit( const int16_t* in, uint8_t* out, int w, int h );\n\n \n\n // convolve image with a (1,2,0,-2,-1) row vector. Result is accumulated into output.\n\n // This one works on 16bit input and 8bit output.\n\n // output is scaled by 1/128, then clamped to [-128,128], and finally shifted to [0,255].\n\n void convolve_12021_row_5x5_16bit( const int16_t* in, uint8_t* out, int w, int h );\n\n\n\n // convolve image with a (1,2,1) row vector. Result is accumulated into output.\n\n // This one works on 16bit input and 8bit output.\n\n // output is scaled by 1/4, then clamped to [-128,128], and finally shifted to [0,255].\n\n void convolve_121_row_3x3_16bit( const int16_t* in, uint8_t* out, int w, int h );\n\n \n\n // convolve image with a (1,0,-1) row vector. Result is accumulated into output.\n\n // This one works on 16bit input and 8bit output.\n\n // output is scaled by 1/4, then clamped to [-128,128], and finally shifted to [0,255].\n\n void convolve_101_row_3x3_16bit( const int16_t* in, uint8_t* out, int w, int h );\n\n \n\n void convolve_cols_5x5( const unsigned char* in, int16_t* out_v, int16_t* out_h, int w, int h );\n\n \n\n void convolve_col_p1p1p0m1m1_5x5( const unsigned char* in, int16_t* out, int w, int h );\n\n \n\n void convolve_row_p1p1p0m1m1_5x5( const int16_t* in, int16_t* out, int w, int h );\n\n \n\n void convolve_cols_3x3( const unsigned char* in, int16_t* out_v, int16_t* out_h, int w, int h );\n\n }\n\n \n\n void sobel3x3( const uint8_t* in, uint8_t* out_v, uint8_t* out_h, int w, int h );\n\n \n\n void sobel5x5( const uint8_t* in, uint8_t* out_v, uint8_t* out_h, int w, int h );\n\n \n\n // -1 -1 0 1 1\n\n // -1 -1 0 1 1\n\n // 0 0 0 0 0\n\n // 1 1 0 -1 -1\n\n // 1 1 0 -1 -1\n\n void checkerboard5x5( const uint8_t* in, int16_t* out, int w, int h );\n\n \n\n // -1 -1 -1 -1 -1\n\n // -1 1 1 1 -1\n\n // -1 1 8 1 -1\n\n // -1 1 1 1 -1\n\n // -1 -1 -1 -1 -1\n\n void blob5x5( const uint8_t* in, int16_t* out, int w, int h );\n\n};\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/filter.h", "rank": 23, "score": 130543.51337785933 }, { "content": "struct memorypool {\n\n int **firstblock, **nowblock;\n\n int *nextitem;\n\n int *deaditemstack;\n\n int **pathblock;\n\n int *pathitem;\n\n int alignbytes;\n\n int itembytes;\n\n int itemsperblock;\n\n int itemsfirstblock;\n\n long items, maxitems;\n\n int unallocateditems;\n\n int pathitemsleft;\n\n};\n\n\n\n\n\n/* Global constants. */\n\n\n\nfloat splitter; /* Used to split float factors for exact multiplication. */\n\nfloat epsilon; /* Floating-point machine epsilon. */\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 24, "score": 130323.92647099718 }, { "content": "struct mesh {\n\n\n\n/* Variables used to allocate memory for triangles, subsegments, vertices, */\n\n/* viri (triangles being eaten), encroached segments, bad (skinny or too */\n\n/* large) triangles, and splay tree nodes. */\n\n\n\n struct memorypool triangles;\n\n struct memorypool subsegs;\n\n struct memorypool vertices;\n\n struct memorypool viri;\n\n struct memorypool badsubsegs;\n\n struct memorypool badtriangles;\n\n struct memorypool flipstackers;\n\n struct memorypool splaynodes;\n\n\n\n/* Variables that maintain the bad triangle queues. The queues are */\n\n/* ordered from 4095 (highest priority) to 0 (lowest priority). */\n\n\n\n struct badtriang *queuefront[4096];\n\n struct badtriang *queuetail[4096];\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 25, "score": 130323.92647099718 }, { "content": "struct splaynode {\n\n struct otri keyedge; /* Lprev of an edge on the front. */\n\n vertex keydest; /* Used to verify that splay node is still live. */\n\n struct splaynode *lchild, *rchild; /* Children in splay tree. */\n\n};\n\n\n\n/* A type used to allocate memory. firstblock is the first block of items. */\n\n/* nowblock is the block from which items are currently being allocated. */\n\n/* nextitem points to the next slab of free memory for an item. */\n\n/* deaditemstack is the head of a linked list (stack) of deallocated items */\n\n/* that can be recycled. unallocateditems is the number of items that */\n\n/* remain to be allocated from nowblock. */\n\n/* */\n\n/* Traversal is the process of walking through the entire list of items, and */\n\n/* is separate from allocation. Note that a traversal will visit items on */\n\n/* the \"deaditemstack\" stack as well as live items. pathblock points to */\n\n/* the block currently being traversed. pathitem points to the next item */\n\n/* to be traversed. pathitemsleft is the number of items that remain to */\n\n/* be traversed in pathblock. */\n\n/* */\n\n/* alignbytes determines how new records should be aligned in memory. */\n\n/* itembytes is the length of a record in bytes (after rounding up). */\n\n/* itemsperblock is the number of items allocated at once in a single */\n\n/* block. itemsfirstblock is the number of items in the first block, */\n\n/* which can vary from the others. items is the number of currently */\n\n/* allocated items. maxitems is the maximum number of items that have */\n\n/* been allocated at once; it is the current number of items plus the */\n\n/* number of records kept on deaditemstack. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 26, "score": 130323.92647099718 }, { "content": "struct event {\n\n float xkey, ykey; /* Coordinates of the event. */\n\n int *eventptr; /* Can be a vertex or the location of a circle event. */\n\n int heapposition; /* Marks this event's position in the heap. */\n\n};\n\n\n\n/* A node in the splay tree. Each node holds an oriented ghost triangle */\n\n/* that represents a boundary edge of the growing triangulation. When a */\n\n/* circle event covers two boundary edges with a triangle, so that they */\n\n/* are no longer boundary edges, those edges are not immediately deleted */\n\n/* from the tree; rather, they are lazily deleted when they are next */\n\n/* encountered. (Since only a random sample of boundary edges are kept */\n\n/* in the tree, lazy deletion is faster.) `keydest' is used to verify */\n\n/* that a triangle is still the same as when it entered the splay tree; if */\n\n/* it has been rotated (due to a circle event), it no longer represents a */\n\n/* boundary edge and should be deleted. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 27, "score": 130323.92647099718 }, { "content": "struct flipstacker {\n\n triangle flippedtri; /* A recently flipped triangle. */\n\n struct flipstacker *prevflip; /* Previous flip in the stack. */\n\n};\n\n\n\n/* A node in a heap used to store events for the sweepline Delaunay */\n\n/* algorithm. Nodes do not point directly to their parents or children in */\n\n/* the heap. Instead, each node knows its position in the heap, and can */\n\n/* look up its parent and children in a separate array. The `eventptr' */\n\n/* points either to a `vertex' or to a triangle (in encoded format, so */\n\n/* that an orientation is included). In the latter case, the origin of */\n\n/* the oriented triangle is the apex of a \"circle event\" of the sweepline */\n\n/* algorithm. To distinguish site events from circle events, all circle */\n\n/* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 28, "score": 130323.92647099718 }, { "content": "struct osub {\n\n subseg *ss;\n\n int ssorient; /* Ranges from 0 to 1. */\n\n};\n\n\n\n/* The vertex data structure. Each vertex is actually an array of floats. */\n\n/* The number of floats is unknown until runtime. An integer boundary */\n\n/* marker, and sometimes a pointer to a triangle, is appended after the */\n\n/* floats. */\n\n\n\ntypedef float *vertex;\n\n\n\n/* A queue used to store encroached subsegments. Each subsegment's vertices */\n\n/* are stored so that we can check whether a subsegment is still the same. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 29, "score": 130323.92647099718 }, { "content": "struct otri {\n\n triangle *tri;\n\n int orient; /* Ranges from 0 to 2. */\n\n};\n\n\n\n/* The subsegment data structure. Each subsegment contains two pointers to */\n\n/* adjoining subsegments, plus four pointers to vertices, plus two */\n\n/* pointers to adjoining triangles, plus one boundary marker, plus one */\n\n/* segment number. */\n\n\n\ntypedef float **subseg; /* Really: typedef subseg *subseg */\n\n\n\n/* An oriented subsegment: includes a pointer to a subsegment and an */\n\n/* orientation. The orientation denotes a side of the edge. Hence, there */\n\n/* are two possible orientations. By convention, the edge is always */\n\n/* directed so that the \"side\" denoted is the right side of the edge. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 30, "score": 130323.92647099718 }, { "content": "struct behavior {\n\n\n\n/* Switches for the triangulator. */\n\n/* poly: -p switch. refine: -r switch. */\n\n/* quality: -q switch. */\n\n/* minangle: minimum angle bound, specified after -q switch. */\n\n/* goodangle: cosine squared of minangle. */\n\n/* offconstant: constant used to place off-center Steiner points. */\n\n/* vararea: -a switch without number. */\n\n/* fixedarea: -a switch with number. */\n\n/* maxarea: maximum area bound, specified after -a switch. */\n\n/* usertest: -u switch. */\n\n/* regionattrib: -A switch. convex: -c switch. */\n\n/* weighted: 1 for -w switch, 2 for -W switch. jettison: -j switch */\n\n/* firstnumber: inverse of -z switch. All items are numbered starting */\n\n/* from `firstnumber'. */\n\n/* edgesout: -e switch. voronoi: -v switch. */\n\n/* neighbors: -n switch. geomview: -g switch. */\n\n/* nobound: -B switch. nopolywritten: -P switch. */\n\n/* nonodewritten: -N switch. noelewritten: -E switch. */\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 31, "score": 130323.92647099718 }, { "content": "struct badtriang {\n\n triangle poortri; /* A skinny or too-large triangle. */\n\n float key; /* cos^2 of smallest (apical) angle. */\n\n vertex triangorg, triangdest, triangapex; /* Its three vertices. */\n\n struct badtriang *nexttriang; /* Pointer to next bad triangle. */\n\n};\n\n\n\n/* A stack of triangles flipped during the most recent vertex insertion. */\n\n/* The stack is used to undo the vertex insertion if the vertex encroaches */\n\n/* upon a subsegment. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 32, "score": 130323.92647099718 }, { "content": "struct badsubseg {\n\n subseg encsubseg; /* An encroached subsegment. */\n\n vertex subsegorg, subsegdest; /* Its two vertices. */\n\n};\n\n\n\n/* A queue used to store bad triangles. The key is the square of the cosine */\n\n/* of the smallest angle of the triangle. Each triangle's vertices are */\n\n/* stored so that one can check whether a triangle is still the same. */\n\n\n", "file_path": "stereo_egomotion/extern/libviso2/src/triangle.cpp", "rank": 33, "score": 130323.92647099718 }, { "content": "struct ReprojectionErrorResidual\n\n{\n\n ReprojectionErrorResidual(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver.h", "rank": 34, "score": 129993.02107052224 }, { "content": "struct ReprojErrorStereo\n\n{\n\n //ReprojErrorStereo(const Eigen::Vector4d& pt3d, const core::Point& left_pt, const core::Point& right_pt,\n\n // const Eigen::VectorXd& cam_intr) : cam_intr_(cam_intr)\n\n //{\n\n // left_pt_[0] = left_pt.x_;\n\n // left_pt_[1] = left_pt.y_;\n\n // right_pt_[0] = right_pt.x_;\n\n // right_pt_[1] = right_pt.y_;\n\n\n\n // pt3d_[0] = pt3d[0];\n\n // pt3d_[1] = pt3d[1];\n\n // pt3d_[2] = pt3d[2];\n\n // \n\n // weight = -1.0;\n\n //}\n\n ReprojErrorStereo(const Eigen::Vector4d& pt3d, const core::Point& left_pt, const core::Point& right_pt,\n\n const Eigen::VectorXd& cam_intr, bool use_weighting) : cam_intr_(cam_intr)\n\n {\n\n left_pt_[0] = left_pt.x_;\n", "file_path": "optimization/bundle_adjustment/bundle_adjustment_solver.h", "rank": 35, "score": 129993.02107052224 }, { "content": "class EgomotionLibviso : public EgomotionBase {\n\n public:\n\n // camera parameters (all are mandatory / need to be supplied)\n\n struct calibration {\n\n double f; // focal length (in pixels)\n\n double cu; // principal point (u-coordinate)\n\n double cv; // principal point (v-coordinate)\n\n calibration () {\n\n f = 1;\n\n cu = 0;\n\n cv = 0;\n\n }\n\n };\n\n // general parameters\n\n struct parameters {\n\n calibration calib; // camera calibration parameters\n\n // stereo-specific parameters (mandatory: base)\n\n double base; // baseline (meters)\n\n int32_t ransac_iters; // number of RANSAC iterations\n\n double inlier_threshold; // fundamental matrix inlier threshold\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 36, "score": 128209.40784269114 }, { "content": "struct ReprojectionErrorResidual\n\n{\n\n ReprojectionErrorResidual(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver_regularized.h", "rank": 37, "score": 127439.91007595963 }, { "content": "struct ReprojectionErrorResidualShareRight\n\n{\n\n ReprojectionErrorResidualShareRight(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver.h", "rank": 38, "score": 125018.87797603954 }, { "content": "struct ReprojectionErrorResidualShareLeft\n\n{\n\n ReprojectionErrorResidualShareLeft(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver.h", "rank": 39, "score": 125018.87797603954 }, { "content": "struct ReprojectionErrorResidual\n\n{\n\n ReprojectionErrorResidual(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "deformation_field/optimization/calibration_bias/deformation_field_solver.h", "rank": 40, "score": 125018.87797603954 }, { "content": "class EgomotionLibviso : public EgomotionBase {\n\n public:\n\n // camera parameters (all are mandatory / need to be supplied)\n\n struct calibration {\n\n double f; // focal length (in pixels)\n\n double cu; // principal point (u-coordinate)\n\n double cv; // principal point (v-coordinate)\n\n calibration () {\n\n f = 1;\n\n cu = 0;\n\n cv = 0;\n\n }\n\n };\n\n // general parameters\n\n struct parameters {\n\n calibration calib; // camera calibration parameters\n\n // stereo-specific parameters (mandatory: base)\n\n double base; // baseline (meters)\n\n int32_t ransac_iters; // number of RANSAC iterations\n\n double inlier_threshold; // fundamental matrix inlier threshold\n", "file_path": "deformation_field/stereo_egomotion/base/egomotion_libviso.h", "rank": 41, "score": 124859.80374815526 }, { "content": "// Templated pinhole camera model for used with Ceres. The camera is\n\n// parameterized using 9 parameters: 3 for rotation, 3 for translation, 1 for\n\n// focal length and 2 for radial distortion. The principal point is not modeled\n\n// (i.e. it is assumed be located at the image center).\n\nstruct SnavelyReprojectionErrorMono {\n\n SnavelyReprojectionErrorMono(double observed_x, double observed_y)\n\n : observed_x(observed_x), observed_y(observed_y) {}\n\n\n\n template <typename T>\n\n bool operator()(const T* const camera,\n\n const T* const point,\n\n T* residuals) const {\n\n // camera[0,1,2] are the angle-axis rotation.\n\n T p[3];\n\n ceres::AngleAxisRotatePoint(camera, point, p);\n\n\n\n // camera[3,4,5] are the translation.\n\n p[0] += camera[3];\n\n p[1] += camera[4];\n\n p[2] += camera[5];\n\n\n\n // Compute the center of distortion. The sign change comes from\n\n // the camera model that Noah Snavely's Bundler assumes, whereby\n\n // the camera coordinate system has a negative z axis.\n", "file_path": "optimization/bundle_adjustment/old_without_quaternions/sba_ceres.h", "rank": 42, "score": 122731.75477838317 }, { "content": "struct ReprojectionErrorResidualShareRight\n\n{\n\n ReprojectionErrorResidualShareRight(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver_regularized.h", "rank": 43, "score": 122719.93403055989 }, { "content": "struct ReprojectionErrorResidualShareLeft\n\n{\n\n ReprojectionErrorResidualShareLeft(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver_regularized.h", "rank": 44, "score": 122719.93403055989 }, { "content": "struct ReprojectionErrorStereoMotion\n\n{\n\n ReprojectionErrorStereoMotion(const double* const stereo_projs, const double* const pos_3dpoint,\n\n const double* const cam_intr, const double weight)\n\n {\n\n left_proj[0] = stereo_projs[0];\n\n left_proj[1] = stereo_projs[1];\n\n right_proj[0] = stereo_projs[2];\n\n right_proj[1] = stereo_projs[3];\n\n this->weight = weight;\n\n\n\n m_pos_3dpoint[0] = pos_3dpoint[0];\n\n m_pos_3dpoint[1] = pos_3dpoint[1];\n\n m_pos_3dpoint[2] = pos_3dpoint[2];\n\n\n\n for(int i = 0; i < 5; i++)\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n }\n\n\n\n /**\n", "file_path": "optimization/bundle_adjustment/old_without_quaternions/sba_ceres.h", "rank": 45, "score": 122719.93403055989 }, { "content": "struct ReprojectionErrorResidualShareLeftAndRight\n\n{\n\n ReprojectionErrorResidualShareLeftAndRight(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver.h", "rank": 46, "score": 122719.93403055989 }, { "content": "struct ReprojectionErrorStereoStructureAndMotion\n\n{\n\n ReprojectionErrorStereoStructureAndMotion(const double* const stereo_projs,\n\n const double* const cam_intr,\n\n const double weight)\n\n {\n\n left_proj[0] = stereo_projs[0];\n\n left_proj[1] = stereo_projs[1];\n\n right_proj[0] = stereo_projs[2];\n\n right_proj[1] = stereo_projs[3];\n\n this->weight = weight;\n\n for(int i = 0; i < 5; i++)\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n }\n\n\n\n /**\n\n * @param[in] cam_Rtf: Camera parameterized using one block of 7 parameters [R;t;f]:\n\n * - 3 for rotation(angle axis), 3 for translation, 1 for the focal length.\n\n * @param[out] out_residuals\n\n */\n", "file_path": "optimization/bundle_adjustment/old_without_quaternions/sba_ceres.h", "rank": 47, "score": 120534.07034669774 }, { "content": "struct ReprojectionErrorResidualShareLeftAndRight\n\n{\n\n ReprojectionErrorResidualShareLeftAndRight(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "optimization/calibration_bias/deformation_field_solver_regularized.h", "rank": 48, "score": 120534.07034669774 }, { "content": "struct ReprojectionErrorResidualShareRight\n\n{\n\n ReprojectionErrorResidualShareRight(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "deformation_field/optimization/calibration_bias/deformation_field_solver.h", "rank": 49, "score": 120534.07034669774 }, { "content": "struct ReprojectionErrorResidualShareLeft\n\n{\n\n ReprojectionErrorResidualShareLeft(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "deformation_field/optimization/calibration_bias/deformation_field_solver.h", "rank": 50, "score": 120534.07034669774 }, { "content": "struct ReprojectionErrorResidualShareLeftAndRight\n\n{\n\n ReprojectionErrorResidualShareLeftAndRight(const core::Point& left_prev, const core::Point& left_curr,\n\n const core::Point& right_prev, const core::Point& right_curr,\n\n const double* const cam_intr,\n\n const std::array<double,3>& cam_trans,\n\n const std::array<double,3>& cam_rot)\n\n {\n\n pt_left_prev_ = left_prev;\n\n pt_left_curr_ = left_curr;\n\n pt_right_prev_ = right_prev;\n\n pt_right_curr_ = right_curr;\n\n\n\n for (int i = 0; i < 5; i++) {\n\n cam_intr_[i] = cam_intr[i]; // 5 params - fx fy cx cy b\n\n if (i < 3) {\n\n cam_trans_[i] = cam_trans[i];\n\n cam_rot_[i] = cam_rot[i];\n\n }\n\n }\n", "file_path": "deformation_field/optimization/calibration_bias/deformation_field_solver.h", "rank": 51, "score": 118453.14391956327 }, { "content": " const double size, double& ival);\n\n\n\n void GetPointDeformation(const core::Point& pt, const cv::Mat& def_x,\n\n const cv::Mat& def_y, double& dx, double& dy);\n\n\n\n void ComputeCellCenters();\n\n int GetBinNum(const core::Point& pt);\n\n\n\n double *X, *Y, *Z = nullptr; // 3d points\n\n double *W = nullptr;\n\n\n\n std::vector<int> inliers_; // ransac inlier set\n\n std::vector<int> tracker_inliers_; // tracker inlier set\n\n std::vector<int> tracker_outliers_;\n\n\n\n cv::Mat left_dx_, left_dy_;\n\n cv::Mat right_dx_, right_dy_;\n\n cv::Mat cell_centers_x_;\n\n cv::Mat cell_centers_y_;\n\n bool use_deformation_map_ = false;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 52, "score": 117065.45167817746 }, { "content": " double w = cell_width_;\n\n double h = cell_height_;\n\n double q12 = ((w-x) / w) * q1 + (x / w) * q2;\n\n double q34 = ((w-x) / w) * q3 + (x / w) * q4;\n\n ival = ((h-y) / h) * q12 + (y / h) * q34;\n\n}\n\n\n\ninline\n\nvoid EgomotionLibviso::InterpolateLinear(const double val1, const double val2, const double x,\n\n const double size, double& ival)\n\n{\n\n ival = ((size - x) / size) * val1 + (x / size) * val2;\n\n}\n\n\n\ninline\n\nvoid EgomotionLibviso::GetPointCell(const core::Point& pt, int& row, int& col)\n\n{\n\n col = pt.x_ / cell_width_;\n\n row = pt.y_ / cell_height_;\n\n //int bin_num = row * bin_cols_ + col;\n\n}\n\n\n\n}\n\n\n\n#endif\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 53, "score": 117061.2863103102 }, { "content": "#ifndef STEREO_ODOMETRY_BASE_EGOMOTION_LIBVISO_\n\n#define STEREO_ODOMETRY_BASE_EGOMOTION_LIBVISO_\n\n\n\n#include \"egomotion_base.h\"\n\n#include \"../../tracker/stereo/stereo_tracker_base.h\"\n\n\n\nnamespace egomotion\n\n{\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 54, "score": 117055.6170828666 }, { "content": "\n\n // constructor, takes as inpute a parameter structure\n\n EgomotionLibviso(parameters params);\n\n EgomotionLibviso(parameters params, std::string deformation_params_fname, int img_rows, int img_cols);\n\n\n\n //virtual bool GetMotion(track::StereoTrackerBase& tracker, cv::Mat& Rt);\n\n bool GetMotion(track::StereoTrackerBase& tracker, Eigen::Matrix4d& Rt) override;\n\n virtual std::vector<int> GetTrackerInliers() { return tracker_inliers_; }\n\n virtual std::vector<int> GetTrackerOutliers() { return tracker_outliers_; }\n\n std::vector<double> estimateMotion(std::vector<StereoMatch>& tracks);\n\n\n\n // ADDED\n\n void setLeftPrevImage(const cv::Mat& img) { img.copyTo(img_left_prev_); }\n\n\n\n // parameters\n\n parameters params_;\n\n\n\nprivate:\n\n enum ResultState { UPDATED, FAILED, CONVERGED }; \n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 55, "score": 117054.93718859315 }, { "content": "\n\n std::vector<int> getInliers(double* p_observe,\n\n double* p_predict,\n\n double* p_residual,\n\n double* J,\n\n std::vector<StereoMatch> &tracks,\n\n std::vector<double> &tr,\n\n std::vector<int>& active);\n\n\n\n void updateTrackerInliers(const std::vector<int>& active_tracks);\n\n\n\n \n\n void GetTracksFromStereoTracker(track::StereoTrackerBase& tracker,\n\n std::vector<StereoMatch>& tracks,\n\n std::vector<int>& active_tracks);\n\n void GetPointCell(const core::Point& pt, int& row, int& col);\n\n\n\n void InterpolateBilinear(const cv::Mat& mat, const int row, const int col,\n\n const double x, const double y, double& ival);\n\n void InterpolateLinear(const double val1, const double val2, const double x,\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 56, "score": 117053.5342306335 }, { "content": " ResultState updateParameters(double* p_observe,\n\n double* p_predict,\n\n double* p_residual,\n\n double* J,\n\n std::vector<StereoMatch> &tracks,\n\n std::vector<int32_t>& active,\n\n std::vector<double>& tr,\n\n double step_size, double eps);\n\n\n\n void computeObservations(double* p_observe,\n\n std::vector<StereoMatch>& tracks,\n\n std::vector<int> &active);\n\n\n\n void computeResidualsAndJacobian(double* p_observe,\n\n double* p_predict,\n\n double* p_residual,\n\n double* J,\n\n std::vector<double>& tr,\n\n std::vector<int>& active);\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 57, "score": 117052.95115729747 }, { "content": "\n\n cv::Mat weights_mat_;\n\n int img_rows_;\n\n int img_cols_;\n\n int cell_width_, cell_height_;\n\n //int bin_rows_, bin_cols_;\n\n\n\n // ADDED\n\n cv::Mat img_left_prev_;\n\n};\n\n\n\ninline\n\nvoid EgomotionLibviso::InterpolateBilinear(const cv::Mat& mat, const int row, const int col,\n\n const double x, const double y, double& ival)\n\n{\n\n double q1 = mat.at<double>(row, col);\n\n double q2 = mat.at<double>(row, col+1);\n\n double q3 = mat.at<double>(row+1, col);\n\n double q4 = mat.at<double>(row+1, col+1);\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 58, "score": 117052.55778729914 }, { "content": " bool reweighting; // lower border weights (more robust to calibration errors)\n\n parameters () {\n\n base = 1.0;\n\n ransac_iters = 200;\n\n inlier_threshold = 1.5;\n\n reweighting = true;\n\n }\n\n };\n\n // structure for storing matches\n\n struct StereoMatch {\n\n float u1p, v1p; // u,v-coordinates in previous left image\n\n float u2p, v2p; // u,v-coordinates in previous right image\n\n float u1c, v1c; // u,v-coordinates in current left image\n\n float u2c, v2c; // u,v-coordinates in current right image\n\n StereoMatch() {}\n\n StereoMatch(float u1p, float v1p, float u2p, float v2p,\n\n float u1c, float v1c, float u2c, float v2c):\n\n u1p(u1p), v1p(v1p), u2p(u2p), v2p(v2p),\n\n u1c(u1c), v1c(v1c), u2c(u2c), v2c(v2c) {}\n\n };\n", "file_path": "stereo_egomotion/base/egomotion_libviso.h", "rank": 59, "score": 117040.92800825722 }, { "content": "class HelperLibviso\n\n{\n\n public:\n\n static void convertAllMatchesToKeys(std::vector<libviso::Matcher::p_match>& matches,\n\n std::vector<std::vector<cv::KeyPoint>>& keypoints);\n\n\n\n static void convertInlierMatchesToKeys(std::vector<libviso::Matcher::p_match>& matches, std::vector<int32_t>& inliers,\n\n std::vector<std::vector<cv::KeyPoint>>& keypoints);\n\n\n\n static cv::Mat getCameraMatrix(libviso::VisualOdometryStereo::parameters& param);\n\n\n\n static void drawOpticalFlow(cv::Mat& img, const std::vector<cv::KeyPoint>& points_prev,\n\n const std::vector<cv::KeyPoint>& points_next, const std::vector<uchar>& track_status, const cv::Scalar& color);\n\n\n\n static void LibvisoInliersToPoints(std::vector<libviso::Matcher::p_match>& matches,\n\n std::vector<int32_t>& inliers,\n\n std::vector<core::Point>& pts_lp, std::vector<core::Point>& pts_rp,\n\n std::vector<core::Point>& pts_lc, std::vector<core::Point>& pts_rc);\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "stereo_egomotion/helper_libviso.h", "rank": 60, "score": 114852.12742021371 }, { "content": " cv::FileStorage mat_file(deformation_params_fname, cv::FileStorage::READ);\n\n if (!mat_file.isOpened()) {\n\n std::cout << \"Deformation file missing!\\n\";\n\n throw 1;\n\n }\n\n mat_file[\"left_dx\"] >> left_dx_;\n\n mat_file[\"left_dy\"] >> left_dy_;\n\n mat_file[\"right_dx\"] >> right_dx_;\n\n mat_file[\"right_dy\"] >> right_dy_;\n\n use_deformation_map_ = true;\n\n\n\n cell_width_ = (double)img_cols / left_dx_.cols;\n\n cell_height_ = (double)img_rows / left_dx_.rows;\n\n\n\n ComputeCellCenters();\n\n}\n\n\n\nvoid EgomotionLibviso::ComputeCellCenters()\n\n{\n\n int rows = left_dx_.rows;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 61, "score": 114306.19495222722 }, { "content": "#include \"egomotion_libviso.h\"\n\n\n\n#include <random>\n\n#include <unordered_set>\n\n#include <omp.h>\n\n\n\n#include <opencv2/highgui/highgui.hpp>\n\n#include <opencv2/imgproc/imgproc.hpp>\n\n\n\n#include \"matrix.h\"\n\n\n\n\n\nnamespace egomotion\n\n{\n\n\n\nnamespace\n\n{\n\n\n\nstd::vector<int> getRandomSample(std::uniform_int_distribution<int>& udist,\n\n std::mt19937& rng, size_t N)\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 62, "score": 114304.73482906511 }, { "content": " dy = left_dy_.at<double>(real_row, real_col);\n\n }\n\n}\n\n\n\nvoid EgomotionLibviso::GetTracksFromStereoTracker(track::StereoTrackerBase& tracker,\n\n std::vector<StereoMatch>& tracks,\n\n std::vector<int>& active_tracks)\n\n{\n\n tracks.clear();\n\n active_tracks.clear();\n\n int feats_num = tracker.countFeatures();\n\n EgomotionLibviso::StereoMatch match;\n\n for (int i = 0; i < feats_num; i++) {\n\n track::FeatureInfo feat_left = tracker.featureLeft(i);\n\n track::FeatureInfo feat_right = tracker.featureRight(i);\n\n if (feat_left.age_ > 0) {\n\n if (!use_deformation_map_) {\n\n match.u1p = feat_left.prev_.x_;\n\n match.v1p = feat_left.prev_.y_;\n\n match.u1c = feat_left.curr_.x_;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 63, "score": 114300.87600601243 }, { "content": "{\n\n use_deformation_map_ = false;\n\n}\n\n\n\n//EgomotionLibviso::EgomotionLibviso(parameters params, std::string weights_filename,\n\n// int img_rows, int img_cols)\n\n// : params_(params), img_rows_(img_rows), img_cols_(img_cols)\n\n//{\n\n// std::cout << weights_filename << \"\\n\";\n\n// cv::FileStorage mat_file(weights_filename, cv::FileStorage::READ);\n\n// mat_file[\"variance_matrix\"] >> weights_mat_;\n\n// bin_width_ = (double)img_cols / weights_mat_.cols;\n\n// bin_height_ = (double)img_rows / weights_mat_.rows;\n\n//}\n\n\n\nEgomotionLibviso::EgomotionLibviso(parameters params,\n\n std::string deformation_params_fname,\n\n int img_rows, int img_cols)\n\n : params_(params), img_rows_(img_rows), img_cols_(img_cols)\n\n{\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 64, "score": 114300.01674023418 }, { "content": " return FAILED;\n\n\n\n // extract observations and compute predictions\n\n computeObservations(p_observe, tracks, active);\n\n computeResidualsAndJacobian(p_observe, p_predict, p_residual, J, tr, active);\n\n\n\n // init\n\n libviso::Matrix A(6,6);\n\n libviso::Matrix B(6,1);\n\n\n\n // fill matrices A and B\n\n for (int32_t m=0; m<6; m++) {\n\n for (int32_t n=0; n<6; n++) {\n\n double a = 0;\n\n for (int32_t i=0; i<4*(int32_t)active.size(); i++) {\n\n a += J[i*6+m]*J[i*6+n];\n\n }\n\n //if (std::isnan(a)) {\n\n // printf(\"NAN\\n\");\n\n // throw \"Error\\n\";\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 65, "score": 114296.92027337196 }, { "content": " if (fabs(B.val[m][0])>eps)\n\n converged = false;\n\n }\n\n if (converged)\n\n return CONVERGED;\n\n else\n\n return UPDATED;\n\n } else {\n\n return FAILED;\n\n }\n\n}\n\n\n\nvoid EgomotionLibviso::computeObservations(double* p_observe, std::vector<StereoMatch>& tracks,\n\n std::vector<int> &active)\n\n{\n\n\n\n // set all observations\n\n for (int i = 0; i < (int32_t)active.size(); i++) {\n\n p_observe[4*i+0] = tracks[active[i]].u1c; // u1\n\n p_observe[4*i+1] = tracks[active[i]].v1c; // v1\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 66, "score": 114293.26636245602 }, { "content": " int cols = left_dx_.cols;\n\n cell_centers_x_ = cv::Mat::zeros(rows, cols, CV_64F);\n\n cell_centers_y_ = cv::Mat::zeros(rows, cols, CV_64F);\n\n for (int i = 0; i < rows; i++) {\n\n for (int j = 0; j < cols; j++) {\n\n cell_centers_x_.at<double>(i,j) = (j * cell_width_) + (cell_width_ / 2.0);\n\n cell_centers_y_.at<double>(i,j) = (i * cell_height_) + (cell_height_ / 2.0);\n\n }\n\n }\n\n //std::cout << cell_centers_x_ << \"\\n\\n\" << cell_centers_y_ << \"\\n\";\n\n}\n\n\n\nvoid EgomotionLibviso::GetPointDeformation(const core::Point& pt, const cv::Mat& def_x,\n\n const cv::Mat& def_y, double& dx, double& dy)\n\n{\n\n // number of rows/cols in interpolation grid is smaller by 1\n\n int rows = left_dx_.rows - 1;\n\n int cols = left_dx_.cols - 1;\n\n double half_width = cell_width_ / 2.0;\n\n double half_height = cell_height_ / 2.0;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 67, "score": 114293.23196170463 }, { "content": "void DrawRansacSample(std::vector<int>& sample, std::vector<EgomotionLibviso::StereoMatch>& tracks,\n\n cv::Mat img_lp)\n\n{\n\n cv::Mat disp_lp;\n\n cv::cvtColor(img_lp, disp_lp, cv::COLOR_GRAY2RGB);\n\n cv::Scalar color_pt(0,0,255);\n\n\n\n for (int i = 0; i < (int)sample.size(); i++) {\n\n cv::Point cvpt;\n\n cvpt.x = tracks[sample[i]].u1p;\n\n cvpt.y = tracks[sample[i]].v1p;\n\n cv::circle(disp_lp, cvpt, 2, color_pt, -1);\n\n }\n\n cv::imshow(\"RANSAC winner\", disp_lp);\n\n //cv::waitKey(0);\n\n}\n\n\n\n}\n\n\n\nEgomotionLibviso::EgomotionLibviso(parameters params) : params_(params)\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 68, "score": 114289.66638534599 }, { "content": "\n\n // parameter estimate succeeded?\n\n if (success) return tr_delta[best_iter];\n\n else return std::vector<double>();\n\n}\n\n\n\nstd::vector<int> EgomotionLibviso::getInliers(double* p_observe,\n\n double* p_predict,\n\n double* p_residual,\n\n double* J,\n\n std::vector<StereoMatch> &tracks,\n\n std::vector<double> &tr,\n\n std::vector<int>& active)\n\n{\n\n // extract observations and compute predictions\n\n computeObservations(p_observe, tracks, active);\n\n computeResidualsAndJacobian(p_observe, p_predict, p_residual, J, tr, active);\n\n\n\n // compute inliers\n\n std::vector<int32_t> inliers;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 69, "score": 114289.04055407523 }, { "content": " p_observe[4*i+2] = tracks[active[i]].u2c; // u2\n\n p_observe[4*i+3] = tracks[active[i]].v2c; // v2\n\n }\n\n}\n\n\n\nvoid EgomotionLibviso::computeResidualsAndJacobian(double* p_observe,\n\n double* p_predict,\n\n double* p_residual,\n\n double* J,\n\n std::vector<double>& tr,\n\n std::vector<int>& active)\n\n{\n\n // extract motion parameters\n\n double rx = tr[0]; double ry = tr[1]; double rz = tr[2];\n\n double tx = tr[3]; double ty = tr[4]; double tz = tr[5];\n\n\n\n // precompute sine/cosine\n\n double sx = sin(rx); double cx = cos(rx); double sy = sin(ry);\n\n double cy = cos(ry); double sz = sin(rz); double cz = cos(rz);\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 70, "score": 114286.5189441525 }, { "content": " //}\n\n A.val[m][n] = a;\n\n }\n\n double b = 0;\n\n for (int32_t i=0; i<4*(int32_t)active.size(); i++) {\n\n b += J[i*6+m]*(p_residual[i]);\n\n }\n\n //if (std::isnan(b)) {\n\n // printf(\"NAN\\n\");\n\n // throw \"Error\\n\";\n\n //}\n\n B.val[m][0] = b;\n\n }\n\n\n\n // perform elimination\n\n if (B.solve(A)) {\n\n bool converged = true;\n\n for (int32_t m=0; m<6; m++) {\n\n tr[m] += step_size*B.val[m][0];\n\n //printf(\"%e\\n\", fabs(B.val[m][0]));\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 71, "score": 114285.16498147545 }, { "content": " for (int32_t i = 0; i < (int32_t)tracks.size(); i++)\n\n if (pow(p_observe[4*i+0] - p_predict[4*i+0],2) + pow(p_observe[4*i+1] - p_predict[4*i+1],2) +\n\n pow(p_observe[4*i+2] - p_predict[4*i+2],2) + pow(p_observe[4*i+3] - p_predict[4*i+3],2)\n\n < params_.inlier_threshold * params_.inlier_threshold)\n\n inliers.push_back(i);\n\n return inliers;\n\n}\n\n\n\nEgomotionLibviso::ResultState EgomotionLibviso::updateParameters(\n\n double* p_observe,\n\n double* p_predict,\n\n double* p_residual,\n\n double* J,\n\n std::vector<StereoMatch> &tracks,\n\n std::vector<int32_t>& active,\n\n std::vector<double>& tr,\n\n double step_size, double eps) {\n\n\n\n // we need at least 3 observations\n\n if (active.size() < 3)\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 72, "score": 114284.13069595586 }, { "content": "{\n\n std::unordered_set<int> set;\n\n std::vector<int> sample;\n\n while(sample.size() < N) {\n\n int rnum = udist(rng);\n\n if (set.find(rnum) == set.end()) {\n\n set.insert(rnum);\n\n sample.push_back(rnum);\n\n }\n\n }\n\n return sample;\n\n}\n\n\n\nvoid TransformationVectorToMatrix(const std::vector<double>& tr, Eigen::Matrix4d& Rt)\n\n{\n\n // extract parameters\n\n double rx = tr[0];\n\n double ry = tr[1];\n\n double rz = tr[2];\n\n double tx = tr[3];\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 73, "score": 114284.03555591116 }, { "content": " p_predict[4*i+2] = params_.calib.f*X2c/Z1c+params_.calib.cu; // right u\n\n p_predict[4*i+3] = params_.calib.f*Y1c/Z1c+params_.calib.cv; // right v\n\n\n\n // set residuals\n\n p_residual[4*i+0] = weight*(p_observe[4*i+0]-p_predict[4*i+0]);\n\n p_residual[4*i+1] = weight*(p_observe[4*i+1]-p_predict[4*i+1]);\n\n p_residual[4*i+2] = weight*(p_observe[4*i+2]-p_predict[4*i+2]);\n\n p_residual[4*i+3] = weight*(p_observe[4*i+3]-p_predict[4*i+3]);\n\n }\n\n}\n\n\n\nvoid EgomotionLibviso::updateTrackerInliers(const std::vector<int>& active_tracks)\n\n{\n\n std::vector<bool> dead_tracks(active_tracks.size(), true);\n\n tracker_inliers_.clear();\n\n tracker_outliers_.clear();\n\n for (size_t i = 0; i < inliers_.size(); i++)\n\n dead_tracks[inliers_[i]] = false;\n\n\n\n for (size_t i = 0; i < dead_tracks.size(); i++) {\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 74, "score": 114283.48140001633 }, { "content": " std::vector<int> active_all;\n\n for (int i = 0; i < (int)tracks.size(); i++)\n\n active_all.push_back(i);\n\n\n\n\n\n std::vector<std::vector<int>> active;\n\n std::vector<std::vector<int>> iter_inliers;\n\n std::vector<std::vector<double>> tr_delta;\n\n active.resize(params_.ransac_iters);\n\n iter_inliers.resize(params_.ransac_iters);\n\n tr_delta.resize(params_.ransac_iters);\n\n // initial RANSAC estimate\n\n //omp_set_num_threads(1);\n\n #pragma omp parallel\n\n {\n\n double* J = new double[4*N*6]; // jacobian\n\n double* p_predict = new double[4*N]; // predicted 2d points\n\n double* p_observe = new double[4*N]; // observed 2d points\n\n double* p_residual = new double[4*N]; // residuals (p_residual=p_observe-p_predict)\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 75, "score": 114283.46880137105 }, { "content": " GetPointDeformation(feat_left.prev_, left_dx_, left_dy_, dx, dy);\n\n match.u1p = feat_left.prev_.x_ + dx;\n\n match.v1p = feat_left.prev_.y_ + dy;\n\n //std::cout << \"Before = \\n\" << feat_left.prev_ << \"\\n\";\n\n //std::cout << \"After = \\n\" << match.u1p << \" -- \" << match.v1p << \"\\n\";\n\n\n\n GetPointDeformation(feat_left.curr_, left_dx_, left_dy_, dx, dy);\n\n match.u1c = feat_left.curr_.x_ + dx;\n\n match.v1c = feat_left.curr_.y_ + dy;\n\n\n\n GetPointDeformation(feat_right.prev_, right_dx_, right_dy_, dx, dy);\n\n match.u2p = feat_right.prev_.x_ + dx;\n\n match.v2p = feat_right.prev_.y_ + dy;\n\n\n\n GetPointDeformation(feat_right.curr_, right_dx_, right_dy_, dx, dy);\n\n match.u2c = feat_right.curr_.x_ + dx;\n\n match.v2c = feat_right.curr_.y_ + dy;\n\n }\n\n //// without interpolation\n\n //else {\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 76, "score": 114282.57317654292 }, { "content": " std::uniform_int_distribution<int> udist(0, N-1);\n\n //rng_type rng(clock() + std::this_thread::get_id().hash());\n\n std::mt19937 rng(int(time(NULL)) ^ omp_get_thread_num());\n\n //rng.seed(seedval);\n\n #pragma omp for\n\n for (int32_t k = 0; k < params_.ransac_iters; k++) {\n\n // draw random sample set\n\n active[k] = getRandomSample(udist, rng, 3);\n\n //bool good_pick = false;\n\n //while(!good_pick) {\n\n // active[k] = getRandomSample(udist, rng, 3);\n\n // for (int idx : active[k])\n\n // if (D[idx] > 5.0) {\n\n // good_pick = true;\n\n // break;\n\n // }\n\n //}\n\n\n\n //int thread_num = omp_get_thread_num();\n\n //for (int num : active[k])\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 77, "score": 114282.05395878201 }, { "content": " assert(!(std::isnan(match.u1p) || std::isnan(match.v1p) || std::isnan(match.u1c)\n\n || std::isnan(match.v1c) || std::isnan(match.u2p) || std::isnan(match.v2p)\n\n || std::isnan(match.u2c) || std::isnan(match.v2c)));\n\n\n\n tracks.push_back(match);\n\n active_tracks.push_back(i);\n\n }\n\n }\n\n}\n\n\n\nstd::vector<double> EgomotionLibviso::estimateMotion(std::vector<StereoMatch>& tracks)\n\n{\n\n // return value\n\n bool success = true;\n\n // get number of matches\n\n int N = tracks.size();\n\n if (N < 6)\n\n return std::vector<double>();\n\n\n\n // allocate dynamic memory\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 78, "score": 114282.05533345047 }, { "content": " if (dead_tracks[i] == false)\n\n tracker_inliers_.push_back(active_tracks[i]);\n\n else\n\n tracker_outliers_.push_back(active_tracks[i]);\n\n }\n\n\n\n //for (size_t i = 0; i < inliers_.size(); i++) {\n\n // int inlier_idx = active_tracks[inliers_[i]];\n\n // tracker_inliers_.push_back(inlier_idx);\n\n //}\n\n}\n\n\n\nbool EgomotionLibviso::GetMotion(track::StereoTrackerBase& tracker, Eigen::Matrix4d& Rt) {\n\n // estimate motion\n\n std::vector<StereoMatch> tracks;\n\n std::vector<int> active_tracks;\n\n GetTracksFromStereoTracker(tracker, tracks, active_tracks);\n\n\n\n std::vector<double> tr_delta = estimateMotion(tracks);\n\n \n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 79, "score": 114281.94713862118 }, { "content": " // int row, col;\n\n // GetPointCell(feat_left.prev_, row, col);\n\n // match.u1p = feat_left.prev_.x_ + left_dx_.at<double>(row, col);\n\n // match.v1p = feat_left.prev_.y_ + left_dy_.at<double>(row, col);\n\n // //std::cout << \"Before = \\n\" << feat_left.prev_ << \"\\n\";\n\n // //std::cout << \"After = \\n\" << match.u1p << \" -- \" << match.v1p << \"\\n\";\n\n\n\n // GetPointCell(feat_left.curr_, row, col);\n\n // match.u1c = feat_left.curr_.x_ + left_dx_.at<double>(row, col);\n\n // match.v1c = feat_left.curr_.y_ + left_dy_.at<double>(row, col);\n\n\n\n // GetPointCell(feat_right.prev_, row, col);\n\n // match.u2p = feat_right.prev_.x_ + right_dx_.at<double>(row, col);\n\n // match.v2p = feat_right.prev_.y_ + right_dy_.at<double>(row, col);\n\n\n\n // GetPointCell(feat_right.curr_, row, col);\n\n // match.u2c = feat_right.curr_.x_ + right_dx_.at<double>(row, col);\n\n // match.v2c = feat_right.curr_.y_ + right_dy_.at<double>(row, col);\n\n //}\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 80, "score": 114281.90049776637 }, { "content": " }\n\n\n\n int best_iter = 0;\n\n int most_inliers = iter_inliers[0].size();\n\n for (int i = 1; i < (int)iter_inliers.size(); i++) {\n\n if ((int)iter_inliers[i].size() > most_inliers) {\n\n best_iter = i;\n\n most_inliers = iter_inliers[i].size();\n\n }\n\n }\n\n printf(\"[EgomotionLibviso]: RANSAC found most inliers in iter %d / %d\\n\",\n\n best_iter, params_.ransac_iters);\n\n\n\n //DrawRansacSample(active[best_iter], tracks, img_left_prev_);\n\n\n\n // final optimization (refinement)\n\n double* J = new double[4*N*6]; // jacobian\n\n double* p_predict = new double[4*N]; // predicted 2d points\n\n double* p_observe = new double[4*N]; // observed 2d points\n\n double* p_residual = new double[4*N]; // residuals (p_residual=p_observe-p_predict)\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 81, "score": 114280.96674495202 }, { "content": " int real_row = static_cast<int>(pt.y_ / cell_height_);\n\n int real_col = static_cast<int>(pt.x_ / cell_width_);\n\n int row = static_cast<int>(std::floor((pt.y_ - half_height) / cell_height_));\n\n int col = static_cast<int>(std::floor((pt.x_ - half_width) / cell_width_));\n\n double cell_x = 0.0, cell_y = 0.0;\n\n if (row >= 0)\n\n cell_x = (pt.x_ - half_width) - (col * cell_width_);\n\n if (col >= 0)\n\n cell_y = (pt.y_ - half_height) - (row * cell_height_);\n\n\n\n // compute bilinear interpolation\n\n if (row >= 0 && row < rows && col >= 0 && col < cols) {\n\n assert(cell_x >= 0.0 && cell_x <= cell_width_);\n\n assert(cell_y >= 0.0 && cell_y <= cell_height_);\n\n InterpolateBilinear(def_x, row, col, cell_x, cell_y, dx);\n\n InterpolateBilinear(def_y, row, col, cell_x, cell_y, dy);\n\n }\n\n // compute left-right liner interpolation on horizontal edges\n\n else if ((row < 0 || row >= rows) && (col >= 0 || col < cols)) {\n\n assert(cell_x >= 0.0 && cell_x <= cell_width_);\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 82, "score": 114280.67187486163 }, { "content": " X = new double[N];\n\n Y = new double[N];\n\n Z = new double[N];\n\n W = new double[N];\n\n //double* D = new double[N];\n\n\n\n // project matches of previous image into 3d\n\n for (int32_t i = 0; i < N; i++) {\n\n double d = std::max(tracks[i].u1p - tracks[i].u2p, 0.01f);\n\n //double d = p_matched[i].u1p - p_matched[i].u2p;\n\n //std::cout << d << \": \" << p_matched[i].u1p << \" - \" << p_matched[i].u2p << \"\\n\";\n\n if (d <= 0.0) {\n\n std::cout << \"[EgomotionLibviso] zero/negative disp: \" << d << \" -> \";\n\n std::cout << tracks[i].u1p << \" - \" << tracks[i].u2p << \"\\n\";\n\n throw 1;\n\n }\n\n //else if (d < 1.0) cout << \"[EgomotionLibviso] small disp: \" << d << \"\\n\";\n\n\n\n //double d = max(p_matched[i].u1p - p_matched[i].u2p, 0.001f);\n\n //d = std::max(d, 0.0001);\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 83, "score": 114280.44430291989 }, { "content": " //printf(\"Iter = %d - Thread = %d - Random num = %d\\n\", k, thread_num, active[k][0]);\n\n\n\n // clear parameter vector\n\n tr_delta[k].assign(6, 0.0);\n\n // minimize reprojection errors\n\n ResultState result = UPDATED;\n\n int32_t iter = 0;\n\n while(result == UPDATED) {\n\n result = updateParameters(p_observe, p_predict, p_residual, J, tracks, active[k], tr_delta[k], 1, 1e-6);\n\n if (iter++ > 20 || result == CONVERGED)\n\n break;\n\n }\n\n if (result != FAILED)\n\n iter_inliers[k] = getInliers(p_observe, p_predict, p_residual, J, tracks, tr_delta[k], active_all);\n\n }\n\n\n\n delete[] J;\n\n delete[] p_predict;\n\n delete[] p_observe;\n\n delete[] p_residual;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 84, "score": 114279.04321360288 }, { "content": "}\n\n\n\nvoid TransformationVectorToMatrix(const std::vector<double>& tr, cv::Mat& Rt)\n\n{\n\n // extract parameters\n\n double rx = tr[0];\n\n double ry = tr[1];\n\n double rz = tr[2];\n\n double tx = tr[3];\n\n double ty = tr[4];\n\n double tz = tr[5];\n\n // precompute sine/cosine\n\n double sx = std::sin(rx);\n\n double cx = std::cos(rx);\n\n double sy = std::sin(ry);\n\n double cy = std::cos(ry);\n\n double sz = std::sin(rz);\n\n double cz = std::cos(rz);\n\n\n\n // compute transformation\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 85, "score": 114278.0960476665 }, { "content": " Rt.create(4, 4, CV_64F);\n\n\n\n Rt.at<double>(0,0) = +cy*cz; Rt.at<double>(0,1) = -cy*sz; \n\n Rt.at<double>(1,0) = +sx*sy*cz+cx*sz; Rt.at<double>(1,1) = -sx*sy*sz+cx*cz; \n\n Rt.at<double>(2,0) = -cx*sy*cz+sx*sz; Rt.at<double>(2,1) = +cx*sy*sz+sx*cz; \n\n Rt.at<double>(3,0) = 0; Rt.at<double>(3,1) = 0; \n\n\n\n Rt.at<double>(0,2) = +sy; Rt.at<double>(0,3) = tx;\n\n Rt.at<double>(1,2) = -sx*cy; Rt.at<double>(1,3) = ty;\n\n Rt.at<double>(2,2) = +cx*cy; Rt.at<double>(2,3) = tz;\n\n Rt.at<double>(3,2) = 0; Rt.at<double>(3,3) = 1;\n\n}\n\n\n\nlibviso::Matrix TransformationVectorToLibvisoMatrix(std::vector<double> tr)\n\n{\n\n // extract parameters\n\n double rx = tr[0];\n\n double ry = tr[1];\n\n double rz = tr[2];\n\n double tx = tr[3];\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 86, "score": 114276.38820376222 }, { "content": " double ty = tr[4];\n\n double tz = tr[5];\n\n\n\n // precompute sine/cosine\n\n double sx = std::sin(rx);\n\n double cx = std::cos(rx);\n\n double sy = std::sin(ry);\n\n double cy = std::cos(ry);\n\n double sz = std::sin(rz);\n\n double cz = std::cos(rz);\n\n\n\n // compute transformation\n\n libviso::Matrix Tr(4,4);\n\n Tr.val[0][0] = +cy*cz; Tr.val[0][1] = -cy*sz; Tr.val[0][2] = +sy; Tr.val[0][3] = tx;\n\n Tr.val[1][0] = +sx*sy*cz+cx*sz; Tr.val[1][1] = -sx*sy*sz+cx*cz; Tr.val[1][2] = -sx*cy; Tr.val[1][3] = ty;\n\n Tr.val[2][0] = -cx*sy*cz+sx*sz; Tr.val[2][1] = +cx*sy*sz+sx*cz; Tr.val[2][2] = +cx*cy; Tr.val[2][3] = tz;\n\n Tr.val[3][0] = 0; Tr.val[3][1] = 0; Tr.val[3][2] = 0; Tr.val[3][3] = 1;\n\n return Tr;\n\n}\n\n\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 87, "score": 114275.97026704163 }, { "content": " // on failure\n\n if (tr_delta.size() != 6)\n\n return false;\n\n\n\n updateTrackerInliers(active_tracks);\n\n // set transformation matrix (previous to current frame)\n\n TransformationVectorToMatrix(tr_delta, Rt);\n\n return true;\n\n}\n\n\n\n}\n\n\n\n\n\n//{\n\n// // init sample and totalset\n\n// std::vector<int32_t> sample;\n\n// std::vector<int32_t> totalset;\n\n// \n\n// // create vector containing all indices\n\n// for (int32_t i=0; i<N; i++)\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 88, "score": 114275.00890208765 }, { "content": " //inliers.clear();\n\n //// initial RANSAC estimate\n\n //int32_t k;\n\n ////#pragma omp parallel for shared(tr_delta, inliers) private(k, tr_delta_curr) schedule(dynamic)\n\n //#pragma omp parallel for shared(tr_delta) private(k) schedule(dynamic)\n\n //for (k=0; k<param.ransac_iters; k++) {\n\n // // draw random sample set\n\n // vector<int32_t> active = getRandomSample(N,3);\n\n // vector<double> tr_delta_curr(6);\n\n // // clear parameter vector\n\n // for (int32_t i=0; i<6; i++)\n\n // tr_delta_curr[i] = 0;\n\n\n\n // // minimize reprojection errors\n\n // EgomotionLibviso::result result = UPDATED;\n\n // int32_t iter=0;\n\n // while (result==UPDATED) {\n\n // result = updateParameters(p_matched,active,tr_delta_curr,1,1e-6);\n\n // if (iter++ > 20 || result==CONVERGED)\n\n // break;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 89, "score": 114274.57509924298 }, { "content": " match.v1c = feat_left.curr_.y_;\n\n match.u2p = feat_right.prev_.x_;\n\n match.v2p = feat_right.prev_.y_;\n\n match.u2c = feat_right.curr_.x_;\n\n match.v2c = feat_right.curr_.y_;\n\n }\n\n // TODO: try combining triangulation in prev and curr\n\n //if (!use_deformation_map_) {\n\n // match.u1c = feat_left.prev_.x_;\n\n // match.v1c = feat_left.prev_.y_;\n\n // match.u1p = feat_left.curr_.x_;\n\n // match.v1p = feat_left.curr_.y_;\n\n // match.u2c = feat_right.prev_.x_;\n\n // match.v2c = feat_right.prev_.y_;\n\n // match.u2p = feat_right.curr_.x_;\n\n // match.v2p = feat_right.curr_.y_;\n\n //}\n\n // with interpolation\n\n else {\n\n double dx, dy;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 90, "score": 114274.53265330743 }, { "content": " double q1 = def_x.at<double>(real_row, col);\n\n double q2 = def_x.at<double>(real_row, col+1);\n\n InterpolateLinear(q1, q2, cell_x, cell_width_, dx);\n\n q1 = def_y.at<double>(real_row, col);\n\n q2 = def_y.at<double>(real_row, col+1);\n\n InterpolateLinear(q1, q2, cell_x, cell_width_, dy);\n\n }\n\n // compute up-down linear interpolation on vertical edges\n\n else if ((row >= 0 || row < rows) && (col < 0 || col >= cols)) {\n\n assert(cell_y >= 0.0 && cell_y <= cell_height_);\n\n double q1 = def_x.at<double>(row, real_col);\n\n double q2 = def_x.at<double>(row+1, real_col);\n\n InterpolateLinear(q1, q2, cell_y, cell_height_, dx);\n\n q1 = def_y.at<double>(row, real_col);\n\n q2 = def_y.at<double>(row+1, real_col);\n\n InterpolateLinear(q1, q2, cell_y, cell_height_, dy);\n\n }\n\n // we can't interpolate on corners\n\n else {\n\n dx = left_dx_.at<double>(real_row, real_col);\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 91, "score": 114274.05814357086 }, { "content": " X[i] = (tracks[i].u1p - params_.calib.cu) * params_.base / d;\n\n Y[i] = (tracks[i].v1p - params_.calib.cv) * params_.base / d;\n\n Z[i] = params_.calib.f * params_.base / d;\n\n //D[i] = d;\n\n if (params_.reweighting) {\n\n if (!weights_mat_.empty()) {\n\n int r = tracks[i].v1p / cell_height_;\n\n int c = tracks[i].u1p / cell_width_;\n\n double variance = weights_mat_.at<double>(r,c);\n\n // TODO\n\n //W[i] = 1.0 / variance;\n\n W[i] = 1.0 / std::sqrt(variance);\n\n }\n\n else {\n\n //W[i] = 1.0/(fabs(p_observe[4*i+0] - params_.calib.cu) / fabs(params_.calib.cu) + 0.05);\n\n W[i] = 1.0/(fabs(tracks[i].u1c - params_.calib.cu) / fabs(params_.calib.cu) + 0.05);\n\n }\n\n }\n\n }\n\n // mark all observations active\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 92, "score": 114271.96970988286 }, { "content": " //printf(\"Final optimization\\n\");\n\n inliers_ = iter_inliers[best_iter];\n\n if (inliers_.size() >= 6) {\n\n int32_t iter = 0;\n\n ResultState result = UPDATED;\n\n while(result == UPDATED) {\n\n // orig\n\n result = updateParameters(p_observe, p_predict, p_residual, J, tracks, inliers_,\n\n tr_delta[best_iter], 1, 1e-8);\n\n // mine - last resort\n\n //result = updateParameters(p_matched,inliers,tr_delta,1,1e-7);\n\n // orig\n\n //if (iter++ > 100 || result==CONVERGED)\n\n // mine\n\n if (iter++ > 500 || result == CONVERGED) {\n\n printf(\"[libviso]: Newton method final iters: %d\\n\", iter+1);\n\n break;\n\n }\n\n }\n\n // not converged\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 93, "score": 114271.60645772569 }, { "content": " //double rz = tr[2];\n\n //double tx = tr[3];\n\n //double ty = tr[4];\n\n //double tz = tr[5];\n\n\n\n //J[(4*i+0)*6+j] = weight_trans * weight*params_.calib.f*(X1cd*Z1c-X1c*Z1cd)/(Z1c*Z1c); // left u'\n\n //J[(4*i+1)*6+j] = weight_trans * weight*params_.calib.f*(Y1cd*Z1c-Y1c*Z1cd)/(Z1c*Z1c); // left v'\n\n //J[(4*i+2)*6+j] = weight_trans * weight*params_.calib.f*(X1cd*Z1c-X2c*Z1cd)/(Z1c*Z1c); // right u'\n\n //J[(4*i+3)*6+j] = weight_trans * weight*params_.calib.f*(Y1cd*Z1c-Y1c*Z1cd)/(Z1c*Z1c); // right v'\n\n\n\n // set jacobian entries (project via K)\n\n J[(4*i+0)*6+j] = weight*params_.calib.f*(X1cd*Z1c-X1c*Z1cd)/(Z1c*Z1c); // left u'\n\n J[(4*i+1)*6+j] = weight*params_.calib.f*(Y1cd*Z1c-Y1c*Z1cd)/(Z1c*Z1c); // left v'\n\n J[(4*i+2)*6+j] = weight*params_.calib.f*(X1cd*Z1c-X2c*Z1cd)/(Z1c*Z1c); // right u'\n\n J[(4*i+3)*6+j] = weight*params_.calib.f*(Y1cd*Z1c-Y1c*Z1cd)/(Z1c*Z1c); // right v'\n\n }\n\n\n\n // set prediction (project via K)\n\n p_predict[4*i+0] = params_.calib.f*X1c/Z1c+params_.calib.cu; // left u\n\n p_predict[4*i+1] = params_.calib.f*Y1c/Z1c+params_.calib.cv; // left v\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 94, "score": 114270.02432115668 }, { "content": " double ty = tr[4];\n\n double tz = tr[5];\n\n // precompute sine/cosine\n\n double sx = std::sin(rx);\n\n double cx = std::cos(rx);\n\n double sy = std::sin(ry);\n\n double cy = std::cos(ry);\n\n double sz = std::sin(rz);\n\n double cz = std::cos(rz);\n\n\n\n // compute transformation\n\n Rt(0,0) = +cy*cz; Rt(0,1) = -cy*sz; \n\n Rt(1,0) = +sx*sy*cz+cx*sz; Rt(1,1) = -sx*sy*sz+cx*cz; \n\n Rt(2,0) = -cx*sy*cz+sx*sz; Rt(2,1) = +cx*sy*sz+sx*cz; \n\n Rt(3,0) = 0; Rt(3,1) = 0; \n\n\n\n Rt(0,2) = +sy; Rt(0,3) = tx;\n\n Rt(1,2) = -sx*cy; Rt(1,3) = ty;\n\n Rt(2,2) = +cx*cy; Rt(2,3) = tz;\n\n Rt(3,2) = 0; Rt(3,3) = 1;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 95, "score": 114269.771437925 }, { "content": "// totalset.push_back(i);\n\n//\n\n// // add num indices to current sample\n\n// sample.clear();\n\n// for (int32_t i=0; i<num; i++) {\n\n// int32_t j = rand()%totalset.size();\n\n// sample.push_back(totalset[j]);\n\n// totalset.erase(totalset.begin()+j);\n\n// }\n\n// \n\n// // return sample\n\n// return sample;\n\n//}\n\n\n\n\n\n\n\n\n\n //// loop variables\n\n //vector<double> tr_delta;\n\n //// clear parameter vector\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 96, "score": 114269.3656601565 }, { "content": " break;\n\n case 2: X1cd = rdrz00*X1p+rdrz01*Y1p;\n\n Y1cd = rdrz10*X1p+rdrz11*Y1p;\n\n Z1cd = rdrz20*X1p+rdrz21*Y1p;\n\n break;\n\n case 3: X1cd = 1; Y1cd = 0; Z1cd = 0; break;\n\n case 4: X1cd = 0; Y1cd = 1; Z1cd = 0; break;\n\n case 5: X1cd = 0; Y1cd = 0; Z1cd = 1; break;\n\n }\n\n\n\n // TODO - increase weights for nearby points for j = translation\n\n //double disp = std::max(p_observe[4*i+0] - p_observe[4*i+2], 0.1);\n\n //std::cout << \"DISP = \" << disp << '\\n';\n\n //double weight_trans = 1.0;\n\n //if (j > 2)\n\n // //weight_trans = 1.0 * disp;\n\n // weight_trans = 1.0 / std::max(10.0 - disp, 1.0);\n\n\n\n //double rx = tr[0];\n\n //double ry = tr[1];\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 97, "score": 114269.11600703884 }, { "content": " if (result != CONVERGED) {\n\n success = false;\n\n inliers_.clear();\n\n }\n\n // not enough inliers\n\n } else {\n\n success = false;\n\n inliers_.clear();\n\n }\n\n // release dynamic memory\n\n delete[] X;\n\n delete[] Y;\n\n delete[] Z;\n\n //delete[] D;\n\n delete[] W;\n\n\n\n delete[] J;\n\n delete[] p_predict;\n\n delete[] p_observe;\n\n delete[] p_residual;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 98, "score": 114268.204094984 }, { "content": " //weight = 1.0;\n\n }\n\n // TODO try to learn a constant\n\n //weight *= 0.8;\n\n //printf(\"weight = %f\\n\", weight);\n\n\n\n // compute 3d point in current right coordinate system\n\n X2c = X1c - params_.base;\n\n\n\n // for all paramters do\n\n for (int j = 0; j < 6; j++) {\n\n // derivatives of 3d pt. in curr. left coordinates wrt. param j\n\n switch (j) {\n\n case 0: X1cd = 0;\n\n Y1cd = rdrx10*X1p+rdrx11*Y1p+rdrx12*Z1p;\n\n Z1cd = rdrx20*X1p+rdrx21*Y1p+rdrx22*Z1p;\n\n break;\n\n case 1: X1cd = rdry00*X1p+rdry01*Y1p+rdry02*Z1p;\n\n Y1cd = rdry10*X1p+rdry11*Y1p+rdry12*Z1p;\n\n Z1cd = rdry20*X1p+rdry21*Y1p+rdry22*Z1p;\n", "file_path": "stereo_egomotion/base/egomotion_libviso.cc", "rank": 99, "score": 114267.03483878162 } ]
C++
Source/Tools/Game/zmq/src/tcp_listener.cpp
299299/tesla_hmi
d5f2ad158d1b69d46d7fc99898ec90e19f1ae419
#include "precompiled.hpp" #include <new> #include <string> #include <stdio.h> #include "tcp_listener.hpp" #include "io_thread.hpp" #include "config.hpp" #include "err.hpp" #include "ip.hpp" #include "tcp.hpp" #include "socket_base.hpp" #include "address.hpp" #ifndef ZMQ_HAVE_WINDOWS #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <netdb.h> #include <fcntl.h> #ifdef ZMQ_HAVE_VXWORKS #include <sockLib.h> #endif #endif #ifdef ZMQ_HAVE_OPENVMS #include <ioctl.h> #endif zmq::tcp_listener_t::tcp_listener_t (io_thread_t *io_thread_, socket_base_t *socket_, const options_t &options_) : stream_listener_base_t (io_thread_, socket_, options_) { } void zmq::tcp_listener_t::in_event () { fd_t fd = accept (); if (fd == retired_fd) { _socket->event_accept_failed ( make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ()); return; } int rc = tune_tcp_socket (fd); rc = rc | tune_tcp_keepalives ( fd, options.tcp_keepalive, options.tcp_keepalive_cnt, options.tcp_keepalive_idle, options.tcp_keepalive_intvl); rc = rc | tune_tcp_maxrt (fd, options.tcp_maxrt); if (rc != 0) { _socket->event_accept_failed ( make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ()); return; } create_engine (fd); } std::string zmq::tcp_listener_t::get_socket_name (zmq::fd_t fd_, socket_end_t socket_end_) const { return zmq::get_socket_name<tcp_address_t> (fd_, socket_end_); } int zmq::tcp_listener_t::create_socket (const char *addr_) { _s = tcp_open_socket (addr_, options, true, true, &_address); if (_s == retired_fd) { return -1; } make_socket_noninheritable (_s); int flag = 1; int rc; #ifdef ZMQ_HAVE_WINDOWS rc = setsockopt (_s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char *> (&flag), sizeof (int)); wsa_assert (rc != SOCKET_ERROR); #elif defined ZMQ_HAVE_VXWORKS rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, (char *) &flag, sizeof (int)); errno_assert (rc == 0); #else rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int)); errno_assert (rc == 0); #endif #if defined ZMQ_HAVE_VXWORKS rc = bind (_s, (sockaddr *) _address.addr (), _address.addrlen ()); #else rc = bind (_s, _address.addr (), _address.addrlen ()); #endif #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { errno = wsa_error_to_errno (WSAGetLastError ()); goto error; } #else if (rc != 0) goto error; #endif rc = listen (_s, options.backlog); #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { errno = wsa_error_to_errno (WSAGetLastError ()); goto error; } #else if (rc != 0) goto error; #endif return 0; error: int err = errno; close (); errno = err; return -1; } int zmq::tcp_listener_t::set_local_address (const char *addr_) { if (options.use_fd != -1) { _s = options.use_fd; } else { if (create_socket (addr_) == -1) return -1; } _endpoint = get_socket_name (_s, socket_end_local); _socket->event_listening (make_unconnected_bind_endpoint_pair (_endpoint), _s); return 0; } zmq::fd_t zmq::tcp_listener_t::accept () { zmq_assert (_s != retired_fd); struct sockaddr_storage ss; memset (&ss, 0, sizeof (ss)); #if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS int ss_len = sizeof (ss); #else socklen_t ss_len = sizeof (ss); #endif #if defined ZMQ_HAVE_SOCK_CLOEXEC && defined HAVE_ACCEPT4 fd_t sock = ::accept4 (_s, reinterpret_cast<struct sockaddr *> (&ss), &ss_len, SOCK_CLOEXEC); #else fd_t sock = ::accept (_s, reinterpret_cast<struct sockaddr *> (&ss), &ss_len); #endif if (sock == retired_fd) { #if defined ZMQ_HAVE_WINDOWS const int last_error = WSAGetLastError (); wsa_assert (last_error == WSAEWOULDBLOCK || last_error == WSAECONNRESET || last_error == WSAEMFILE || last_error == WSAENOBUFS); #elif defined ZMQ_HAVE_ANDROID errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR || errno == ECONNABORTED || errno == EPROTO || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE || errno == ENFILE || errno == EINVAL); #else errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR || errno == ECONNABORTED || errno == EPROTO || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE || errno == ENFILE); #endif return retired_fd; } make_socket_noninheritable (sock); if (!options.tcp_accept_filters.empty ()) { bool matched = false; for (options_t::tcp_accept_filters_t::size_type i = 0; i != options.tcp_accept_filters.size (); ++i) { if (options.tcp_accept_filters[i].match_address ( reinterpret_cast<struct sockaddr *> (&ss), ss_len)) { matched = true; break; } } if (!matched) { #ifdef ZMQ_HAVE_WINDOWS int rc = closesocket (sock); wsa_assert (rc != SOCKET_ERROR); #else int rc = ::close (sock); errno_assert (rc == 0); #endif return retired_fd; } } if (zmq::set_nosigpipe (sock)) { #ifdef ZMQ_HAVE_WINDOWS int rc = closesocket (sock); wsa_assert (rc != SOCKET_ERROR); #else int rc = ::close (sock); errno_assert (rc == 0); #endif return retired_fd; } if (options.tos != 0) set_ip_type_of_service (sock, options.tos); return sock; }
#include "precompiled.hpp" #include <new> #include <string> #include <stdio.h> #include "tcp_listener.hpp" #include "io_thread.hpp" #include "config.hpp" #include "err.hpp" #include "ip.hpp" #include "tcp.hpp" #include "socket_base.hpp" #include "address.hpp" #ifndef ZMQ_HAVE_WINDOWS #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <netdb.h> #include <fcntl.h> #ifdef ZMQ_HAVE_VXWORKS #include <sockLib.h> #endif #endif #ifdef ZMQ_HAVE_OPENVMS #include <ioctl.h> #endif zmq::tcp_listener_t::tcp_listener_t (
_socket->event_accept_failed ( make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ()); return; } create_engine (fd); } std::string zmq::tcp_listener_t::get_socket_name (zmq::fd_t fd_, socket_end_t socket_end_) const { return zmq::get_socket_name<tcp_address_t> (fd_, socket_end_); } int zmq::tcp_listener_t::create_socket (const char *addr_) { _s = tcp_open_socket (addr_, options, true, true, &_address); if (_s == retired_fd) { return -1; } make_socket_noninheritable (_s); int flag = 1; int rc; #ifdef ZMQ_HAVE_WINDOWS rc = setsockopt (_s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char *> (&flag), sizeof (int)); wsa_assert (rc != SOCKET_ERROR); #elif defined ZMQ_HAVE_VXWORKS rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, (char *) &flag, sizeof (int)); errno_assert (rc == 0); #else rc = setsockopt (_s, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (int)); errno_assert (rc == 0); #endif #if defined ZMQ_HAVE_VXWORKS rc = bind (_s, (sockaddr *) _address.addr (), _address.addrlen ()); #else rc = bind (_s, _address.addr (), _address.addrlen ()); #endif #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { errno = wsa_error_to_errno (WSAGetLastError ()); goto error; } #else if (rc != 0) goto error; #endif rc = listen (_s, options.backlog); #ifdef ZMQ_HAVE_WINDOWS if (rc == SOCKET_ERROR) { errno = wsa_error_to_errno (WSAGetLastError ()); goto error; } #else if (rc != 0) goto error; #endif return 0; error: int err = errno; close (); errno = err; return -1; } int zmq::tcp_listener_t::set_local_address (const char *addr_) { if (options.use_fd != -1) { _s = options.use_fd; } else { if (create_socket (addr_) == -1) return -1; } _endpoint = get_socket_name (_s, socket_end_local); _socket->event_listening (make_unconnected_bind_endpoint_pair (_endpoint), _s); return 0; } zmq::fd_t zmq::tcp_listener_t::accept () { zmq_assert (_s != retired_fd); struct sockaddr_storage ss; memset (&ss, 0, sizeof (ss)); #if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS int ss_len = sizeof (ss); #else socklen_t ss_len = sizeof (ss); #endif #if defined ZMQ_HAVE_SOCK_CLOEXEC && defined HAVE_ACCEPT4 fd_t sock = ::accept4 (_s, reinterpret_cast<struct sockaddr *> (&ss), &ss_len, SOCK_CLOEXEC); #else fd_t sock = ::accept (_s, reinterpret_cast<struct sockaddr *> (&ss), &ss_len); #endif if (sock == retired_fd) { #if defined ZMQ_HAVE_WINDOWS const int last_error = WSAGetLastError (); wsa_assert (last_error == WSAEWOULDBLOCK || last_error == WSAECONNRESET || last_error == WSAEMFILE || last_error == WSAENOBUFS); #elif defined ZMQ_HAVE_ANDROID errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR || errno == ECONNABORTED || errno == EPROTO || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE || errno == ENFILE || errno == EINVAL); #else errno_assert (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR || errno == ECONNABORTED || errno == EPROTO || errno == ENOBUFS || errno == ENOMEM || errno == EMFILE || errno == ENFILE); #endif return retired_fd; } make_socket_noninheritable (sock); if (!options.tcp_accept_filters.empty ()) { bool matched = false; for (options_t::tcp_accept_filters_t::size_type i = 0; i != options.tcp_accept_filters.size (); ++i) { if (options.tcp_accept_filters[i].match_address ( reinterpret_cast<struct sockaddr *> (&ss), ss_len)) { matched = true; break; } } if (!matched) { #ifdef ZMQ_HAVE_WINDOWS int rc = closesocket (sock); wsa_assert (rc != SOCKET_ERROR); #else int rc = ::close (sock); errno_assert (rc == 0); #endif return retired_fd; } } if (zmq::set_nosigpipe (sock)) { #ifdef ZMQ_HAVE_WINDOWS int rc = closesocket (sock); wsa_assert (rc != SOCKET_ERROR); #else int rc = ::close (sock); errno_assert (rc == 0); #endif return retired_fd; } if (options.tos != 0) set_ip_type_of_service (sock, options.tos); return sock; }
io_thread_t *io_thread_, socket_base_t *socket_, const options_t &options_) : stream_listener_base_t (io_thread_, socket_, options_) { } void zmq::tcp_listener_t::in_event () { fd_t fd = accept (); if (fd == retired_fd) { _socket->event_accept_failed ( make_unconnected_bind_endpoint_pair (_endpoint), zmq_errno ()); return; } int rc = tune_tcp_socket (fd); rc = rc | tune_tcp_keepalives ( fd, options.tcp_keepalive, options.tcp_keepalive_cnt, options.tcp_keepalive_idle, options.tcp_keepalive_intvl); rc = rc | tune_tcp_maxrt (fd, options.tcp_maxrt); if (rc != 0) {
random
[ { "content": " FT_Byte* string; /* this string is *not* null-terminated! */\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftsnames.h", "rank": 0, "score": 203889.44645226406 }, { "content": " FT_Byte* string;\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/tttypes.h", "rank": 1, "score": 201920.61618855584 }, { "content": "class TypeSerializer<std::string>\n\n{\n\npublic:\n\n\tstatic size_t Size(const std::string &value)\n\n\t{\n\n\t\treturn value.length()+1;\n\n\t}\n\n\n\n\tstatic void SerializeTo(DataSerializer &dst, const std::string &src)\n\n\t{\n\n#ifdef _DEBUG\n\n\t\tsize_t bitPos = dst.BitsFilled();\n\n#endif\n\n\t\tdst.AddString(src);\n\n#ifdef _DEBUG\n\n\t\tassert(bitPos + Size(src)*8 == dst.BitsFilled());\n\n#endif\n\n\t}\n\n\n\n\tstatic void DeserializeFrom(DataDeserializer &src, std::string &dst)\n\n\t{\n\n\t\tdst = src.ReadString();\n\n\t}\n\n};\n\n} // ~kNet\n", "file_path": "Source/ThirdParty/kNet/include/kNet/DataSerializer.h", "rank": 2, "score": 178177.17786104788 }, { "content": "class GenericStringBuffer;\n\n\n\ntypedef GenericStringBuffer<UTF8<char>, CrtAllocator> StringBuffer;\n\n\n\n// filereadstream.h\n\n\n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/fwd.h", "rank": 3, "score": 145429.67503816876 }, { "content": "class GenericStringBuffer {\n\npublic:\n\n typedef typename Encoding::Ch Ch;\n\n\n\n GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}\n\n\n\n#if RAPIDJSON_HAS_CXX11_RVALUE_REFS\n\n GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {}\n\n GenericStringBuffer& operator=(GenericStringBuffer&& rhs) {\n\n if (&rhs != this)\n\n stack_ = std::move(rhs.stack_);\n\n return *this;\n\n }\n\n#endif\n\n\n\n void Put(Ch c) { *stack_.template Push<Ch>() = c; }\n\n void PutUnsafe(Ch c) { *stack_.template PushUnsafe<Ch>() = c; }\n\n void Flush() {}\n\n\n\n void Clear() { stack_.Clear(); }\n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/stringbuffer.h", "rank": 4, "score": 145429.67503816876 }, { "content": "struct GenericStringRef;\n\n\n\ntemplate <typename Encoding, typename Allocator> \n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/fwd.h", "rank": 5, "score": 145429.67503816876 }, { "content": "struct GenericStringStream;\n\n\n\ntypedef GenericStringStream<UTF8<char> > StringStream;\n\n\n\ntemplate <typename Encoding>\n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/fwd.h", "rank": 6, "score": 145429.67503816876 }, { "content": "struct GenericStringRef {\n\n typedef CharType Ch; //!< character type of the string\n\n\n\n //! Create string reference from \\c const character array\n\n#ifndef __clang__ // -Wdocumentation\n\n /*!\n\n This constructor implicitly creates a constant string reference from\n\n a \\c const character array. It has better performance than\n\n \\ref StringRef(const CharType*) by inferring the string \\ref length\n\n from the array length, and also supports strings containing null\n\n characters.\n\n\n\n \\tparam N length of the string, automatically inferred\n\n\n\n \\param str Constant character array, lifetime assumed to be longer\n\n than the use of the string in e.g. a GenericValue\n\n\n\n \\post \\ref s == str\n\n\n\n \\note Constant complexity.\n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/document.h", "rank": 7, "score": 145429.67503816876 }, { "content": "capn_ptr capn_new_string(struct capn_segment *seg, const char *str, ssize_t sz) {\n\n\tcapn_ptr p = {CAPN_LIST};\n\n\tp.seg = seg;\n\n\tp.len = ((sz >= 0) ? (size_t)sz : strlen(str)) + 1;\n\n\tp.datasz = 1;\n\n\tnew_object(&p, p.len);\n\n\tif (p.data) {\n\n\t\tmemcpy(p.data, str, p.len - 1);\n\n\t\tp.data[p.len - 1] = '\\0';\n\n\t}\n\n\treturn p;\n", "file_path": "Source/Tools/Game/capn/capn.c", "rank": 8, "score": 143679.04084930403 }, { "content": "\tconst char *query_string; /* URL part after '?', not including '?', or\n", "file_path": "Source/ThirdParty/Civetweb/include/civetweb.h", "rank": 9, "score": 143345.5221400923 }, { "content": "struct GenericInsituStringStream;\n\n\n\ntypedef GenericInsituStringStream<UTF8<char> > InsituStringStream;\n\n\n\n// stringbuffer.h\n\n\n\ntemplate <typename Encoding, typename Allocator>\n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/fwd.h", "rank": 10, "score": 143345.5221400923 }, { "content": " C_STRUCT aiString mName;\n", "file_path": "Source/ThirdParty/Assimp/include/assimp/anim.h", "rank": 11, "score": 141327.201281131 }, { "content": " C_STRUCT aiString mName;\n", "file_path": "Source/ThirdParty/Assimp/include/assimp/camera.h", "rank": 12, "score": 141320.2612572707 }, { "content": "class GenericStringBuffer {\n\npublic:\n\n typedef typename Encoding::Ch Ch;\n\n\n\n GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}\n\n\n\n#if RAPIDJSON_HAS_CXX11_RVALUE_REFS\n\n GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {}\n\n GenericStringBuffer& operator=(GenericStringBuffer&& rhs) {\n\n if (&rhs != this)\n\n stack_ = std::move(rhs.stack_);\n\n return *this;\n\n }\n\n#endif\n\n\n\n void Put(Ch c) { *stack_.template Push<Ch>() = c; }\n\n void Flush() {}\n\n\n\n void Clear() { stack_.Clear(); }\n\n void ShrinkToFit() {\n", "file_path": "Source/ThirdParty/Assimp/contrib/rapidjson/include/rapidjson/stringbuffer.h", "rank": 13, "score": 141320.2612572707 }, { "content": "struct GenericStringRef {\n\n typedef CharType Ch; //!< character type of the string\n\n\n\n //! Create string reference from \\c const character array\n\n /*!\n\n This constructor implicitly creates a constant string reference from\n\n a \\c const character array. It has better performance than\n\n \\ref StringRef(const CharType*) by inferring the string \\ref length\n\n from the array length, and also supports strings containing null\n\n characters.\n\n\n\n \\tparam N length of the string, automatically inferred\n\n\n\n \\param str Constant character array, lifetime assumed to be longer\n\n than the use of the string in e.g. a GenericValue\n\n\n\n \\post \\ref s == str\n\n\n\n \\note Constant complexity.\n\n \\note There is a hidden, private overload to disallow references to\n", "file_path": "Source/ThirdParty/Assimp/contrib/rapidjson/include/rapidjson/document.h", "rank": 14, "score": 141320.2612572707 }, { "content": " FT_UInt string_len; /* in bytes */\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftsnames.h", "rank": 15, "score": 139359.43465342338 }, { "content": " FT_Byte* strings;\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/tttypes.h", "rank": 16, "score": 139351.43099356248 }, { "content": " FT_Raster_NewFunc raster_new;\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftimage.h", "rank": 17, "score": 139334.5275320568 }, { "content": "", "file_path": "Source/ThirdParty/Assimp/contrib/irrXML/irrString.h", "rank": 18, "score": 139322.9958108139 }, { "content": "static MOJOSHADER_astExpression *new_literal_string_expr(Context *ctx,\n\n const char *string)\n\n{\n\n NEW_AST_NODE(retval, MOJOSHADER_astExpressionStringLiteral,\n\n MOJOSHADER_AST_OP_STRING_LITERAL);\n\n retval->datatype = &ctx->dt_string;\n\n retval->string = string; // cached; don't copy string.\n\n return (MOJOSHADER_astExpression *) retval;\n", "file_path": "Source/ThirdParty/MojoShader/mojoshader_compiler.c", "rank": 19, "score": 137764.4611777328 }, { "content": " FT_ULong strings_size;\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/tttypes.h", "rank": 20, "score": 137436.7052337791 }, { "content": "IK_PUBLIC_API void\n", "file_path": "Source/ThirdParty/ik/include/ik/memory.h", "rank": 21, "score": 137436.7052337791 }, { "content": " FT_ULong stringOffset;\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/tttypes.h", "rank": 22, "score": 137436.7052337791 }, { "content": " FT_UShort stringLength;\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/tttypes.h", "rank": 23, "score": 137436.7052337791 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_Stroker_New( FT_Library library,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftstroke.h", "rank": 24, "score": 137428.91630624753 }, { "content": " FT_EXPORT( FT_Error )\n\n FTC_Manager_New( FT_Library library,\n\n FT_UInt max_faces,\n\n FT_UInt max_sizes,\n\n FT_ULong max_bytes,\n\n FTC_Face_Requester requester,\n\n FT_Pointer req_data,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftcache.h", "rank": 25, "score": 137420.0340303345 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_Outline_New( FT_Library library,\n\n FT_UInt numPoints,\n\n FT_Int numContours,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftoutln.h", "rank": 26, "score": 137420.0340303345 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_New_Face( FT_Library library,\n\n const char* filepathname,\n\n FT_Long face_index,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/freetype.h", "rank": 27, "score": 137420.0340303345 }, { "content": " FT_EXPORT( void )\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftbitmap.h", "rank": 28, "score": 137420.0340303345 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_New_Library( FT_Memory memory,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftmodapi.h", "rank": 29, "score": 137420.0340303345 }, { "content": "FT_BEGIN_HEADER\n\n\n\n\n\n /*************************************************************************/\n\n /* */\n\n /* <Section> */\n\n /* sizes_management */\n\n /* */\n\n /* <Title> */\n\n /* Size Management */\n\n /* */\n\n /* <Abstract> */\n\n /* Managing multiple sizes per face. */\n\n /* */\n\n /* <Description> */\n\n /* When creating a new face object (e.g., with @FT_New_Face), an */\n\n /* @FT_Size object is automatically created and used to store all */\n\n /* pixel-size dependent information, available in the `face->size' */\n\n /* field. */\n\n /* */\n\n /* It is however possible to create more sizes for a given face, */\n\n /* mostly in order to manage several character pixel sizes of the */\n\n /* same font family and style. See @FT_New_Size and @FT_Done_Size. */\n\n /* */\n\n /* Note that @FT_Set_Pixel_Sizes and @FT_Set_Char_Size only */\n\n /* modify the contents of the current `active' size; you thus need */\n\n /* to use @FT_Activate_Size to change it. */\n\n /* */\n\n /* 99% of applications won't need the functions provided here, */\n\n /* especially if they use the caching sub-system, so be cautious */\n\n /* when using these. */\n\n /* */\n\n /*************************************************************************/\n\n\n\n\n\n /*************************************************************************/\n\n /* */\n\n /* <Function> */\n\n /* FT_New_Size */\n\n /* */\n\n /* <Description> */\n\n /* Create a new size object from a given face object. */\n\n /* */\n\n /* <Input> */\n\n /* face :: A handle to a parent face object. */\n\n /* */\n\n /* <Output> */\n\n /* asize :: A handle to a new size object. */\n\n /* */\n\n /* <Return> */\n\n /* FreeType error code. 0~means success. */\n\n /* */\n\n /* <Note> */\n\n /* You need to call @FT_Activate_Size in order to select the new size */\n\n /* for upcoming calls to @FT_Set_Pixel_Sizes, @FT_Set_Char_Size, */\n\n /* @FT_Load_Glyph, @FT_Load_Char, etc. */\n\n /* */\n\n FT_EXPORT( FT_Error )\n\n FT_New_Size( FT_Face face,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftsizes.h", "rank": 30, "score": 137420.0340303345 }, { "content": " FT_BASE( FT_Error )\n\n FT_Stream_New( FT_Library library,\n\n const FT_Open_Args* args,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/ftstream.h", "rank": 31, "score": 135565.18814619308 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_New_Memory_Face( FT_Library library,\n\n const FT_Byte* file_base,\n\n FT_Long file_size,\n\n FT_Long face_index,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/freetype.h", "rank": 32, "score": 135557.43873422543 }, { "content": " FT_EXPORT( FT_Error )\n\n FTC_ImageCache_New( FTC_Manager manager,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftcache.h", "rank": 33, "score": 135557.43873422543 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_Outline_New_Internal( FT_Memory memory,\n\n FT_UInt numPoints,\n\n FT_Int numContours,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftoutln.h", "rank": 34, "score": 135557.43873422543 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_New_Face_From_FOND( FT_Library library,\n\n Handle fond,\n\n FT_Long face_index,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftmac.h", "rank": 35, "score": 135557.43873422543 }, { "content": " const char *string;\n", "file_path": "Source/ThirdParty/MojoShader/mojoshader.h", "rank": 36, "score": 135469.9698167737 }, { "content": " char *string;\n", "file_path": "Source/ThirdParty/MojoShader/mojoshader_common.c", "rank": 37, "score": 134417.39959393124 }, { "content": "struct BoneWithHash : public std::pair<uint32_t,aiString*> {\n\n std::vector<BoneSrcIndex> pSrcBones;\n\n};\n\n\n\n// ---------------------------------------------------------------------------\n\n/** @brief Utility for SceneCombiner\n\n */\n", "file_path": "Source/ThirdParty/Assimp/include/assimp/SceneCombiner.h", "rank": 38, "score": 133760.88489754472 }, { "content": " FT_EXPORT( FT_Error )\n\n FTC_CMapCache_New( FTC_Manager manager,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftcache.h", "rank": 39, "score": 133753.3459058579 }, { "content": " FT_BASE( FT_Error )\n\n FT_GlyphLoader_New( FT_Memory memory,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/ftgloadr.h", "rank": 40, "score": 133752.58444997115 }, { "content": " FT_BASE( FT_Error )\n\n FT_CMap_New( FT_CMap_Class clazz,\n\n FT_Pointer init_data,\n\n FT_CharMap charmap,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/ftobjs.h", "rank": 41, "score": 133752.52508592792 }, { "content": " FT_BASE( FT_Error )\n\n FT_New_GlyphSlot( FT_Face face,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/internal/ftobjs.h", "rank": 42, "score": 133744.65957461327 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_New_Face_From_FSRef( FT_Library library,\n\n const FSRef *ref,\n\n FT_Long face_index,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftmac.h", "rank": 43, "score": 133744.65957461327 }, { "content": " FT_EXPORT( FT_Error )\n\n FTC_SBitCache_New( FTC_Manager manager,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftcache.h", "rank": 44, "score": 133744.65957461327 }, { "content": " FT_EXPORT( FT_Error )\n\n FT_New_Face_From_FSSpec( FT_Library library,\n\n const FSSpec *spec,\n\n FT_Long face_index,\n", "file_path": "Source/ThirdParty/FreeType/include/freetype/ftmac.h", "rank": 45, "score": 133744.65957461327 }, { "content": " AF_Blue_String string;\n", "file_path": "Source/ThirdParty/FreeType/src/autofit/afblue.h", "rank": 46, "score": 133402.29025566715 }, { "content": "bool isStringLiteral( const T in ) {\n\n return ( in == '\\\"' );\n", "file_path": "Source/ThirdParty/Assimp/contrib/openddlparser/include/openddlparser/OpenDDLParserUtils.h", "rank": 47, "score": 131995.7355934871 }, { "content": "bool isNewLine( const T in ) {\n\n return ( '\\n' == in || ( '\\r' == in ) );\n", "file_path": "Source/ThirdParty/Assimp/contrib/openddlparser/include/openddlparser/OpenDDLParserUtils.h", "rank": 48, "score": 131979.72438484998 }, { "content": "struct TypeHelper<ValueType, std::basic_string<typename ValueType::Ch> > {\n\n typedef std::basic_string<typename ValueType::Ch> StringType;\n\n static bool Is(const ValueType& v) { return v.IsString(); }\n\n static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); }\n\n static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }\n\n};\n\n#endif\n\n\n\ntemplate<typename ValueType> \n", "file_path": "Source/ThirdParty/rapidjson/include/rapidjson/document.h", "rank": 49, "score": 130276.5664154469 }, { "content": "class String\n\n{\n\npublic:\n\n~String();\n\nString();\n\nString(const String&in);\n\nString(int);\n\nString(uint);\n\nString(float);\n\nString(double);\n\nString(bool);\n\nString(const char*);\n\n// Methods:\n\nvoid AppendUTF8(uint);\n\nuint AtUTF8(uint) const;\n\nuint ByteOffsetUTF8(uint) const;\n\nvoid Clear();\n\nint Compare(const String&, bool = true) const;\n\nbool Contains(const String&, bool = true) const;\n\nbool Contains(uint8, bool = true) const;\n", "file_path": "Docs/AngelScriptAPI.h", "rank": 50, "score": 129371.71752746878 }, { "content": "class String;\n", "file_path": "Source/Urho3D/Container/Swap.h", "rank": 51, "score": 128158.24407462322 }, { "content": "class String;\n\n\n", "file_path": "Source/Urho3D/Math/Color.h", "rank": 52, "score": 128158.24407462322 }, { "content": "/// %String class.\n\nclass URHO3D_API String\n\n{\n\npublic:\n\n using Iterator = RandomAccessIterator<char>;\n\n using ConstIterator = RandomAccessConstIterator<char>;\n\n\n\n /// Construct empty.\n\n String() noexcept :\n\n length_(0),\n\n capacity_(0),\n\n buffer_(&endZero)\n\n {\n\n }\n\n\n\n /// Construct from another string.\n\n String(const String& str) :\n\n length_(0),\n\n capacity_(0),\n\n buffer_(&endZero)\n\n {\n", "file_path": "Source/Urho3D/Container/Str.h", "rank": 53, "score": 117790.95285905895 }, { "content": " // -------------------------------------------------------------------------------\n\n class ENUMERATION : public STRING\n\n {\n\n public:\n\n\n\n ENUMERATION (const std::string& val)\n\n : STRING(val)\n\n {}\n\n\n\n private:\n\n };\n\n\n\n typedef ENUMERATION BOOLEAN;\n\n\n\n // -------------------------------------------------------------------------------\n\n /** This is just a reference to an entity/object somewhere else */\n", "file_path": "Source/ThirdParty/Assimp/code/STEPFile.h", "rank": 54, "score": 109749.75843177989 }, { "content": "struct sql_ctype<nanodbc::string>\n\n{\n\n#ifdef NANODBC_ENABLE_UNICODE\n\n static const SQLSMALLINT value = SQL_C_WCHAR;\n\n#else\n\n static const SQLSMALLINT value = SQL_C_CHAR;\n\n#endif\n\n};\n\n\n\ntemplate <>\n", "file_path": "Source/ThirdParty/nanodbc/nanodbc/nanodbc.cpp", "rank": 55, "score": 108705.13100271505 }, { "content": "struct sql_ctype<nanodbc::string::value_type>\n\n{\n\n#ifdef NANODBC_ENABLE_UNICODE\n\n static const SQLSMALLINT value = SQL_C_WCHAR;\n\n#else\n\n static const SQLSMALLINT value = SQL_C_CHAR;\n\n#endif\n\n};\n\n\n\ntemplate <>\n", "file_path": "Source/ThirdParty/nanodbc/nanodbc/nanodbc.cpp", "rank": 56, "score": 102262.77069226523 }, { "content": "class asCString\n\n{\n\npublic:\n\n\tasCString();\n\n\t~asCString();\n\n\n\n#ifdef AS_CAN_USE_CPP11\n\n\tasCString(asCString &&);\n\n\tasCString &operator =(asCString &&);\n\n#endif // c++11\n\n\n\n\tasCString(const asCString &);\n\n\tasCString(const char *);\n\n\tasCString(const char *, size_t length);\n\n\texplicit asCString(char);\n\n\n\n\tvoid Allocate(size_t len, bool keepData);\n\n\tvoid SetLength(size_t len);\n\n\tsize_t GetLength() const;\n\n\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string.h", "rank": 57, "score": 89347.74832264139 }, { "content": "/// 32-bit hash value for a string.\n\nclass URHO3D_API StringHash\n\n{\n\npublic:\n\n /// Construct with zero value.\n\n StringHash() noexcept :\n\n value_(0)\n\n {\n\n }\n\n\n\n /// Copy-construct from another hash.\n\n StringHash(const StringHash& rhs) noexcept = default;\n\n\n\n /// Construct with an initial value.\n\n explicit StringHash(unsigned value) noexcept :\n\n value_(value)\n\n {\n\n }\n\n\n\n /// Construct from a C string case-insensitively.\n\n StringHash(const char* str) noexcept; // NOLINT(google-explicit-constructor)\n", "file_path": "Source/Urho3D/Math/StringHash.h", "rank": 58, "score": 88566.56749520356 }, { "content": "// a wrapper for using the pointer of asCString in asCMap\n\nclass asCStringPointer\n\n{\n\npublic:\n\n\tasCStringPointer();\n\n\tasCStringPointer(const char *str, size_t len);\n\n\tasCStringPointer(asCString *cstr);\n\n\n\n\tconst char *AddressOf() const;\n\n\tsize_t GetLength() const;\n\n\n\n\tbool operator==(const asCStringPointer& other) const;\n\n\tbool operator<(const asCStringPointer& other) const;\n\n\n\nprivate:\n\n\t// Either string/length or cstring is stored\n\n\tconst char *string;\n\n\tsize_t length;\n\n\tasCString *cstring;\n\n};\n\n\n\n#endif\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string.h", "rank": 59, "score": 88566.39032753753 }, { "content": "#define lib_string_c\n", "file_path": "Source/ThirdParty/LuaJIT/src/lib_string.c", "rank": 60, "score": 86279.49031135095 }, { "content": "BEGIN_AS_NAMESPACE\n\n\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string_util.h", "rank": 61, "score": 86272.72996888023 }, { "content": "LUALIB_API int luaopen_string(lua_State *L)\n\n{\n\n GCtab *mt;\n\n global_State *g;\n\n LJ_LIB_REG(L, LUA_STRLIBNAME, string);\n\n#if defined(LUA_COMPAT_GFIND) && !LJ_52\n\n lua_getfield(L, -1, \"gmatch\");\n\n lua_setfield(L, -2, \"gfind\");\n\n#endif\n\n mt = lj_tab_new(L, 0, 1);\n\n /* NOBARRIER: basemt is a GC root. */\n\n g = G(L);\n\n setgcref(basemt_it(g, LJ_TSTR), obj2gco(mt));\n\n settabV(L, lj_tab_setstr(L, mt, mmname_str(g, MM_index)), tabV(L->top-1));\n\n mt->nomm = (uint8_t)(~(1u<<MM_index));\n\n return 1;\n", "file_path": "Source/ThirdParty/LuaJIT/src/lib_string.c", "rank": 62, "score": 86272.72996888023 }, { "content": "int asStringDecodeUTF8(const char *encodedBuffer, unsigned int *outLength);\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string_util.h", "rank": 63, "score": 85536.76535775581 }, { "content": "static GCstr *string_fmt_tostring(lua_State *L, int arg, int retry)\n\n{\n\n TValue *o = L->base+arg-1;\n\n cTValue *mo;\n\n lua_assert(o < L->top); /* Caller already checks for existence. */\n\n if (LJ_LIKELY(tvisstr(o)))\n\n return strV(o);\n\n if (retry != 2 && !tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) {\n\n copyTV(L, L->top++, mo);\n\n copyTV(L, L->top++, o);\n\n lua_call(L, 1, 1);\n\n copyTV(L, L->base+arg-1, --L->top);\n\n return NULL; /* Buffer may be overwritten, retry. */\n\n }\n\n return lj_strfmt_obj(L, o);\n", "file_path": "Source/ThirdParty/LuaJIT/src/lib_string.c", "rank": 64, "score": 85536.76535775581 }, { "content": "int asStringEncodeUTF16(unsigned int value, char *outEncodedBuffer);\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string_util.h", "rank": 65, "score": 85536.76535775581 }, { "content": "double asStringScanDouble(const char *string, size_t *numScanned);\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string_util.h", "rank": 66, "score": 85536.76535775581 }, { "content": "int asStringEncodeUTF8(unsigned int value, char *outEncodedBuffer);\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string_util.h", "rank": 67, "score": 85536.76535775581 }, { "content": "#define LJLIB_MODULE_string\n\n\n", "file_path": "Source/ThirdParty/LuaJIT/src/lib_string.c", "rank": 68, "score": 85536.76535775581 }, { "content": "asQWORD asStringScanUInt64(const char *string, int base, size_t *numScanned, bool *overflow);\n", "file_path": "Source/ThirdParty/AngelScript/source/as_string_util.h", "rank": 69, "score": 84813.25108648403 }, { "content": "struct FIStringValueImpl: public FIStringValue {\n\n inline FIStringValueImpl(std::string &&value_) { value = std::move(value_); }\n\n virtual const std::string &toString() const /*override*/ { return value; }\n\n};\n\n\n\nstd::shared_ptr<FIStringValue> FIStringValue::create(std::string &&value) {\n\n return std::make_shared<FIStringValueImpl>(std::move(value));\n\n}\n\n\n", "file_path": "Source/ThirdParty/Assimp/code/FIReader.cpp", "rank": 70, "score": 84101.87387071415 }, { "content": "public class Urho3D_MapNew extends SDLActivity implements AMapNaviViewListener, AMapNaviListener, AMap.OnMapLongClickListener, AimlessModeListener {\n\n\n\n static final String SCRIPTS = \"scripts\";\n\n static final String PICKED_SCRIPT = \"pickedScript\";\n\n private static final String TAG = \"Urho3D\";\n\n private static final int OBTAINING_SCRIPT = 1;\n\n private static String[] mArguments = new String[0];\n\n\n\n protected AMapNavi mAMapNavi;\n\n protected MapView mAmapView;\n\n protected AMap mAmap;\n\n\n\n // 是否需要跟随定位\n\n private boolean isNeedFollow = true;\n\n\n\n private static final int SET_IP = 2;\n\n private static final int NAVI_INIT = 4;\n\n private static final int NAVI_ROUTE_NOTIFY = 5;\n\n private static final int NAVI_ARRIVED = 6;\n\n private static final int NAVI_TEXT = 7;\n\n private static final int NAVI_INFO = 8;\n\n private static final int NAVI_MAP_TYPE = 9;\n\n private static final int NAVI_CAMERA_INFO = 10;\n\n private static final int NAVI_INFO2 = 11;\n\n private static final int NAVI_FACILITY = 12;\n\n\n\n private boolean init_called = false;\n\n\n\n public static final int RUN_NAVI = 0;\n\n public static final int RUN_SIM = 1;\n\n public static final int RUN_MAP = 2;\n\n public static int run_type = RUN_NAVI;\n\n\n\n private static final int FROM_NATIVE_GPS = 100;\n\n\n\n public static String IP_ADDRESS;\n\n\n\n private Marker myLocationMarker;\n\n // 处理静止后跟随的timer\n\n private Timer needFollowTimer;\n\n // 屏幕静止DELAY_TIME之后,再次跟随\n\n private long DELAY_TIME = 5000;\n\n\n\n private int BASE_ZOOM = 17;\n\n\n\n @Override\n\n protected String[] getArguments() {\n\n return mArguments;\n\n }\n\n\n\n @Override\n\n protected boolean onLoadLibrary(ArrayList<String> libraryNames) {\n\n // Ensure \"Urho3D\" shared library (if any) and \"Urho3DPlayer\" are being sorted to the top of the list\n\n // Also ensure STL runtime shared library (if any) is sorted to the top most entry\n\n Collections.sort(libraryNames, new Comparator<String>() {\n\n private String sortName(String name) {\n\n return name.matches(\"^\\\\d+_.+$\") ? name : (name.matches(\"^.+_shared$\") ? \"0000_\" : \"000_\") + name;\n\n }\n\n\n\n @Override\n\n public int compare(String lhs, String rhs) {\n\n return sortName(lhs).compareTo(sortName(rhs));\n\n }\n\n });\n\n\n\n // All shared shared libraries must always be loaded if available, so exclude it from return result and all list operations below\n\n int startIndex = libraryNames.indexOf(\"Game\");\n\n\n\n // Determine the intention\n\n Intent intent = getIntent();\n\n String pickedLibrary = intent.getStringExtra(SampleLauncher.PICKED_LIBRARY);\n\n if (pickedLibrary == null) {\n\n // Intention for obtaining library names\n\n String[] array = libraryNames.subList(startIndex, libraryNames.size()).toArray(new String[libraryNames.size() - startIndex]);\n\n if (array.length > 1) {\n\n setResult(RESULT_OK, intent.putExtra(SampleLauncher.LIBRARY_NAMES, array));\n\n\n\n // End Urho3D activity lifecycle\n\n finish();\n\n\n\n // Return false to indicate no library is being loaded yet\n\n return false;\n\n } else {\n\n // There is only one library available, so cancel the intention for obtaining the library name and by not returning any result\n\n // However, since we have already started Urho3D activity, let's the activity runs its whole lifecycle by falling through to call the super implementation\n\n setResult(RESULT_CANCELED);\n\n }\n\n } else {\n\n // Intention for loading a picked library name (and remove all others)\n\n libraryNames.subList(startIndex, libraryNames.size()).clear();\n\n mArguments = pickedLibrary.split(\":\");\n\n libraryNames.add(mArguments[0]);\n\n if (\"Urho3DPlayer\".equals(mArguments[0]) && mArguments.length == 1) {\n\n // Urho3DPlayer needs a script name to play\n\n try {\n\n final AssetManager assetManager = getAssets();\n\n HashMap<String, ArrayList<String>> scripts = new HashMap<String, ArrayList<String>>(2) {{\n\n put(\"AngelScript\", new ArrayList<>(Arrays.asList(assetManager.list(\"Data/Scripts\"))));\n\n put(\"Lua\", new ArrayList<>(Arrays.asList(assetManager.list(\"Data/LuaScripts\"))));\n\n }};\n\n startActivityForResult(new Intent(this, ScriptPicker.class).putExtra(SCRIPTS, scripts), OBTAINING_SCRIPT);\n\n } catch (IOException e) {\n\n Log.e(TAG, \"Could not scan assets directory for playable scripts\", e);\n\n }\n\n }\n\n }\n\n\n\n return super.onLoadLibrary(libraryNames);\n\n }\n\n\n\n @Override\n\n protected void onCreate(Bundle savedInstanceState) {\n\n\n\n Log.i(TAG, \"onCreate !!!\");\n\n super.onCreate(savedInstanceState);\n\n\n\n mAMapNavi.addAMapNaviListener(this);\n\n\n\n mAmapView.onCreate(savedInstanceState);\n\n mAmap = mAmapView.getMap();\n\n mAmap.setOnMapLongClickListener(this);\n\n\n\n Log.i(TAG, \"startAimlessMode\");\n\n mAMapNavi.startAimlessMode(AimLessMode.CAMERA_AND_SPECIALROAD_DETECTED);\n\n mAMapNavi.addAimlessModeListener(this);\n\n mAmap.setTrafficEnabled(true);\n\n\n\n //mAmap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口\n\n //mAmap.getUiSettings().setMyLocationButtonEnabled(true); // 是否显示定位按钮\n\n //mAmap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase\n\n mAmap.moveCamera(CameraUpdateFactory.zoomTo(BASE_ZOOM));//设置地图缩放级别\n\n// MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类\n\n// myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。\n\n// myLocationStyle.strokeColor(Color.TRANSPARENT);//设置定位蓝点精度圆圈的边框颜色\n\n// myLocationStyle.radiusFillColor(Color.TRANSPARENT);//设置定位蓝点精度圆圈的填充颜色\n\n// mAmap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style\n\n\n\n LocalTime time = LocalTime.now();\n\n if (time.getHour() >= 17 || time.getHour() <= 5)\n\n {\n\n mAmap.setMapType(AMap.MAP_TYPE_NIGHT);\n\n }\n\n //\n\n\n\n init_called = false;\n\n\n\n // 初始化 显示我的位置的Marker\n\n myLocationMarker = mAmap.addMarker(new MarkerOptions()\n\n .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory\n\n .decodeResource(getResources(), R.drawable.car))));\n\n\n\n setMapInteractiveListener();\n\n\n\n // Log.i(TAG, \"WTF !!!\");\n\n SDLActivity.onNativeMessage(NAVI_INIT, (double)mAMapNavi.getNaviType(), 0, 0, \"Init NAVI\");\n\n SDLActivity.onNativeMessage(SET_IP, 0, 0, 0, IP_ADDRESS);\n\n SDLActivity.onNativeMessage(9, (double) mAmap.getMapType(), 0, 0, \"\");\n\n }\n\n\n\n @Override\n\n protected void onInitLayout() {\n\n setContentView(R.layout.activity_basic_map);\n\n mSurface = findViewById(R.id.sdl_view);\n\n mAmapView = findViewById(R.id.map_view);\n\n mAMapNavi = AMapNavi.getInstance(getApplicationContext());\n\n mLayout = findViewById(R.id.basic_map);\n\n Log.i(TAG, \"layout init OK\");\n\n }\n\n\n\n /**\n\n * 方法必须重写\n\n */\n\n @Override\n\n protected void onResume() {\n\n super.onResume();\n\n mAmapView.onResume();\n\n }\n\n\n\n /**\n\n * 方法必须重写\n\n */\n\n @Override\n\n protected void onPause() {\n\n super.onPause();\n\n mAmapView.onPause();\n\n }\n\n\n\n /**\n\n * 方法必须重写\n\n */\n\n @Override\n\n protected void onSaveInstanceState(Bundle outState) {\n\n super.onSaveInstanceState(outState);\n\n mAmapView.onSaveInstanceState(outState);\n\n }\n\n\n\n @Override\n\n protected void onDestroy() {\n\n Log.i(TAG, \"onDestroy !!!\");\n\n mAMapNavi.stopAimlessMode();\n\n super.onDestroy();\n\n }\n\n\n\n @Override\n\n protected void onStop() {\n\n Log.i(TAG, \"onStop !!!\");\n\n super.onStop();\n\n finish();\n\n }\n\n\n\n @Override\n\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\n if (OBTAINING_SCRIPT != requestCode || RESULT_CANCELED == resultCode)\n\n return;\n\n String script = data.getStringExtra(PICKED_SCRIPT);\n\n script = (script.endsWith(\".as\") ? \"Scripts/\" : \"LuaScripts/\") + script;\n\n mArguments = new String[]{mArguments[0], script};\n\n }\n\n\n\n @Override\n\n public void onInitNaviFailure() {\n\n }\n\n\n\n @Override\n\n public void onInitNaviSuccess() {\n\n }\n\n\n\n @Override\n\n public void onStartNavi(int type) {\n\n //开始导航回调\n\n SDLActivity.onNativeMessage(0, (double) type, 0, 0, \"\");\n\n }\n\n\n\n @Override\n\n public void onTrafficStatusUpdate() {\n\n //\n\n }\n\n\n\n @Override\n\n public void onLocationChange(AMapNaviLocation location) {\n\n //当前位置回调\n\n\n\n if (location != null) {\n\n LatLng latLng = new LatLng(location.getCoord().getLatitude(),\n\n location.getCoord().getLongitude());\n\n // 显示定位小图标,初始化时已经创建过了,这里修改位置即可\n\n myLocationMarker.setPosition(latLng);\n\n if (isNeedFollow) {\n\n // 跟随\n\n mAmap.animateCamera(CameraUpdateFactory.changeLatLng(latLng));\n\n mAmap.moveCamera(CameraUpdateFactory.zoomTo(BASE_ZOOM));//设置地图缩放级别\n\n }\n\n } else {\n\n// Toast.makeText(IntelligentBroadcastActivity.this, \"定位出现异常\",\n\n// Toast.LENGTH_SHORT).show();\n\n }\n\n }\n\n\n\n @Override\n\n public void onGetNavigationText(int type, String text) {\n\n //播报类型和播报文字回调\n\n SDLActivity.onNativeMessage(NAVI_TEXT, 0, 0, 0, text);\n\n }\n\n\n\n @Override\n\n public void onGetNavigationText(String s) {\n\n SDLActivity.onNativeMessage(NAVI_TEXT, 0, 0, 0, s);\n\n }\n\n\n\n @Override\n\n public void onEndEmulatorNavi() {\n\n //结束模拟导航\n\n }\n\n\n\n @Override\n\n public void onArriveDestination() {\n\n //到达目的地\n\n SDLActivity.onNativeMessage(NAVI_ARRIVED, 0, 0, 0, \"\");\n\n }\n\n\n\n @Override\n\n public void onCalculateRouteFailure(int errorInfo) {\n\n //路线计算失败\n\n //Log.e(\"dm\", \"--------------------------------------------\");\n\n //Log.i(\"dm\", \"路线计算失败:错误码=\" + errorInfo + \",Error Message= \" + ErrorInfo.getError(errorInfo));\n\n //Log.i(\"dm\", \"错误码详细链接见:http://lbs.amap.com/api/android-navi-sdk/guide/tools/errorcode/\");\n\n //Log.e(\"dm\", \"--------------------------------------------\");\n\n //Toast.makeText(this, \"errorInfo:\" + errorInfo + \",Message:\" + ErrorInfo.getError(errorInfo), Toast.LENGTH_LONG).show();\n\n }\n\n\n\n @Override\n\n public void onReCalculateRouteForYaw() {\n\n //偏航后重新计算路线回调\n\n }\n\n\n\n @Override\n\n public void onReCalculateRouteForTrafficJam() {\n\n //拥堵后重新计算路线回调\n\n }\n\n\n\n @Override\n\n public void onArrivedWayPoint(int wayID) {\n\n //到达途径点\n\n }\n\n\n\n @Override\n\n public void onGpsOpenStatus(boolean enabled) {\n\n //GPS开关状态回调\n\n }\n\n\n\n @Override\n\n public void onNaviSetting() {\n\n //底部导航设置点击回调\n\n }\n\n\n\n @Override\n\n public void onNaviMapMode(int naviMode) {\n\n //导航态车头模式,0:车头朝上状态;1:正北朝上模式。\n\n }\n\n\n\n @Override\n\n public void onNaviCancel() {\n\n finish();\n\n }\n\n\n\n\n\n @Override\n\n public void onNaviTurnClick() {\n\n //转弯view的点击回调\n\n }\n\n\n\n @Override\n\n public void onNextRoadClick() {\n\n //下一个道路View点击回调\n\n }\n\n\n\n\n\n @Override\n\n public void onScanViewButtonClick() {\n\n //全览按钮点击回调\n\n\n\n }\n\n\n\n @Override\n\n public void updateCameraInfo(AMapNaviCameraInfo[] aMapCameraInfos) {\n\n try {\n\n for (int i = 0; i < aMapCameraInfos.length; ++i) {\n\n SDLActivity.onNativeMessage(NAVI_CAMERA_INFO,\n\n (double) aMapCameraInfos[i].getCameraType(),\n\n (double) aMapCameraInfos[i].getCameraSpeed(),\n\n (double) aMapCameraInfos[i].getCameraDistance(),\n\n \"\");\n\n }\n\n }\n\n catch(Exception e) {\n\n Log.w(TAG, e.getMessage());\n\n }\n\n }\n\n\n\n @Override\n\n public void onServiceAreaUpdate(AMapServiceAreaInfo[] amapServiceAreaInfos) {\n\n\n\n }\n\n\n\n @Override\n\n public void onNaviInfoUpdate(NaviInfo info) {\n\n\n\n if (!init_called) {\n\n init_called = true;\n\n SDLActivity.onNativeMessage(NAVI_INIT, (double) mAMapNavi.getNaviType(), 0, 0, \"Init NAVI\");\n\n SDLActivity.onNativeMessage(NAVI_MAP_TYPE, (double) mAmap.getMapType(), 0, 0, \"\");\n\n }\n\n\n\n //导航过程中的信息更新,请看NaviInfo的具体说明\n\n String info_text = \"\";\n\n\n\n try {\n\n AMapExitDirectionInfo exit = info.getExitDirectionInfo();\n\n if (exit.getExitNameInfo().length > 0) {\n\n info_text = exit.getExitNameInfo()[0];\n\n }\n\n }\n\n catch(Exception e) {\n\n Log.w(TAG, e.getMessage());\n\n }\n\n\n\n SDLActivity.onNativeMessage(NAVI_INFO,\n\n (double) info.getCurStepRetainDistance(),\n\n (double) info.getCurStepRetainTime(),\n\n (double) info.getIconType(),\n\n info_text);\n\n\n\n SDLActivity.onNativeMessage(NAVI_INFO2,\n\n (double) info.getPathRetainDistance(),\n\n (double) info.getPathRetainTime(),\n\n (double) info.getCurStep(),\n\n info.getNextRoadName());\n\n\n\n// Log.d(TAG, info.getCurrentRoadName() + \" retain_dist:\" + info.getCurStepRetainDistance());\n\n//\n\n// AMapExitDirectionInfo exit = info.getExitDirectionInfo();\n\n// for (int i=0; i<exit.getDirectionInfo().length; ++i)\n\n// {\n\n// Log.d(TAG, \"exit dir: \" + exit.getDirectionInfo()[i]);\n\n// }\n\n//\n\n// for (int i=0; i<exit.getExitNameInfo().length; ++i)\n\n// {\n\n// Log.d(TAG, \"exit name: \" + exit.getExitNameInfo()[i]);\n\n// }\n\n }\n\n\n\n @Override\n\n public void showCross(AMapNaviCross aMapNaviCross) {\n\n //显示转弯回调\n\n }\n\n\n\n @Override\n\n public void hideCross() {\n\n //隐藏转弯回调\n\n }\n\n\n\n @Override\n\n public void showLaneInfo(AMapLaneInfo[] laneInfos, byte[] laneBackgroundInfo, byte[] laneRecommendedInfo) {\n\n //显示车道信息\n\n\n\n }\n\n\n\n @Override\n\n public void hideLaneInfo() {\n\n //隐藏车道信息\n\n }\n\n\n\n @Override\n\n public void onCalculateRouteSuccess(int[] ints) {\n\n //多路径算路成功回调\n\n SDLActivity.onNativeMessage(2, 0, 0, 0, \"onCalculateRouteSuccess\");\n\n }\n\n\n\n @Override\n\n public void notifyParallelRoad(int i) {\n\n }\n\n\n\n @Override\n\n public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {\n\n //更新巡航模式的统计信息\n\n }\n\n\n\n\n\n @Override\n\n public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {\n\n //更新巡航模式的拥堵信息\n\n }\n\n\n\n @Override\n\n public void onPlayRing(int i) {\n\n\n\n }\n\n\n\n @Override\n\n public void onLockMap(boolean isLock) {\n\n //锁地图状态发生变化时回调\n\n }\n\n\n\n @Override\n\n public void onNaviViewLoaded() {\n\n Log.d(TAG, \"导航页面加载成功\");\n\n Log.d(TAG, \"请不要使用AMapNaviView.getMap().setOnMapLoadedListener();会overwrite导航SDK内部画线逻辑\");\n\n }\n\n\n\n @Override\n\n public void onMapTypeChanged(int i) {\n\n SDLActivity.onNativeMessage(NAVI_MAP_TYPE, (double) i, 0, 0, \"\");\n\n }\n\n\n\n @Override\n\n public void onNaviViewShowMode(int i) {\n\n\n\n }\n\n\n\n @Override\n\n public boolean onNaviBackClick() {\n\n return false;\n\n }\n\n\n\n\n\n @Override\n\n public void showModeCross(AMapModelCross aMapModelCross) {\n\n\n\n }\n\n\n\n @Override\n\n public void hideModeCross() {\n\n\n\n }\n\n\n\n @Override\n\n public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {\n\n\n\n }\n\n\n\n @Override\n\n public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {\n\n\n\n }\n\n\n\n @Override\n\n public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {\n\n\n\n }\n\n\n\n @Override\n\n public void onCalculateRouteFailure(AMapCalcRouteResult aMapCalcRouteResult) {\n\n\n\n }\n\n\n\n @Override\n\n public void onNaviRouteNotify(AMapNaviRouteNotifyData aData) {\n\n Log.i(TAG, \"onNaviRouteNotify\" + aData.getReason());\n\n SDLActivity.onNativeMessage(NAVI_ROUTE_NOTIFY,\n\n (double) aData.getDistance(),\n\n aData.getLatitude(),\n\n aData.getLongitude(),\n\n aData.getReason());\n\n }\n\n\n\n @Override\n\n protected void onMessage2(int cmd, double data1, double data2, double data3, double data4, double data5)\n\n {\n\n Log.i(TAG, \"onMessage2 \" + cmd + \" \" + data1 + \" \" + data2 + \" \" + data3 + \" \" + data4 + \" \" + data5);\n\n if (cmd == FROM_NATIVE_GPS)\n\n {\n\n Location location = new Location(\"GPS\");\n\n location.setLongitude(data1);\n\n location.setLatitude(data2);\n\n location.setSpeed((float)data3);\n\n location.setAccuracy((float)data4);\n\n location.setBearing((float)data5);\n\n location.setTime(System.currentTimeMillis());\n\n //以上6项数据缺一不可\n\n Log.i(TAG, \"setExtraGPSData\");\n\n mAMapNavi.setExtraGPSData(1,location);\n\n //type字段传1时代表WGS84坐标;\n\n }\n\n }\n\n\n\n //@Override\n\n public void onGpsSignalWeak(boolean var1) {\n\n\n\n }\n\n\n\n @Override\n\n public void onMapLongClick(LatLng var1)\n\n {\n\n Log.i(TAG, \"onMapLongClick!!!\");\n\n int map_type = mAmap.getMapType();\n\n if (map_type == AMap.MAP_TYPE_SATELLITE)\n\n {\n\n mAmap.setMapType(AMap.MAP_TYPE_NORMAL);\n\n LocalTime time = LocalTime.now();\n\n if (time.getHour() >= 17 || time.getHour() <= 5)\n\n {\n\n mAmap.setMapType(AMap.MAP_TYPE_NIGHT);\n\n }\n\n }\n\n else\n\n {\n\n mAmap.setMapType(AMap.MAP_TYPE_SATELLITE);\n\n }\n\n }\n\n\n\n @Override\n\n public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo var1) {\n\n try {\n\n SDLActivity.onNativeMessage(NAVI_FACILITY,\n\n (double) var1.distance,\n\n (double) var1.type,\n\n (double) var1.limitSpeed,\n\n \"\");\n\n }\n\n catch(Exception e) {\n\n Log.w(TAG, e.getMessage());\n\n }\n\n }\n\n\n\n @Override\n\n public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] var1) {\n\n try {\n\n for (int i = 0; i < var1.length; ++i) {\n\n SDLActivity.onNativeMessage(NAVI_FACILITY,\n\n (double) var1[i].distance,\n\n (double) var1[i].type,\n\n (double) var1[i].limitSpeed,\n\n \"\");\n\n }\n\n }\n\n catch(Exception e) {\n\n Log.w(TAG, e.getMessage());\n\n }\n\n }\n\n\n\n\n\n @Override\n\n public void onUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] var1)\n\n {\n\n try {\n\n for (int i = 0; i < var1.length; ++i) {\n\n SDLActivity.onNativeMessage(NAVI_FACILITY,\n\n (double) var1[i].distance,\n\n (double) var1[i].type,\n\n (double) var1[i].limitSpeed,\n\n \"\");\n\n }\n\n }\n\n catch(Exception e) {\n\n Log.w(TAG, e.getMessage());\n\n }\n\n }\n\n\n\n @Override\n\n public void onUpdateAimlessModeElecCameraInfo(AMapNaviTrafficFacilityInfo[] var1)\n\n {\n\n try {\n\n for (int i = 0; i < var1.length; ++i) {\n\n SDLActivity.onNativeMessage(NAVI_FACILITY,\n\n (double) var1[i].distance,\n\n (double) var1[i].type,\n\n (double) var1[i].limitSpeed,\n\n \"\");\n\n }\n\n }\n\n catch(Exception e) {\n\n Log.w(TAG, e.getMessage());\n\n }\n\n }\n\n\n\n /**\n\n * 设置导航监听\n\n */\n\n private void setMapInteractiveListener() {\n\n\n\n mAmap.setOnMapTouchListener(new AMap.OnMapTouchListener() {\n\n\n\n @Override\n\n public void onTouch(MotionEvent event) {\n\n\n\n switch (event.getAction()) {\n\n case MotionEvent.ACTION_DOWN:\n\n // 按下屏幕\n\n // 如果timer在执行,关掉它\n\n clearTimer();\n\n // 改变跟随状态\n\n isNeedFollow = false;\n\n break;\n\n\n\n case MotionEvent.ACTION_UP:\n\n // 离开屏幕\n\n startTimerSomeTimeLater();\n\n break;\n\n\n\n default:\n\n break;\n\n }\n\n }\n\n });\n\n\n\n }\n\n\n\n /**\n\n * 取消timer任务\n\n */\n\n private void clearTimer() {\n\n if (needFollowTimer != null) {\n\n needFollowTimer.cancel();\n\n needFollowTimer = null;\n\n }\n\n }\n\n\n\n /**\n\n * 如果地图在静止的情况下\n\n */\n\n private void startTimerSomeTimeLater() {\n\n // 首先关闭上一个timer\n\n clearTimer();\n\n needFollowTimer = new Timer();\n\n // 开启一个延时任务,改变跟随状态\n\n needFollowTimer.schedule(new TimerTask() {\n\n @Override\n\n public void run() {\n\n isNeedFollow = true;\n\n }\n\n }, DELAY_TIME);\n\n }\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 71, "score": 83382.14669523256 }, { "content": " static final String SCRIPTS = \"scripts\";\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 72, "score": 82694.31150383364 }, { "content": " @Override\n\n protected void onCreate(Bundle savedInstanceState) {\n\n\n\n Log.i(TAG, \"onCreate !!!\");\n\n super.onCreate(savedInstanceState);\n\n\n\n mAMapNavi.addAMapNaviListener(this);\n\n\n\n mAmapView.onCreate(savedInstanceState);\n\n mAmap = mAmapView.getMap();\n\n mAmap.setOnMapLongClickListener(this);\n\n\n\n Log.i(TAG, \"startAimlessMode\");\n\n mAMapNavi.startAimlessMode(AimLessMode.CAMERA_AND_SPECIALROAD_DETECTED);\n\n mAMapNavi.addAimlessModeListener(this);\n\n mAmap.setTrafficEnabled(true);\n\n\n\n //mAmap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口\n\n //mAmap.getUiSettings().setMyLocationButtonEnabled(true); // 是否显示定位按钮\n\n //mAmap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase\n\n mAmap.moveCamera(CameraUpdateFactory.zoomTo(BASE_ZOOM));//设置地图缩放级别\n\n// MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类\n\n// myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。\n\n// myLocationStyle.strokeColor(Color.TRANSPARENT);//设置定位蓝点精度圆圈的边框颜色\n\n// myLocationStyle.radiusFillColor(Color.TRANSPARENT);//设置定位蓝点精度圆圈的填充颜色\n\n// mAmap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style\n\n\n\n LocalTime time = LocalTime.now();\n\n if (time.getHour() >= 17 || time.getHour() <= 5)\n\n {\n\n mAmap.setMapType(AMap.MAP_TYPE_NIGHT);\n\n }\n\n //\n\n\n\n init_called = false;\n\n\n\n // 初始化 显示我的位置的Marker\n\n myLocationMarker = mAmap.addMarker(new MarkerOptions()\n\n .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory\n\n .decodeResource(getResources(), R.drawable.car))));\n\n\n\n setMapInteractiveListener();\n\n\n\n // Log.i(TAG, \"WTF !!!\");\n\n SDLActivity.onNativeMessage(NAVI_INIT, (double)mAMapNavi.getNaviType(), 0, 0, \"Init NAVI\");\n\n SDLActivity.onNativeMessage(SET_IP, 0, 0, 0, IP_ADDRESS);\n\n SDLActivity.onNativeMessage(9, (double) mAmap.getMapType(), 0, 0, \"\");\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 73, "score": 82694.31150383364 }, { "content": " @Override\n\n protected void onStop() {\n\n Log.i(TAG, \"onStop !!!\");\n\n super.onStop();\n\n finish();\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 74, "score": 82694.31150383364 }, { "content": " @Override\n\n protected void onDestroy() {\n\n Log.i(TAG, \"onDestroy !!!\");\n\n mAMapNavi.stopAimlessMode();\n\n super.onDestroy();\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 75, "score": 82694.31150383364 }, { "content": " @Override\n\n protected void onPause() {\n\n super.onPause();\n\n mAmapView.onPause();\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 76, "score": 82694.31150383364 }, { "content": " @Override\n\n protected void onResume() {\n\n super.onResume();\n\n mAmapView.onResume();\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 77, "score": 82694.31150383364 }, { "content": " private static String[] mArguments = new String[0];\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 78, "score": 82694.31150383364 }, { "content": " protected AMap mAmap;\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 79, "score": 82694.31150383364 }, { "content": " @Override\n\n protected void onMessage2(int cmd, double data1, double data2, double data3, double data4, double data5)\n\n {\n\n Log.i(TAG, \"onMessage2 \" + cmd + \" \" + data1 + \" \" + data2 + \" \" + data3 + \" \" + data4 + \" \" + data5);\n\n if (cmd == FROM_NATIVE_GPS)\n\n {\n\n Location location = new Location(\"GPS\");\n\n location.setLongitude(data1);\n\n location.setLatitude(data2);\n\n location.setSpeed((float)data3);\n\n location.setAccuracy((float)data4);\n\n location.setBearing((float)data5);\n\n location.setTime(System.currentTimeMillis());\n\n //以上6项数据缺一不可\n\n Log.i(TAG, \"setExtraGPSData\");\n\n mAMapNavi.setExtraGPSData(1,location);\n\n //type字段传1时代表WGS84坐标;\n\n }\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 80, "score": 82694.31150383364 }, { "content": " private static final String TAG = \"Urho3D\";\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 81, "score": 82694.31150383364 }, { "content": "function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end\n", "file_path": "Source/ThirdParty/LuaJIT/dynasm/dynasm.lua", "rank": 82, "score": 82310.35239609641 }, { "content": " @Override\n\n protected boolean onLoadLibrary(ArrayList<String> libraryNames) {\n\n // Ensure \"Urho3D\" shared library (if any) and \"Urho3DPlayer\" are being sorted to the top of the list\n\n // Also ensure STL runtime shared library (if any) is sorted to the top most entry\n\n Collections.sort(libraryNames, new Comparator<String>() {\n\n private String sortName(String name) {\n\n return name.matches(\"^\\\\d+_.+$\") ? name : (name.matches(\"^.+_shared$\") ? \"0000_\" : \"000_\") + name;\n\n }\n\n\n\n @Override\n\n public int compare(String lhs, String rhs) {\n\n return sortName(lhs).compareTo(sortName(rhs));\n\n }\n\n });\n\n\n\n // All shared shared libraries must always be loaded if available, so exclude it from return result and all list operations below\n\n int startIndex = libraryNames.indexOf(\"Game\");\n\n\n\n // Determine the intention\n\n Intent intent = getIntent();\n\n String pickedLibrary = intent.getStringExtra(SampleLauncher.PICKED_LIBRARY);\n\n if (pickedLibrary == null) {\n\n // Intention for obtaining library names\n\n String[] array = libraryNames.subList(startIndex, libraryNames.size()).toArray(new String[libraryNames.size() - startIndex]);\n\n if (array.length > 1) {\n\n setResult(RESULT_OK, intent.putExtra(SampleLauncher.LIBRARY_NAMES, array));\n\n\n\n // End Urho3D activity lifecycle\n\n finish();\n\n\n\n // Return false to indicate no library is being loaded yet\n\n return false;\n\n } else {\n\n // There is only one library available, so cancel the intention for obtaining the library name and by not returning any result\n\n // However, since we have already started Urho3D activity, let's the activity runs its whole lifecycle by falling through to call the super implementation\n\n setResult(RESULT_CANCELED);\n\n }\n\n } else {\n\n // Intention for loading a picked library name (and remove all others)\n\n libraryNames.subList(startIndex, libraryNames.size()).clear();\n\n mArguments = pickedLibrary.split(\":\");\n\n libraryNames.add(mArguments[0]);\n\n if (\"Urho3DPlayer\".equals(mArguments[0]) && mArguments.length == 1) {\n\n // Urho3DPlayer needs a script name to play\n\n try {\n\n final AssetManager assetManager = getAssets();\n\n HashMap<String, ArrayList<String>> scripts = new HashMap<String, ArrayList<String>>(2) {{\n\n put(\"AngelScript\", new ArrayList<>(Arrays.asList(assetManager.list(\"Data/Scripts\"))));\n\n put(\"Lua\", new ArrayList<>(Arrays.asList(assetManager.list(\"Data/LuaScripts\"))));\n\n }};\n\n startActivityForResult(new Intent(this, ScriptPicker.class).putExtra(SCRIPTS, scripts), OBTAINING_SCRIPT);\n\n } catch (IOException e) {\n\n Log.e(TAG, \"Could not scan assets directory for playable scripts\", e);\n\n }\n\n }\n\n }\n\n\n\n return super.onLoadLibrary(libraryNames);\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 83, "score": 82017.73163186999 }, { "content": " @Override\n\n public void onNaviCancel() {\n\n finish();\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 84, "score": 82017.73163186999 }, { "content": " @Override\n\n public void onLocationChange(AMapNaviLocation location) {\n\n //当前位置回调\n\n\n\n if (location != null) {\n\n LatLng latLng = new LatLng(location.getCoord().getLatitude(),\n\n location.getCoord().getLongitude());\n\n // 显示定位小图标,初始化时已经创建过了,这里修改位置即可\n\n myLocationMarker.setPosition(latLng);\n\n if (isNeedFollow) {\n\n // 跟随\n\n mAmap.animateCamera(CameraUpdateFactory.changeLatLng(latLng));\n\n mAmap.moveCamera(CameraUpdateFactory.zoomTo(BASE_ZOOM));//设置地图缩放级别\n\n }\n\n } else {\n\n// Toast.makeText(IntelligentBroadcastActivity.this, \"定位出现异常\",\n\n// Toast.LENGTH_SHORT).show();\n\n }\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 85, "score": 82017.73163186999 }, { "content": " @Override\n\n protected String[] getArguments() {\n\n return mArguments;\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 86, "score": 82017.73163186999 }, { "content": " @Override\n\n public void onStartNavi(int type) {\n\n //开始导航回调\n\n SDLActivity.onNativeMessage(0, (double) type, 0, 0, \"\");\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 87, "score": 82017.73163186999 }, { "content": " @Override\n\n public void onArriveDestination() {\n\n //到达目的地\n\n SDLActivity.onNativeMessage(NAVI_ARRIVED, 0, 0, 0, \"\");\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 88, "score": 82017.73163186999 }, { "content": " @Override\n\n protected void onInitLayout() {\n\n setContentView(R.layout.activity_basic_map);\n\n mSurface = findViewById(R.id.sdl_view);\n\n mAmapView = findViewById(R.id.map_view);\n\n mAMapNavi = AMapNavi.getInstance(getApplicationContext());\n\n mLayout = findViewById(R.id.basic_map);\n\n Log.i(TAG, \"layout init OK\");\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 89, "score": 82017.73163186999 }, { "content": " @Override\n\n public void showCross(AMapNaviCross aMapNaviCross) {\n\n //显示转弯回调\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 90, "score": 82017.73163186999 }, { "content": " @Override\n\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\n if (OBTAINING_SCRIPT != requestCode || RESULT_CANCELED == resultCode)\n\n return;\n\n String script = data.getStringExtra(PICKED_SCRIPT);\n\n script = (script.endsWith(\".as\") ? \"Scripts/\" : \"LuaScripts/\") + script;\n\n mArguments = new String[]{mArguments[0], script};\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 91, "score": 82017.73163186999 }, { "content": " @Override\n\n public void onNaviSetting() {\n\n //底部导航设置点击回调\n", "file_path": "Android/src/com/github/urho3d/Urho3D_MapNew.java", "rank": 92, "score": 82017.73163186999 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../AngelScript/APITemplates.h\"\n\n#include \"../Core/ProcessUtils.h\"\n\n#include \"../Core/Spline.h\"\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nstatic void ConstructStringHash(StringHash* ptr)\n\n{\n\n new(ptr) StringHash();\n\n}\n\n\n\nstatic void ConstructStringHashCopy(const StringHash& hash, StringHash* ptr)\n\n{\n\n new(ptr) StringHash(hash);\n\n}\n", "file_path": "Source/Urho3D/AngelScript/CoreAPI.cpp", "rank": 93, "score": 26.29747850771536 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../Math/MathDefs.h\"\n\n#include \"../Math/StringHash.h\"\n\n\n\n#include <cstdio>\n\n\n\n#include \"../DebugNew.h\"\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nconst StringHash StringHash::ZERO;\n\n\n\nStringHash::StringHash(const char* str) noexcept :\n\n value_(Calculate(str))\n\n{\n\n}\n", "file_path": "Source/Urho3D/Math/StringHash.cpp", "rank": 94, "score": 25.475327907297235 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../IO/Log.h\"\n\n\n\n#include <cstdio>\n\n\n\n#include \"../DebugNew.h\"\n\n\n\n#ifdef _MSC_VER\n\n#pragma warning(disable:6293)\n\n#endif\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nchar String::endZero = 0;\n\n\n\nconst String String::EMPTY;\n", "file_path": "Source/Urho3D/Container/Str.cpp", "rank": 95, "score": 25.26351692915062 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../Math/Vector4.h\"\n\n\n\n#include <cstdio>\n\n\n\n#include \"../DebugNew.h\"\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nconst Vector4 Vector4::ZERO;\n\nconst Vector4 Vector4::ONE(1.0f, 1.0f, 1.0f, 1.0f);\n\n\n\nString Vector4::ToString() const\n\n{\n\n char tempBuffer[CONVERSION_BUFFER_LENGTH];\n\n sprintf(tempBuffer, \"%g %g %g %g\", x_, y_, z_, w_);\n\n return String(tempBuffer);\n\n}\n\n\n\n}\n", "file_path": "Source/Urho3D/Math/Vector4.cpp", "rank": 96, "score": 24.468175403187438 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../Core/Context.h\"\n\n#include \"../Core/StringUtils.h\"\n\n#include \"../IO/Log.h\"\n\n#include \"../Resource/JSONValue.h\"\n\n\n\n#include \"../DebugNew.h\"\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nstatic const char* valueTypeNames[] =\n\n{\n\n \"Null\",\n\n \"Bool\",\n\n \"Number\",\n\n \"String\",\n", "file_path": "Source/Urho3D/Resource/JSONValue.cpp", "rank": 97, "score": 24.46423081982215 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../Core/StringUtils.h\"\n\n\n\n#include <cstdio>\n\n\n\n#include \"../DebugNew.h\"\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nstatic const String base64_chars =\n\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n \"abcdefghijklmnopqrstuvwxyz\"\n\n \"0123456789+/\";\n\n\n\nunsigned CountElements(const char* buffer, char separator)\n\n{\n", "file_path": "Source/Urho3D/Core/StringUtils.cpp", "rank": 98, "score": 24.415857062871638 }, { "content": "//\n\n\n\n#include \"../Precompiled.h\"\n\n\n\n#include \"../Core/Context.h\"\n\n#include \"../IO/Deserializer.h\"\n\n#include \"../IO/Log.h\"\n\n#include \"../IO/Serializer.h\"\n\n#include \"../Resource/XMLElement.h\"\n\n#include \"../Resource/JSONValue.h\"\n\n#include \"../Scene/UnknownComponent.h\"\n\n\n\n#include \"../DebugNew.h\"\n\n\n\nnamespace Urho3D\n\n{\n\n\n\nstatic HashMap<StringHash, String> unknownTypeToName;\n\nstatic String letters(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n\n\n", "file_path": "Source/Urho3D/Scene/UnknownComponent.cpp", "rank": 99, "score": 24.380462571114794 } ]
C++
framework/frontend/fsa/fsa_transition.hpp
aamshukov/frontend
6be5fea43b7776691034f3b4f56d318d7cdf18f8
 #ifndef __FSA_TRANSITION_H__ #define __FSA_TRANSITION_H__ #pragma once BEGIN_NAMESPACE(frontend) USINGNAMESPACE(core) #define MAX_TRANSITION_RANK (5) class fsa_transition { public: using datum_type = text::datum_type; using predicate_type = string_type; using predicates_type = std::set<predicate_type>; private: uint32_t my_id; uint32_t my_start_state; uint32_t my_end_state; predicate_type my_predicate; datum_type my_switch_predicate; int16_t my_rank; public: fsa_transition(); fsa_transition(uint32_t start_state, uint32_t end_state, const predicate_type& predicate); fsa_transition(uint32_t start_state, uint32_t end_state, datum_type switch_predicate); fsa_transition(const fsa_transition& other); fsa_transition(fsa_transition&& other); const fsa_transition& operator = (const fsa_transition& other); fsa_transition& operator = (fsa_transition&& other); uint32_t id() const; uint32_t& id(); uint32_t start_state() const; uint32_t& start_state(); uint32_t end_state() const; uint32_t& end_state(); const predicate_type& predicate() const; predicate_type& predicate(); datum_type switch_char() const; datum_type& switch_char(); int16_t rank() const; int16_t& rank(); bool is_epsilon_transition() const; static const predicate_type& empty_predicate(); static const predicate_type& epsilon_predicate(); }; inline uint32_t fsa_transition::id() const { return my_id; } inline uint32_t& fsa_transition::id() { return my_id; } inline uint32_t fsa_transition::start_state() const { return my_start_state; } inline uint32_t& fsa_transition::start_state() { return my_start_state; } inline uint32_t fsa_transition::end_state() const { return my_end_state; } inline uint32_t& fsa_transition::end_state() { return my_end_state; } inline const typename fsa_transition::predicate_type& fsa_transition::predicate() const { return my_predicate; } inline typename fsa_transition::predicate_type& fsa_transition::predicate() { return const_cast<typename fsa_transition::predicate_type&>(static_cast<const fsa_transition&>(*this).predicate()); } inline typename fsa_transition::datum_type fsa_transition::switch_char() const { return my_switch_predicate; } inline typename fsa_transition::datum_type& fsa_transition::switch_char() { return my_switch_predicate; } inline int16_t fsa_transition::rank() const { return my_rank; } inline int16_t& fsa_transition::rank() { return my_rank; } inline bool fsa_transition::is_epsilon_transition() const { return my_predicate.compare(epsilon_predicate()) == 0 || my_switch_predicate == text::epsilon_codepoint(); } inline typename fsa_transition::predicate_type const& fsa_transition::empty_predicate() { static typename fsa_transition::predicate_type result; return result; } inline string_type const& fsa_transition::epsilon_predicate() { static string_type result(L"ε"); return result; } END_NAMESPACE #endif
 #ifndef __FSA_TRANSITION_H__ #define __FSA_TRANSITION_H__ #pragma once BEGIN_NAMESPACE(frontend) USINGNAMESPACE(core) #define MAX_TRANSITION_RANK (5) class fsa_transition { public: using datum_type = text::datum_type; using predicate_type = string_type; using predicates_type = std::set<predicate_type>; private: uint32_t my_id; uint32_t my_start_state; uint32_t my_end_state; predicate_type
public: fsa_transition(); fsa_transition(uint32_t start_state, uint32_t end_state, const predicate_type& predicate); fsa_transition(uint32_t start_state, uint32_t end_state, datum_type switch_predicate); fsa_transition(const fsa_transition& other); fsa_transition(fsa_transition&& other); const fsa_transition& operator = (const fsa_transition& other); fsa_transition& operator = (fsa_transition&& other); uint32_t id() const; uint32_t& id(); uint32_t start_state() const; uint32_t& start_state(); uint32_t end_state() const; uint32_t& end_state(); const predicate_type& predicate() const; predicate_type& predicate(); datum_type switch_char() const; datum_type& switch_char(); int16_t rank() const; int16_t& rank(); bool is_epsilon_transition() const; static const predicate_type& empty_predicate(); static const predicate_type& epsilon_predicate(); }; inline uint32_t fsa_transition::id() const { return my_id; } inline uint32_t& fsa_transition::id() { return my_id; } inline uint32_t fsa_transition::start_state() const { return my_start_state; } inline uint32_t& fsa_transition::start_state() { return my_start_state; } inline uint32_t fsa_transition::end_state() const { return my_end_state; } inline uint32_t& fsa_transition::end_state() { return my_end_state; } inline const typename fsa_transition::predicate_type& fsa_transition::predicate() const { return my_predicate; } inline typename fsa_transition::predicate_type& fsa_transition::predicate() { return const_cast<typename fsa_transition::predicate_type&>(static_cast<const fsa_transition&>(*this).predicate()); } inline typename fsa_transition::datum_type fsa_transition::switch_char() const { return my_switch_predicate; } inline typename fsa_transition::datum_type& fsa_transition::switch_char() { return my_switch_predicate; } inline int16_t fsa_transition::rank() const { return my_rank; } inline int16_t& fsa_transition::rank() { return my_rank; } inline bool fsa_transition::is_epsilon_transition() const { return my_predicate.compare(epsilon_predicate()) == 0 || my_switch_predicate == text::epsilon_codepoint(); } inline typename fsa_transition::predicate_type const& fsa_transition::empty_predicate() { static typename fsa_transition::predicate_type result; return result; } inline string_type const& fsa_transition::epsilon_predicate() { static string_type result(L"ε"); return result; } END_NAMESPACE #endif
my_predicate; datum_type my_switch_predicate; int16_t my_rank;
random
[ { "content": "class string_data_provider : public data_provider, private noncopyable\n\n{\n\n public:\n\n using datum_type = data_provider::datum_type;\n\n\n\n private:\n\n string_type my_data_content;\n\n\n\n public:\n\n string_data_provider(const string_type& data_content);\n\n virtual ~string_data_provider();\n\n\n\n virtual bool load(std::shared_ptr<datum_type[]>& data, size_type& count, operation_status& status) override;\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __STRING_DATA_PROVIDER_H__\n", "file_path": "framework/core/string_data_provider.hpp", "rank": 0, "score": 130932.05812871986 }, { "content": "class file_data_provider : public data_provider, private noncopyable\n\n{\n\n public:\n\n using datum_type = data_provider::datum_type;\n\n\n\n using callback_type = std::function<bool(std::shared_ptr<datum_type[]>, void*, size_type&)>;\n\n\n\n private:\n\n string_type my_file_name;\n\n callback_type my_callback;\n\n\n\n private:\n\n static size_type get_file_size(const string_type& file_name);\n\n static string_type get_encoding(const string_type& file_name);\n\n\n\n static bool read_raw_data(const string_type& file_name, std::shared_ptr<byte[]>& data, size_type& count, offset_type offset, operation_status& status);\n\n\n\n static bool read_utf8_data(std::shared_ptr<byte[]> raw_data, size_type raw_count, std::shared_ptr<datum_type[]>& data, size_type& count, operation_status& status);\n\n static bool read_utf16_data(std::shared_ptr<byte[]> raw_data, size_type raw_count, std::shared_ptr<datum_type[]>& data, size_type& count, bool big_endian, operation_status& status);\n\n static bool read_utf32_data(std::shared_ptr<byte[]> raw_data, size_type raw_count, std::shared_ptr<datum_type[]>& data, size_type& count, bool big_endian, operation_status& status);\n", "file_path": "framework/core/file_data_provider.hpp", "rank": 1, "score": 130932.05812871986 }, { "content": "//template <typename TReturn, typename TParam>\n\nclass type : public noncopyable\n\n{\n\n public:\n\n using size_type = std::size_t;\n\n\n\n //using return_type = TReturn;\n\n //using param_type = TParam;\n\n\n\n\n\n private:\n\n size_type my_size; // size in bits, width for runtime allocation\n\n\n\n\n\n //flags my_flags;\n\n //private:\n\n // hash_type hashcode();\n\n\n\n\n\n\n\n public:\n", "file_path": "framework/frontend/type/type.hpp", "rank": 2, "score": 117471.52917062829 }, { "content": "class scope : public tree\n\n{\n\n public:\n\n using size_type = std::size_t;\n\n using scope_type = std::shared_ptr<scope>;\n\n\n\n public:\n\n //enum class kind //?? inheritance instead\n\n //{\n\n // scope_namespace = 1,\n\n // scope_structure = 2,\n\n // scope_function = 3,\n\n // scope_parameter = 4\n\n //};\n\n\n\n private:\n\n //??scope::kind my_kind;\n\n scope_type my_papa; // parent scope\n\n\n\n size_type my_level; // depth\n", "file_path": "framework/symtable/scope/scope.hpp", "rank": 3, "score": 117471.52917062829 }, { "content": "class command_line : public noncopyable\n\n{\n\n private:\n\n // list of warnings\n\n // list of options\n\n\n\n\n\n public:\n\n command_line() = default;\n\n\n\n void parse(const char* command_line);\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __COMMAND_LINE_H__\n", "file_path": "framework/core/command_line.hpp", "rank": 4, "score": 114964.88209939364 }, { "content": "class configurator : public singleton<configurator>\n\n{\n\n private:\n\n // list of warnings\n\n // list of options\n\n // list of features\n\n\n\n public:\n\n configurator() = default;\n\n\n\n // generate_fsa_as_case...\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __CONFIGURATOR_H__\n", "file_path": "framework/core/configurator.hpp", "rank": 5, "score": 112627.97247304875 }, { "content": "class statistics : public singleton<statistics>\n\n{\n\n public:\n\n statistics() = default;\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __STATISTICS_H__\n", "file_path": "framework/core/statistics.hpp", "rank": 6, "score": 112627.97247304875 }, { "content": "class diagnostics : public singleton<diagnostics>\n\n{\n\n public:\n\n using data_type = std::vector<status>;\n\n using size_type = std::size_t;\n\n\n\n private:\n\n data_type my_data;\n\n size_type my_spurious_errors; // how many spurious error before termination\n\n bool my_state; // quick state check, true - valid (continue), false - erroneous\n\n\n\n public:\n\n diagnostics(size_type spurious_errors);\n\n\n\n const data_type& warnings() const;\n\n const data_type& errors() const;\n\n\n\n const data_type& data() const;\n\n\n\n bool state() const;\n", "file_path": "framework/core/diagnostics.hpp", "rank": 7, "score": 112627.97247304875 }, { "content": "class scope_namespace : public scope\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SCOPE_NAMESPACE_H__\n", "file_path": "framework/symtable/scope/scope_namespace.hpp", "rank": 8, "score": 112605.17129024974 }, { "content": "class scope_structure : public scope\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SCOPE_STRUCTURE_H__\n", "file_path": "framework/symtable/scope/scope_structure.hpp", "rank": 9, "score": 112605.17129024974 }, { "content": "class scope_function : public scope\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SCOPE_FUNCTION_H__\n", "file_path": "framework/symtable/scope/scope_function.hpp", "rank": 10, "score": 112605.17129024974 }, { "content": "class scope_block : public scope\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SCOPE_BLOCK_H__\n", "file_path": "framework/symtable/scope/scope_block.hpp", "rank": 11, "score": 112605.17129024974 }, { "content": "class scope_parameter : public scope\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SCOPE_PARAMETER_H__\n", "file_path": "framework/symtable/scope/scope_parameter.hpp", "rank": 12, "score": 112605.17129024974 }, { "content": "class lexical_content : public content\n\n{\n\n public:\n\n using datum_type = data_provider::datum_type;\n\n using data_type = std::shared_ptr<datum_type[]>;\n\n\n\n using line_map_type = std::unique_ptr<loc_type[]>;\n\n using tab_map_type = std::vector<bool>;\n\n\n\n private:\n\n line_map_type my_line_map; // start position of each line\n\n uint32_t my_line_map_size;\n\n loc_type my_cached_line;\n\n loc_type my_cached_line_position;\n\n\n\n tab_map_type my_tab_map; // tab positions\n\n uint8_t my_tab_size; // tab size, default is 4\n\n\n\n private:\n\n loc_type find_line_number(loc_type position);\n", "file_path": "framework/frontend/lexical_analyzer/lexical_content.hpp", "rank": 13, "score": 110379.84482394617 }, { "content": "class controller : private noncopyable\n\n{\n\n //??\n\n //lexer\n\n //parser\n\n //ir\n\n //optimization\n\n //generator\n\n\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __CONTROLLER_H__\n", "file_path": "framework/controller/controller.hpp", "rank": 14, "score": 102746.84579553723 }, { "content": "class context : private noncopyable\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __CONTEXT_H__\n", "file_path": "framework/core/context.hpp", "rank": 15, "score": 102746.84579553723 }, { "content": "class text : private noncopyable\n\n{\n\n public:\n\n using datum_type = cp_type;\n\n\n\n public:\n\n static constexpr datum_type ascii_numbers[128] =\n\n {\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,\n\n 0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n\n 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\n };\n\n\n\n public:\n\n static const datum_type invalid_codepoint = 0x0000FFFD;\n\n\n\n // http://www.unicode.org/glossary/#supplementary_code_point\n\n static const datum_type kSupplementaryCodePointStart = 0x010000; //?? rename\n\n static const datum_type kSupplementaryCodePointEnd = 0x10FFFF;\n", "file_path": "framework/core/text.hpp", "rank": 16, "score": 102746.84579553723 }, { "content": "class logger : private noncopyable\n\n{\n\n public:\n", "file_path": "framework/core/logger.hpp", "rank": 17, "score": 102746.84579553723 }, { "content": "class factory : private noncopyable\n\n{\n\n public:\n\n template <typename T, typename ... ARGS> static std::shared_ptr<T> create(const ARGS&... args);\n\n};\n\n\n\ntemplate <typename T, typename ... ARGS>\n\ninline static std::shared_ptr<T> factory::create(const ARGS&... args)\n\n{\n\n return std::make_shared<T>(args...);\n\n}\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __FACTORY_H__\n", "file_path": "framework/core/factory.hpp", "rank": 18, "score": 102746.84579553723 }, { "content": "class counter : private noncopyable\n\n{\n\n private:\n\n uint32_t my_count;\n\n\n\n public:\n\n explicit counter(uint32_t count = 0);\n\n\n\n uint32_t number();\n\n uint32_t value();\n\n\n\n void rewind();\n\n void reset(uint32_t count = 0);\n\n};\n\n\n\ninline counter::counter(uint32_t count)\n\n : my_count(count)\n\n{\n\n}\n\n\n", "file_path": "framework/core/counter.hpp", "rank": 19, "score": 102746.84579553723 }, { "content": "class symbol : private noncopyable\n\n{\n\n public:\n\n using token_type = Token;\n\n\n\n using datum_type = text::datum_type;\n\n using codepoints_type = std::basic_string<datum_type>;\n\n\n\n using index_type = std::size_t;\n\n using size_type = std::size_t;\n\n\n\n using value_type = std::variant<int8_t,\n\n uint8_t,\n\n int16_t,\n\n uint16_t,\n\n int32_t,\n\n uint32_t,\n\n int64_t,\n\n uint64_t,\n\n float,\n\n double,\n\n void*,\n\n datum_type,\n\n codepoints_type>;\n\n using type_type = type;\n\n\n", "file_path": "framework/symtable/symbol.hpp", "rank": 20, "score": 102746.84579553723 }, { "content": "class content : private noncopyable\n\n{\n\n public:\n\n using datum_type = data_provider::datum_type;\n\n using data_type = std::shared_ptr<datum_type[]>;\n\n\n\n using id_type = int32_t;\n\n using source_type = string_type;\n\n\n\n protected:\n\n id_type my_id;\n\n source_type my_source;\n\n\n\n data_type my_data;\n\n size_type my_count;\n\n\n\n public:\n\n content(const id_type& id, const source_type& source);\n\n ~content();\n\n\n", "file_path": "framework/core/content.hpp", "rank": 21, "score": 102746.84579553723 }, { "content": "class visitable : private noncopyable\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __VISITABLE_H__\n", "file_path": "framework/core/visitable.hpp", "rank": 22, "score": 102746.84579553723 }, { "content": "class parser : private noncopyable\n\n{\n\n public:\n\n using token_type = typename parse_tree<Token, TreeTraits>::token_type;\n\n using tokens_type = std::vector<token_type>;\n\n\n\n using tree_traits_type = typename parse_tree<Token, TreeTraits>::tree_traits_type;\n\n\n\n using parse_tree_type = std::shared_ptr<parse_tree<token_type, tree_traits_type>>;\n\n using parse_trees_type = std::vector<parse_tree_type>;\n\n\n\n using parse_dag_type = std::shared_ptr<parse_dag<token_type, tree_traits_type>>;\n\n using parse_dags_type = std::vector<parse_dag_type>;\n\n\n\n using lexical_analyzer_type = std::shared_ptr<lexical_analyzer<token_type>>;\n\n using lexical_analyzers_type = std::vector<lexical_analyzer_type>;\n\n\n\n protected:\n\n lexical_analyzer_type my_lexical_analyzer; // master lexer\n\n lexical_analyzers_type my_lexical_analyzers; // slave lexers, for example migh be introduced by #include(C/C++) or by import(arktur)\n", "file_path": "framework/frontend/parser/parser.hpp", "rank": 23, "score": 100080.36381958098 }, { "content": "class fsa : private noncopyable\n\n{\n\n public:\n\n using datum_type = text::datum_type;\n\n\n\n using token_type = fsa_state::token_type;\n\n\n\n using state_type = fsa_state::state_type;\n\n using states_type = fsa_state::states_type;\n\n\n\n using transition_type = fsa_state::transition_type;\n\n using transitions_type = fsa_state::transitions_type;\n\n\n\n using predicate_type = fsa_transition::predicate_type;\n\n using predicates_type = fsa_transition::predicates_type;\n\n\n\n using fsa_type = std::shared_ptr<fsa>;\n\n\n\n private:\n\n using counter_type = counter;\n", "file_path": "framework/frontend/fsa/fsa.hpp", "rank": 24, "score": 100080.36381958098 }, { "content": "class grammar : private noncopyable\n\n{\n\n public:\n\n using symbol_type = rule::symbol_type;\n\n using symbols_type = rule::symbols_type;\n\n\n\n using pool_type = std::map<string_type, symbol_type>;\n\n using pool_index_type = std::map<uint32_t, symbol_type>;\n\n\n\n using rule_type = std::shared_ptr<rule>;\n\n using rules_type = std::vector<rule_type>;\n\n\n\n using nts_rules_type = std::map<string_type, rules_type>; // mapping nonterminal to rules\n\n\n\n using set_type = symbol::set_type;\n\n using sets_type = symbol::sets_type;\n\n\n\n private:\n\n rules_type my_rules;\n\n pool_type my_pool;\n", "file_path": "framework/frontend/grammar/grammar.hpp", "rank": 25, "score": 100080.36381958098 }, { "content": "class ssa : private noncopyable\n\n{\n\n public:\n\n// using quadruples_type = std::vector<quadruple<>>\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SSA_H__\n", "file_path": "framework/backend/ir/ssa.hpp", "rank": 26, "score": 100080.36381958098 }, { "content": "class graph : private noncopyable\n\n{\n\n private:\n", "file_path": "framework/core/graph/graph.hpp", "rank": 27, "score": 100080.36381958098 }, { "content": "class ir : private noncopyable\n\n{\n\n public:\n\n using token_type = Token;\n\n using tree_traits_type = TreeTraits;\n\n\n\n using parse_tree_type = typename parser<token_type, tree_traits_type>::parse_tree_type;\n\n using parse_trees_type = typename parser<token_type, tree_traits_type>::parse_trees_type;\n\n\n\n using parse_dag_type = typename parser<token_type, tree_traits_type>::parse_dag_type;\n\n using parse_dags_type = typename parser<token_type, tree_traits_type>::parse_dags_type;\n\n\n\n using symbol_type = std::shared_ptr<symtable::symbol<token_type>>;\n\n using symbols_type = std::vector<symbol_type>;\n\n\n\n using dag_key_pair = std::tuple<typename token_type::token_type,\n\n typename token_type::codepoints_type,\n\n typename symtable::symbol<token_type>::value_type>;\n\n using dag_key_type = std::vector<dag_key_pair>;\n\n\n", "file_path": "framework/backend/ir/ir.hpp", "rank": 28, "score": 100080.36381958098 }, { "content": "class semantics : private noncopyable\n\n{\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using parse_tree_type = std::shared_ptr<parse_tree<token_type, tree_traits_type>>;\n\n using parse_trees_type = std::vector<parse_tree_type>;\n\n\n\n public:\n\n semantics();\n\n ~semantics();\n\n\n\n void populate_symbol_table(const parse_tree_type& tree);\n\n\n\n};\n\n\n\ntemplate <typename Token, typename TreeTraits>\n\nsemantics<Token, TreeTraits>::semantics()\n\n{\n", "file_path": "framework/frontend/semantics/semantics.hpp", "rank": 29, "score": 100080.36381958098 }, { "content": "class code : private noncopyable\n\n{\n\n public:\n\n using token_type = Token;\n\n\n\n public:\n\n using id_type = std::size_t;\n\n\n\n using quadruple_type = std::shared_ptr<quadruple<token_traits>>;\n\n using quadruples_type = std::list<quadruple_type>;\n\n\n\n private:\n\n quadruples_type my_quadruples;\n\n\n\n public:\n\n code();\n\n ~code();\n\n\n\n const quadruples_type& quadruples() const;\n\n quadruples_type& quadruples();\n", "file_path": "framework/backend/ir/code.hpp", "rank": 30, "score": 100080.36381958098 }, { "content": "class symbol_table : public singleton<symbol_table<Token>>\n\n{\n\n // hashtable and stack, LeBlanc/Cook\n\n\n\n //public:\n\n // using symbol_attribute_type = std::shared_ptr<symbol_attribute<T>>;\n\n // using symbol_attributes_type = std::map<std::size_t, symbol_attribute_type>;\n\n // using stack_type = std::stack<symbol_attribute_type>;\n\n\n\n //private:\n\n // symbol_attributes_type table;\n\n // stack_type stack; // display\n\n\n\n public:\n\n using size_type = std::size_t;\n\n using scope_type = std::shared_ptr<scope>;\n\n\n\n private:\n\n scope_type my_root; // root of scope tree, might represent 'global' scope\n\n\n", "file_path": "framework/symtable/symbol_table.hpp", "rank": 31, "score": 99784.58789058596 }, { "content": "class earley_parser : public parser<Token, TreeTraits>\n\n{\n\n // optimization heuristics might be introduced:\n\n // - optimization lists, which are predictor-list, completer-list and scanner-list\n\n // - if grammar is static it is possible to precalculate 'prediction table',\n\n // this implementation handles generic cases where grammars may change between invokations\n\n // - predictor prediction table, see above item\n\n // - 'execute predictor' flag indicates if predictor should proceed, set when an item is added\n\n // - 'execute completer' flag indicates if completer should proceed, set when an item is added\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type;\n\n\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using pool_type = grammar::pool_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using set_type = grammar::set_type;\n\n using sets_type = grammar::sets_type;\n\n\n", "file_path": "framework/frontend/parser/earley/earley_parser.hpp", "rank": 32, "score": 95911.25636455519 }, { "content": "class fsa_re : private noncopyable\n\n{\n\n public:\n\n using datum_type = text::datum_type;\n\n using token_type = fsa::token_type;\n\n\n\n using state_type = fsa::state_type;\n\n using fsa_type = fsa::fsa_type;\n\n\n\n public:\n\n struct fsa_tree : public tree\n\n {\n\n datum_type symbol;\n\n\n\n std::size_t index;\n\n\n\n std::vector<std::size_t> firstpos;\n\n std::vector<std::size_t> lastpos;\n\n\n\n bool nullable;\n", "file_path": "framework/frontend/fsa/fsa_re.hpp", "rank": 33, "score": 95216.31657194914 }, { "content": "class ir_visualization : private noncopyable\n\n{\n\n public:\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using set_type = frontend::symbol::set_type;\n\n using sets_type = frontend::symbol::sets_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using ir_type = typename ir<Token, TreeTraits>;\n\n using token_type = typename ir_type::token_type;\n\n using tree_traits_type = typename ir_type::tree_traits_type;\n\n\n\n using parse_tree_type = typename ir_type::parse_tree_type;\n\n using parse_trees_type = typename ir_type::parse_trees_type;\n\n\n\n using parse_dag_type = typename ir_type::parse_dag_type;\n", "file_path": "framework/backend/ir/ir_visualization.hpp", "rank": 34, "score": 95216.31657194914 }, { "content": "class grammar_visualization : private noncopyable\n\n{\n\n public:\n\n using symbol_type = rule::symbol_type;\n\n using symbols_type = rule::symbols_type;\n\n\n\n using set_type = symbol::set_type;\n\n using sets_type = symbol::sets_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n public:\n\n static string_type decorate_set(const set_type& set, bool add_brackets = true);\n\n static string_type decorate_sets(const sets_type& sets, bool add_brackets = true);\n\n\n\n static string_type decorate_symbol(const symbol_type& symbol);\n\n static string_type decorate_symbols(const grammar& grammar);\n\n\n\n static string_type decorate_rule(const rule_type& rule, bool decorate = true);\n\n\n\n static string_type decorate_grammar(const grammar& grammar);\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __GRAMMAR_VISUALIZATION_H__\n", "file_path": "framework/frontend/grammar/grammar_visualization.hpp", "rank": 35, "score": 95216.31657194914 }, { "content": "class parser_visualization : private noncopyable\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __PARSER_VISUALIZATION_H__\n", "file_path": "framework/frontend/parser/parser_visualization.hpp", "rank": 36, "score": 95216.31657194914 }, { "content": "class fsa_visualization : private noncopyable\n\n{\n\n public:\n\n using token_type = typename fsa::token_type;\n\n\n\n using state_type = fsa::state_type;\n\n using states_type = fsa::states_type;\n\n\n\n using transition_type = fsa::transition_type;\n\n using transitions_type = fsa::transitions_type;\n\n\n\n using fsa_type = fsa::fsa_type;\n\n\n\n private:\n\n static string_type get_state_label(const typename fsa_visualization::state_type& state);\n\n\n\n public:\n\n static void generate_graphviz_file(const fsa_type& fsa, const string_type& file_name);\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __FSA_VISUALIZATION_H__\n", "file_path": "framework/frontend/fsa/fsa_visualization.hpp", "rank": 37, "score": 95216.31657194914 }, { "content": "class parser_algorithm : private noncopyable\n\n{\n\n public:\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using pool_type = grammar::pool_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using set_type = grammar::set_type;\n\n using sets_type = grammar::sets_type;\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __PARSER_ALGORITHM_H__\n", "file_path": "framework/frontend/parser/parser_algorithm.hpp", "rank": 38, "score": 95216.31657194914 }, { "content": "class fsa_algorithm : private noncopyable\n\n{\n\n public:\n\n using datum_type = text::datum_type;\n\n\n\n using token_type = fsa::token_type;\n\n\n\n using state_type = fsa::state_type;\n\n using states_type = fsa::states_type;\n\n\n\n using transition_type = fsa::transition_type;\n\n using transitions_type = fsa::transitions_type;\n\n\n\n using predicate_type = fsa::predicate_type;\n\n using predicates_type = fsa::predicates_type;\n\n\n\n using fsa_type = fsa::fsa_type;\n\n\n\n using state_set_type = std::shared_ptr<fsa_state_set>;\n\n\n", "file_path": "framework/frontend/fsa/fsa_algorithm.hpp", "rank": 39, "score": 95216.31657194914 }, { "content": "class grammar_algorithm : private noncopyable\n\n{\n\n public:\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using pool_type = grammar::pool_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using set_type = grammar::set_type;\n\n using sets_type = grammar::sets_type;\n\n\n\n public:\n\n static void create_production_combinations(const symbols_type& rhs,\n\n const symbol_type& nonterminal,\n\n std::vector<symbols_type>& new_productions);\n\n\n\n static void calculate_longest_common_prefixes(rules_type& rules,\n", "file_path": "framework/frontend/grammar/grammar_algorithm.hpp", "rank": 40, "score": 95216.31657194914 }, { "content": "class fsa_codegen : private noncopyable\n\n{\n\n public:\n\n using state_type = fsa::state_type;\n\n using states_type = fsa::states_type;\n\n\n\n using transition_type = fsa::transition_type;\n\n using transitions_type = fsa::transitions_type;\n\n\n\n using fsa_type = fsa::fsa_type;\n\n\n\n private:\n\n static string_type build_predicate(const string_type& predicate);\n\n\n\n public:\n\n template <typename T>\n\n static void generate(const fsa_type& fsa,\n\n const string_type& file_name,\n\n const string_type& label_prefix = empty_string(),\n\n bool case_mode = false);\n", "file_path": "framework/frontend/fsa/fsa_codegen.hpp", "rank": 41, "score": 95216.31657194914 }, { "content": "class activation_record : private noncopyable\n\n{\n\n // abstract class to implement activationrecord/frame interface\n\n public:\n\n virtual access add_local(bool escape) = 0; // true - escapes (goes into frame), false - goes into register\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __ACTIVATION_RECORD_H__\n", "file_path": "framework/backend/generator/activation_record.hpp", "rank": 42, "score": 95216.31657194914 }, { "content": "class basic_block : private noncopyable\n\n{\n\n public:\n\n using token_type = Token;\n\n\n\n public:\n\n using id_type = std::size_t;\n\n\n\n using quadruple_type = std::shared_ptr<quadruple<token_traits>>;\n\n using quadruples_type = std::list<quadruple_type>;\n\n\n\n using basic_block_type = std::shared_ptr<basic_block>;\n\n using basic_blocks_type = std::vector<basic_block_type>;\n\n\n\n private:\n\n id_type my_id; // 0 - entry-block, 1 - exit-block\n\n string_type my_label;\n\n\n\n quadruples_type my_code;\n\n\n", "file_path": "framework/backend/ir/basic_block.hpp", "rank": 43, "score": 95216.31657194914 }, { "content": "class ll_algorithm : private noncopyable\n\n{\n\n public:\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using pool_type = grammar::pool_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using set_type = grammar::set_type;\n\n using sets_type = grammar::sets_type;\n\n\n\n public:\n\n // strong-LL(k)\n\n using strong_ll_table_row_type = std::vector<std::optional<rule_type>>;\n\n using strong_ll_table_type = std::vector<strong_ll_table_row_type>;\n\n\n\n // LL(k)\n", "file_path": "framework/frontend/parser/ll/ll_algorithm.hpp", "rank": 44, "score": 92992.04672999 }, { "content": "class lexical_analyzer : private noncopyable\n\n{\n\n public:\n\n using content_type = std::shared_ptr<lexical_content>;\n\n\n\n using datum_type = text::datum_type;\n\n using codepoints_type = std::basic_string<datum_type>;\n\n\n\n using token_type = Token;\n\n using tokens_type = std::queue<token_type>;\n\n\n\n using snapshots_type = std::stack<const datum_type*>;\n\n\n\n protected:\n\n content_type my_content; // loaded content\n\n\n\n const datum_type* my_start_content; // begining of content\n\n const datum_type* my_end_content; // end of content\n\n\n\n token_type my_token; // current lexeme\n", "file_path": "framework/frontend/lexical_analyzer/lexical_analyzer.hpp", "rank": 45, "score": 92992.04672999 }, { "content": "class ll_visualization : private noncopyable\n\n{\n\n public:\n\n using symbol_type = rule::symbol_type;\n\n using symbols_type = rule::symbols_type;\n\n\n\n using set_type = symbol::set_type;\n\n using sets_type = symbol::sets_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using strong_ll_table_type = ll_algorithm::strong_ll_table_type;\n\n\n\n using ll_tal_table_row_type = ll_algorithm::ll_tal_table_row_type;\n\n using ll_tal_table_key_type = ll_algorithm::ll_tal_table_key_type;\n\n using ll_tal_table_type = ll_algorithm::ll_tal_table_type;\n\n using ll_tal_tables_type = ll_algorithm::ll_tal_tables_type;\n\n\n\n using ll_table_entry_type = ll_algorithm::ll_table_entry_type;\n", "file_path": "framework/frontend/parser/ll/ll_visualization.hpp", "rank": 46, "score": 92992.04672999 }, { "content": "class lr_algorithm : private noncopyable\n\n{\n\n public:\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using pool_type = grammar::pool_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using set_type = grammar::set_type;\n\n using sets_type = grammar::sets_type;\n\n\n\n struct lr_item\n\n {\n\n rule_type rule; // production (rule)\n\n uint32_t dot; // dot - position in rhs, if dot_position = rhs.size() it means it points to the end of the rhs\n\n\n\n sets_type la; // lookahead for LR(k)/LALR(k) where k > 0, for LALR(k) might be set\n", "file_path": "framework/frontend/parser/lr/lr_algorithm.hpp", "rank": 47, "score": 92992.04672999 }, { "content": "class lr_visualization : private noncopyable\n\n{\n\n public:\n\n using symbol_type = rule::symbol_type;\n\n using symbols_type = rule::symbols_type;\n\n\n\n using set_type = symbol::set_type;\n\n using sets_type = symbol::sets_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using lr_item_type = lr_algorithm::lr_item_type;\n\n using lr_items_type = lr_algorithm::lr_items_type;\n\n\n\n using lr_state_type = lr_algorithm::lr_state_type;\n\n using lr_states_type = lr_algorithm::lr_states_type;\n\n\n\n using lr_transition_type = lr_algorithm::lr_transition_type;\n\n using lr_transitions_type = lr_algorithm::lr_transitions_type;\n", "file_path": "framework/frontend/parser/lr/lr_visualization.hpp", "rank": 48, "score": 92992.04672999 }, { "content": "class earley_visualization : private noncopyable\n\n{\n\n public:\n\n using symbol_type = rule::symbol_type;\n\n using symbols_type = rule::symbols_type;\n\n\n\n using set_type = symbol::set_type;\n\n using sets_type = symbol::sets_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using earley_parser_type = earley_parser<Token, TreeTraits>;\n\n\n\n using item_type = typename earley_parser_type::item_type;\n\n using chart_type = typename earley_parser_type::chart_type;\n\n using charts_type = typename earley_parser_type::charts_type;\n\n\n\n using earley_tree = typename earley_parser_type::earley_tree;\n\n using tree_type = typename earley_parser_type::tree_type;\n", "file_path": "framework/frontend/parser/earley/earley_visualization.hpp", "rank": 49, "score": 92992.04672999 }, { "content": "class earley_lexical_analyzer : public lexical_analyzer<token<earley_token_traits>>\n\n{\n\n private:\n\n std::size_t k = 0;\n\n const grammar& my_gr;\n\n\n\n protected:\n\n virtual void next_lexeme_impl() override\n\n {\n\n if(k == (*content()).count())\n\n {\n\n my_token.type = token_type::traits::type::eos;\n\n }\n\n else\n\n {\n\n string_type name(text::codepoint_to_string((*content()).data()[k]));\n\n\n\n auto& symbol((*(my_gr.pool().find(name))).second);\n\n\n\n if(name == L\"+\")\n", "file_path": "projects/framework.tests/tests_earley.cpp", "rank": 50, "score": 92424.11067728684 }, { "content": "class precedence_visualization : private noncopyable\n\n{\n\n public:\n\n using symbol_type = rule::symbol_type;\n\n using symbols_type = rule::symbols_type;\n\n\n\n using set_type = symbol::set_type;\n\n using sets_type = symbol::sets_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using precedence_table_row_type = precedence_algorithm::precedence_table_row_type;\n\n using precedence_table_type = precedence_algorithm::precedence_table_type;\n\n\n\n using operators_type = precedence_algorithm::operators_type;\n\n\n\n public:\n\n static string_type decorate_operator_precedence_matrix(const grammar& gr,\n\n const operators_type& operators,\n", "file_path": "framework/frontend/parser/operator_precedence/precedence_visualization.hpp", "rank": 51, "score": 90890.94087250209 }, { "content": "class control_flow_graph : private noncopyable\n\n{\n\n //?? list of basic blocks\n\n //?? template <typename VertexType, typename EdgeType, typename VisitorType> graph;\n\n\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __CONTROL_FLOW_GRAPH_H__\n", "file_path": "framework/backend/ir/control_flow_graph.hpp", "rank": 52, "score": 90890.94087250209 }, { "content": "class precedence_algorithm : private noncopyable\n\n{\n\n public:\n\n using symbol_type = grammar::symbol_type;\n\n using symbols_type = grammar::symbols_type;\n\n\n\n using pool_type = grammar::pool_type;\n\n\n\n using rule_type = grammar::rule_type;\n\n using rules_type = grammar::rules_type;\n\n\n\n using set_type = grammar::set_type;\n\n using sets_type = grammar::sets_type;\n\n\n", "file_path": "framework/frontend/parser/operator_precedence/precedence_algorithm.hpp", "rank": 53, "score": 90890.94087250209 }, { "content": "class rd_lexical_analyzer : public lexical_analyzer<token<rd_token_traits>>\n\n{\n\n using token_type = uilab::frontend::token<rd_token_traits>;\n\n\n\n protected:\n\n virtual void next_lexeme_impl() override\n\n {\n\n static std::pair<char, token_type::token_type> lexemes[1] =\n\n {\n\n std::make_pair('a', rd_token_traits::type::a)\n\n };\n\n\n\n static int index = 0;\n\n\n\n my_token.type = lexemes[index++].second;\n\n }\n\n\n\n public:\n\n rd_lexical_analyzer(const content_type& content) : lexical_analyzer(content)\n\n {\n\n }\n\n};\n\n\n", "file_path": "projects/framework.tests/tests_recursive_descent.cpp", "rank": 54, "score": 90807.74762640022 }, { "content": "class java_symtab_symbol : public symtab_symbol<token<java_token_traits>>\n\n{\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __JAVA_SYMTAB_SYMBOL_H__\n", "file_path": "languages/java/backend/symtable/java_symtab_symbol.hpp", "rank": 55, "score": 89268.13707994725 }, { "content": "class java_symbol_table : public symbol_table<token<java_token_traits>>\n\n{\n\n // hashtable and stack, LeBlanc/Cook\n\n\n\n //public:\n\n // using symbol_attribute_type = std::shared_ptr<symbol_attribute<T>>;\n\n // using symbol_attributes_type = std::map<std::size_t, symbol_attribute_type>;\n\n // using stack_type = std::stack<symbol_attribute_type>;\n\n\n\n //private:\n\n // symbol_attributes_type table;\n\n // stack_type stack; // display\n\n\n\n //public:\n\n // symbol_table();\n\n // ~symbol_table();\n\n // // enter scope\n\n // // leave scope\n\n\n\n // // add\n\n // // get/lookup\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __JAVA_SYMBOL_TABLE_H__\n", "file_path": "languages/java/backend/symtable/java_symbol_table.hpp", "rank": 56, "score": 89268.13707994725 }, { "content": "class symbol_table_builder : public visitor<bool, char, symbol<Token>>\n\n{\n\n public:\n\n using token_type = Token;\n\n using tree_type = Tree;\n\n\n\n using parse_tree_type = std::shared_ptr<tree_type>;\n\n\n\n public:\n\n // symbol_table_builder();\n\n // ~symbol_table_builder();\n\n\n\n //void build(const parse_tree_type& tree);\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __SYMBOL_TABLE_BUILDER_H__\n", "file_path": "framework/symtable/symbol_table_builder.hpp", "rank": 57, "score": 88989.11791203808 }, { "content": "class java_lexical_analyzer : public lexical_analyzer<token<java_token_traits>>\n\n{\n\n public:\n\n using fsa_type = fsa::fsa_type;\n\n using lexical_analyzer_type = std::shared_ptr<java_lexical_analyzer>;\n\n\n\n using line_map_type = std::unique_ptr<loc_type[]>;\n\n using tab_map_type = std::vector<bool>;\n\n\n\n using indents_type = std::stack<std::size_t>;\n\n\n\n private:\n\n bool my_unicode; // true if the last obtained codepoint from unicode-escape\n\n uint8_t my_unicode_length;\n\n uint32_t my_unicode_backslash_count;\n\n\n\n //line_map_type my_line_map; // start position of each line\n\n //uint32_t my_line_map_size;\n\n //loc_type my_cached_line;\n\n //loc_type my_cached_line_position;\n", "file_path": "languages/java/frontend/lexical_analyzer/java_lexical_analyzer.hpp", "rank": 58, "score": 87799.93896992528 }, { "content": "class my_earley_parser : public earley_parser<token<earley_token_traits>, my_earley_tree_traits>\n\n{\n\n public:\n\n using eparser_type = earley_parser<token<earley_token_traits>, my_earley_tree_traits>;\n\n\n\n public:\n\n my_earley_parser(const lexical_analyzer_type& lexical_analyzer, grammar& gr, earley_parser::tree_kind kind) : earley_parser(lexical_analyzer, gr, kind)\n\n {\n\n }\n\n\n\n tree_type handle_start(const item_type& item) override\n\n {\n\n auto result(factory::create<parse_tree<token_type, my_earley_tree_traits>>());\n\n\n\n (*result).gr_symbol = ((*(*item).rule).lhs()[0]);\n\n (*result).ir_symbol = factory::create<uilab::symtable::symbol<token_type>>();\n\n\n\n return result;\n\n }\n\n\n", "file_path": "projects/framework.tests/tests_earley.cpp", "rank": 59, "score": 86419.46793400303 }, { "content": "class ll_parser : private parser<Token, TreeTraits>\n\n{\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type;\n\n\n\n public:\n\n ll_parser(const lexical_analyzer_type& lexical_analyzer);\n\n ~ll_parser();\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __LL_PARSER_H__\n", "file_path": "framework/frontend/parser/ll/ll_parser.hpp", "rank": 60, "score": 82803.586160611 }, { "content": "class lr_parser : private parser<Token, TreeTraits>\n\n{\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type;\n\n\n\n public:\n\n lr_parser(const lexical_analyzer_type& lexical_analyzer);\n\n ~lr_parser();\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __LR_PARSER_H__\n", "file_path": "framework/frontend/parser/lr/lr_parser.hpp", "rank": 61, "score": 82803.586160611 }, { "content": "class precedence_parser : private parser<Token, TreeTraits>\n\n{\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type;\n\n\n\n public:\n\n precedence_parser(const lexical_analyzer_type& lexical_analyzer);\n\n ~precedence_parser();\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __PRECEDENCE_PARSER_H__\n", "file_path": "framework/frontend/parser/operator_precedence/precedence_parser.hpp", "rank": 62, "score": 81016.29117453868 }, { "content": "struct vertex : private noncopyable, public visitable<vertex<VertexValueType>>\n\n{\n\n using vertex_type = vertex<VertexValueType>;\n\n using vertices_type = std::list<std::weak_ptr<vertex>>;\n\n\n\n using vertex_value_type = VertexValueType;\n\n\n\n using visitor_type = visitor<vertex_type>;\n\n\n\n using index_type = int;\n\n\n\n index_type id = 0;\n\n vertex_value_type value = vertex_value_type();\n\n vertices_type adjacencies;\n\n\n\n void accept(visitor_type& visitor) override;\n\n};\n\n\n\ntemplate <typename VertexValueType>\n\nvoid vertex<VertexValueType>::accept(typename vertex<VertexValueType>::visitor_type& visitor)\n\n{\n\n visitor.visit(static_cast<vertex<VertexValueType>&>(*this));\n\n}\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __GRAPH_VERTEX_H__\n", "file_path": "framework/core/graph/vertex.hpp", "rank": 63, "score": 80563.71022730305 }, { "content": "class packrat_parser : private recursive_descent_parser<Token, TreeTraits>\n\n{\n\n //?? Memoization table --> key<position(my_ptr), rule(my_id)> value<tree>\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type;\n\n\n\n public:\n\n packrat_parser(const lexical_analyzer_type& lexical_analyzer);\n\n ~packrat_parser();\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __PACKRAT_PARSER_H__\n", "file_path": "framework/frontend/parser/packrat/packrat_parser.hpp", "rank": 64, "score": 79318.09623175903 }, { "content": "class recursive_descent_parser : private parser<Token, TreeTraits>\n\n{\n\n public:\n\n using token_type = typename parser<Token, TreeTraits>::token_type;\n\n using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type;\n\n\n\n using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type;\n\n\n\n public:\n\n recursive_descent_parser(const lexical_analyzer_type& lexical_analyzer);\n\n ~recursive_descent_parser();\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __RECURSIVE_DESCENT_PARSER_H__\n", "file_path": "framework/frontend/parser/backtracking/recursive_descent_parser.hpp", "rank": 65, "score": 79318.09623175903 }, { "content": "class visitor<TReturn, TParam, TVisitable, TVisitables ...> : public visitor<TReturn, TParam, TVisitables ...>\n\n{\n\n public:\n\n using return_type = TReturn;\n\n using param_type = TParam;\n\n\n\n public:\n\n using visitor<TReturn, TParam, TVisitables ...>::visit; // promote the function(s) from the base class\n\n\n\n public:\n\n virtual TReturn visit(TVisitable& visitable, const TParam& param) = 0;\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif // __VISITOR_H__\n", "file_path": "framework/core/visitor.hpp", "rank": 66, "score": 75160.10054830299 }, { "content": "struct parse_tree : public tree, public visitable\n\n{\n\n using token_type = Token;\n\n using tree_traits_type = TreeTraits;\n\n\n\n using gr_symbol_type = grammar::symbol_type;\n\n\n\n using ir_symbol_type = std::shared_ptr<symtable::symbol<token_type>>;\n\n using ir_symbols_type = std::vector<ir_symbol_type>;\n\n\n\n gr_symbol_type gr_symbol;\n\n ir_symbol_type ir_symbol;\n\n\n\n virtual ~parse_tree()\n\n {\n\n }\n\n\n\n template <typename TVisitor> // deficiency of C++ ... template methods cannot be virtual ...\n\n typename TVisitor::return_type accept(TVisitor& visitor, const typename TVisitor::param_type& param)\n\n {\n", "file_path": "framework/frontend/parser/parse_tree.hpp", "rank": 67, "score": 71363.01579949638 }, { "content": "struct parse_dag : public dag, public visitable\n\n{\n\n using token_type = Token;\n\n using tree_traits_type = TreeTraits;\n\n\n\n using gr_symbol_type = grammar::symbol_type;\n\n\n\n using ir_symbol_type = std::shared_ptr<symtable::symbol<token_type>>;\n\n using ir_symbols_type = std::vector<ir_symbol_type>;\n\n\n\n gr_symbol_type gr_symbol;\n\n ir_symbol_type ir_symbol;\n\n\n\n virtual ~parse_dag()\n\n {\n\n }\n\n\n\n template <typename TVisitor> // deficiency of C++ ... template methods cannot be virtual ...\n\n typename TVisitor::return_type accept(TVisitor& visitor, const typename TVisitor::param_type& param)\n\n {\n", "file_path": "framework/frontend/parser/parse_dag.hpp", "rank": 68, "score": 71363.01579949638 }, { "content": "class noncopyable\n\n{\n\n protected:\n\n constexpr noncopyable() = default;\n\n\n\n noncopyable(const noncopyable&) = delete;\n\n noncopyable(const noncopyable&&) = delete;\n\n\n\n ~noncopyable() = default;\n\n\n\n noncopyable& operator = (const noncopyable&) = delete;\n\n noncopyable& operator = (const noncopyable&&) = delete;\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\nusing noncopyable = COMPANY::core::noncopyable;\n\n\n\n#endif // __NONCOPYABLE_H__\n", "file_path": "framework/core/noncopyable.hpp", "rank": 69, "score": 71099.74360608267 }, { "content": "class visitor;\n\n\n\n// specialization for single type \n\ntemplate <typename TReturn, typename TParam, typename TVisitable>\n", "file_path": "framework/core/visitor.hpp", "rank": 70, "score": 71099.74360608267 }, { "content": "class status\n\n{\n\n public:\n", "file_path": "framework/core/status.hpp", "rank": 71, "score": 71099.74360608267 }, { "content": "class symbol\n\n{\n\n public:\n\n using symbol_type = std::shared_ptr<symbol>;\n\n using symbols_type = std::vector<symbol_type>;\n\n\n\n struct symbol_key_comparator\n\n {\n\n bool operator() (const symbol_type& lhs, const symbol_type& rhs) const\n\n {\n\n return (*lhs).id() < (*rhs).id();\n\n }\n\n };\n\n\n\n using set_type = std::vector<symbol_type>;\n\n using sets_type = std::vector<set_type>;\n\n\n", "file_path": "framework/frontend/grammar/symbol.hpp", "rank": 72, "score": 69583.02750300113 }, { "content": "class rule\n\n{\n\n public:\n\n using symbol_type = symbol::symbol_type;\n\n using symbols_type = symbol::symbols_type;\n\n\n", "file_path": "framework/frontend/grammar/rule.hpp", "rank": 73, "score": 69583.02750300113 }, { "content": "class fsa_algorithm;\n\n\n", "file_path": "framework/frontend/fsa/fsa.hpp", "rank": 74, "score": 68163.79037578446 }, { "content": "class access; //??\n\n\n", "file_path": "framework/backend/generator/activation_record.hpp", "rank": 75, "score": 68163.79037578446 }, { "content": "class fsa_state\n\n{\n\n public:\n\n using token_type = uint32_t;\n\n\n\n using state_type = std::shared_ptr<fsa_state>;\n\n using states_type = std::map<uint32_t, state_type>;\n\n\n\n using transition_type = std::shared_ptr<fsa_transition>;\n\n using transitions_type = std::map<uint32_t, transition_type>;\n\n\n\n private:\n\n uint32_t my_id;\n\n string_type my_label;\n\n\n\n token_type my_token; // final state token type\n\n\n\n transitions_type my_transitions; // outcomming transitions\n\n\n\n bool my_marked;\n", "file_path": "framework/frontend/fsa/fsa_state.hpp", "rank": 76, "score": 66832.92738224792 }, { "content": "struct my_tree0 : public A, public visitable//<my_tree0<T, U>>\n\n{\n\n T k;\n\n U u;\n\n\n\n my_tree0() : k(0), u(0)\n\n {\n\n }\n\n\n\n my_tree0(T i, U u) : k(i), u(u)\n\n {\n\n }\n\n\n\n virtual ~my_tree0() {}\n\n\n\n //int accept(my_visitor& visitor, const char& param) override\n\n //template <typename TReturn, typename TParam, typename TVisitor>\n\n template <typename TVisitor>\n\n typename TVisitor::return_type accept(TVisitor& visitor, const typename TVisitor::param_type& param)\n\n {\n", "file_path": "projects/framework.tests/test_visitor.cpp", "rank": 78, "score": 65329.967599785195 }, { "content": " enum class contributer\n\n {\n\n lexer = 1,\n\n parser = 2,\n\n semantics = 3,\n\n lir = 4,\n\n mir = 5,\n\n hir = 6,\n\n generator = 7\n\n };\n\n\n\n using custom_code_type = custom_code;\n\n using system_code_type = uint32_t;\n\n\n\n using contributer_type = contributer;\n\n\n\n private:\n\n custom_code_type my_custom_code;\n\n system_code_type my_system_code;\n\n\n", "file_path": "framework/core/status.hpp", "rank": 79, "score": 64612.19086747836 }, { "content": " enum class severity\n\n {\n\n info = 0,\n\n warning,\n\n error,\n\n critical,\n\n debug\n\n };\n\n\n\n private:\n\n std::wofstream my_stream;\n\n severity my_severity;\n\n\n\n private:\n\n static void format_time(char_type* buffer, uint16_t buffer_size);\n\n\n\n public:\n\n logger();\n\n ~logger();\n\n\n", "file_path": "framework/core/logger.hpp", "rank": 80, "score": 64612.19086747836 }, { "content": "class fsa_state_set\n\n{\n\n public:\n\n using state_type = fsa_state::state_type;\n\n using states_type = fsa_state::states_type;\n\n\n\n private:\n\n states_type my_states;\n\n state_type my_dfa_state;\n\n\n\n bool my_marked;\n\n\n\n public:\n\n fsa_state_set();\n\n\n\n fsa_state_set(const fsa_state_set& other);\n\n fsa_state_set(fsa_state_set&& other);\n\n\n\n const fsa_state_set& operator = (const fsa_state_set& other);\n\n fsa_state_set& operator = (fsa_state_set&& other);\n", "file_path": "framework/frontend/fsa/fsa_state_set.hpp", "rank": 81, "score": 64405.24156285847 }, { "content": "//template <typename V>\n\nstruct my_visitor : public visitor<int, char, my_tree<int, char>, my_tree<int, char>, my_tree<int, char>>, private noncopyable\n\n{\n\n int visit(my_tree<int, char>& tree, const char& param) override\n\n {\n\n std::wcout << tree.k + param << tree.u << std::endl;\n\n return 0;\n\n }\n\n\n\n //int visit(int& integer, const int& k) override\n\n //{\n\n // std::wcout << integer << std::endl;\n\n // return 0;\n\n //}\n\n};\n\n\n", "file_path": "projects/framework.tests/test_visitor.cpp", "rank": 82, "score": 63469.249999819636 }, { "content": " enum class kind\n\n {\n\n nonterminal,\n\n terminal\n\n };\n\n\n", "file_path": "framework/frontend/grammar/symbol.hpp", "rank": 83, "score": 63192.9537402617 }, { "content": " enum class color\n\n {\n\n white = 0, // not processed\n\n grey, // processed\n\n black // processed with kids\n\n };\n\n\n\n public:\n\n using vertex_type = std::shared_ptr<VertexType>;\n\n using vertex_value_type = typename VertexType::vertex_value_type;\n\n\n\n struct vertex_key_comparator\n\n {\n\n bool operator() (const vertex_type& lhs, const vertex_type& rhs) const\n\n {\n\n return (*lhs).id < (*rhs).id;\n\n }\n\n };\n\n\n\n using vertices_type = std::set<vertex_type, vertex_key_comparator>;\n", "file_path": "framework/core/graph/graph.hpp", "rank": 84, "score": 63192.9537402617 }, { "content": "enum class color\n\n{\n\n RED, BLUE, GREEN = 5\n\n};\n\n\n\n\n\n// https://devblogs.microsoft.com/oldnewthing/20200529-00/?p=103810\n\ntemplate<typename... Args>\n", "file_path": "projects/framework.tests/tests.cpp", "rank": 85, "score": 63192.9537402617 }, { "content": " enum class custom_code\n\n {\n\n success = 1,\n\n warning = 2,\n\n error = -1\n\n };\n\n\n", "file_path": "framework/core/status.hpp", "rank": 86, "score": 63192.9537402617 }, { "content": " enum class tree_action\n\n {\n\n propagate,\n\n remove\n\n };\n\n\n", "file_path": "framework/frontend/grammar/symbol.hpp", "rank": 87, "score": 61862.09074672515 }, { "content": " enum class associativity_type\n\n {\n\n left,\n\n right\n\n };\n\n\n", "file_path": "framework/frontend/grammar/symbol.hpp", "rank": 88, "score": 61862.09074672515 }, { "content": "#define DECLARE_ENUM(E, T, ...) \\\n\n enum class E : T \\\n\n { \\\n\n __VA_ARGS__ \\\n\n }; \\\n\n using enum_map_type = std::map<E, string_type>; \\\n\n \\\n\n static enum_map_type mapping; \\\n\n \\\n\n static void initialize() \\\n\n { \\\n\n mapping = parse_enum<E>(L#__VA_ARGS__); \\\n\n } \\\n\n \\\n\n static string_type name(const E& token_type) \\\n\n { \\\n\n auto it(mapping.find(token_type)); \\\n\n \\\n\n if(it != mapping.end()) \\\n\n { \\\n\n return (*it).second; \\\n", "file_path": "framework/core/enum.hpp", "rank": 89, "score": 59853.731651725815 }, { "content": "", "file_path": "framework/core/tree.hpp", "rank": 90, "score": 59848.31952478282 }, { "content": " enum class flags : uint64_t\n\n {\n\n clear = 0x0000,\n\n deleted = 0x0001,\n\n processed = 0x0008\n\n };\n\n\n\n using flags_type = tmpl_flags<flags>;\n\n\n\n using dag_type = std::shared_ptr<dag>;\n\n using dags_type = std::vector<dag_type>;\n\n\n\n struct dag_key_comparator\n\n {\n\n bool operator () (const dag_type& lhs, const dag_type& rhs) const\n\n {\n\n return (*lhs).id < (*rhs).id;\n\n }\n\n };\n\n\n", "file_path": "framework/core/dag.hpp", "rank": 91, "score": 59848.31952478282 }, { "content": " enum class flags : uint64_t\n\n {\n\n clear = 0x0000,\n\n reg = 0x0001 // if the symbol's value is in a register\n\n };\n\n\n\n using flags_type = tmpl_flags<flags>;\n\n\n\n private:\n\n token_type my_token; // link with content\n\n value_type my_value; // inffered value if any, might be integer value, real value or identifier\n\n\n\n std::size_t my_ssa_id; // 0 - unassigned, 1+\n\n\n\n type_type my_type;\n\n string_type my_machine_type; //??\n\n\n\n size_type my_offset; // runtime offset\n\n\n\n size_type my_size; // runtime size in bytes, might be aligned\n", "file_path": "framework/symtable/symbol.hpp", "rank": 92, "score": 59848.31952478282 }, { "content": " // what to build while calling parse, AST or tree(s)\n\n enum class tree_kind\n\n {\n\n build_ast,\n\n build_trees\n\n };\n\n\n\n // the stack to keep elemens of parse tree's level\n\n struct rhs_stack_element\n\n {\n", "file_path": "framework/frontend/parser/earley/earley_parser.hpp", "rank": 93, "score": 59434.40492733571 }, { "content": " // precedence relations\n\n enum class precedence\n\n {\n\n unknown_relation = 0,\n\n less_relation = 1, // ⋖, op1 has higher precedence than op2\n\n equal_relation = 2, // ≗, op1 an op2 have the same precedence\n\n greater_relation = 3 // ⋗, op1 has lower precedence than op2\n\n };\n\n\n\n using operators_type = std::set<symbol_type, symbol::symbol_key_comparator>;\n\n\n\n using first_precedence_set_type = std::map<symbol_type, set_type, symbol::symbol_key_comparator>;\n\n using last_precedence_set_type = std::map<symbol_type, set_type, symbol::symbol_key_comparator>;\n\n\n\n using precedence_table_row_type = std::vector<std::optional<precedence>>;\n\n using precedence_table_type = std::vector<precedence_table_row_type>;\n\n\n\n private:\n\n static void make_vector_unique(set_type& sequence);\n\n\n\n public:\n", "file_path": "framework/frontend/parser/operator_precedence/precedence_algorithm.hpp", "rank": 94, "score": 59434.40492733571 }, { "content": " enum class element_type\n\n {\n\n item = 1, // earley item\n\n rptrs, // rightmost child(s), if grammar is ambiguous\n\n symbol // terminal and its position in the rule.rhs\n\n };\n\n\n\n using data_type = std::variant<item_type, items_type, symbol_type>;\n\n\n\n data_type data;\n\n token_type token;\n\n element_type type;\n\n };\n\n\n\n using rhs_stack_type = std::stack<rhs_stack_element>;\n\n\n\n using earley_tree = parse_tree<token_type, tree_traits_type>;\n\n\n\n using tree_type = typename parser<token_type, tree_traits_type>::parse_tree_type;\n\n using trees_type = typename parser<token_type, tree_traits_type>::parse_trees_type;\n", "file_path": "framework/frontend/parser/earley/earley_parser.hpp", "rank": 95, "score": 59434.40492733571 }, { "content": " enum class flags : uint64_t\n\n {\n\n clear = 0x0000\n\n };\n\n\n\n using flags_type = tmpl_flags<flags>;\n\n\n\n static symbol_type epsilon;\n\n static symbol_type eof;\n\n static symbol_type op_mark; // operator precedence mark symbol, #\n\n\n\n private:\n\n uint32_t my_id; // enumerable type, will be cast to specific enum values\n\n string_type my_name; // name (label) of the symbol\n\n\n\n kind my_kind; // terminal or non-terminal\n\n\n\n flags_type my_flags; // flags\n\n\n\n bool my_nullable; // if A ->* e\n", "file_path": "framework/frontend/grammar/symbol.hpp", "rank": 96, "score": 58517.456531246266 }, { "content": " enum class flags : uint64_t\n\n {\n\n clear = 0x00,\n\n genuine = 0x02,\n\n synthetic = 0x04 // additional (artificial) tokens which are inserted into the token stream ...\n\n };\n\n\n\n using flags_type = tmpl_flags<flags>;\n\n\n\n using traits = Traits;\n\n using token_type = typename traits::type;\n\n\n\n token_type type; // type of lexeme\n\n\n\n loc_type offset; // offset in context (absolute address)\n\n uint32_t length; // length of lexeme\n\n\n\n codepoints_type literal; // string or char literal, numeric value\n\n\n\n flags_type flags;\n", "file_path": "framework/frontend/grammar/token.hpp", "rank": 97, "score": 58517.456531246266 }, { "content": " enum class flags : uint64_t\n\n {\n\n clear = 0x00\n\n };\n\n\n\n using flags_type = tmpl_flags<flags>;\n\n using ast_operators_type = std::map<std::size_t, tree::flags_type>;\n\n\n\n private:\n\n uint32_t my_id; // enumerable type, will be cast to specific enum values\n\n string_type my_name;\n\n\n\n uint8_t my_lhs_terminal_count;\n\n uint8_t my_lhs_nonterminal_count;\n\n\n\n uint8_t my_rhs_terminal_count;\n\n uint8_t my_rhs_nonterminal_count;\n\n\n\n uint8_t my_precedence; // production either inherits the precedence number of the rightmost terminal in the RHS or has explicitly set it up\n\n uint8_t my_precedences; // context dependent precedence level of terminals for the rule (shift/reduce parsers)\n", "file_path": "framework/frontend/grammar/rule.hpp", "rank": 98, "score": 58517.456531246266 }, { "content": "struct my_token_traits : public token_traits\n\n{\n\n DECLARE_ENUM\n\n (\n\n type,\n\n uint32_t,\n\n unknown = 0,\n\n epsilon = 5,\n\n eol,\n\n eos,\n\n indent,\n\n dedent,\n\n\n\n binary_integer_lit,\n\n octal_integer_lit,\n\n decimal_integer_lit,\n\n hexadecimal_integer_lit,\n\n decimal_floating_lit,\n\n hexadecimal_floating_lit,\n\n\n", "file_path": "projects/framework.tests/tests.cpp", "rank": 99, "score": 56515.40057839292 } ]
C++
spline_planner/src/eigen_spline.cpp
Veilkrand/drone_race
7391f1a94bfe354aab3e24be61b76e1595481ad9
#include <boost/python.hpp> #include <boost/assert.hpp> #include <vector> #include <Eigen/Dense> #include "eigen_spline.hpp" using namespace spline_planner; namespace py = boost::python; py::list ColumnMajorMatrixToRowMajorPython2DList(const Eigen::MatrixXd& mat) { py::list result; const size_t cols = mat.cols(); const size_t rows = mat.rows(); for (size_t i = 0; i < cols; ++i) { py::list vec; for (size_t j = 0; j < rows; ++j) { vec.append(mat(j, i)); } result.append(vec); } return result; } Eigen::MatrixXd RowMajorPython2DListToColumnMajorMatrix(py::list list) { const size_t rows = py::len(list); const size_t cols = py::len(list[0]); Eigen::MatrixXd mat(rows, cols); for (size_t r = 0; r < rows; ++r) { py::list row = static_cast<py::list>(list[r]); for (size_t c = 0; c < cols; ++c) { mat(c, r) = py::extract<double>(row[c]); } } return mat; } struct SplineSamplingCallback { void operator()(double t, double s, const Eigen::MatrixXd& derivatives) { py::list point; point.append(t); point.append(s); point.append(ColumnMajorMatrixToRowMajorPython2DList(derivatives)); result.append(point); } py::list result; }; typedef spline_planner::Spline3D<3> CubicSpline3D; struct CubicSpline3DWrapper { CubicSpline3DWrapper(py::list points) : spline_(nullptr) { const int num_pts = py::len(points); Eigen::MatrixXd mat(3, num_pts); for (size_t i = 0; i < num_pts; ++i) { mat(0, i) = py::extract<double>(points[i][0]); mat(1, i) = py::extract<double>(points[i][1]); mat(2, i) = py::extract<double>(points[i][2]); } spline_ = new CubicSpline3D(mat); } CubicSpline3DWrapper(py::list points, py::list derivatives, py::list index) : spline_(nullptr) { const int num_pts = py::len(points); Eigen::MatrixXd mat(3, num_pts); for (size_t i = 0; i < num_pts; ++i) { mat(0, i) = py::extract<double>(points[i][0]); mat(1, i) = py::extract<double>(points[i][1]); mat(2, i) = py::extract<double>(points[i][2]); } const int num_derivs = py::len(derivatives); Eigen::MatrixXd mat_derivs(3, num_derivs); for (size_t i = 0; i < num_derivs; ++i) { mat_derivs(0, i) = py::extract<double>(derivatives[i][0]); mat_derivs(1, i) = py::extract<double>(derivatives[i][1]); mat_derivs(2, i) = py::extract<double>(derivatives[i][2]); } Eigen::VectorXi vec_index(num_derivs); for (size_t i = 0; i < num_derivs; ++i) { vec_index(i) = py::extract<int>(index[i]); } spline_ = new CubicSpline3D(mat, mat_derivs, vec_index); } py::list SampleAndCollect0() { return SampleAndCollect(); } py::list SampleAndCollect1(double sample_ds) { return SampleAndCollect(sample_ds); } py::list SampleAndCollect2(double sample_ds, double s_limit) { return SampleAndCollect(sample_ds, s_limit); } py::list SampleAndCollect(double sample_ds = 0.1, double s_limit=100.0, double dt = 0.01) { SplineSamplingCallback callback; spline_->Sample(callback, sample_ds, s_limit, 2, dt); return callback.result; } ~CubicSpline3DWrapper() { if (spline_) { delete spline_; } } CubicSpline3D* spline_; }; BOOST_PYTHON_MODULE(eigen_spline) { py::class_<CubicSpline3DWrapper>("CubicSpline3DWrapper", py::init<py::list>()) .def(py::init<py::list, py::list, py::list>()) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect0) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect1) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect2) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect); }
#include <boost/python.hpp> #include <boost/assert.hpp> #include <vector> #include <Eigen/Dense> #include "eigen_spline.hpp" using namespace spline_planner; namespace py = boost::python; py::list ColumnMajorMatrixToRowMajorPython2DList(const Eigen::MatrixXd& mat) { py::list result; const size_t cols = mat.cols(); const size_t rows = mat.rows(); for (size_t i = 0; i < cols; ++i) { py::list vec; for (size_t j = 0; j < rows; ++j) { vec.append(mat(j, i)); } result.append(vec); } return result; } Eigen::MatrixXd RowMajorPython2DListToColumnMajorMatrix(py::list list) { const size_t rows = py::len(list); const size_t cols = py::len(list[0]); Eigen::MatrixXd mat(rows, cols); for (size_t r = 0; r < rows; ++r) { py::list row = static_cast<py::list>(list[r]); for (size_t c = 0; c < cols; ++c) { mat(c, r) = py::extract<double>(row[c]); } } return mat; } struct SplineSamplingCallback { void operator()(double t, double s, const Eigen::MatrixXd& derivatives) { py::list point; point.append(t); point.append(s); point.append(ColumnMajorMatrixToRowMajorPython2DList(derivatives)); result.append(point); } py::list result; }; typedef spline_planner::Spline3D<3> CubicSpline3D; struct CubicSpline3DWrapper { CubicSpline3DWrapper(py::list points) : spline_(nullptr) { const int num_pts = py::len(points); Eigen::MatrixXd mat(3, num_pts); for (size_t i = 0; i < num_pts; ++i) { mat(0, i) = py::extract<double>(points[i][0]); mat(1, i) = py::extract<double>(points[i][1]); mat(2, i) = py::extract<double>(points[i][2]); } spline_ = new CubicSpline3D(mat); } CubicSpline3DWrapper(py::list points, py::list derivatives, py::list index) : spline_(nullptr) { const int num_pts = py::len(points); Eigen::MatrixXd mat(3, num_pts); for (size_t i = 0; i < num_pts; ++i) { mat(0, i) = py::extract<double>(points[i][0]); mat(1, i) = py::extract<double>(points[i][1]); mat(2, i) = py::extract<double>(points[i][2]); } const int num_derivs = py::len(derivatives); Eigen::MatrixXd mat_derivs(3, num_derivs); for (size_t i = 0; i < num_derivs; ++i) { mat_derivs(0, i) = py::extract<double>(derivatives[i][0]); mat_derivs(1, i) = py::extract<double>(derivatives[i][1]); mat_derivs(2, i) = py::extract<double>(derivatives[i][2]); } Eigen::VectorXi vec_index(num_derivs); for (size_t i = 0; i < num_derivs; ++i) { vec_index(i) = py::extract<int>(index[i]); } spline_ = new CubicSpline3D(mat, mat_derivs, vec_index); } py::list SampleAndCollect0() { return SampleAndCollect(); } py::list SampleAndCollect1(double sample_ds) { return SampleAndCollect(sample_ds); } py::list SampleAndCollect2(double sample_ds, double s_limit) { return SampleAndCollect(sample_ds, s_limit); } py::list SampleAndCollect(double sample_ds = 0.1, double s_limit=100.0, double dt = 0.01) { SplineSamplingCallback callback; spline_->Sample(callback, sample_ds, s_limit, 2, dt); return callback.result; } ~CubicSpline3DWrapper() { if (spline_) { delete spline_; } } CubicSpline3D* spline_; }; BOOST_PYTHON_MODULE(eigen_spline) {
.def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect1) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect2) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect); }
py::class_<CubicSpline3DWrapper>("CubicSpline3DWrapper", py::init<py::list>()) .def(py::init<py::list, py::list, py::list>()) .def("sampleAndCollect", &CubicSpline3DWrapper::SampleAndCollect0)
call_expression
[ { "content": "def vector_to_list(vec):\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 1, "score": 85291.53639601504 }, { "content": "def vec_to_quat(vec):\n\n \"\"\"To fully determine the orientation represented by the resulting quaternion, this method will assume the top of objects would always facing up\n\n \"\"\"\n\n norm = np.linalg.norm(vec)\n\n if norm < 1e-5:\n\n return np.array([0, 0, 0, 1], dtype=np.float)\n\n obj_x = vec / norm\n\n obj_z_t = np.array([0, 0, 1], dtype=np.float)\n\n obj_y = np.cross(obj_z_t, obj_x)\n\n obj_y /= np.linalg.norm(obj_y) \n\n obj_z = np.cross(obj_x, obj_y)\n\n rot_mat = np.identity(4)\n\n rot_mat[:3,:3] = np.array([obj_x,\n\n obj_y,\n\n obj_z]).T\n\n q = tf.transformations.quaternion_from_matrix(rot_mat)\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 2, "score": 85173.02924359952 }, { "content": "def point_to_vector(point):\n\n res = Vector3()\n\n res.x = point.x\n\n res.y = point.y\n\n res.z = point.z\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 3, "score": 85143.61658902235 }, { "content": "def point_to_ndarray(point):\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 4, "score": 85037.93683043121 }, { "content": " def odometry_callback(self, odometry):\n\n # type: (Odometry) -> None\n\n prev_time = self.current_time\n\n self.current_time = odometry.header.stamp.to_sec()\n\n\n\n self.last_position = self.current_position\n\n self.current_position = point_to_ndarray(odometry.pose.pose.position)\n\n\n\n prev_velocity = self.current_velocity\n\n self.current_velocity = SplinePlannerNew.rotate_vector_wrt_quaternion(\n\n quaternion_to_ndarray(odometry.pose.pose.orientation),\n\n vector3_to_ndarray(odometry.twist.twist.linear))\n\n\n\n if prev_velocity is not None and prev_time is not None:\n\n self.current_acceleration = (self.current_velocity - prev_velocity) / (self.current_time - prev_time)\n\n\n\n if self.last_position is None or self.target_gate_idx is None:\n\n return\n\n # check if the drone has passed the target gate\n\n if self.is_cross_gate(self.target_gate_idx, self.last_position, self.current_position):\n\n rospy.loginfo(\"Drone has passed gate {}\".format(self.target_gate_idx))\n\n if self.head_for_next_gate():\n\n rospy.loginfo(\"Heading for gate {}\".format(self.target_gate_idx))\n\n else:\n\n rospy.loginfo(\"All gates have been visited. Stop planning.\")\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 5, "score": 84919.63194776098 }, { "content": "def vector_two_points(p0, p1):\n\n\n\n v = Point()\n\n v.x = p1.x - p0.x\n\n v.y = p1.y - p0.y\n\n v.z = p1.z - p0.z\n\n\n", "file_path": "waypoint_controller/src/ros_geometry.py", "rank": 6, "score": 82996.72124096652 }, { "content": "def point_plus_vector(point, vector):\n\n res = Vector3()\n\n res.x = point.x + vector.x\n\n res.y = point.y + vector.y\n\n res.z = point.z + vector.z\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 7, "score": 82996.72124096651 }, { "content": "def unit_vector_two_points(point1, point2):\n\n\n\n v = Point()\n\n v.x = point2.x-point1.x\n\n v.y = point2.y-point1.y\n\n v.z = point2.z - point1.z\n\n\n", "file_path": "waypoint_controller/src/ros_geometry.py", "rank": 8, "score": 80955.43094741712 }, { "content": " def calculate_points_with_geometric_information(self, points):\n\n result = []\n\n info = {}\n\n max_k = 0\n\n this_point = None # type: {}\n\n last_point = None # type: {}\n\n for (s, t), (pt, d1, d2) in points:\n\n last_point = this_point\n\n # curvature is calcuated as norm(deriv1 x deriv2) / norm(deriv1)**3\n\n # see: https://en.wikipedia.org/wiki/Curvature#Local_expressions_2\n\n d1xd2 = np.cross(d1, d2)\n\n norm_d1 = np.linalg.norm(d1)\n\n norm_d2 = np.linalg.norm(d2)\n\n k = 0 # curvature\n\n if norm_d1 > 1e-5:\n\n k = np.linalg.norm(d1xd2) / norm_d1 ** 3\n\n\n\n # the first order derivative is given as ds/dt, where s is the arc length and t is the internal parameter of the spline,\n\n # not time.\n\n # because of this, the magnitude of first order derivative is not the same with viable speed,\n\n # but nevertheless, the direction of the derivative of them are the same.\n\n\n\n # also note that unit normal vector at point is just the normalized second order derivative,\n\n # it is in the opposite direction of the radius vector\n\n\n\n # the cross product of unit tangent vector and unit normal vector\n\n # is also mentioned as unit binormal vector\n\n if norm_d1 > 1e-5:\n\n unit_d1 = d1 / norm_d1\n\n else:\n\n unit_d1 = np.array([0, 0, 0], dtype=np.float)\n\n \n\n if norm_d2 > 1e-5:\n\n unit_d2 = d2 / norm_d2\n\n else:\n\n unit_d2 = np.array([0, 0, 0], dtype=np.float)\n\n\n\n unit_binormal = np.cross(unit_d1, unit_d2)\n\n\n\n ds = s - last_point['s'] if last_point is not None else 0.0\n\n\n\n this_point = {\n\n 't': t,\n\n 's': s,\n\n 'ds': ds,\n\n 'point': pt,\n\n 'd1': d1, \n\n 'd2': d2,\n\n 'unit_d1': unit_d1,\n\n 'unit_d2': unit_d2,\n\n 'unit_b': unit_binormal,\n\n 'curvature': k\n\n }\n\n if k > max_k:\n\n max_k = k\n\n result.append(this_point)\n\n info['max_k'] = max_k\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 9, "score": 80854.94954033218 }, { "content": " def rotate_vector_wrt_quaternion(q, v):\n\n p = np.array([0, 0, 0, 0], dtype=np.float)\n\n p[0:3] = v\n\n # p' = q * p * q'\n\n p_prime = tf.transformations.quaternion_multiply(\n\n tf.transformations.quaternion_multiply(q, p),\n\n tf.transformations.quaternion_inverse(q))\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 10, "score": 80742.46403474249 }, { "content": "class SplinePlannerNew(object):\n\n def __init__(self):\n\n self.srv = None\n\n self.max_speed = 6.0\n\n self.max_acceleration = 3.0\n\n self.ds = 0.2\n\n self.gate_locations = []\n\n self.odometry_sub = None\n\n self.raw_waypoints_viz_pub = None # type: rospy.Publisher\n\n self.traj_pub = None # type: rospy.Publisher\n\n self.last_position = None\n\n self.current_time = None\n\n self.current_position = None\n\n self.current_velocity = None\n\n self.current_acceleration = None\n\n self.initial_position = None\n\n self.previous_gate_idx = None\n\n self.target_gate_idx = None\n\n self.gates_sequence = []\n\n self.current_path = None\n\n self.stop_planning = False\n\n self.waypoint_speeds = []\n\n\n\n def rprop_optimize(self, waypoints, d1, d2):\n\n new_d1 = d1.copy()\n\n start = time.time()\n\n\n\n min_k_path = None\n\n min_k = None\n\n t_start = None\n\n\n\n eta_inc = 1.2\n\n eta_dec = 0.5\n\n factor = 1\n\n delta = 0.1\n\n last_ks = []\n\n last_factors = []\n\n\n\n for i in range(1):\n\n path = propose_geometric_spline_path(waypoints, new_d1, d2)\n\n trajectory_points = sample_path([path[0]])\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n print(factor, info['max_k'])\n\n if min_k is None or info['max_k'] < min_k:\n\n min_k = info['max_k']\n\n min_k_path = path\n\n\n\n last_factors.append(factor)\n\n last_ks.append(info['max_k'])\n\n if len(last_ks) > 3:\n\n del last_factors[0]\n\n del last_ks[0]\n\n\n\n if len(last_ks) == 1:\n\n t_start = trajectory_points[0]['d1']\n\n\n\n if len(last_ks) == 3:\n\n grad_1 = last_ks[-1] - last_ks[-2]\n\n grad_2 = last_ks[-2] - last_ks[-3]\n\n change = last_factors[-1] - last_factors[-2]\n\n if grad_1 * grad_2 > 0:\n\n change *= eta_inc\n\n else:\n\n change *= eta_dec\n\n\n\n delta = np.sign(grad_1) * change\n\n\n\n factor += delta\n\n new_d1[0] = t_start * factor\n\n end = time.time()\n\n rospy.loginfo(\"Time used: {}\".format(end-start))\n\n trajectory_points = sample_path(min_k_path)\n\n trajectory_points, _ = self.calculate_points_with_geometric_information(trajectory_points)\n\n return trajectory_points\n\n\n\n def generate_trajectory_strategy_2(self):\n\n \"\"\"Instead of using current position as the starting re-planning waypoint, this strategy don't\n\n use any information about the current position of the drone. It instead only use 3 nearby gate \n\n positions (or the initial position if we're at the very beginning) to generate a new trajectory.\n\n \"\"\"\n\n if self.previous_gate_idx is None:\n\n wp0 = self.initial_position\n\n else:\n\n wp0 = self.gate_locations[self.previous_gate_idx]['center']\n\n wp1 = self.get_waypoint_for_next_n_gate(1)\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n d1, d2 = {}, {}\n\n path = propose_geometric_spline_path((wp0, wp1, wp2))\n\n trajectory_points = sample_path(path)\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n path = self.generate_velocity_profile(trajectory_points)\n\n self.current_path = path\n\n return path\n\n\n\n def generate_trajectory(self):\n\n # every time when re-planning, there are 3 raw waypoints:\n\n # the current position, position of the next gate, position of the next next gate\n\n #\n\n # in case that the drone is too close to \n\n # the next gate, an alternate waypoint from the last trajectory is used instead of the position\n\n # of the next gate. the alternate waypoint must not be too close to the gate too.\n\n #\n\n # in case that we don't have a next next gate, a waypoint that is 5 meter away from the last gate\n\n # along the trajectory direction is used instead\n\n next_gate = self.get_waypoint_for_next_n_gate()\n\n wp0 = self.current_position\n\n d1 = {}\n\n d2 = {}\n\n if self.current_path is not None:\n\n skip_next_gate = False\n\n if np.linalg.norm(next_gate - wp0) <= 0.5:\n\n rospy.loginfo(\"Too close to next gate: {}. Will head for more future gates for waypoints.\".format(self.target_gate_idx))\n\n skip_next_gate = True\n\n \n\n if skip_next_gate:\n\n wp1 = self.get_waypoint_for_next_n_gate(2)\n\n wp2 = self.get_waypoint_for_next_n_gate(3)\n\n else:\n\n wp1 = next_gate\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n else:\n\n rospy.loginfo(\"Planning for the first time\")\n\n wp1 = next_gate\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n\n\n self.publish_raw_waypoints_viz(wp0, wp1, wp2)\n\n # path = propose_geometric_spline_path((wp0, wp1, wp2), d1, d2)\n\n # trajectory_points = sample_path(path)\n\n\n\n current_speed = np.linalg.norm(self.current_velocity)\n\n if current_speed > 0.01:\n\n d1[0] = self.current_velocity / current_speed * np.linalg.norm(wp1 - wp0) * 0.1\n\n \n\n #path = self.rprop_optimize((wp0, wp1, wp2), d1, d2)\n\n path = propose_geometric_spline_path((wp0, wp1, wp2), d1, d2)\n\n trajectory_points = sample_path(path)\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n path = self.generate_velocity_profile(trajectory_points)\n\n self.current_path = path\n\n return path\n\n\n\n def search_for_nearest_waypoint(self, position):\n\n num_points = len(self.current_path)\n\n for i in range(num_points - 1, -1, -1):\n\n prev_pt = self.current_path[i - 1][\"point\"]\n\n next_pt = self.current_path[i][\"point\"]\n\n vec_ref = np.array(next_pt) - np.array(prev_pt)\n\n vec = np.array(next_pt) - np.array(position)\n\n if np.dot(vec, vec_ref) <= 0:\n\n return i\n\n return 0\n\n\n\n def get_waypoint_for_next_n_gate(self, n=1):\n\n if n == 1:\n\n return self.gate_locations[self.target_gate_idx]['center']\n\n if n - 1 > len(self.gates_sequence):\n\n if len(self.gates_sequence) <= 1:\n\n # no gates or only one gate left. get waypoint 5 meters along the direction from the current position to the target gate\n\n target_gate_loc = self.gate_locations[self.target_gate_idx]['center']\n\n direction = target_gate_loc - self.current_position\n\n direction /= np.linalg.norm(direction)\n\n else:\n\n # in this case, direction is defined as the last but 1 gate towards the last gate.\n\n target_gate_loc = self.gate_locations[self.gates_sequence[-1]]['center']\n\n direction = target_gate_loc - self.gate_locations[self.gates_sequence[-2]]['center']\n\n direction /= np.linalg.norm(direction)\n\n return target_gate_loc + 5 * direction\n\n else:\n\n return self.gate_locations[self.gates_sequence[n - 2]]['center']\n\n\n\n def generate_velocity_profile(self, points):\n\n # trajectory_points = self.calculate_points_with_geometric_information(points)\n\n trajectory_points = points\n\n\n\n trajectory_points[0]['speed'] = np.linalg.norm(self.current_velocity)\n\n trajectory_points[0]['velocity'] = self.current_velocity\n\n trajectory_points[0]['time'] = 0.0\n\n num_traj = len(trajectory_points)\n\n for i in range(num_traj - 1):\n\n prev_speed = trajectory_points[i]['speed']\n\n prev_time = trajectory_points[i]['time']\n\n ds = trajectory_points[i + 1]['ds']\n\n\n\n speed = self.calculate_safe_speed(trajectory_points[i + 1]['curvature'], prev_speed, ds)\n\n trajectory_points[i + 1]['speed'] = speed\n\n trajectory_points[i + 1]['velocity'] = speed * trajectory_points[i + 1]['unit_d1']\n\n\n\n avg_speed = 0.5 * (prev_speed + speed)\n\n current_time = prev_time + ds / avg_speed\n\n trajectory_points[i + 1]['time'] = current_time\n\n\n\n accel = (trajectory_points[i + 1]['velocity'] - trajectory_points[i]['velocity']) / (current_time - prev_time)\n\n trajectory_points[i]['acceleration'] = accel\n\n if len(trajectory_points) > 1:\n\n trajectory_points[-1]['acceleration'] = trajectory_points[-2]['acceleration']\n\n return trajectory_points\n\n\n\n\n\n def calculate_safe_speed(self, curvature, speed_neighbor, ds):\n\n centripetal = curvature * speed_neighbor**2\n\n if centripetal >= self.max_acceleration:\n\n return min(self.max_speed, np.sqrt(abs(self.max_acceleration / curvature)))\n\n\n\n remaining_acceleration = np.sqrt(self.max_acceleration**2 - centripetal**2)\n\n # see /Planning Motion Trajectories for Mobile Robots Using Splines/\n\n # (refered as Sprunk[2008] later) for more details (eq 3.21)\n\n v_this = np.sqrt(speed_neighbor ** 2 + 2 * ds * remaining_acceleration)\n\n return min(self.max_speed, v_this)\n\n\n\n def calculate_points_with_geometric_information(self, points):\n\n result = []\n\n info = {}\n\n max_k = 0\n\n this_point = None # type: {}\n\n last_point = None # type: {}\n\n for (s, t), (pt, d1, d2) in points:\n\n last_point = this_point\n\n # curvature is calcuated as norm(deriv1 x deriv2) / norm(deriv1)**3\n\n # see: https://en.wikipedia.org/wiki/Curvature#Local_expressions_2\n\n d1xd2 = np.cross(d1, d2)\n\n norm_d1 = np.linalg.norm(d1)\n\n norm_d2 = np.linalg.norm(d2)\n\n k = 0 # curvature\n\n if norm_d1 > 1e-5:\n\n k = np.linalg.norm(d1xd2) / norm_d1 ** 3\n\n\n\n # the first order derivative is given as ds/dt, where s is the arc length and t is the internal parameter of the spline,\n\n # not time.\n\n # because of this, the magnitude of first order derivative is not the same with viable speed,\n\n # but nevertheless, the direction of the derivative of them are the same.\n\n\n\n # also note that unit normal vector at point is just the normalized second order derivative,\n\n # it is in the opposite direction of the radius vector\n\n\n\n # the cross product of unit tangent vector and unit normal vector\n\n # is also mentioned as unit binormal vector\n\n if norm_d1 > 1e-5:\n\n unit_d1 = d1 / norm_d1\n\n else:\n\n unit_d1 = np.array([0, 0, 0], dtype=np.float)\n\n \n\n if norm_d2 > 1e-5:\n\n unit_d2 = d2 / norm_d2\n\n else:\n\n unit_d2 = np.array([0, 0, 0], dtype=np.float)\n\n\n\n unit_binormal = np.cross(unit_d1, unit_d2)\n\n\n\n ds = s - last_point['s'] if last_point is not None else 0.0\n\n\n\n this_point = {\n\n 't': t,\n\n 's': s,\n\n 'ds': ds,\n\n 'point': pt,\n\n 'd1': d1, \n\n 'd2': d2,\n\n 'unit_d1': unit_d1,\n\n 'unit_d2': unit_d2,\n\n 'unit_b': unit_binormal,\n\n 'curvature': k\n\n }\n\n if k > max_k:\n\n max_k = k\n\n result.append(this_point)\n\n info['max_k'] = max_k\n\n return result, info\n\n\n\n def publish_raw_waypoints_viz(self, *waypoints):\n\n raw_waypoints_marker = Marker()\n\n raw_waypoints_marker.header.stamp = rospy.Time.now()\n\n raw_waypoints_marker.header.frame_id = \"world\"\n\n raw_waypoints_marker.color = ColorRGBA(1.0, 1.0, 0.0, 1.0)\n\n raw_waypoints_marker.scale = Vector3(0.5, 0.5, 0.5)\n\n raw_waypoints_marker.type = Marker.SPHERE_LIST\n\n raw_waypoints_marker.action = Marker.ADD\n\n raw_waypoints_marker.id = 1\n\n for wp in waypoints:\n\n if wp is not None:\n\n raw_waypoints_marker.points.append(Point(wp[0], wp[1], wp[2]))\n\n self.raw_waypoints_viz_pub.publish(raw_waypoints_marker)\n\n\n\n def publish_trajectory(self, trajectory):\n\n trajectory_msg = MultiDOFJointTrajectory()\n\n trajectory_msg.header.frame_id='world'\n\n trajectory_msg.joint_names = ['base']\n\n for idx in range(len(trajectory)):\n\n point = trajectory[idx]\n\n point['time'] = trajectory[idx]['time']\n\n transform = Transform()\n\n transform.translation = Vector3(*(point['point'].tolist()))\n\n transform.rotation = Quaternion(*(vec_to_quat(point['velocity']).tolist()))\n\n velocity = Twist()\n\n velocity.linear = Vector3(*(point['velocity'].tolist()))\n\n acceleration = Twist()\n\n acceleration.linear = Vector3(*(point['acceleration'].tolist()))\n\n \n\n trajectory_msg.points.append(MultiDOFJointTrajectoryPoint([transform], [velocity], [acceleration], rospy.Duration(point['time'])))\n\n\n\n trajectory_msg.header.stamp = rospy.Time.now()\n\n self.traj_pub.publish(trajectory_msg)\n\n\n\n def head_for_next_gate(self):\n\n if len(self.gates_sequence) == 0:\n\n rospy.loginfo(\"No next targeting gate.\")\n\n self.target_gate_idx = None\n\n return False\n\n self.previous_gate_idx = self.target_gate_idx\n\n self.target_gate_idx = self.gates_sequence[0]\n\n del self.gates_sequence[0]\n\n rospy.loginfo(\"Next gate: {}\".format(self.target_gate_idx))\n\n return True\n\n\n\n def is_cross_gate(self, gate_index, position_before, position_after):\n\n \"\"\"Check if the drone has passed the target gate.\n\n\n\n To do this, make two vectors: from last position to gate and current position to gate,\n\n project them and the vector from gate center to gate edge(left/right edge) onto the XY-plane.\n\n By comparing the sign of the cross products of position-gate vector and gate-border vector,\n\n if they are not the same, then we have cross the gate.\n\n \"\"\"\n\n if np.linalg.norm(position_after - position_before) < 1e-5:\n\n # the two positions are too close\n\n return False\n\n gate_position = self.gate_locations[gate_index][\"center\"]\n\n gate_proj_xy = self.gate_locations[gate_index][\"gate_proj_xy\"]\n\n\n\n position_before_xy = (position_before - gate_position)[:2]\n\n position_after_xy = (position_after - gate_position)[:2]\n\n\n\n return np.cross(position_before_xy, gate_proj_xy) * np.cross(position_after_xy, gate_proj_xy) < 0\n\n\n\n def odometry_callback(self, odometry):\n\n # type: (Odometry) -> None\n\n prev_time = self.current_time\n\n self.current_time = odometry.header.stamp.to_sec()\n\n\n\n self.last_position = self.current_position\n\n self.current_position = point_to_ndarray(odometry.pose.pose.position)\n\n\n\n prev_velocity = self.current_velocity\n\n self.current_velocity = SplinePlannerNew.rotate_vector_wrt_quaternion(\n\n quaternion_to_ndarray(odometry.pose.pose.orientation),\n\n vector3_to_ndarray(odometry.twist.twist.linear))\n\n\n\n if prev_velocity is not None and prev_time is not None:\n\n self.current_acceleration = (self.current_velocity - prev_velocity) / (self.current_time - prev_time)\n\n\n\n if self.last_position is None or self.target_gate_idx is None:\n\n return\n\n # check if the drone has passed the target gate\n\n if self.is_cross_gate(self.target_gate_idx, self.last_position, self.current_position):\n\n rospy.loginfo(\"Drone has passed gate {}\".format(self.target_gate_idx))\n\n if self.head_for_next_gate():\n\n rospy.loginfo(\"Heading for gate {}\".format(self.target_gate_idx))\n\n else:\n\n rospy.loginfo(\"All gates have been visited. Stop planning.\")\n\n self.stop_planning = True\n\n\n\n @staticmethod\n\n def rotate_vector_wrt_quaternion(q, v):\n\n p = np.array([0, 0, 0, 0], dtype=np.float)\n\n p[0:3] = v\n\n # p' = q * p * q'\n\n p_prime = tf.transformations.quaternion_multiply(\n\n tf.transformations.quaternion_multiply(q, p),\n\n tf.transformations.quaternion_inverse(q))\n\n return p_prime[:3]\n\n\n\n def reconfigure_parameteres(self, config, level):\n\n rospy.loginfo(\"\"\"Parameters reconfiguration requested:\n\nds: {ds}\n\nmax_speed: {max_linear_speed}\n\nmax_total_acceleration: {max_total_acceleration}\"\"\".format(**config))\n\n self.max_speed = config.max_linear_speed\n\n self.max_acceleration = config.max_total_acceleration\n\n self.ds = config.ds\n\n\n\n return config\n\n\n\n def load_nominal_gates_locations(self):\n\n \"\"\"Load nominal gates information from parameter server and store it as the \n\n initial position of gates.\n\n \"\"\"\n\n # for convenient, append a None at index 0 and let gate 1 be in index 1 of \n\n # self.gate_locations\n\n self.gate_locations.append(None)\n\n num_total_gates = 23\n\n for i in range(1, num_total_gates + 1):\n\n nominal_gate_param_name = \"/uav/Gate{}/nominal_location\".format(i)\n\n corners = np.array(rospy.get_param(nominal_gate_param_name))\n\n norms = [np.linalg.norm(corners[1] - corners[0]),\n\n np.linalg.norm(corners[2] - corners[0]),\n\n np.linalg.norm(corners[3] - corners[0])]\n\n idx = np.argmax(norms)\n\n center = (corners[idx + 1] + corners[0]) / 2\n\n gate_proj_xy = (corners[idx + 1] - corners[0])[:2]\n\n self.gate_locations.append({\n\n \"center\": center,\n\n \"gate_proj_xy\": gate_proj_xy / np.linalg.norm(gate_proj_xy)\n\n })\n\n\n\n def load_course_gates(self):\n\n \"\"\"Load gate sequence of course from parameter /uav/gate_names\n\n \"\"\"\n\n gates = rospy.get_param(\"/uav/gate_names\", None)\n\n \n\n if gates is None:\n\n rospy.logwarn(\"Unable to load course definition from /uav/gate_names\")\n\n self.gates_sequence = []\n\n return\n\n\n\n self.gates_sequence = list(int(g.replace(\"Gate\", \"\"), 10) for g in gates)\n\n rospy.loginfo(\"Course loaded. Gate sequence: {}\".format(self.gates_sequence))\n\n\n\n def load_initial_pose(self):\n\n \"\"\"Load initial pose of the drone\"\"\"\n\n pose = rospy.get_param(\"/uav/flightgoggles_uav_dynamics/init_pose\")\n\n px, py, pz, qx, qy, qz, qw = pose\n\n self.initial_position = np.array([px, py, pz], dtype=np.float)\n\n self.initial_orientation = np.array([qx, qy, qz, qw], dtype=np.float)\n\n\n\n def start(self, name=\"SplinePlannerNew\"):\n\n rospy.init_node(name)\n\n self.srv = Server(PlannerConfig, self.reconfigure_parameteres)\n\n\n\n self.load_nominal_gates_locations()\n\n self.load_course_gates()\n\n self.load_initial_pose()\n\n \n\n self.odometry_sub = rospy.Subscriber(\"~odometry\", Odometry, self.odometry_callback)\n\n self.traj_pub = rospy.Publisher(\"~trajectory\", MultiDOFJointTrajectory, queue_size=1, latch=True)\n\n self.raw_waypoints_viz_pub = rospy.Publisher(\"~raw_waypoints_viz\", Marker, queue_size=1, latch=True)\n\n rospy.loginfo(\"Planner node ready.\")\n\n self.head_for_next_gate()\n\n rate = rospy.Rate(1)\n\n while not rospy.is_shutdown():\n\n if not self.stop_planning:\n\n if self.current_position is not None and self.target_gate_idx is not None:\n\n trajectory = self.generate_trajectory_strategy_2()\n\n if trajectory is None:\n\n rospy.logwarn(\"Failed to generate trajectory\")\n\n else:\n\n self.publish_trajectory(trajectory)\n\n elif self.target_gate_idx is None:\n\n rospy.logwarn(\"No target gate. Planning aborted.\")\n\n else:\n\n rospy.loginfo(\"Planner is still waiting for current position be initialized\")\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 11, "score": 63444.1324448293 }, { "content": "#!/usr/bin/env python\n\n\n\nimport rospy\n\nfrom dynamic_reconfigure.server import Server\n\nfrom spline_planner.cfg import PlannerConfig\n\nfrom nav_msgs.msg import Odometry\n\nfrom geometry_msgs.msg import PoseArray, Pose, Point, Transform, Twist, Vector3, Quaternion\n\nfrom trajectory_msgs.msg import MultiDOFJointTrajectory, MultiDOFJointTrajectoryPoint\n\nfrom visualization_msgs.msg import Marker\n\nfrom std_msgs.msg import ColorRGBA\n\nfrom collections import deque\n\nimport tf\n\nimport numpy as np\n\nimport time\n\n\n\nfrom spline import *\n\n\n\n\n\ndef vector3_to_ndarray(vec):\n\n return np.array([vec.x, vec.y, vec.z])\n\n\n\ndef point_to_ndarray(point):\n\n return np.array([point.x, point.y, point.z])\n\n\n\ndef quaternion_to_ndarray(q):\n\n return np.array([q.x, q.y, q.z, q.w])\n\n\n\ndef vec_to_quat(vec):\n\n \"\"\"To fully determine the orientation represented by the resulting quaternion, this method will assume the top of objects would always facing up\n\n \"\"\"\n\n norm = np.linalg.norm(vec)\n\n if norm < 1e-5:\n\n return np.array([0, 0, 0, 1], dtype=np.float)\n\n obj_x = vec / norm\n\n obj_z_t = np.array([0, 0, 1], dtype=np.float)\n\n obj_y = np.cross(obj_z_t, obj_x)\n\n obj_y /= np.linalg.norm(obj_y) \n\n obj_z = np.cross(obj_x, obj_y)\n\n rot_mat = np.identity(4)\n\n rot_mat[:3,:3] = np.array([obj_x,\n\n obj_y,\n\n obj_z]).T\n\n q = tf.transformations.quaternion_from_matrix(rot_mat)\n\n return q / np.linalg.norm(q)\n\n\n\n\n\nclass SplinePlannerNew(object):\n\n def __init__(self):\n\n self.srv = None\n\n self.max_speed = 6.0\n\n self.max_acceleration = 3.0\n\n self.ds = 0.2\n\n self.gate_locations = []\n\n self.odometry_sub = None\n\n self.raw_waypoints_viz_pub = None # type: rospy.Publisher\n\n self.traj_pub = None # type: rospy.Publisher\n\n self.last_position = None\n\n self.current_time = None\n\n self.current_position = None\n\n self.current_velocity = None\n\n self.current_acceleration = None\n\n self.initial_position = None\n\n self.previous_gate_idx = None\n\n self.target_gate_idx = None\n\n self.gates_sequence = []\n\n self.current_path = None\n\n self.stop_planning = False\n\n self.waypoint_speeds = []\n\n\n\n def rprop_optimize(self, waypoints, d1, d2):\n\n new_d1 = d1.copy()\n\n start = time.time()\n\n\n\n min_k_path = None\n\n min_k = None\n\n t_start = None\n\n\n\n eta_inc = 1.2\n\n eta_dec = 0.5\n\n factor = 1\n\n delta = 0.1\n\n last_ks = []\n\n last_factors = []\n\n\n\n for i in range(1):\n\n path = propose_geometric_spline_path(waypoints, new_d1, d2)\n\n trajectory_points = sample_path([path[0]])\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n print(factor, info['max_k'])\n\n if min_k is None or info['max_k'] < min_k:\n\n min_k = info['max_k']\n\n min_k_path = path\n\n\n\n last_factors.append(factor)\n\n last_ks.append(info['max_k'])\n\n if len(last_ks) > 3:\n\n del last_factors[0]\n\n del last_ks[0]\n\n\n\n if len(last_ks) == 1:\n\n t_start = trajectory_points[0]['d1']\n\n\n\n if len(last_ks) == 3:\n\n grad_1 = last_ks[-1] - last_ks[-2]\n\n grad_2 = last_ks[-2] - last_ks[-3]\n\n change = last_factors[-1] - last_factors[-2]\n\n if grad_1 * grad_2 > 0:\n\n change *= eta_inc\n\n else:\n\n change *= eta_dec\n\n\n\n delta = np.sign(grad_1) * change\n\n\n\n factor += delta\n\n new_d1[0] = t_start * factor\n\n end = time.time()\n\n rospy.loginfo(\"Time used: {}\".format(end-start))\n\n trajectory_points = sample_path(min_k_path)\n\n trajectory_points, _ = self.calculate_points_with_geometric_information(trajectory_points)\n\n return trajectory_points\n\n\n\n def generate_trajectory_strategy_2(self):\n\n \"\"\"Instead of using current position as the starting re-planning waypoint, this strategy don't\n\n use any information about the current position of the drone. It instead only use 3 nearby gate \n\n positions (or the initial position if we're at the very beginning) to generate a new trajectory.\n\n \"\"\"\n\n if self.previous_gate_idx is None:\n\n wp0 = self.initial_position\n\n else:\n\n wp0 = self.gate_locations[self.previous_gate_idx]['center']\n\n wp1 = self.get_waypoint_for_next_n_gate(1)\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n d1, d2 = {}, {}\n\n path = propose_geometric_spline_path((wp0, wp1, wp2))\n\n trajectory_points = sample_path(path)\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n path = self.generate_velocity_profile(trajectory_points)\n\n self.current_path = path\n\n return path\n\n\n\n def generate_trajectory(self):\n\n # every time when re-planning, there are 3 raw waypoints:\n\n # the current position, position of the next gate, position of the next next gate\n\n #\n\n # in case that the drone is too close to \n\n # the next gate, an alternate waypoint from the last trajectory is used instead of the position\n\n # of the next gate. the alternate waypoint must not be too close to the gate too.\n\n #\n\n # in case that we don't have a next next gate, a waypoint that is 5 meter away from the last gate\n\n # along the trajectory direction is used instead\n\n next_gate = self.get_waypoint_for_next_n_gate()\n\n wp0 = self.current_position\n\n d1 = {}\n\n d2 = {}\n\n if self.current_path is not None:\n\n skip_next_gate = False\n\n if np.linalg.norm(next_gate - wp0) <= 0.5:\n\n rospy.loginfo(\"Too close to next gate: {}. Will head for more future gates for waypoints.\".format(self.target_gate_idx))\n\n skip_next_gate = True\n\n \n\n if skip_next_gate:\n\n wp1 = self.get_waypoint_for_next_n_gate(2)\n\n wp2 = self.get_waypoint_for_next_n_gate(3)\n\n else:\n\n wp1 = next_gate\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n else:\n\n rospy.loginfo(\"Planning for the first time\")\n\n wp1 = next_gate\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n\n\n self.publish_raw_waypoints_viz(wp0, wp1, wp2)\n\n # path = propose_geometric_spline_path((wp0, wp1, wp2), d1, d2)\n\n # trajectory_points = sample_path(path)\n\n\n\n current_speed = np.linalg.norm(self.current_velocity)\n\n if current_speed > 0.01:\n\n d1[0] = self.current_velocity / current_speed * np.linalg.norm(wp1 - wp0) * 0.1\n\n \n\n #path = self.rprop_optimize((wp0, wp1, wp2), d1, d2)\n\n path = propose_geometric_spline_path((wp0, wp1, wp2), d1, d2)\n\n trajectory_points = sample_path(path)\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n path = self.generate_velocity_profile(trajectory_points)\n\n self.current_path = path\n\n return path\n\n\n\n def search_for_nearest_waypoint(self, position):\n\n num_points = len(self.current_path)\n\n for i in range(num_points - 1, -1, -1):\n\n prev_pt = self.current_path[i - 1][\"point\"]\n\n next_pt = self.current_path[i][\"point\"]\n\n vec_ref = np.array(next_pt) - np.array(prev_pt)\n\n vec = np.array(next_pt) - np.array(position)\n\n if np.dot(vec, vec_ref) <= 0:\n\n return i\n\n return 0\n\n\n\n def get_waypoint_for_next_n_gate(self, n=1):\n\n if n == 1:\n\n return self.gate_locations[self.target_gate_idx]['center']\n\n if n - 1 > len(self.gates_sequence):\n\n if len(self.gates_sequence) <= 1:\n\n # no gates or only one gate left. get waypoint 5 meters along the direction from the current position to the target gate\n\n target_gate_loc = self.gate_locations[self.target_gate_idx]['center']\n\n direction = target_gate_loc - self.current_position\n\n direction /= np.linalg.norm(direction)\n\n else:\n\n # in this case, direction is defined as the last but 1 gate towards the last gate.\n\n target_gate_loc = self.gate_locations[self.gates_sequence[-1]]['center']\n\n direction = target_gate_loc - self.gate_locations[self.gates_sequence[-2]]['center']\n\n direction /= np.linalg.norm(direction)\n\n return target_gate_loc + 5 * direction\n\n else:\n\n return self.gate_locations[self.gates_sequence[n - 2]]['center']\n\n\n\n def generate_velocity_profile(self, points):\n\n # trajectory_points = self.calculate_points_with_geometric_information(points)\n\n trajectory_points = points\n\n\n\n trajectory_points[0]['speed'] = np.linalg.norm(self.current_velocity)\n\n trajectory_points[0]['velocity'] = self.current_velocity\n\n trajectory_points[0]['time'] = 0.0\n\n num_traj = len(trajectory_points)\n\n for i in range(num_traj - 1):\n\n prev_speed = trajectory_points[i]['speed']\n\n prev_time = trajectory_points[i]['time']\n\n ds = trajectory_points[i + 1]['ds']\n\n\n\n speed = self.calculate_safe_speed(trajectory_points[i + 1]['curvature'], prev_speed, ds)\n\n trajectory_points[i + 1]['speed'] = speed\n\n trajectory_points[i + 1]['velocity'] = speed * trajectory_points[i + 1]['unit_d1']\n\n\n\n avg_speed = 0.5 * (prev_speed + speed)\n\n current_time = prev_time + ds / avg_speed\n\n trajectory_points[i + 1]['time'] = current_time\n\n\n\n accel = (trajectory_points[i + 1]['velocity'] - trajectory_points[i]['velocity']) / (current_time - prev_time)\n\n trajectory_points[i]['acceleration'] = accel\n\n if len(trajectory_points) > 1:\n\n trajectory_points[-1]['acceleration'] = trajectory_points[-2]['acceleration']\n\n return trajectory_points\n\n\n\n\n\n def calculate_safe_speed(self, curvature, speed_neighbor, ds):\n\n centripetal = curvature * speed_neighbor**2\n\n if centripetal >= self.max_acceleration:\n\n return min(self.max_speed, np.sqrt(abs(self.max_acceleration / curvature)))\n\n\n\n remaining_acceleration = np.sqrt(self.max_acceleration**2 - centripetal**2)\n\n # see /Planning Motion Trajectories for Mobile Robots Using Splines/\n\n # (refered as Sprunk[2008] later) for more details (eq 3.21)\n\n v_this = np.sqrt(speed_neighbor ** 2 + 2 * ds * remaining_acceleration)\n\n return min(self.max_speed, v_this)\n\n\n\n def calculate_points_with_geometric_information(self, points):\n\n result = []\n\n info = {}\n\n max_k = 0\n\n this_point = None # type: {}\n\n last_point = None # type: {}\n\n for (s, t), (pt, d1, d2) in points:\n\n last_point = this_point\n\n # curvature is calcuated as norm(deriv1 x deriv2) / norm(deriv1)**3\n\n # see: https://en.wikipedia.org/wiki/Curvature#Local_expressions_2\n\n d1xd2 = np.cross(d1, d2)\n\n norm_d1 = np.linalg.norm(d1)\n\n norm_d2 = np.linalg.norm(d2)\n\n k = 0 # curvature\n\n if norm_d1 > 1e-5:\n\n k = np.linalg.norm(d1xd2) / norm_d1 ** 3\n\n\n\n # the first order derivative is given as ds/dt, where s is the arc length and t is the internal parameter of the spline,\n\n # not time.\n\n # because of this, the magnitude of first order derivative is not the same with viable speed,\n\n # but nevertheless, the direction of the derivative of them are the same.\n\n\n\n # also note that unit normal vector at point is just the normalized second order derivative,\n\n # it is in the opposite direction of the radius vector\n\n\n\n # the cross product of unit tangent vector and unit normal vector\n\n # is also mentioned as unit binormal vector\n\n if norm_d1 > 1e-5:\n\n unit_d1 = d1 / norm_d1\n\n else:\n\n unit_d1 = np.array([0, 0, 0], dtype=np.float)\n\n \n\n if norm_d2 > 1e-5:\n\n unit_d2 = d2 / norm_d2\n\n else:\n\n unit_d2 = np.array([0, 0, 0], dtype=np.float)\n\n\n\n unit_binormal = np.cross(unit_d1, unit_d2)\n\n\n\n ds = s - last_point['s'] if last_point is not None else 0.0\n\n\n\n this_point = {\n\n 't': t,\n\n 's': s,\n\n 'ds': ds,\n\n 'point': pt,\n\n 'd1': d1, \n\n 'd2': d2,\n\n 'unit_d1': unit_d1,\n\n 'unit_d2': unit_d2,\n\n 'unit_b': unit_binormal,\n\n 'curvature': k\n\n }\n\n if k > max_k:\n\n max_k = k\n\n result.append(this_point)\n\n info['max_k'] = max_k\n\n return result, info\n\n\n\n def publish_raw_waypoints_viz(self, *waypoints):\n\n raw_waypoints_marker = Marker()\n\n raw_waypoints_marker.header.stamp = rospy.Time.now()\n\n raw_waypoints_marker.header.frame_id = \"world\"\n\n raw_waypoints_marker.color = ColorRGBA(1.0, 1.0, 0.0, 1.0)\n\n raw_waypoints_marker.scale = Vector3(0.5, 0.5, 0.5)\n\n raw_waypoints_marker.type = Marker.SPHERE_LIST\n\n raw_waypoints_marker.action = Marker.ADD\n\n raw_waypoints_marker.id = 1\n\n for wp in waypoints:\n\n if wp is not None:\n\n raw_waypoints_marker.points.append(Point(wp[0], wp[1], wp[2]))\n\n self.raw_waypoints_viz_pub.publish(raw_waypoints_marker)\n\n\n\n def publish_trajectory(self, trajectory):\n\n trajectory_msg = MultiDOFJointTrajectory()\n\n trajectory_msg.header.frame_id='world'\n\n trajectory_msg.joint_names = ['base']\n\n for idx in range(len(trajectory)):\n\n point = trajectory[idx]\n\n point['time'] = trajectory[idx]['time']\n\n transform = Transform()\n\n transform.translation = Vector3(*(point['point'].tolist()))\n\n transform.rotation = Quaternion(*(vec_to_quat(point['velocity']).tolist()))\n\n velocity = Twist()\n\n velocity.linear = Vector3(*(point['velocity'].tolist()))\n\n acceleration = Twist()\n\n acceleration.linear = Vector3(*(point['acceleration'].tolist()))\n\n \n\n trajectory_msg.points.append(MultiDOFJointTrajectoryPoint([transform], [velocity], [acceleration], rospy.Duration(point['time'])))\n\n\n\n trajectory_msg.header.stamp = rospy.Time.now()\n\n self.traj_pub.publish(trajectory_msg)\n\n\n\n def head_for_next_gate(self):\n\n if len(self.gates_sequence) == 0:\n\n rospy.loginfo(\"No next targeting gate.\")\n\n self.target_gate_idx = None\n\n return False\n\n self.previous_gate_idx = self.target_gate_idx\n\n self.target_gate_idx = self.gates_sequence[0]\n\n del self.gates_sequence[0]\n\n rospy.loginfo(\"Next gate: {}\".format(self.target_gate_idx))\n\n return True\n\n\n\n def is_cross_gate(self, gate_index, position_before, position_after):\n\n \"\"\"Check if the drone has passed the target gate.\n\n\n\n To do this, make two vectors: from last position to gate and current position to gate,\n\n project them and the vector from gate center to gate edge(left/right edge) onto the XY-plane.\n\n By comparing the sign of the cross products of position-gate vector and gate-border vector,\n\n if they are not the same, then we have cross the gate.\n\n \"\"\"\n\n if np.linalg.norm(position_after - position_before) < 1e-5:\n\n # the two positions are too close\n\n return False\n\n gate_position = self.gate_locations[gate_index][\"center\"]\n\n gate_proj_xy = self.gate_locations[gate_index][\"gate_proj_xy\"]\n\n\n\n position_before_xy = (position_before - gate_position)[:2]\n\n position_after_xy = (position_after - gate_position)[:2]\n\n\n\n return np.cross(position_before_xy, gate_proj_xy) * np.cross(position_after_xy, gate_proj_xy) < 0\n\n\n\n def odometry_callback(self, odometry):\n\n # type: (Odometry) -> None\n\n prev_time = self.current_time\n\n self.current_time = odometry.header.stamp.to_sec()\n\n\n\n self.last_position = self.current_position\n\n self.current_position = point_to_ndarray(odometry.pose.pose.position)\n\n\n\n prev_velocity = self.current_velocity\n\n self.current_velocity = SplinePlannerNew.rotate_vector_wrt_quaternion(\n\n quaternion_to_ndarray(odometry.pose.pose.orientation),\n\n vector3_to_ndarray(odometry.twist.twist.linear))\n\n\n\n if prev_velocity is not None and prev_time is not None:\n\n self.current_acceleration = (self.current_velocity - prev_velocity) / (self.current_time - prev_time)\n\n\n\n if self.last_position is None or self.target_gate_idx is None:\n\n return\n\n # check if the drone has passed the target gate\n\n if self.is_cross_gate(self.target_gate_idx, self.last_position, self.current_position):\n\n rospy.loginfo(\"Drone has passed gate {}\".format(self.target_gate_idx))\n\n if self.head_for_next_gate():\n\n rospy.loginfo(\"Heading for gate {}\".format(self.target_gate_idx))\n\n else:\n\n rospy.loginfo(\"All gates have been visited. Stop planning.\")\n\n self.stop_planning = True\n\n\n\n @staticmethod\n\n def rotate_vector_wrt_quaternion(q, v):\n\n p = np.array([0, 0, 0, 0], dtype=np.float)\n\n p[0:3] = v\n\n # p' = q * p * q'\n\n p_prime = tf.transformations.quaternion_multiply(\n\n tf.transformations.quaternion_multiply(q, p),\n\n tf.transformations.quaternion_inverse(q))\n\n return p_prime[:3]\n\n\n\n def reconfigure_parameteres(self, config, level):\n\n rospy.loginfo(\"\"\"Parameters reconfiguration requested:\n\nds: {ds}\n\nmax_speed: {max_linear_speed}\n\nmax_total_acceleration: {max_total_acceleration}\"\"\".format(**config))\n\n self.max_speed = config.max_linear_speed\n\n self.max_acceleration = config.max_total_acceleration\n\n self.ds = config.ds\n\n\n\n return config\n\n\n\n def load_nominal_gates_locations(self):\n\n \"\"\"Load nominal gates information from parameter server and store it as the \n\n initial position of gates.\n\n \"\"\"\n\n # for convenient, append a None at index 0 and let gate 1 be in index 1 of \n\n # self.gate_locations\n\n self.gate_locations.append(None)\n\n num_total_gates = 23\n\n for i in range(1, num_total_gates + 1):\n\n nominal_gate_param_name = \"/uav/Gate{}/nominal_location\".format(i)\n\n corners = np.array(rospy.get_param(nominal_gate_param_name))\n\n norms = [np.linalg.norm(corners[1] - corners[0]),\n\n np.linalg.norm(corners[2] - corners[0]),\n\n np.linalg.norm(corners[3] - corners[0])]\n\n idx = np.argmax(norms)\n\n center = (corners[idx + 1] + corners[0]) / 2\n\n gate_proj_xy = (corners[idx + 1] - corners[0])[:2]\n\n self.gate_locations.append({\n\n \"center\": center,\n\n \"gate_proj_xy\": gate_proj_xy / np.linalg.norm(gate_proj_xy)\n\n })\n\n\n\n def load_course_gates(self):\n\n \"\"\"Load gate sequence of course from parameter /uav/gate_names\n\n \"\"\"\n\n gates = rospy.get_param(\"/uav/gate_names\", None)\n\n \n\n if gates is None:\n\n rospy.logwarn(\"Unable to load course definition from /uav/gate_names\")\n\n self.gates_sequence = []\n\n return\n\n\n\n self.gates_sequence = list(int(g.replace(\"Gate\", \"\"), 10) for g in gates)\n\n rospy.loginfo(\"Course loaded. Gate sequence: {}\".format(self.gates_sequence))\n\n\n\n def load_initial_pose(self):\n\n \"\"\"Load initial pose of the drone\"\"\"\n\n pose = rospy.get_param(\"/uav/flightgoggles_uav_dynamics/init_pose\")\n\n px, py, pz, qx, qy, qz, qw = pose\n\n self.initial_position = np.array([px, py, pz], dtype=np.float)\n\n self.initial_orientation = np.array([qx, qy, qz, qw], dtype=np.float)\n\n\n\n def start(self, name=\"SplinePlannerNew\"):\n\n rospy.init_node(name)\n\n self.srv = Server(PlannerConfig, self.reconfigure_parameteres)\n\n\n\n self.load_nominal_gates_locations()\n\n self.load_course_gates()\n\n self.load_initial_pose()\n\n \n\n self.odometry_sub = rospy.Subscriber(\"~odometry\", Odometry, self.odometry_callback)\n\n self.traj_pub = rospy.Publisher(\"~trajectory\", MultiDOFJointTrajectory, queue_size=1, latch=True)\n\n self.raw_waypoints_viz_pub = rospy.Publisher(\"~raw_waypoints_viz\", Marker, queue_size=1, latch=True)\n\n rospy.loginfo(\"Planner node ready.\")\n\n self.head_for_next_gate()\n\n rate = rospy.Rate(1)\n\n while not rospy.is_shutdown():\n\n if not self.stop_planning:\n\n if self.current_position is not None and self.target_gate_idx is not None:\n\n trajectory = self.generate_trajectory_strategy_2()\n\n if trajectory is None:\n\n rospy.logwarn(\"Failed to generate trajectory\")\n\n else:\n\n self.publish_trajectory(trajectory)\n\n elif self.target_gate_idx is None:\n\n rospy.logwarn(\"No target gate. Planning aborted.\")\n\n else:\n\n rospy.loginfo(\"Planner is still waiting for current position be initialized\")\n\n rate.sleep()\n\n\n\n\n\nif __name__ == '__main__':\n\n rospy.loginfo(\"Starting the new spline planner node\")\n\n node = SplinePlannerNew()\n\n node.start()\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 13, "score": 58136.805635390534 }, { "content": " def evaluate_with_derivatives(self, t):\n\n t2 = t ** 2\n\n t3 = t * t2\n\n t4 = t2 ** 2\n\n t5 = t2 * t3\n\n return np.matmul(np.array([t5, t4, t3, t2, t, 1], dtype=np.float), self.cm).reshape(-1), \\\n\n np.matmul(np.array([t4, t3, t2, t, 1], dtype=np.float), self.cm_d1).reshape(-1), \\\n", "file_path": "spline_planner/scripts/spline.py", "rank": 14, "score": 56974.81441633877 }, { "content": "#!/usr/bin/python\n\n\n\nimport rospy\n\nimport sys\n\nfrom trajectory_msgs.msg import MultiDOFJointTrajectory, MultiDOFJointTrajectoryPoint\n\nfrom geometry_msgs.msg import Transform, Quaternion, Twist, Point, Vector3\n\nimport tf\n\nimport math\n\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) < 4:\n\n print(\"Usage: rosrun cascaded_pid_control set_point.py target_x target_y target_z [target_yaw]\")\n\n exit(-1)\n\n\n\n rospy.init_node(\"SetPoint\")\n\n x, y, z = float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3])\n\n yaw = 0\n\n if len(sys.argv) > 4:\n\n yaw = float(sys.argv[4])\n\n\n\n print(\"Will set location of the drone to {}, {}, {}. Yaw: {} degree\".format(x, y, z, yaw))\n\n \n\n traj_pub = rospy.Publisher(\"/CascadedPidControl/trajectory\", MultiDOFJointTrajectory, queue_size=1, latch=True)\n\n trajectory = MultiDOFJointTrajectory()\n\n trajectory.header.frame_id = 'world'\n\n trajectory.header.stamp = rospy.Time.now()\n\n trajectory.joint_names = ['base']\n\n transform = Transform()\n\n transform.translation = Vector3(x, y, z)\n\n transform.rotation = Quaternion(*tf.transformations.quaternion_from_euler(0, 0, yaw * math.pi / 180.0, 'rxyz').tolist())\n\n\n\n trajectory.points.append(MultiDOFJointTrajectoryPoint([transform], [Twist()], [Twist()], rospy.Duration(0)))\n\n traj_pub.publish(trajectory)\n\n while not rospy.is_shutdown():\n\n rospy.sleep(rospy.Duration(3))\n\n rospy.signal_shutdown(\"Job done.\")\n\n rospy.spin()\n", "file_path": "cascaded_pid_control/scripts/set_point.py", "rank": 15, "score": 56822.96673019468 }, { "content": "def vector_from_to(p0, p1):\n\n v = Vector3()\n\n v.x = p1.x - p0.x\n\n v.y = p1.y - p0.y\n\n v.z = p1.z - p0.z\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 16, "score": 56701.52036639631 }, { "content": " def odometry_callback(self, msg):\n\n # http://docs.ros.org/melodic/api/nav_msgs/html/msg/Odometry.html\n\n self.odometry = msg\n\n self.odometry_time = rospy.Time.now()\n\n for gate in self.gates:\n\n if geo.distance(self.odometry.pose.pose.position, gate.position) < 1.0:\n\n if self.last_visited_gate is None or self.last_visited_gate != gate:\n\n self.last_visited_gate = gate\n\n #print(\"Visited gate:\")\n\n #print(str(gate))\n\n\n\n current_position = geo.vector_to_list(self.odometry.pose.pose.position)\n\n # print(current_position, self.last_position)\n\n if self.last_position is not None and self.target_gate_idx is not None:\n\n # check if the drone has crossed the gate\n\n current_gate_location = geo.vector_to_list(self.gates[self.target_gate_idx].position)\n\n if self.is_cross_gate(self.target_gate_idx, self.last_position, current_position):\n\n rospy.loginfo(\"Passed gate {}\".format(self.target_gate_idx))\n\n if self.target_gate_idx + 1 < len(self.gates):\n\n self.target_gate_idx += 1\n\n rospy.loginfo(\"Next gate index: {}\".format(self.target_gate_idx))\n\n else:\n\n rospy.loginfo(\"All gates have been visited.\")\n\n \n", "file_path": "spline_planner/scripts/planner.py", "rank": 17, "score": 56701.52036639631 }, { "content": " def gates_callback(self, msg):\n\n self.gates = msg.poses\n\n # print(\"gates_callback \" + str(msg.poses))\n\n if self.target_gate_idx is None:\n\n self.target_gate_idx = 0\n", "file_path": "spline_planner/scripts/planner.py", "rank": 18, "score": 56701.52036639631 }, { "content": " def _callback(self, data):\n\n self.latest_msg = data\n", "file_path": "waypoint_controller/src/control_node.py", "rank": 19, "score": 56701.52036639631 }, { "content": " def start(self, name=\"SplinePlannerNew\"):\n\n rospy.init_node(name)\n\n self.srv = Server(PlannerConfig, self.reconfigure_parameteres)\n\n\n\n self.load_nominal_gates_locations()\n\n self.load_course_gates()\n\n self.load_initial_pose()\n\n \n\n self.odometry_sub = rospy.Subscriber(\"~odometry\", Odometry, self.odometry_callback)\n\n self.traj_pub = rospy.Publisher(\"~trajectory\", MultiDOFJointTrajectory, queue_size=1, latch=True)\n\n self.raw_waypoints_viz_pub = rospy.Publisher(\"~raw_waypoints_viz\", Marker, queue_size=1, latch=True)\n\n rospy.loginfo(\"Planner node ready.\")\n\n self.head_for_next_gate()\n\n rate = rospy.Rate(1)\n\n while not rospy.is_shutdown():\n\n if not self.stop_planning:\n\n if self.current_position is not None and self.target_gate_idx is not None:\n\n trajectory = self.generate_trajectory_strategy_2()\n\n if trajectory is None:\n\n rospy.logwarn(\"Failed to generate trajectory\")\n\n else:\n\n self.publish_trajectory(trajectory)\n\n elif self.target_gate_idx is None:\n\n rospy.logwarn(\"No target gate. Planning aborted.\")\n\n else:\n\n rospy.loginfo(\"Planner is still waiting for current position be initialized\")\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 20, "score": 56593.03437563833 }, { "content": " def __init__(self):\n\n self.srv = None\n\n self.max_speed = 6.0\n\n self.max_acceleration = 3.0\n\n self.ds = 0.2\n\n self.gate_locations = []\n\n self.odometry_sub = None\n\n self.raw_waypoints_viz_pub = None # type: rospy.Publisher\n\n self.traj_pub = None # type: rospy.Publisher\n\n self.last_position = None\n\n self.current_time = None\n\n self.current_position = None\n\n self.current_velocity = None\n\n self.current_acceleration = None\n\n self.initial_position = None\n\n self.previous_gate_idx = None\n\n self.target_gate_idx = None\n\n self.gates_sequence = []\n\n self.current_path = None\n\n self.stop_planning = False\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 21, "score": 56593.03437563833 }, { "content": "def points_to_spline(points):\n\n # returns \"spline\" data that can be used for mapping between path distance s and Point on the spline.\n\n # https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html\n\n distance_so_far = 0.0\n\n last_point = points[0]\n\n distances = []\n\n for point in points:\n\n distances.append(distance_so_far + distance(last_point, point))\n\n distance_so_far = distances[-1]\n\n return {'x': interp1d(distances, [p.x for p in points], kind='cubic', bounds_error=False, fill_value=\"extrapolate\"),\n\n 'y': interp1d(distances, [p.y for p in points], kind='cubic', bounds_error=False, fill_value=\"extrapolate\"),\n\n 'z': interp1d(distances, [p.z for p in points], kind='cubic', bounds_error=False, fill_value=\"extrapolate\"),\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 22, "score": 55353.11393225584 }, { "content": "def vector_to_quat(vec):\n\n \"\"\"To fully determine the orientation represented by the resulting quaternion, this method will assume the top of objects would always facing up\n\n \"\"\"\n\n np_vec = np.array([vec.x, vec.y, vec.z])\n\n norm = np.linalg.norm(np_vec)\n\n if norm < 1e-5:\n\n return np.array([0.0, 0.0, 0.0, 1.0])\n\n obj_x = np.array([vec.x, vec.y, vec.z]) / norm\n\n obj_z_t = np.array([0.0, 0.0, 1.0])\n\n obj_y = np.cross(obj_z_t, obj_x)\n\n obj_y /= np.linalg.norm(obj_y) \n\n obj_z = np.cross(obj_x, obj_y)\n\n rot_mat = np.identity(4)\n\n rot_mat[:3,:3] = np.array([obj_x,\n\n obj_y,\n\n obj_z]).T\n\n q = tf.transformations.quaternion_from_matrix(rot_mat)\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 23, "score": 55238.0652303194 }, { "content": " def imu_callback(self, imu):\n\n imu.header.frame_id = 'base_link'\n", "file_path": "odometry/scripts/odometry_imu_node.py", "rank": 24, "score": 55234.80904958562 }, { "content": " def vector_magnitude(self, v):\n", "file_path": "odometry/scripts/odometry_diagnostic_node.py", "rank": 25, "score": 55234.80904958562 }, { "content": " def odometry_callback(self, odometry):\n\n if odometry.header.frame_id == 'odom':\n\n self.odometry_odom_publisher.publish(odometry)\n\n elif odometry.header.frame_id == 'map':\n\n self.odometry_map_publisher.publish(odometry)\n\n else:\n", "file_path": "odometry/scripts/odometry_split_node.py", "rank": 26, "score": 55234.80904958562 }, { "content": "def magnitude_vector(point):\n", "file_path": "waypoint_controller/src/ros_geometry.py", "rank": 27, "score": 55234.80904958562 }, { "content": "def rpy_to_vector(roll, pitch, yaw, magnitude=1.0):\n\n v = Point()\n\n v.y = math.sin(yaw)*math.cos(pitch)\n\n v.x = math.cos(yaw)*math.cos(pitch)\n\n v.z = - math.sin(pitch)\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 28, "score": 55234.80904958562 }, { "content": "def trajectory_callback(traj):\n\n id_gen = id_generator(1)\n\n # path visualizing\n\n # waypoint position, connected with line\n\n traj_viz = MarkerArray()\n\n \n\n path_viz = Marker()\n\n path_viz.header.frame_id = 'world'\n\n path_viz.header.stamp = rospy.Time.now()\n\n path_viz.id = next(id_gen)\n\n path_viz.scale = Vector3(0.05, 0, 0)\n\n path_viz.color = ColorRGBA(0, 1, 0, 1) \n\n path_viz.type = Marker.LINE_STRIP\n\n path_viz.action = Marker.ADD\n\n for pt in traj.points:\n\n path_viz.points.append(pt.transforms[0].translation)\n\n\n\n traj_viz.markers.append(path_viz)\n\n\n\n # waypoint direction. (linear velocity at waypoint)\n\n # the direction of linear velocity is the same as the x direction of the drone, which is also the\n\n # desired heading of the drone.\n\n #\n\n # to fully determine the orientation, we still need the direction of y or z axis of the drone\n\n # after that we can construct a rotation matrix, and then convert it into quaternion\n\n num_points = len(traj.points)\n\n num_velocity_viz = 5\n\n step = max(1, num_points / num_velocity_viz)\n\n i = 0\n\n while i < num_points:\n\n pt = traj.points[i]\n\n translation = pt.transforms[0].translation\n\n linear = pt.velocities[0].linear\n\n norm = math.sqrt(linear.x ** 2 + linear.y ** 2 + linear.z ** 2)\n\n if norm < 1e-3:\n\n i += step\n\n continue\n\n q = geo.vector_to_quat(linear)\n\n velocity_viz = Marker()\n\n velocity_viz.header.frame_id = \"world\"\n\n velocity_viz.header.stamp = rospy.Time.now()\n\n velocity_viz.id = next(id_gen)\n\n velocity_viz.type = Marker.ARROW\n\n velocity_viz.action = Marker.ADD\n\n velocity_viz.pose.position = translation\n\n velocity_viz.pose.orientation = Quaternion(*(q.tolist()))\n\n velocity_viz.scale = Vector3(norm, 0.05, 0.05)\n\n velocity_viz.color = ColorRGBA(1, 0, 0, 0.5)\n\n\n\n traj_viz.markers.append(velocity_viz)\n\n\n\n i += step\n\n viz_pub.publish(traj_viz)\n\n\n\n # visualize information of the next 3 waypoints\n\n if num_points >= 3:\n\n p1 = traj.points[0]\n\n p2 = traj.points[1]\n\n p3 = traj.points[2]\n\n waypoints_info_text = OverlayText()\n\n waypoints_info_text.action = OverlayText.ADD\n\n waypoints_info_text.width = 128\n\n waypoints_info_text.height = 64\n\n waypoints_info_text.left = 0\n\n waypoints_info_text.top = 0\n\n waypoints_info_text.bg_color = ColorRGBA(0, 0, 0, 0.5)\n\n waypoints_info_text.fg_color = ColorRGBA(1, 1, 1, 1)\n\n waypoints_info_text.text_size = 8\n\n waypoints_info_text.text = \"\"\"Next waypoint @ {:.2f}s: {:.2f} {:.2f} {:.2f}. Speed: {:.2f}\n\nNext waypoint @ {:.2f}s: {:.2f} {:.2f} {:.2f}. Speed: {:.2f}\n\nNext waypoint @ {:.2f}s: {:.2f} {:.2f} {:.2f}. Speed: {:.2f}\n\n\"\"\".format(p1.time_from_start.to_sec(), p1.transforms[0].translation.x, p1.transforms[0].translation.y, p1.transforms[0].translation.z, magnitude(p1.velocities[0].linear),\n\n p2.time_from_start.to_sec(), p2.transforms[0].translation.x, p2.transforms[0].translation.y, p2.transforms[0].translation.z, magnitude(p2.velocities[0].linear),\n\n p3.time_from_start.to_sec(), p3.transforms[0].translation.x, p3.transforms[0].translation.y, p3.transforms[0].translation.z, magnitude(p3.velocities[0].linear),)\n", "file_path": "spline_planner/scripts/trajectory_visualizer.py", "rank": 29, "score": 55234.80904958562 }, { "content": "def unit_vector(point):\n\n\n\n m = magnitude_vector(point)\n\n\n\n point.x /= m\n\n point.y /= m\n\n point.z /= m\n\n\n", "file_path": "waypoint_controller/src/ros_geometry.py", "rank": 30, "score": 55234.80904958562 }, { "content": " def irmarker_callback(self, irmarkers):\n\n if self.last_odometry is None:\n\n return\n\n gates_input = {}\n\n for marker in irmarkers.markers:\n\n name = marker.landmarkID.data\n\n if not gates_input.has_key(name):\n\n gates_input[name] = []\n\n gates_input[name].append(marker)\n\n for name in gates_input.keys():\n\n spread = self.pixel_spread(gates_input[name])\n\n drone_pos = self.gt_odometry.pose.pose.position # TODO: switch to measured odometry\n\n dist = self.dist(self.get_nominal(name)['location'], [drone_pos.x, drone_pos.y, drone_pos.z])\n\n width = self.get_nominal(name)['width']\n\n ratio = dist * spread / width\n\n num_points = len(gates_input[name])\n\n estimated_distance = self.estimate_gate_distance(name, gates_input[name])\n\n #rospy.loginfo(\"points=\" + str(num_points) + \" ratio=\" + str(ratio) + \" spread=\" + str(spread) + \" dist=\" + str(dist))\n\n if estimated_distance['min_distance'] > dist or estimated_distance['max_distance'] < dist:\n\n rospy.loginfo(\"Distance \" + str(dist) + \" out of range (\" + str(estimated_distance['min_distance']) + \", \" + str(estimated_distance['max_distance']) + \")\")\n\n if dist > 20:\n\n if ratio > self.ratios[num_points]['max']:\n\n self.ratios[num_points]['max'] = ratio\n\n self.ratios[num_points]['max_details'] = {'name': name, 'spread': spread, 'dist': dist}\n\n if ratio < self.ratios[num_points]['min']:\n\n self.ratios[num_points]['min'] = ratio\n\n self.ratios[num_points]['min_details'] = {'name': name, 'spread': spread, 'dist': dist}\n", "file_path": "odometry/scripts/odometry_gate_node.py", "rank": 31, "score": 55234.80904958562 }, { "content": "def unit_vector_from_to(point1, point2):\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 32, "score": 55234.80904958562 }, { "content": " def _irmarker_callback(self, data):\n\n\n\n viz_marker_array = MarkerArray()\n\n\n\n for m in data.markers:\n\n\n\n if m.landmarkID.data not in self.gates:\n\n self.gates[m.landmarkID.data] = {}\n\n\n\n self.gates[m.landmarkID.data][m.markerID.data] = (m.x, m.y)\n\n\n\n # self._print_gates_stats()\n\n\n\n # if m.landmarkID.data in self.track:\n\n # print('Waypoint detected')\n\n # self.estimator.estimate_gate_markers(self.gates[m.landmarkID.data])\n\n\n\n #print(m.landmarkID.data)\n\n #print(self.gates[m.landmarkID.data])\n\n\n\n result = self.estimator.estimate_gate_markers( self.gates[m.landmarkID.data] )\n\n\n\n if result is not None:\n\n print(m.landmarkID.data, result)\n\n pose = Pose()\n\n pose.position.x = result['position'][0]\n\n pose.position.y = result['position'][1]\n\n pose.position.z = result['position'][2]\n\n\n\n # _q = tf.transformations.quaternion_from_euler(result['rpy'][0], result['rpy'][1], result['rpy'][2])\n\n # pose.orientation.x = _q[0]\n\n # pose.orientation.y = _q[1]\n\n # pose.orientation.z = _q[2]\n\n # pose.orientation.w = _q[3]\n\n\n\n\n\n _id = int(m.landmarkID.data[4:]) # Only the numeral of Gate00\n\n marker = self._create_gate_rviz_marker(pose, _id, 'world')\n\n\n\n viz_marker_array.markers.append(marker)\n\n\n\n # Publish results\n", "file_path": "ap_irmarkers/src/irmarkers_node.py", "rank": 33, "score": 55234.80904958562 }, { "content": " def vector_distance(self, v1, v2):\n", "file_path": "odometry/scripts/odometry_diagnostic_node.py", "rank": 34, "score": 55234.80904958562 }, { "content": "def vector_from_RPY(roll, pitch, yaw):\n\n\n\n v = Point()\n\n v.y = math.sin(yaw)*math.cos(pitch)\n\n v.x = math.cos(yaw)*math.cos(pitch)\n\n v.z = - math.sin(pitch)\n", "file_path": "waypoint_controller/src/ros_geometry.py", "rank": 35, "score": 55234.80904958562 }, { "content": " def range_callback(self, range_msg):\n\n distance = abs(range_msg.range)\n\n if not self.completed_launch and distance > 0.5 and self.latest_odometry is not None:\n\n self.completed_launch = True\n\n height_from_floor = distance\n\n floor_height = self.init_position[2]\n\n height_variance = self.range_variance\n\n\n\n if self.latest_odometry is not None:\n\n expected_height = self.latest_odometry.pose.pose.position.z\n\n\n\n orientation = self.latest_odometry.pose.pose.orientation\n\n orientation_list = [orientation.x, orientation.y, orientation.z, orientation.w]\n\n (roll, pitch, yaw) = euler_from_quaternion(orientation_list)\n\n range_to_height_ratio = max(0.1, abs(math.cos(roll) * math.cos(pitch)))\n\n height_from_floor = distance * range_to_height_ratio\n\n\n\n if self.completed_launch:\n\n expected_floor = expected_height - height_from_floor\n\n for floor in self.floor_heights:\n\n if abs(floor - expected_floor) < abs(floor_height - expected_floor):\n\n floor_height = floor\n\n\n\n # High uncertainty when at or near max range\n\n if distance > self.max_range * 0.9:\n\n height_variance += 100.0\n\n\n\n # Uncertainty due to debris and slabs is far greater than measurement uncertainty\n\n if self.completed_launch:\n\n height_variance += 0.25\n\n\n\n xy_variance = 1000000\n\n orientation_variance = 1000000\n\n if not self.completed_launch:\n\n xy_variance = 0.1 + height_from_floor**2\n\n orientation_variance = 0.1 + 100.0 * height_from_floor**2\n\n\n\n pose = PoseWithCovarianceStamped()\n\n pose.header.seq = range_msg.header.seq\n\n pose.header.stamp = range_msg.header.stamp\n\n pose.header.frame_id = 'map'\n\n\n\n if self.completed_launch:\n\n pose.pose.pose.position = self.latest_odometry.pose.pose.position\n\n pose.pose.pose.orientation = self.latest_odometry.pose.pose.orientation\n\n else:\n\n pose.pose.pose.position.x = self.init_position[0]\n\n pose.pose.pose.position.y = self.init_position[1]\n\n pose.pose.pose.orientation.x = self.init_orientation[0]\n\n pose.pose.pose.orientation.y = self.init_orientation[1]\n\n pose.pose.pose.orientation.z = self.init_orientation[2]\n\n pose.pose.pose.orientation.w = self.init_orientation[3]\n\n\n\n pose.pose.pose.position.z = floor_height + height_from_floor\n\n\n\n variances = [xy_variance] * 2 + [height_variance] + [orientation_variance] * 4\n\n\n\n for i in range(6):\n\n pose.pose.covariance[i*6 + i] = variances[i]\n\n\n", "file_path": "odometry/scripts/odometry_altimeter_node.py", "rank": 36, "score": 55234.80904958562 }, { "content": " def odometry_callback(self, odometry):\n", "file_path": "odometry/scripts/odometry_gate_node.py", "rank": 37, "score": 55234.80904958562 }, { "content": "def quaternion_to_vector(quaternion, magnitude=1.0):\n\n tf_quat = [quaternion.x,quaternion.y,quaternion.z,quaternion.w]\n\n tf_euler = tf.transformations.euler_from_quaternion(tf_quat)\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 38, "score": 55234.80904958562 }, { "content": " def odometry_callback(self, odometry):\n", "file_path": "odometry/scripts/odometry_altimeter_node.py", "rank": 39, "score": 55234.80904958562 }, { "content": "def magnitude_vector(vec):\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 40, "score": 55234.80904958562 }, { "content": "def odometry_callback(odometry):\n\n # speed info\n\n twist = odometry.twist.twist\n\n speed = magnitude(twist.linear)\n\n msg = Float32()\n\n msg.data = speed\n\n linear_speed_pub.publish(msg)\n\n\n\n # position info\n\n pos = odometry.pose.pose.position\n\n position_text = OverlayText()\n\n position_text.action = OverlayText.ADD\n\n position_text.width = 128\n\n position_text.height = 64\n\n position_text.left = 0\n\n position_text.top = 0\n\n position_text.bg_color = ColorRGBA(0, 0, 0, 0.5)\n\n position_text.fg_color = ColorRGBA(1, 1, 1, 1)\n\n position_text.text_size = 8\n\n position_text.text = \"Current position: {:.2f} {:.2f} {:.2f}\".format(pos.x, pos.y, pos.z)\n", "file_path": "spline_planner/scripts/trajectory_visualizer.py", "rank": 41, "score": 55234.80904958562 }, { "content": " def is_cross_gate(self, gate_index, position_before, position_after):\n\n \"\"\"Check if the drone has passed the target gate.\n\n\n\n To do this, make two vectors: from last position to gate and current position to gate,\n\n project them and the vector from gate center to gate edge(left/right edge) onto the XY-plane.\n\n By comparing the sign of the cross products of position-gate vector and gate-border vector,\n\n if they are not the same, then we have cross the gate.\n\n \"\"\"\n\n if np.linalg.norm(position_after - position_before) < 1e-5:\n\n # the two positions are too close\n\n return False\n\n gate_position = self.gate_locations[gate_index][\"center\"]\n\n gate_proj_xy = self.gate_locations[gate_index][\"gate_proj_xy\"]\n\n\n\n position_before_xy = (position_before - gate_position)[:2]\n\n position_after_xy = (position_after - gate_position)[:2]\n\n\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 42, "score": 55133.057294983475 }, { "content": " def publish_trajectory(self, trajectory):\n\n trajectory_msg = MultiDOFJointTrajectory()\n\n trajectory_msg.header.frame_id='world'\n\n trajectory_msg.joint_names = ['base']\n\n for idx in range(len(trajectory)):\n\n point = trajectory[idx]\n\n point['time'] = trajectory[idx]['time']\n\n transform = Transform()\n\n transform.translation = Vector3(*(point['point'].tolist()))\n\n transform.rotation = Quaternion(*(vec_to_quat(point['velocity']).tolist()))\n\n velocity = Twist()\n\n velocity.linear = Vector3(*(point['velocity'].tolist()))\n\n acceleration = Twist()\n\n acceleration.linear = Vector3(*(point['acceleration'].tolist()))\n\n \n\n trajectory_msg.points.append(MultiDOFJointTrajectoryPoint([transform], [velocity], [acceleration], rospy.Duration(point['time'])))\n\n\n\n trajectory_msg.header.stamp = rospy.Time.now()\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 43, "score": 55129.12929099447 }, { "content": "def quaternion_to_ndarray(q):\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 44, "score": 55129.12929099447 }, { "content": "def vector3_to_ndarray(vec):\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 45, "score": 55129.12929099447 }, { "content": " def rprop_optimize(self, waypoints, d1, d2):\n\n new_d1 = d1.copy()\n\n start = time.time()\n\n\n\n min_k_path = None\n\n min_k = None\n\n t_start = None\n\n\n\n eta_inc = 1.2\n\n eta_dec = 0.5\n\n factor = 1\n\n delta = 0.1\n\n last_ks = []\n\n last_factors = []\n\n\n\n for i in range(1):\n\n path = propose_geometric_spline_path(waypoints, new_d1, d2)\n\n trajectory_points = sample_path([path[0]])\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n print(factor, info['max_k'])\n\n if min_k is None or info['max_k'] < min_k:\n\n min_k = info['max_k']\n\n min_k_path = path\n\n\n\n last_factors.append(factor)\n\n last_ks.append(info['max_k'])\n\n if len(last_ks) > 3:\n\n del last_factors[0]\n\n del last_ks[0]\n\n\n\n if len(last_ks) == 1:\n\n t_start = trajectory_points[0]['d1']\n\n\n\n if len(last_ks) == 3:\n\n grad_1 = last_ks[-1] - last_ks[-2]\n\n grad_2 = last_ks[-2] - last_ks[-3]\n\n change = last_factors[-1] - last_factors[-2]\n\n if grad_1 * grad_2 > 0:\n\n change *= eta_inc\n\n else:\n\n change *= eta_dec\n\n\n\n delta = np.sign(grad_1) * change\n\n\n\n factor += delta\n\n new_d1[0] = t_start * factor\n\n end = time.time()\n\n rospy.loginfo(\"Time used: {}\".format(end-start))\n\n trajectory_points = sample_path(min_k_path)\n\n trajectory_points, _ = self.calculate_points_with_geometric_information(trajectory_points)\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 46, "score": 55129.12929099447 }, { "content": " def generate_trajectory(self):\n\n # every time when re-planning, there are 3 raw waypoints:\n\n # the current position, position of the next gate, position of the next next gate\n\n #\n\n # in case that the drone is too close to \n\n # the next gate, an alternate waypoint from the last trajectory is used instead of the position\n\n # of the next gate. the alternate waypoint must not be too close to the gate too.\n\n #\n\n # in case that we don't have a next next gate, a waypoint that is 5 meter away from the last gate\n\n # along the trajectory direction is used instead\n\n next_gate = self.get_waypoint_for_next_n_gate()\n\n wp0 = self.current_position\n\n d1 = {}\n\n d2 = {}\n\n if self.current_path is not None:\n\n skip_next_gate = False\n\n if np.linalg.norm(next_gate - wp0) <= 0.5:\n\n rospy.loginfo(\"Too close to next gate: {}. Will head for more future gates for waypoints.\".format(self.target_gate_idx))\n\n skip_next_gate = True\n\n \n\n if skip_next_gate:\n\n wp1 = self.get_waypoint_for_next_n_gate(2)\n\n wp2 = self.get_waypoint_for_next_n_gate(3)\n\n else:\n\n wp1 = next_gate\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n else:\n\n rospy.loginfo(\"Planning for the first time\")\n\n wp1 = next_gate\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n\n\n self.publish_raw_waypoints_viz(wp0, wp1, wp2)\n\n # path = propose_geometric_spline_path((wp0, wp1, wp2), d1, d2)\n\n # trajectory_points = sample_path(path)\n\n\n\n current_speed = np.linalg.norm(self.current_velocity)\n\n if current_speed > 0.01:\n\n d1[0] = self.current_velocity / current_speed * np.linalg.norm(wp1 - wp0) * 0.1\n\n \n\n #path = self.rprop_optimize((wp0, wp1, wp2), d1, d2)\n\n path = propose_geometric_spline_path((wp0, wp1, wp2), d1, d2)\n\n trajectory_points = sample_path(path)\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n path = self.generate_velocity_profile(trajectory_points)\n\n self.current_path = path\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 47, "score": 55129.12929099447 }, { "content": " def reconfigure_parameteres(self, config, level):\n\n rospy.loginfo(\"\"\"Parameters reconfiguration requested:\n\nds: {ds}\n\nmax_speed: {max_linear_speed}\n\nmax_total_acceleration: {max_total_acceleration}\"\"\".format(**config))\n\n self.max_speed = config.max_linear_speed\n\n self.max_acceleration = config.max_total_acceleration\n\n self.ds = config.ds\n\n\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 48, "score": 55129.12929099447 }, { "content": " def publish_point_command(self, x, y, z, yaw_deg):\n\n quaternion = tf.transformations.quaternion_from_euler(0, 0, math.radians(yaw_deg))\n\n\n\n traj = MultiDOFJointTrajectory()\n\n\n\n header = std_msgs.msg.Header()\n\n header.stamp = rospy.Time()\n\n header.frame_id = 'frame'\n\n traj.joint_names.append('base_link')\n\n traj.header = header\n\n\n\n transforms = Transform(translation=Point(x, y, z),\n\n rotation=Quaternion(quaternion[0], quaternion[1], quaternion[2], quaternion[3]))\n\n\n\n velocities = Twist()\n\n accelerations = Twist()\n\n point = MultiDOFJointTrajectoryPoint([transforms], [velocities], [accelerations], rospy.Time(2))\n\n\n\n traj.points.append(point)\n\n\n", "file_path": "waypoint_controller/src/CommandPublisher.py", "rank": 49, "score": 53957.38577831592 }, { "content": "def spline_distance_to_point(spline, distance):\n\n res = Point()\n\n res.x = spline['x'](distance)\n\n res.y = spline['y'](distance)\n\n res.z = spline['z'](distance)\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 50, "score": 53957.38577831592 }, { "content": "def dot_product_vectors(p0,p1):\n\n\n", "file_path": "waypoint_controller/src/ros_geometry.py", "rank": 51, "score": 53842.063951950244 }, { "content": " def odometry_actual_callback(self, odometry):\n\n if self.odometry_actual is None:\n\n rospy.loginfo(\"Received ground truth odometry\")\n", "file_path": "odometry/scripts/odometry_diagnostic_node.py", "rank": 52, "score": 53842.063951950244 }, { "content": " def odometry_measured_callback(self, odometry):\n\n if self.odometry_measured is None:\n\n rospy.loginfo(\"Received measured odometry\")\n", "file_path": "odometry/scripts/odometry_diagnostic_node.py", "rank": 53, "score": 53842.063951950244 }, { "content": " def gt_odometry_callback(self, odometry):\n", "file_path": "odometry/scripts/odometry_gate_node.py", "rank": 54, "score": 53842.063951950244 }, { "content": " def generate_trajectory_strategy_2(self):\n\n \"\"\"Instead of using current position as the starting re-planning waypoint, this strategy don't\n\n use any information about the current position of the drone. It instead only use 3 nearby gate \n\n positions (or the initial position if we're at the very beginning) to generate a new trajectory.\n\n \"\"\"\n\n if self.previous_gate_idx is None:\n\n wp0 = self.initial_position\n\n else:\n\n wp0 = self.gate_locations[self.previous_gate_idx]['center']\n\n wp1 = self.get_waypoint_for_next_n_gate(1)\n\n wp2 = self.get_waypoint_for_next_n_gate(2)\n\n d1, d2 = {}, {}\n\n path = propose_geometric_spline_path((wp0, wp1, wp2))\n\n trajectory_points = sample_path(path)\n\n trajectory_points, info = self.calculate_points_with_geometric_information(trajectory_points)\n\n path = self.generate_velocity_profile(trajectory_points)\n\n self.current_path = path\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 55, "score": 53745.71600980324 }, { "content": " def generate_velocity_profile(self, points):\n\n # trajectory_points = self.calculate_points_with_geometric_information(points)\n\n trajectory_points = points\n\n\n\n trajectory_points[0]['speed'] = np.linalg.norm(self.current_velocity)\n\n trajectory_points[0]['velocity'] = self.current_velocity\n\n trajectory_points[0]['time'] = 0.0\n\n num_traj = len(trajectory_points)\n\n for i in range(num_traj - 1):\n\n prev_speed = trajectory_points[i]['speed']\n\n prev_time = trajectory_points[i]['time']\n\n ds = trajectory_points[i + 1]['ds']\n\n\n\n speed = self.calculate_safe_speed(trajectory_points[i + 1]['curvature'], prev_speed, ds)\n\n trajectory_points[i + 1]['speed'] = speed\n\n trajectory_points[i + 1]['velocity'] = speed * trajectory_points[i + 1]['unit_d1']\n\n\n\n avg_speed = 0.5 * (prev_speed + speed)\n\n current_time = prev_time + ds / avg_speed\n\n trajectory_points[i + 1]['time'] = current_time\n\n\n\n accel = (trajectory_points[i + 1]['velocity'] - trajectory_points[i]['velocity']) / (current_time - prev_time)\n\n trajectory_points[i]['acceleration'] = accel\n\n if len(trajectory_points) > 1:\n\n trajectory_points[-1]['acceleration'] = trajectory_points[-2]['acceleration']\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 56, "score": 53739.04890729998 }, { "content": " def calculate_safe_speed(self, curvature, speed_neighbor, ds):\n\n centripetal = curvature * speed_neighbor**2\n\n if centripetal >= self.max_acceleration:\n\n return min(self.max_speed, np.sqrt(abs(self.max_acceleration / curvature)))\n\n\n\n remaining_acceleration = np.sqrt(self.max_acceleration**2 - centripetal**2)\n\n # see /Planning Motion Trajectories for Mobile Robots Using Splines/\n\n # (refered as Sprunk[2008] later) for more details (eq 3.21)\n\n v_this = np.sqrt(speed_neighbor ** 2 + 2 * ds * remaining_acceleration)\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 57, "score": 53739.04890729998 }, { "content": " def head_for_next_gate(self):\n\n if len(self.gates_sequence) == 0:\n\n rospy.loginfo(\"No next targeting gate.\")\n\n self.target_gate_idx = None\n\n return False\n\n self.previous_gate_idx = self.target_gate_idx\n\n self.target_gate_idx = self.gates_sequence[0]\n\n del self.gates_sequence[0]\n\n rospy.loginfo(\"Next gate: {}\".format(self.target_gate_idx))\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 58, "score": 53739.04890729998 }, { "content": " def load_initial_pose(self):\n\n \"\"\"Load initial pose of the drone\"\"\"\n\n pose = rospy.get_param(\"/uav/flightgoggles_uav_dynamics/init_pose\")\n\n px, py, pz, qx, qy, qz, qw = pose\n\n self.initial_position = np.array([px, py, pz], dtype=np.float)\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 59, "score": 53739.04890729998 }, { "content": " def load_course_gates(self):\n\n \"\"\"Load gate sequence of course from parameter /uav/gate_names\n\n \"\"\"\n\n gates = rospy.get_param(\"/uav/gate_names\", None)\n\n \n\n if gates is None:\n\n rospy.logwarn(\"Unable to load course definition from /uav/gate_names\")\n\n self.gates_sequence = []\n\n return\n\n\n\n self.gates_sequence = list(int(g.replace(\"Gate\", \"\"), 10) for g in gates)\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 60, "score": 53739.04890729998 }, { "content": " def search_for_nearest_waypoint(self, position):\n\n num_points = len(self.current_path)\n\n for i in range(num_points - 1, -1, -1):\n\n prev_pt = self.current_path[i - 1][\"point\"]\n\n next_pt = self.current_path[i][\"point\"]\n\n vec_ref = np.array(next_pt) - np.array(prev_pt)\n\n vec = np.array(next_pt) - np.array(position)\n\n if np.dot(vec, vec_ref) <= 0:\n\n return i\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 61, "score": 53739.04890729998 }, { "content": "def propose_geometric_spline_path_with_2_points(p1, p2, t1=None, t2=None, a1=None, a2=None):\n\n direct12 = p2 - p1\n\n if t1 is None:\n\n t1 = 0.5 * direct12\n\n if t2 is None:\n\n t2 = 0.5 * direct12\n\n if a1 is None:\n\n a1 = np.array([0, 0, 0], dtype=np.float)\n\n if a2 is None:\n\n a2 = np.array([0, 0, 0], dtype=np.float)\n", "file_path": "spline_planner/scripts/spline.py", "rank": 62, "score": 52630.31301920298 }, { "content": "def rotate_vector_wrt_quaternion(quaternion, vector):\n\n p = np.array([vector.x, vector.y, vector.z, 0])\n\n q = np.array([quaternion.x, quaternion.y, quaternion.z, quaternion.w])\n\n # p' = q * p * q'\n\n p_prime = tf.transformations.quaternion_multiply(\n\n tf.transformations.quaternion_multiply(q, p),\n\n tf.transformations.quaternion_inverse(q))\n", "file_path": "spline_planner/scripts/ros_geometry.py", "rank": 63, "score": 52517.827513613294 }, { "content": " def load_nominal_gates_locations(self):\n\n \"\"\"Load nominal gates information from parameter server and store it as the \n\n initial position of gates.\n\n \"\"\"\n\n # for convenient, append a None at index 0 and let gate 1 be in index 1 of \n\n # self.gate_locations\n\n self.gate_locations.append(None)\n\n num_total_gates = 23\n\n for i in range(1, num_total_gates + 1):\n\n nominal_gate_param_name = \"/uav/Gate{}/nominal_location\".format(i)\n\n corners = np.array(rospy.get_param(nominal_gate_param_name))\n\n norms = [np.linalg.norm(corners[1] - corners[0]),\n\n np.linalg.norm(corners[2] - corners[0]),\n\n np.linalg.norm(corners[3] - corners[0])]\n\n idx = np.argmax(norms)\n\n center = (corners[idx + 1] + corners[0]) / 2\n\n gate_proj_xy = (corners[idx + 1] - corners[0])[:2]\n\n self.gate_locations.append({\n\n \"center\": center,\n\n \"gate_proj_xy\": gate_proj_xy / np.linalg.norm(gate_proj_xy)\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 64, "score": 52417.34610652834 }, { "content": " def get_waypoint_for_next_n_gate(self, n=1):\n\n if n == 1:\n\n return self.gate_locations[self.target_gate_idx]['center']\n\n if n - 1 > len(self.gates_sequence):\n\n if len(self.gates_sequence) <= 1:\n\n # no gates or only one gate left. get waypoint 5 meters along the direction from the current position to the target gate\n\n target_gate_loc = self.gate_locations[self.target_gate_idx]['center']\n\n direction = target_gate_loc - self.current_position\n\n direction /= np.linalg.norm(direction)\n\n else:\n\n # in this case, direction is defined as the last but 1 gate towards the last gate.\n\n target_gate_loc = self.gate_locations[self.gates_sequence[-1]]['center']\n\n direction = target_gate_loc - self.gate_locations[self.gates_sequence[-2]]['center']\n\n direction /= np.linalg.norm(direction)\n\n return target_gate_loc + 5 * direction\n\n else:\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 65, "score": 52417.34610652834 }, { "content": " def publish_raw_waypoints_viz(self, *waypoints):\n\n raw_waypoints_marker = Marker()\n\n raw_waypoints_marker.header.stamp = rospy.Time.now()\n\n raw_waypoints_marker.header.frame_id = \"world\"\n\n raw_waypoints_marker.color = ColorRGBA(1.0, 1.0, 0.0, 1.0)\n\n raw_waypoints_marker.scale = Vector3(0.5, 0.5, 0.5)\n\n raw_waypoints_marker.type = Marker.SPHERE_LIST\n\n raw_waypoints_marker.action = Marker.ADD\n\n raw_waypoints_marker.id = 1\n\n for wp in waypoints:\n\n if wp is not None:\n\n raw_waypoints_marker.points.append(Point(wp[0], wp[1], wp[2]))\n", "file_path": "spline_planner/scripts/planner_new.py", "rank": 66, "score": 52417.34610652834 }, { "content": " def vec_to_quat(vec):\n\n \"\"\"To fully determine the orientation represented by the resulting quaternion, this method will assume the top of objects would always facing up\n\n \"\"\"\n\n np_vec = vec\n\n norm = np.linalg.norm(np_vec)\n\n if norm < 1e-5:\n\n return np.array([0.0, 0.0, 0.0, 1.0])\n\n obj_x = np_vec / norm\n\n obj_z_t = np.array([0.0, 0.0, 1.0])\n\n obj_y = np.cross(obj_z_t, obj_x)\n\n obj_y /= np.linalg.norm(obj_y) \n\n obj_z = np.cross(obj_x, obj_y)\n\n rot_mat = np.identity(4)\n\n rot_mat[:3,:3] = np.array([obj_x,\n\n obj_y,\n\n obj_z]).T\n\n q = tf.transformations.quaternion_from_matrix(rot_mat)\n", "file_path": "cascaded_pid_control/scripts/cheat_gate_locations_node.py", "rank": 67, "score": 51492.54999720566 }, { "content": " def _markers_callback(self, data):\n\n\n\n if len(data.marker) <= 0:\n\n return None\n\n\n\n stamp = data.camera_frame_stamp # For synchronizing TF\n\n\n\n try:\n\n camera_tf = self.tf_buffer.lookup_transform(self.fixed_frame_id, self.camera_frame_id, stamp, rospy.Duration(0.1))\n\n #print('camera_tf', camera_tf)\n\n except (tf2.LookupException, tf2.ConnectivityException, tf2.ExtrapolationException):\n\n return None\n\n\n\n # world_pose_array = MarkersArray()\n\n\n\n for m in data.marker:\n\n pose = m.pose_cov_stamped.pose\n\n #print(pose)\n\n pose_stamped_world = do_transform_pose(pose, camera_tf)\n\n m.pose_cov_stamped.pose.pose = pose_stamped_world\n\n self.gates_map.process_marker_observation(m)\n\n\n", "file_path": "drone_map_builder/src/observed_gates_map_node.py", "rank": 68, "score": 51257.16619748728 }, { "content": " def _ego_pose_callback(self, data):\n\n pose = self.create_marker_line_object(data, self.fixed_frame_id)\n\n #print(pose.id)\n", "file_path": "drone_map_builder/src/gt_ego_position.py", "rank": 69, "score": 51257.16619748728 }, { "content": " * \\param knots The underlying spline's knot vector.\n\n **/ \n\n static BasisDerivativeType BasisFunctionDerivatives(\n\n const Scalar u, const DenseIndex order, const DenseIndex degree, const KnotVectorType& knots);\n\n\n\n private:\n\n KnotVectorType m_knots; /*!< Knot vector. */\n\n ControlPointVectorType m_ctrls; /*!< Control points. */\n\n\n\n template <typename DerivativeType>\n\n static void BasisFunctionDerivativesImpl(\n\n const typename Spline<_Scalar, _Dim, _Degree>::Scalar u,\n\n const DenseIndex order,\n\n const DenseIndex p, \n\n const typename Spline<_Scalar, _Dim, _Degree>::KnotVectorType& U,\n\n DerivativeType& N_);\n\n };\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n DenseIndex Spline<_Scalar, _Dim, _Degree>::Span(\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 70, "score": 35120.04146252431 }, { "content": " enum { Dimension = SplineTraits<SplineType>::Dimension };\n\n enum { Order = SplineTraits<SplineType>::OrderAtCompileTime };\n\n enum { DerivativeOrder = DerivativeType::ColsAtCompileTime };\n\n\n\n typedef typename SplineTraits<SplineType>::ControlPointVectorType ControlPointVectorType;\n\n typedef typename SplineTraits<SplineType,DerivativeOrder>::BasisDerivativeType BasisDerivativeType;\n\n typedef typename BasisDerivativeType::ConstRowXpr BasisDerivativeRowXpr; \n\n\n\n const DenseIndex p = spline.degree();\n\n const DenseIndex span = spline.span(u);\n\n\n\n const DenseIndex n = (std::min)(p, order);\n\n\n\n der.resize(Dimension,n+1);\n\n\n\n // Retrieve the basis function derivatives up to the desired order... \n\n const BasisDerivativeType basis_func_ders = spline.template basisFunctionDerivatives<DerivativeOrder>(u, n+1);\n\n\n\n // ... and perform the linear combinations of the control points.\n\n for (DenseIndex der_order=0; der_order<n+1; ++der_order)\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 71, "score": 35119.85698895727 }, { "content": " * Using the template version of this function is more efficieent since\n\n * temporary objects are allocated on the stack whenever this is possible.\n\n **/ \n\n template <int DerivativeOrder>\n\n typename SplineTraits<Spline,DerivativeOrder>::BasisDerivativeType\n\n basisFunctionDerivatives(Scalar u, DenseIndex order = DerivativeOrder) const;\n\n\n\n /**\n\n * \\brief Returns the spline degree.\n\n **/ \n\n DenseIndex degree() const;\n\n\n\n /** \n\n * \\brief Returns the span within the knot vector in which u is falling.\n\n * \\param u The site for which the span is determined.\n\n **/\n\n DenseIndex span(Scalar u) const;\n\n\n\n /**\n\n * \\brief Computes the spang within the provided knot vector in which u is falling.\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 72, "score": 35119.24893983777 }, { "content": " {\n\n const Replicate<BasisDerivativeRowXpr,Dimension,1> ctrl_weights( basis_func_ders.row(der_order) );\n\n const Block<const ControlPointVectorType,Dimension,Order> ctrl_pts(spline.ctrls(),0,span-p,Dimension,p+1);\n\n der.col(der_order) = (ctrl_weights * ctrl_pts).rowwise().sum();\n\n }\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n typename SplineTraits< Spline<_Scalar, _Dim, _Degree> >::DerivativeType\n\n Spline<_Scalar, _Dim, _Degree>::derivatives(Scalar u, DenseIndex order) const\n\n {\n\n typename SplineTraits< Spline >::DerivativeType res;\n\n derivativesImpl(*this, u, order, res);\n\n return res;\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n template <int DerivativeOrder>\n\n typename SplineTraits< Spline<_Scalar, _Dim, _Degree>, DerivativeOrder >::DerivativeType\n\n Spline<_Scalar, _Dim, _Degree>::derivatives(Scalar u, DenseIndex order) const\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 73, "score": 35118.9946449203 }, { "content": "\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n typename Spline<_Scalar, _Dim, _Degree>::PointType Spline<_Scalar, _Dim, _Degree>::operator()(Scalar u) const\n\n {\n\n enum { Order = SplineTraits<Spline>::OrderAtCompileTime };\n\n\n\n const DenseIndex span = this->span(u);\n\n const DenseIndex p = degree();\n\n const BasisVectorType basis_funcs = basisFunctions(u);\n\n\n\n const Replicate<BasisVectorType,Dimension,1> ctrl_weights(basis_funcs);\n\n const Block<const ControlPointVectorType,Dimension,Order> ctrl_pts(ctrls(),0,span-p,Dimension,p+1);\n\n return (ctrl_weights * ctrl_pts).rowwise().sum();\n\n }\n\n\n\n /* --------------------------------------------------------------------------------------------- */\n\n\n\n template <typename SplineType, typename DerivativeType>\n\n void derivativesImpl(const SplineType& spline, typename SplineType::Scalar u, DenseIndex order, DerivativeType& der)\n\n { \n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 74, "score": 35117.77649272442 }, { "content": " * \\brief Evaluation of spline derivatives of up-to given order.\n\n *\n\n * The function returns\n\n * \\f{align*}\n\n * \\frac{d^i}{du^i}C(u) & = \\sum_{i=0}^{n} \\frac{d^i}{du^i} N_{i,p}(u)P_i\n\n * \\f}\n\n * for i ranging between 0 and order.\n\n *\n\n * \\param u Parameter \\f$u \\in [0;1]\\f$ at which the spline derivative is evaluated.\n\n * \\param order The order up to which the derivatives are computed.\n\n **/\n\n typename SplineTraits<Spline>::DerivativeType\n\n derivatives(Scalar u, DenseIndex order) const;\n\n\n\n /**\n\n * \\copydoc Spline::derivatives\n\n * Using the template version of this function is more efficieent since\n\n * temporary objects are allocated on the stack whenever this is possible.\n\n **/ \n\n template <int DerivativeOrder>\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 75, "score": 35114.91529430708 }, { "content": " typedef typename SplineTraits<Spline>::BasisDerivativeType BasisDerivativeType;\n\n \n\n /** \\brief The data type representing the spline's control points. */\n\n typedef typename SplineTraits<Spline>::ControlPointVectorType ControlPointVectorType;\n\n \n\n /**\n\n * \\brief Creates a (constant) zero spline.\n\n * For Splines with dynamic degree, the resulting degree will be 0.\n\n **/\n\n Spline() \n\n : m_knots(1, (Degree==Dynamic ? 2 : 2*Degree+2))\n\n , m_ctrls(ControlPointVectorType::Zero(Dimension,(Degree==Dynamic ? 1 : Degree+1))) \n\n {\n\n // in theory this code can go to the initializer list but it will get pretty\n\n // much unreadable ...\n\n enum { MinDegree = (Degree==Dynamic ? 0 : Degree) };\n\n m_knots.template segment<MinDegree+1>(0) = Array<Scalar,1,MinDegree+1>::Zero();\n\n m_knots.template segment<MinDegree+1>(MinDegree+1) = Array<Scalar,1,MinDegree+1>::Ones();\n\n }\n\n\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 76, "score": 35114.16537375501 }, { "content": " \n\n /**\n\n * \\brief Returns the knots of the underlying spline.\n\n **/ \n\n const ControlPointVectorType& ctrls() const { return m_ctrls; }\n\n\n\n /**\n\n * \\brief Returns the spline value at a given site \\f$u\\f$.\n\n *\n\n * The function returns\n\n * \\f{align*}\n\n * C(u) & = \\sum_{i=0}^{n}N_{i,p}P_i\n\n * \\f}\n\n *\n\n * \\param u Parameter \\f$u \\in [0;1]\\f$ at which the spline is evaluated.\n\n * \\return The spline value at the given location \\f$u\\f$.\n\n **/\n\n PointType operator()(Scalar u) const;\n\n\n\n /**\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 77, "score": 35114.06656642636 }, { "content": " *\n\n * The class represents B-splines with non-uniform knot vectors. Each control\n\n * point of the B-spline is associated with a basis function\n\n * \\f{align*}\n\n * C(u) & = \\sum_{i=0}^{n}N_{i,p}(u)P_i\n\n * \\f}\n\n *\n\n * \\tparam _Scalar The underlying data type (typically float or double)\n\n * \\tparam _Dim The curve dimension (e.g. 2 or 3)\n\n * \\tparam _Degree Per default set to Dynamic; could be set to the actual desired\n\n * degree for optimization purposes (would result in stack allocation\n\n * of several temporary variables).\n\n **/\n\n template <typename _Scalar, int _Dim, int _Degree>\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 78, "score": 35113.822488107064 }, { "content": " return der;\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n typename SplineTraits<Spline<_Scalar, _Dim, _Degree> >::BasisDerivativeType\n\n Spline<_Scalar, _Dim, _Degree>::BasisFunctionDerivatives(\n\n const typename Spline<_Scalar, _Dim, _Degree>::Scalar u,\n\n const DenseIndex order,\n\n const DenseIndex degree,\n\n const typename Spline<_Scalar, _Dim, _Degree>::KnotVectorType& knots)\n\n {\n\n typename SplineTraits<Spline>::BasisDerivativeType der;\n\n BasisFunctionDerivativesImpl(u, order, degree, knots, der);\n\n return der;\n\n }\n\n}\n\n\n\n#endif // EIGEN_SPLINE_H\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 79, "score": 35113.45104211489 }, { "content": " {\n\n typename SplineTraits< Spline, DerivativeOrder >::DerivativeType res;\n\n derivativesImpl(*this, u, order, res);\n\n return res;\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n typename SplineTraits< Spline<_Scalar, _Dim, _Degree> >::BasisVectorType\n\n Spline<_Scalar, _Dim, _Degree>::basisFunctions(Scalar u) const\n\n {\n\n return Spline::BasisFunctions(u, degree(), knots());\n\n }\n\n\n\n /* --------------------------------------------------------------------------------------------- */\n\n \n\n \n\n template <typename _Scalar, int _Dim, int _Degree>\n\n template <typename DerivativeType>\n\n void Spline<_Scalar, _Dim, _Degree>::BasisFunctionDerivativesImpl(\n\n const typename Spline<_Scalar, _Dim, _Degree>::Scalar u,\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 80, "score": 35113.428634956435 }, { "content": " **/\n\n static DenseIndex Span(typename SplineTraits<Spline>::Scalar u, DenseIndex degree, const typename SplineTraits<Spline>::KnotVectorType& knots);\n\n \n\n /**\n\n * \\brief Returns the spline's non-zero basis functions.\n\n *\n\n * The function computes and returns\n\n * \\f{align*}{\n\n * N_{i,p}(u), \\hdots, N_{i+p+1,p}(u)\n\n * \\f}\n\n *\n\n * \\param u The site at which the basis functions are computed.\n\n * \\param degree The degree of the underlying spline.\n\n * \\param knots The underlying spline's knot vector.\n\n **/\n\n static BasisVectorType BasisFunctions(Scalar u, DenseIndex degree, const KnotVectorType& knots);\n\n\n\n /**\n\n * \\copydoc Spline::basisFunctionDerivatives\n\n * \\param degree The degree of the underlying spline\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 81, "score": 35112.74204924941 }, { "content": " /**\n\n * \\brief Creates a spline from a knot vector and control points.\n\n * \\param knots The spline's knot vector.\n\n * \\param ctrls The spline's control point vector.\n\n **/\n\n template <typename OtherVectorType, typename OtherArrayType>\n\n Spline(const OtherVectorType& knots, const OtherArrayType& ctrls) : m_knots(knots), m_ctrls(ctrls) {}\n\n\n\n /**\n\n * \\brief Copy constructor for splines.\n\n * \\param spline The input spline.\n\n **/\n\n template <int OtherDegree>\n\n Spline(const Spline<Scalar, Dimension, OtherDegree>& spline) : \n\n m_knots(spline.knots()), m_ctrls(spline.ctrls()) {}\n\n\n\n /**\n\n * \\brief Returns the knots of the underlying spline.\n\n **/\n\n const KnotVectorType& knots() const { return m_knots; }\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 82, "score": 35112.71947752956 }, { "content": " typename SplineTraits<Spline,DerivativeOrder>::DerivativeType\n\n derivatives(Scalar u, DenseIndex order = DerivativeOrder) const;\n\n\n\n /**\n\n * \\brief Computes the non-zero basis functions at the given site.\n\n *\n\n * Splines have local support and a point from their image is defined\n\n * by exactly \\f$p+1\\f$ control points \\f$P_i\\f$ where \\f$p\\f$ is the\n\n * spline degree.\n\n *\n\n * This function computes the \\f$p+1\\f$ non-zero basis function values\n\n * for a given parameter value \\f$u\\f$. It returns\n\n * \\f{align*}{\n\n * N_{i,p}(u), \\hdots, N_{i+p+1,p}(u)\n\n * \\f}\n\n *\n\n * \\param u Parameter \\f$u \\in [0;1]\\f$ at which the non-zero basis functions \n\n * are computed.\n\n **/\n\n typename SplineTraits<Spline>::BasisVectorType\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 83, "score": 35112.65544634223 }, { "content": " saved = left[j-r] * temp;\n\n }\n\n\n\n ndu(j,j) = static_cast<Scalar>(saved);\n\n }\n\n\n\n for (j = p; j>=0; --j) \n\n N_(0,j) = ndu(j,p);\n\n\n\n // Compute the derivatives\n\n DerivativeType a(n+1,p+1);\n\n DenseIndex r=0;\n\n for (; r<=p; ++r)\n\n {\n\n DenseIndex s1,s2;\n\n s1 = 0; s2 = 1; // alternate rows in array a\n\n a(0,0) = 1.0;\n\n\n\n // Compute the k-th derivative\n\n for (DenseIndex k=1; k<=static_cast<DenseIndex>(n); ++k)\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 84, "score": 35112.64832591652 }, { "content": " r *= p-k;\n\n }\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n typename SplineTraits< Spline<_Scalar, _Dim, _Degree> >::BasisDerivativeType\n\n Spline<_Scalar, _Dim, _Degree>::basisFunctionDerivatives(Scalar u, DenseIndex order) const\n\n {\n\n typename SplineTraits<Spline<_Scalar, _Dim, _Degree> >::BasisDerivativeType der;\n\n BasisFunctionDerivativesImpl(u, order, degree(), knots(), der);\n\n return der;\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n template <int DerivativeOrder>\n\n typename SplineTraits< Spline<_Scalar, _Dim, _Degree>, DerivativeOrder >::BasisDerivativeType\n\n Spline<_Scalar, _Dim, _Degree>::basisFunctionDerivatives(Scalar u, DenseIndex order) const\n\n {\n\n typename SplineTraits< Spline<_Scalar, _Dim, _Degree>, DerivativeOrder >::BasisDerivativeType der;\n\n BasisFunctionDerivativesImpl(u, order, degree(), knots(), der);\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 85, "score": 35112.178796406486 }, { "content": " }\n\n N(j) = saved;\n\n }\n\n return N;\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n DenseIndex Spline<_Scalar, _Dim, _Degree>::degree() const\n\n {\n\n if (_Degree == Dynamic)\n\n return m_knots.size() - m_ctrls.cols() - 1;\n\n else\n\n return _Degree;\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n DenseIndex Spline<_Scalar, _Dim, _Degree>::span(Scalar u) const\n\n {\n\n return Spline::Span(u, degree(), knots());\n\n }\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 86, "score": 35111.73224950493 }, { "content": " const DenseIndex order,\n\n const DenseIndex p, \n\n const typename Spline<_Scalar, _Dim, _Degree>::KnotVectorType& U,\n\n DerivativeType& N_)\n\n {\n\n typedef Spline<_Scalar, _Dim, _Degree> SplineType;\n\n enum { Order = SplineTraits<SplineType>::OrderAtCompileTime };\n\n\n\n typedef typename SplineTraits<SplineType>::Scalar Scalar;\n\n typedef typename SplineTraits<SplineType>::BasisVectorType BasisVectorType;\n\n \n\n const DenseIndex span = SplineType::Span(u, p, U);\n\n\n\n const DenseIndex n = (std::min)(p, order);\n\n\n\n N_.resize(n+1, p+1);\n\n\n\n BasisVectorType left = BasisVectorType::Zero(p+1);\n\n BasisVectorType right = BasisVectorType::Zero(p+1);\n\n\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 87, "score": 35111.31163601266 }, { "content": " typename SplineTraits< Spline<_Scalar, _Dim, _Degree> >::Scalar u,\n\n DenseIndex degree,\n\n const typename SplineTraits< Spline<_Scalar, _Dim, _Degree> >::KnotVectorType& knots)\n\n {\n\n // Piegl & Tiller, \"The NURBS Book\", A2.1 (p. 68)\n\n if (u <= knots(0)) return degree;\n\n const Scalar* pos = std::upper_bound(knots.data()+degree-1, knots.data()+knots.size()-degree-1, u);\n\n return static_cast<DenseIndex>( std::distance(knots.data(), pos) - 1 );\n\n }\n\n\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n typename Spline<_Scalar, _Dim, _Degree>::BasisVectorType\n\n Spline<_Scalar, _Dim, _Degree>::BasisFunctions(\n\n typename Spline<_Scalar, _Dim, _Degree>::Scalar u,\n\n DenseIndex degree,\n\n const typename Spline<_Scalar, _Dim, _Degree>::KnotVectorType& knots)\n\n {\n\n typedef typename Spline<_Scalar, _Dim, _Degree>::BasisVectorType BasisVectorType;\n\n\n\n const DenseIndex p = degree;\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 88, "score": 35111.15376671875 }, { "content": " const DenseIndex i = Spline::Span(u, degree, knots);\n\n\n\n const KnotVectorType& U = knots;\n\n\n\n BasisVectorType left(p+1); left(0) = Scalar(0);\n\n BasisVectorType right(p+1); right(0) = Scalar(0); \n\n\n\n VectorBlock<BasisVectorType,Degree>(left,1,p) = u - VectorBlock<const KnotVectorType,Degree>(U,i+1-p,p).reverse();\n\n VectorBlock<BasisVectorType,Degree>(right,1,p) = VectorBlock<const KnotVectorType,Degree>(U,i+1,p) - u;\n\n\n\n BasisVectorType N(1,p+1);\n\n N(0) = Scalar(1);\n\n for (DenseIndex j=1; j<=p; ++j)\n\n {\n\n Scalar saved = Scalar(0);\n\n for (DenseIndex r=0; r<j; r++)\n\n {\n\n const Scalar tmp = N(r)/(right(r+1)+left(j-r));\n\n N[r] = saved + right(r+1)*tmp;\n\n saved = left(j-r)*tmp;\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 89, "score": 35109.65059841472 }, { "content": "// This file is part of Eigen, a lightweight C++ template library\n\n// for linear algebra.\n\n//\n\n// Copyright (C) 20010-2011 Hauke Heibel <[email protected]>\n\n//\n\n// This Source Code Form is subject to the terms of the Mozilla\n\n// Public License v. 2.0. If a copy of the MPL was not distributed\n\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n\n\n#ifndef EIGEN_SPLINE_H\n\n#define EIGEN_SPLINE_H\n\n\n\n#include \"SplineFwd.h\"\n\n\n\nnamespace Eigen\n\n{\n\n /**\n\n * \\ingroup Splines_Module\n\n * \\class Spline\n\n * \\brief A class representing multi-dimensional spline curves.\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 90, "score": 35109.447971534246 }, { "content": " basisFunctions(Scalar u) const;\n\n\n\n /**\n\n * \\brief Computes the non-zero spline basis function derivatives up to given order.\n\n *\n\n * The function computes\n\n * \\f{align*}{\n\n * \\frac{d^i}{du^i} N_{i,p}(u), \\hdots, \\frac{d^i}{du^i} N_{i+p+1,p}(u)\n\n * \\f}\n\n * with i ranging from 0 up to the specified order.\n\n *\n\n * \\param u Parameter \\f$u \\in [0;1]\\f$ at which the non-zero basis function\n\n * derivatives are computed.\n\n * \\param order The order up to which the basis function derivatives are computes.\n\n **/\n\n typename SplineTraits<Spline>::BasisDerivativeType\n\n basisFunctionDerivatives(Scalar u, DenseIndex order) const;\n\n\n\n /**\n\n * \\copydoc Spline::basisFunctionDerivatives\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 91, "score": 35108.313409748196 }, { "content": " d += a(s2,j)*ndu(rk+j,pk);\n\n }\n\n\n\n if (r<=pk)\n\n {\n\n a(s2,k) = -a(s1,k-1)/ndu(pk+1,r);\n\n d += a(s2,k)*ndu(r,pk);\n\n }\n\n\n\n N_(k,r) = static_cast<Scalar>(d);\n\n j = s1; s1 = s2; s2 = j; // Switch rows\n\n }\n\n }\n\n\n\n /* Multiply through by the correct factors */\n\n /* (Eq. [2.9]) */\n\n r = p;\n\n for (DenseIndex k=1; k<=static_cast<DenseIndex>(n); ++k)\n\n {\n\n for (j=p; j>=0; --j) N_(k,j) *= r;\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 92, "score": 35108.26580290433 }, { "content": " Matrix<Scalar,Order,Order> ndu(p+1,p+1);\n\n\n\n double saved, temp;\n\n\n\n ndu(0,0) = 1.0;\n\n\n\n DenseIndex j;\n\n for (j=1; j<=p; ++j)\n\n {\n\n left[j] = u-U[span+1-j];\n\n right[j] = U[span+j]-u;\n\n saved = 0.0;\n\n\n\n for (DenseIndex r=0; r<j; ++r)\n\n {\n\n /* Lower triangle */\n\n ndu(j,r) = right[r+1]+left[j-r];\n\n temp = ndu(r,j-1)/ndu(j,r);\n\n /* Upper triangle */\n\n ndu(r,j) = static_cast<Scalar>(saved+right[r+1] * temp);\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 93, "score": 35105.5263515156 }, { "content": " {\n\n double d = 0.0;\n\n DenseIndex rk,pk,j1,j2;\n\n rk = r-k; pk = p-k;\n\n\n\n if (r>=k)\n\n {\n\n a(s2,0) = a(s1,0)/ndu(pk+1,rk);\n\n d = a(s2,0)*ndu(rk,pk);\n\n }\n\n\n\n if (rk>=-1) j1 = 1;\n\n else j1 = -rk;\n\n\n\n if (r-1 <= pk) j2 = k-1;\n\n else j2 = p-r;\n\n\n\n for (j=j1; j<=j2; ++j)\n\n {\n\n a(s2,j) = (a(s1,j)-a(s1,j-1))/ndu(pk+1,rk+j);\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 94, "score": 35104.808961817405 }, { "content": " class Spline\n\n {\n\n public:\n\n typedef _Scalar Scalar; /*!< The spline curve's scalar type. */\n\n enum { Dimension = _Dim /*!< The spline curve's dimension. */ };\n\n enum { Degree = _Degree /*!< The spline curve's degree. */ };\n\n\n\n /** \\brief The point type the spline is representing. */\n\n typedef typename SplineTraits<Spline>::PointType PointType;\n\n \n\n /** \\brief The data type used to store knot vectors. */\n\n typedef typename SplineTraits<Spline>::KnotVectorType KnotVectorType;\n\n\n\n /** \\brief The data type used to store parameter vectors. */\n\n typedef typename SplineTraits<Spline>::ParameterVectorType ParameterVectorType;\n\n \n\n /** \\brief The data type used to store non-zero basis functions. */\n\n typedef typename SplineTraits<Spline>::BasisVectorType BasisVectorType;\n\n\n\n /** \\brief The data type used to store the values of the basis function derivatives. */\n", "file_path": "spline_planner/include/Eigen/Spline/Spline.h", "rank": 95, "score": 34059.33531742093 }, { "content": "namespace Eigen\n\n{\n\n /**\n\n * \\brief Computes knot averages.\n\n * \\ingroup Splines_Module\n\n *\n\n * The knots are computed as\n\n * \\f{align*}\n\n * u_0 & = \\hdots = u_p = 0 \\\\\n\n * u_{m-p} & = \\hdots = u_{m} = 1 \\\\\n\n * u_{j+p} & = \\frac{1}{p}\\sum_{i=j}^{j+p-1}\\bar{u}_i \\quad\\quad j=1,\\hdots,n-p\n\n * \\f}\n\n * where \\f$p\\f$ is the degree and \\f$m+1\\f$ the number knots\n\n * of the desired interpolating spline.\n\n *\n\n * \\param[in] parameters The input parameters. During interpolation one for each data point.\n\n * \\param[in] degree The spline degree which is used during the interpolation.\n\n * \\param[out] knots The output knot vector.\n\n *\n\n * \\sa Les Piegl and Wayne Tiller, The NURBS book (2nd ed.), 1997, 9.2.1 Global Curve Interpolation to Point Data\n\n **/\n\n template <typename KnotVectorType>\n\n void KnotAveraging(const KnotVectorType& parameters, DenseIndex degree, KnotVectorType& knots)\n\n {\n\n knots.resize(parameters.size()+degree+1); \n\n\n\n for (DenseIndex j=1; j<parameters.size()-degree; ++j)\n\n knots(j+degree) = parameters.segment(j,degree).mean();\n\n\n\n knots.segment(0,degree+1) = KnotVectorType::Zero(degree+1);\n\n knots.segment(knots.size()-degree-1,degree+1) = KnotVectorType::Ones(degree+1);\n\n }\n\n\n\n /**\n\n * \\brief Computes knot averages when derivative constraints are present.\n\n * Note that this is a technical interpretation of the referenced article\n\n * since the algorithm contained therein is incorrect as written.\n\n * \\ingroup Splines_Module\n\n *\n\n * \\param[in] parameters The parameters at which the interpolation B-Spline\n\n * will intersect the given interpolation points. The parameters\n\n * are assumed to be a non-decreasing sequence.\n\n * \\param[in] degree The degree of the interpolating B-Spline. This must be\n\n * greater than zero.\n\n * \\param[in] derivativeIndices The indices corresponding to parameters at\n\n * which there are derivative constraints. The indices are assumed\n\n * to be a non-decreasing sequence.\n\n * \\param[out] knots The calculated knot vector. These will be returned as a\n\n * non-decreasing sequence\n\n *\n\n * \\sa Les A. Piegl, Khairan Rajab, Volha Smarodzinana. 2008.\n\n * Curve interpolation with directional constraints for engineering design. \n\n * Engineering with Computers\n\n **/\n\n template <typename KnotVectorType, typename ParameterVectorType, typename IndexArray>\n\n void KnotAveragingWithDerivatives(const ParameterVectorType& parameters,\n\n const unsigned int degree,\n\n const IndexArray& derivativeIndices,\n\n KnotVectorType& knots)\n\n {\n\n typedef typename ParameterVectorType::Scalar Scalar;\n\n\n\n DenseIndex numParameters = parameters.size();\n\n DenseIndex numDerivatives = derivativeIndices.size();\n\n\n\n if (numDerivatives < 1)\n\n {\n\n KnotAveraging(parameters, degree, knots);\n\n return;\n\n }\n\n\n\n DenseIndex startIndex;\n\n DenseIndex endIndex;\n\n \n\n DenseIndex numInternalDerivatives = numDerivatives;\n\n \n\n if (derivativeIndices[0] == 0)\n\n {\n\n startIndex = 0;\n\n --numInternalDerivatives;\n\n }\n\n else\n\n {\n\n startIndex = 1;\n\n }\n\n if (derivativeIndices[numDerivatives - 1] == numParameters - 1)\n\n {\n\n endIndex = numParameters - degree;\n\n --numInternalDerivatives;\n\n }\n\n else\n\n {\n\n endIndex = numParameters - degree - 1;\n\n }\n\n\n\n // There are (endIndex - startIndex + 1) knots obtained from the averaging\n\n // and 2 for the first and last parameters.\n\n DenseIndex numAverageKnots = endIndex - startIndex + 3;\n\n KnotVectorType averageKnots(numAverageKnots);\n\n averageKnots[0] = parameters[0];\n\n\n\n int newKnotIndex = 0;\n\n for (DenseIndex i = startIndex; i <= endIndex; ++i)\n\n averageKnots[++newKnotIndex] = parameters.segment(i, degree).mean();\n\n averageKnots[++newKnotIndex] = parameters[numParameters - 1];\n\n\n\n newKnotIndex = -1;\n\n \n\n ParameterVectorType temporaryParameters(numParameters + 1);\n\n KnotVectorType derivativeKnots(numInternalDerivatives);\n\n for (unsigned int i = 0; i < numAverageKnots - 1; ++i)\n\n {\n\n temporaryParameters[0] = averageKnots[i];\n\n ParameterVectorType parameterIndices(numParameters);\n\n int temporaryParameterIndex = 1;\n\n for (int j = 0; j < numParameters; ++j)\n\n {\n\n Scalar parameter = parameters[j];\n\n if (parameter >= averageKnots[i] && parameter < averageKnots[i + 1])\n\n {\n\n parameterIndices[temporaryParameterIndex] = j;\n\n temporaryParameters[temporaryParameterIndex++] = parameter;\n\n }\n\n }\n\n temporaryParameters[temporaryParameterIndex] = averageKnots[i + 1];\n\n\n\n for (int j = 0; j <= temporaryParameterIndex - 2; ++j)\n\n {\n\n for (DenseIndex k = 0; k < derivativeIndices.size(); ++k)\n\n {\n\n if (parameterIndices[j + 1] == derivativeIndices[k]\n\n && parameterIndices[j + 1] != 0\n\n && parameterIndices[j + 1] != numParameters - 1)\n\n {\n\n derivativeKnots[++newKnotIndex] = temporaryParameters.segment(j, 3).mean();\n\n break;\n\n }\n\n }\n\n }\n\n }\n\n \n\n KnotVectorType temporaryKnots(averageKnots.size() + derivativeKnots.size());\n\n\n\n std::merge(averageKnots.data(), averageKnots.data() + averageKnots.size(),\n\n derivativeKnots.data(), derivativeKnots.data() + derivativeKnots.size(),\n\n temporaryKnots.data());\n\n\n\n // Number of control points (one for each point and derivative) plus spline order.\n\n DenseIndex numKnots = numParameters + numDerivatives + degree + 1;\n\n knots.resize(numKnots);\n\n\n\n knots.head(degree).fill(temporaryKnots[0]);\n\n knots.tail(degree).fill(temporaryKnots.template tail<1>()[0]);\n\n knots.segment(degree, temporaryKnots.size()) = temporaryKnots;\n\n }\n\n\n\n /**\n\n * \\brief Computes chord length parameters which are required for spline interpolation.\n\n * \\ingroup Splines_Module\n\n *\n\n * \\param[in] pts The data points to which a spline should be fit.\n\n * \\param[out] chord_lengths The resulting chord lenggth vector.\n\n *\n\n * \\sa Les Piegl and Wayne Tiller, The NURBS book (2nd ed.), 1997, 9.2.1 Global Curve Interpolation to Point Data\n\n **/ \n\n template <typename PointArrayType, typename KnotVectorType>\n\n void ChordLengths(const PointArrayType& pts, KnotVectorType& chord_lengths)\n\n {\n\n typedef typename KnotVectorType::Scalar Scalar;\n\n\n\n const DenseIndex n = pts.cols();\n\n\n\n // 1. compute the column-wise norms\n\n chord_lengths.resize(pts.cols());\n\n chord_lengths[0] = 0;\n\n chord_lengths.rightCols(n-1) = (pts.array().leftCols(n-1) - pts.array().rightCols(n-1)).matrix().colwise().norm();\n\n\n\n // 2. compute the partial sums\n\n std::partial_sum(chord_lengths.data(), chord_lengths.data()+n, chord_lengths.data());\n\n\n\n // 3. normalize the data\n\n chord_lengths /= chord_lengths(n-1);\n\n chord_lengths(n-1) = Scalar(1);\n\n }\n\n\n\n /**\n\n * \\brief Spline fitting methods.\n\n * \\ingroup Splines_Module\n\n **/ \n\n template <typename SplineType>\n\n struct SplineFitting\n\n {\n\n typedef typename SplineType::KnotVectorType KnotVectorType;\n\n typedef typename SplineType::ParameterVectorType ParameterVectorType;\n\n\n\n /**\n\n * \\brief Fits an interpolating Spline to the given data points.\n\n *\n\n * \\param pts The points for which an interpolating spline will be computed.\n\n * \\param degree The degree of the interpolating spline.\n\n *\n\n * \\returns A spline interpolating the initially provided points.\n\n **/\n\n template <typename PointArrayType>\n\n static SplineType Interpolate(const PointArrayType& pts, DenseIndex degree);\n\n\n\n /**\n\n * \\brief Fits an interpolating Spline to the given data points.\n\n *\n\n * \\param pts The points for which an interpolating spline will be computed.\n\n * \\param degree The degree of the interpolating spline.\n\n * \\param knot_parameters The knot parameters for the interpolation.\n\n *\n\n * \\returns A spline interpolating the initially provided points.\n\n **/\n\n template <typename PointArrayType>\n\n static SplineType Interpolate(const PointArrayType& pts, DenseIndex degree, const KnotVectorType& knot_parameters);\n\n\n\n /**\n\n * \\brief Fits an interpolating spline to the given data points and\n\n * derivatives.\n\n * \n\n * \\param points The points for which an interpolating spline will be computed.\n\n * \\param derivatives The desired derivatives of the interpolating spline at interpolation\n\n * points.\n\n * \\param derivativeIndices An array indicating which point each derivative belongs to. This\n\n * must be the same size as @a derivatives.\n\n * \\param degree The degree of the interpolating spline.\n\n *\n\n * \\returns A spline interpolating @a points with @a derivatives at those points.\n\n *\n\n * \\sa Les A. Piegl, Khairan Rajab, Volha Smarodzinana. 2008.\n\n * Curve interpolation with directional constraints for engineering design. \n\n * Engineering with Computers\n\n **/\n\n template <typename PointArrayType, typename IndexArray>\n\n static SplineType InterpolateWithDerivatives(const PointArrayType& points,\n\n const PointArrayType& derivatives,\n\n const IndexArray& derivativeIndices,\n\n const unsigned int degree);\n\n\n\n /**\n\n * \\brief Fits an interpolating spline to the given data points and derivatives.\n\n * \n\n * \\param points The points for which an interpolating spline will be computed.\n\n * \\param derivatives The desired derivatives of the interpolating spline at interpolation points.\n\n * \\param derivativeIndices An array indicating which point each derivative belongs to. This\n\n * must be the same size as @a derivatives.\n\n * \\param degree The degree of the interpolating spline.\n\n * \\param parameters The parameters corresponding to the interpolation points.\n\n *\n\n * \\returns A spline interpolating @a points with @a derivatives at those points.\n\n *\n\n * \\sa Les A. Piegl, Khairan Rajab, Volha Smarodzinana. 2008.\n\n * Curve interpolation with directional constraints for engineering design. \n\n * Engineering with Computers\n\n */\n\n template <typename PointArrayType, typename IndexArray>\n\n static SplineType InterpolateWithDerivatives(const PointArrayType& points,\n\n const PointArrayType& derivatives,\n\n const IndexArray& derivativeIndices,\n\n const unsigned int degree,\n\n const ParameterVectorType& parameters);\n\n };\n\n\n\n template <typename SplineType>\n\n template <typename PointArrayType>\n\n SplineType SplineFitting<SplineType>::Interpolate(const PointArrayType& pts, DenseIndex degree, const KnotVectorType& knot_parameters)\n\n {\n\n typedef typename SplineType::KnotVectorType::Scalar Scalar; \n\n typedef typename SplineType::ControlPointVectorType ControlPointVectorType; \n\n\n\n typedef Matrix<Scalar,Dynamic,Dynamic> MatrixType;\n\n\n\n KnotVectorType knots;\n\n KnotAveraging(knot_parameters, degree, knots);\n\n\n\n DenseIndex n = pts.cols();\n\n MatrixType A = MatrixType::Zero(n,n);\n\n for (DenseIndex i=1; i<n-1; ++i)\n\n {\n\n const DenseIndex span = SplineType::Span(knot_parameters[i], degree, knots);\n\n\n\n // The segment call should somehow be told the spline order at compile time.\n\n A.row(i).segment(span-degree, degree+1) = SplineType::BasisFunctions(knot_parameters[i], degree, knots);\n\n }\n\n A(0,0) = 1.0;\n\n A(n-1,n-1) = 1.0;\n\n\n\n HouseholderQR<MatrixType> qr(A);\n\n\n\n // Here, we are creating a temporary due to an Eigen issue.\n\n ControlPointVectorType ctrls = qr.solve(MatrixType(pts.transpose())).transpose();\n\n\n\n return SplineType(knots, ctrls);\n\n }\n\n\n\n template <typename SplineType>\n\n template <typename PointArrayType>\n\n SplineType SplineFitting<SplineType>::Interpolate(const PointArrayType& pts, DenseIndex degree)\n\n {\n\n KnotVectorType chord_lengths; // knot parameters\n\n ChordLengths(pts, chord_lengths);\n\n return Interpolate(pts, degree, chord_lengths);\n\n }\n\n \n\n template <typename SplineType>\n\n template <typename PointArrayType, typename IndexArray>\n\n SplineType \n\n SplineFitting<SplineType>::InterpolateWithDerivatives(const PointArrayType& points,\n\n const PointArrayType& derivatives,\n\n const IndexArray& derivativeIndices,\n\n const unsigned int degree,\n\n const ParameterVectorType& parameters)\n\n {\n\n typedef typename SplineType::KnotVectorType::Scalar Scalar; \n\n typedef typename SplineType::ControlPointVectorType ControlPointVectorType;\n\n\n\n typedef Matrix<Scalar, Dynamic, Dynamic> MatrixType;\n\n\n\n const DenseIndex n = points.cols() + derivatives.cols();\n\n \n\n KnotVectorType knots;\n\n\n\n KnotAveragingWithDerivatives(parameters, degree, derivativeIndices, knots);\n\n \n\n // fill matrix\n\n MatrixType A = MatrixType::Zero(n, n);\n\n\n\n // Use these dimensions for quicker populating, then transpose for solving.\n\n MatrixType b(points.rows(), n);\n\n\n\n DenseIndex startRow;\n\n DenseIndex derivativeStart;\n\n\n\n // End derivatives.\n\n if (derivativeIndices[0] == 0)\n\n {\n\n A.template block<1, 2>(1, 0) << -1, 1;\n\n \n\n Scalar y = (knots(degree + 1) - knots(0)) / degree;\n\n b.col(1) = y*derivatives.col(0);\n\n \n\n startRow = 2;\n\n derivativeStart = 1;\n\n }\n\n else\n\n {\n\n startRow = 1;\n\n derivativeStart = 0;\n\n }\n\n if (derivativeIndices[derivatives.cols() - 1] == points.cols() - 1)\n\n {\n\n A.template block<1, 2>(n - 2, n - 2) << -1, 1;\n\n\n\n Scalar y = (knots(knots.size() - 1) - knots(knots.size() - (degree + 2))) / degree;\n\n b.col(b.cols() - 2) = y*derivatives.col(derivatives.cols() - 1);\n\n }\n\n \n\n DenseIndex row = startRow;\n\n DenseIndex derivativeIndex = derivativeStart;\n\n for (DenseIndex i = 1; i < parameters.size() - 1; ++i)\n\n {\n\n const DenseIndex span = SplineType::Span(parameters[i], degree, knots);\n\n\n\n if (derivativeIndex < derivativeIndices.size() && derivativeIndices[derivativeIndex] == i)\n\n {\n\n A.block(row, span - degree, 2, degree + 1)\n\n = SplineType::BasisFunctionDerivatives(parameters[i], 1, degree, knots);\n\n\n\n b.col(row++) = points.col(i);\n\n b.col(row++) = derivatives.col(derivativeIndex++);\n\n }\n\n else\n\n {\n\n A.row(row).segment(span - degree, degree + 1)\n\n = SplineType::BasisFunctions(parameters[i], degree, knots);\n\n b.col(row++) = points.col(i);\n\n }\n\n }\n\n b.col(0) = points.col(0);\n\n b.col(b.cols() - 1) = points.col(points.cols() - 1);\n\n A(0,0) = 1;\n\n A(n - 1, n - 1) = 1;\n\n \n\n // Solve\n\n FullPivLU<MatrixType> lu(A);\n\n ControlPointVectorType controlPoints = lu.solve(MatrixType(b.transpose())).transpose();\n\n\n\n SplineType spline(knots, controlPoints);\n\n \n\n return spline;\n\n }\n\n \n\n template <typename SplineType>\n\n template <typename PointArrayType, typename IndexArray>\n\n SplineType\n\n SplineFitting<SplineType>::InterpolateWithDerivatives(const PointArrayType& points,\n\n const PointArrayType& derivatives,\n\n const IndexArray& derivativeIndices,\n\n const unsigned int degree)\n\n {\n\n ParameterVectorType parameters;\n\n ChordLengths(points, parameters);\n\n return InterpolateWithDerivatives(points, derivatives, derivativeIndices, degree, parameters);\n\n }\n", "file_path": "spline_planner/include/Eigen/Spline/SplineFitting.h", "rank": 96, "score": 29654.231871313244 }, { "content": "namespace Eigen\n\n{\n\n template <typename Scalar, int Dim, int Degree = Dynamic> class Spline;\n\n\n\n template < typename SplineType, int DerivativeOrder = Dynamic > struct SplineTraits {};\n\n\n\n /**\n\n * \\ingroup Splines_Module\n\n * \\brief Compile-time attributes of the Spline class for Dynamic degree.\n\n **/\n\n template <typename _Scalar, int _Dim, int _Degree>\n\n struct SplineTraits< Spline<_Scalar, _Dim, _Degree>, Dynamic >\n\n {\n\n typedef _Scalar Scalar; /*!< The spline curve's scalar type. */\n\n enum { Dimension = _Dim /*!< The spline curve's dimension. */ };\n\n enum { Degree = _Degree /*!< The spline curve's degree. */ };\n\n\n\n enum { OrderAtCompileTime = _Degree==Dynamic ? Dynamic : _Degree+1 /*!< The spline curve's order at compile-time. */ };\n\n enum { NumOfDerivativesAtCompileTime = OrderAtCompileTime /*!< The number of derivatives defined for the current spline. */ };\n\n \n\n enum { DerivativeMemoryLayout = Dimension==1 ? RowMajor : ColMajor /*!< The derivative type's memory layout. */ };\n\n\n\n /** \\brief The data type used to store non-zero basis functions. */\n\n typedef Array<Scalar,1,OrderAtCompileTime> BasisVectorType;\n\n\n\n /** \\brief The data type used to store the values of the basis function derivatives. */\n\n typedef Array<Scalar,Dynamic,Dynamic,RowMajor,NumOfDerivativesAtCompileTime,OrderAtCompileTime> BasisDerivativeType;\n\n \n\n /** \\brief The data type used to store the spline's derivative values. */\n\n typedef Array<Scalar,Dimension,Dynamic,DerivativeMemoryLayout,Dimension,NumOfDerivativesAtCompileTime> DerivativeType;\n\n\n\n /** \\brief The point type the spline is representing. */\n\n typedef Array<Scalar,Dimension,1> PointType;\n\n \n\n /** \\brief The data type used to store knot vectors. */\n\n typedef Array<Scalar,1,Dynamic> KnotVectorType;\n\n\n\n /** \\brief The data type used to store parameter vectors. */\n\n typedef Array<Scalar,1,Dynamic> ParameterVectorType;\n\n \n\n /** \\brief The data type representing the spline's control points. */\n\n typedef Array<Scalar,Dimension,Dynamic> ControlPointVectorType;\n", "file_path": "spline_planner/include/Eigen/Spline/SplineFwd.h", "rank": 97, "score": 29654.231871313244 }, { "content": "from distutils.core import setup\n\nfrom catkin_pkg.python_setup import generate_distutils_setup\n\n\n\nsetup_args = generate_distutils_setup(\n\n packages=['spline_planner'],\n\n package_dir={'':'src'})\n\n\n\nsetup(**setup_args)\n", "file_path": "spline_planner/setup.py", "rank": 98, "score": 28380.84150881657 }, { "content": "#!/usr/bin/env python\n\n\"\"\"\n\n# Spline-based planning node\n\n\n\nSubscribe to gate (PoseArray) and odometry messages.\n\nConstruct trajectory by smoothly connecting current post and upcoming gates via spline.\n\nPublish MultiDOFJointTrajectory.\n\n\"\"\"\n\n\n\nfrom __future__ import print_function\n\nimport rospy\n\nimport math\n\nfrom geometry_msgs.msg import PoseArray, Pose, Point, Transform, Twist, Vector3, Quaternion\n\nfrom nav_msgs.msg import Odometry\n\nfrom trajectory_msgs.msg import MultiDOFJointTrajectory, MultiDOFJointTrajectoryPoint\n\nfrom visualization_msgs.msg import Marker\n\nfrom std_msgs.msg import ColorRGBA\n\nfrom scipy.interpolate import interp1d\n\nimport ros_geometry as geo\n\nfrom SmoothedPath import SmoothedPath\n\nfrom LowPassFilter import LowPassFilter\n\nimport numpy as np\n\n\n\nfrom dynamic_reconfigure.server import Server\n\nfrom spline_planner.cfg import PlannerConfig\n\n\n\nclass SplinePlanner():\n\n\n\n def __init__(self, _node_name, _namespace):\n\n self.node_name = _node_name\n\n self._namespace = _namespace\n\n self.gates = []\n\n self.last_visited_gate = None\n\n self.odometry = None\n\n self.min_speed = 0.1\n\n self.max_speed = rospy.get_param(\"~target_exit_speed\", 1.0)\n\n self.max_acceleration = 1 # Racing drone is probably around 10 m/s2. Set very low for now.\n\n self.gates_sub = rospy.Subscriber('gt_gates_publisher/gt_gates', PoseArray, self.gates_callback)\n\n self.odometry_sub = rospy.Subscriber('/' + self._namespace + '/odometry_sensor1/odometry', Odometry, self.odometry_callback)\n\n self.traj_pub = rospy.Publisher('/' + _namespace + '/command/trajectory', MultiDOFJointTrajectory, queue_size=1, latch=True)\n\n self.raw_waypoints_viz_pub = rospy.Publisher(\"~raw_waypoints_viz\", Marker, queue_size=1, latch=True)\n\n self.current_path = None\n\n self.last_position = None\n\n self.target_gate_idx = None\n\n self.stop_planning = False\n\n\n\n def reconfigure_parameters(self, config, level):\n\n rospy.loginfo(\"Parameters reconfiguration requested.\")\n\n rospy.loginfo(\"\"\"Parameters reconfiguration requested:\n\nds: {ds}\n\nmax_speed: {max_linear_speed}\n\nmax_total_acceleration: {max_total_acceleration}\n\ntrajectory_length: {trajectory_length}\"\"\".format(**config))\n\n\n\n self.max_speed = config.max_linear_speed\n\n self.max_acceleration = config.max_total_acceleration\n\n self.ds = config.ds\n\n self.trajectory_length = config.trajectory_length\n\n\n\n return config\n\n\n\n def gates_callback(self, msg):\n\n self.gates = msg.poses\n\n # print(\"gates_callback \" + str(msg.poses))\n\n if self.target_gate_idx is None:\n\n self.target_gate_idx = 0\n\n rospy.loginfo(\"Next gate index: {}\".format(self.target_gate_idx))\n\n\n\n def odometry_callback(self, msg):\n\n # http://docs.ros.org/melodic/api/nav_msgs/html/msg/Odometry.html\n\n self.odometry = msg\n\n self.odometry_time = rospy.Time.now()\n\n for gate in self.gates:\n\n if geo.distance(self.odometry.pose.pose.position, gate.position) < 1.0:\n\n if self.last_visited_gate is None or self.last_visited_gate != gate:\n\n self.last_visited_gate = gate\n\n #print(\"Visited gate:\")\n\n #print(str(gate))\n\n\n\n current_position = geo.vector_to_list(self.odometry.pose.pose.position)\n\n # print(current_position, self.last_position)\n\n if self.last_position is not None and self.target_gate_idx is not None:\n\n # check if the drone has crossed the gate\n\n current_gate_location = geo.vector_to_list(self.gates[self.target_gate_idx].position)\n\n if self.is_cross_gate(self.target_gate_idx, self.last_position, current_position):\n\n rospy.loginfo(\"Passed gate {}\".format(self.target_gate_idx))\n\n if self.target_gate_idx + 1 < len(self.gates):\n\n self.target_gate_idx += 1\n\n rospy.loginfo(\"Next gate index: {}\".format(self.target_gate_idx))\n\n else:\n\n rospy.loginfo(\"All gates have been visited.\")\n\n \n\n self.last_position = current_position\n\n\n\n def start(self):\n\n rate = rospy.Rate(2)\n\n started = False\n\n while not rospy.is_shutdown():\n\n if not self.stop_planning:\n\n if started and False:\n\n pass\n\n elif len(self.gates) > 0 and self.odometry is not None and self.target_gate_idx is not None:\n\n trajectory = self.create_path(self.odometry, self.gates, self.last_visited_gate)\n\n if self.stop_planning:\n\n rospy.loginfo(\"All gates have been visited. Planning stopped.\")\n\n elif trajectory is None:\n\n print(\"Failed to create trajectory\")\n\n else:\n\n self.traj_pub.publish(trajectory)\n\n if not started:\n\n started = True\n\n print(\"spline_planner published first trajectory\")\n\n #print(\"Trajectory:\")\n\n #print(str(trajectory))\n\n else:\n\n print(\"spline_planner waiting for input\")\n\n rate.sleep()\n\n\n\n def search_for_nearest_waypoint(self, position):\n\n for i in range(len(self.current_path['path']) - 1, -1, -1):\n\n # point in path format: ((s, t), (pt, deriv1))\n\n prev_pt = self.current_path['path'][i - 1][\"point_as_list\"]\n\n next_pt = self.current_path['path'][i][\"point_as_list\"]\n\n vec_ref = np.array(next_pt) - np.array(prev_pt)\n\n vec = np.array(next_pt) - np.array(position)\n\n if np.dot(vec, vec_ref) <= 0:\n\n return i\n\n #return i + 1 if i < len(self.current_path['path']) - 1 else i\n\n return 0\n\n\n\n def distance_to_gate(self, position, gate_index):\n\n if self.gates is None or gate_index >= len(self.gates):\n\n rospy.logwarn(\"Currently no gates information or do not have gate at index {}. Will return a very large value\".format(gate_index))\n\n return 1e6\n\n\n\n gate_loc = geo.vector_to_list(self.gates[gate_index].position)\n\n return SplinePlanner.distance(gate_loc, position)\n\n\n\n @staticmethod\n\n def distance(p1, p2):\n\n return np.linalg.norm(np.array(p1) - np.array(p2))\n\n\n\n def is_cross_gate(self, gate_index, position_before, position_after):\n\n if SplinePlanner.distance(position_before, position_after) < 1e-5:\n\n # the two positions are too close\n\n return False\n\n gate_orientation = self.gates[gate_index].orientation\n\n gate_heading = geo.rotate_vector_wrt_quaternion(gate_orientation, Vector3(1, 0, 0))\n\n gate_normal_xy = np.array([-gate_heading.y, gate_heading.x])\n\n\n\n gate_position = np.array(geo.vector_to_list(self.gates[gate_index].position))\n\n position_before_xy = (np.array(position_before) - gate_position)[:2]\n\n position_after_xy = (np.array(position_after) - gate_position)[:2]\n\n\n\n return np.cross(position_before_xy, gate_normal_xy) * np.cross(position_after_xy, gate_normal_xy) < 0\n\n\n\n @staticmethod\n\n def is_cross_position(target_position, position_before, position_after):\n\n if SplinePlanner.distance(position_before, position_after) < 1e-5:\n\n # the two position is too close\n\n return False\n\n vec1 = np.array(target_position) - np.array(position_before)\n\n vec2 = np.array(target_position) - np.array(position_after)\n\n if np.dot(vec1, vec2) < 0:\n\n # the two vectors are in the opposite direction, so we think we have cross the target position\n\n return True\n\n return False\n\n\n\n @staticmethod\n\n def is_cross_position_debug(target_position, position_before, position_after):\n\n print(\"Distance: \", SplinePlanner.distance(position_before, position_after))\n\n if SplinePlanner.distance(position_before, position_after) < 1e-5:\n\n # the two position is too close\n\n return False\n\n vec1 = np.array(target_position) - np.array(position_before)\n\n vec2 = np.array(target_position) - np.array(position_after)\n\n print(\"Vec1: \", vec1)\n\n print(\"Vec2: \", vec2)\n\n print(\"Dot: \", np.dot(vec1, vec2))\n\n if np.dot(vec1, vec2) < 0:\n\n # the two vectors are in the opposite direction, so we think we have cross the target position\n\n return True\n\n return False\n\n\n\n def create_path(self, odometry, gates, last_visited_gate): # types are Odometry, [Pose], Pose\n\n start_position = odometry.pose.pose.position\n\n start_velocity = geo.rotate_vector_wrt_quaternion(odometry.pose.pose.orientation, odometry.twist.twist.linear)\n\n if last_visited_gate is not None:\n\n visited_index = None\n\n for i in range(len(gates)):\n\n if geo.distance(last_visited_gate.position, gates[i].position) < 1.0:\n\n visited_index = i\n\n if visited_index is not None:\n\n gates = gates[visited_index+1:] + gates[:visited_index+1]\n\n\n\n # in case of re-planning, determine the current nearest waypoint. look forward about some specific \n\n # time into the current path (currently 1s) and let that future waypoint be the starting waypoint of \n\n # re-planning\n\n waypoints = []\n\n start = geo.vector_to_list(start_position)\n\n look_ahead_time = 1\n\n nearest_waypoint_idx = None\n\n planning_waypoint_idx = None\n\n current_gate_location = geo.vector_to_list(self.gates[self.target_gate_idx].position)\n\n if self.current_path is not None:\n\n nearest_waypoint_idx = self.search_for_nearest_waypoint(geo.vector_to_list(start_position))\n\n if nearest_waypoint_idx >= 0:\n\n current_path = self.current_path[\"path\"]\n\n waypoints.append(current_path[nearest_waypoint_idx][\"point_as_list\"])\n\n\n\n waypoint_time = current_path[nearest_waypoint_idx][\"time\"]\n\n\n\n planning_waypoint_idx = nearest_waypoint_idx\n\n current_path_length = len(current_path)\n\n while planning_waypoint_idx < current_path_length:\n\n planning_waypoint = current_path[planning_waypoint_idx]\n\n if planning_waypoint[\"time\"] - waypoint_time < look_ahead_time:\n\n planning_waypoint_idx += 1\n\n else:\n\n break\n\n if planning_waypoint_idx >= current_path_length:\n\n planning_waypoint_idx = current_path_length - 1\n\n start_position = current_path[planning_waypoint_idx][\"point_as_list\"]\n\n waypoints.append(start_position)\n\n \n\n if len(waypoints) == 0:\n\n print(\"The first planning or a re-planning from scratch is needed.\")\n\n orientation = np.array(current_gate_location) - np.array(start)\n\n orientation_normalized = orientation / np.linalg.norm(orientation)\n\n # append a point 5 meters behind along with the current position as the starting position\n\n waypoints.append((np.array(start) - 5 * orientation_normalized).tolist())\n\n waypoints.append(start)\n\n else:\n\n print(\"Re-planning\")\n\n\n\n # we already have two position around current position,\n\n # we still need 2 positionp around the gate\n\n # \n\n # make sure we won't going back if we're still heading to the current gate\n\n # and if we're too close to the target gate, head for the next too.\n\n target_gate_location = geo.vector_to_list(self.gates[self.target_gate_idx].position)\n\n if self.is_cross_gate(self.target_gate_idx, waypoints[0], waypoints[1]):\n\n if self.target_gate_idx + 1 < len(self.gates):\n\n rospy.loginfo(\"About to cross gate{}. Heading for next gate at index {}\".format(self.target_gate_idx, self.target_gate_idx + 1))\n\n gate = self.gates[self.target_gate_idx + 1]\n\n else:\n\n rospy.loginfo(\"Gates are about to be all passed. Stop planning.\")\n\n gate = self.gates[self.target_gate_idx]\n\n self.stop_planning = True\n\n return\n\n elif self.distance_to_gate(waypoints[0], self.target_gate_idx) <= 0.5 or \\\n\n self.distance_to_gate(waypoints[1], self.target_gate_idx) <= 0.5:\n\n if self.target_gate_idx + 1 < len(self.gates):\n\n rospy.loginfo(\"Close to gate {}. Heading for gate at index {}\".format(self.target_gate_idx, self.target_gate_idx + 1))\n\n gate = self.gates[self.target_gate_idx + 1]\n\n else:\n\n rospy.loginfo(\"Gates are about to be all passed. Stop planning.\")\n\n gate = self.gates[self.target_gate_idx]\n\n self.stop_planning = True\n\n return\n\n else:\n\n gate = self.gates[self.target_gate_idx]\n\n\n\n # append waypoints +- 0.5 meters around the next gate\n\n offsets = [-0.5, 0.5]\n\n for offset in offsets:\n\n waypoints.append(\n\n geo.vector_to_list(\n\n geo.point_plus_vector(gate.position, geo.quaternion_to_vector(gate.orientation, offset))))\n\n\n\n # wp = np.array(waypoints)\n\n # w0 = wp[:-1]\n\n # w1 = wp[1:]\n\n # diff = w0 - w1\n\n # norm = np.linalg.norm(diff, axis=1)\n\n # new_path_chord_length = np.sum(norm)\n\n \n\n # scale derivative w.r.t. total chord length\n\n # if deriv is not None:\n\n # old_path_chord_length = self.current_path[\"chord_length\"]\n\n # ratio = min(new_path_chord_length / old_path_chord_length, 1.0)\n\n # deriv = list(ratio * v for v in deriv)\n\n raw_waypoints_marker = Marker()\n\n raw_waypoints_marker.header.stamp = rospy.Time.now()\n\n raw_waypoints_marker.header.frame_id = \"world\"\n\n raw_waypoints_marker.color = ColorRGBA(1.0, 1.0, 0.0, 1.0)\n\n raw_waypoints_marker.scale = Vector3(0.5, 0.5, 0.5)\n\n raw_waypoints_marker.type = Marker.SPHERE_LIST\n\n raw_waypoints_marker.action = Marker.ADD\n\n raw_waypoints_marker.id = 1\n\n for wp in waypoints:\n\n raw_waypoints_marker.points.append(Point(wp[0], wp[1], wp[2]))\n\n self.raw_waypoints_viz_pub.publish(raw_waypoints_marker)\n\n \n\n path = SmoothedPath()\n\n path.fit(waypoints)\n\n\n\n trajectory_points = []\n\n def visit_cb(pt, deriv1, deriv2, s, t):\n\n # curvature is calcuated as norm(deriv1 x deriv2) / norm(deriv1)**3\n\n # see: https://en.wikipedia.org/wiki/Curvature#Local_expressions_2\n\n d1xd2 = np.cross(deriv1, deriv2)\n\n norm_d1 = np.linalg.norm(deriv1)\n\n norm_d2 = np.linalg.norm(deriv2)\n\n if norm_d1 > 1e-5:\n\n c = np.linalg.norm(d1xd2) / norm_d1 ** 3\n\n else:\n\n c = 0\n\n # the first order derivative is given as ds/dt, where s is the arc length and t is the internal parameter of the spline,\n\n # not time.\n\n # because of this, the magnitude of first order derivative is not the same with viable speed,\n\n # but nevertheless, the direction of the derivative of them are the same.\n\n\n\n # also note that unit normal vector at point is just the normalized second order derivative,\n\n # it is in the opposite direction of the radius vector\n\n\n\n # the cross product of unit tangent vector and unit normal vector\n\n # is also mentioned as unit binormal vector\n\n if norm_d1 > 1e-5:\n\n unit_d1 = deriv1 / norm_d1\n\n else:\n\n unit_d1 = np.array([0.0, 0.0, 0.0])\n\n \n\n if norm_d2 > 1e-5:\n\n unit_d2 = deriv2 / norm_d2\n\n else:\n\n unit_d2 = np.array([0.0, 0.0, 0.0])\n\n \n\n unit_binormal = np.cross(unit_d1, unit_d2)\n\n\n\n ds = 0\n\n if len(trajectory_points) > 0:\n\n last_point = trajectory_points[-1]\n\n ds = s - last_point['s']\n\n \n\n trajectory_points.append({\n\n 't': t,\n\n 's': s,\n\n 'point_as_list': pt,\n\n 'derivative': deriv1,\n\n 'derivative2': deriv2,\n\n\n\n 'ds': ds,\n\n 'point': Vector3(*(pt.tolist())),\n\n 'speed': self.max_speed,\n\n 'speed_direction': Vector3(*(unit_d1.tolist())),\n\n 'unit_normal': Vector3(*(unit_d2.tolist())),\n\n 'unit_binormal': Vector3(*(unit_binormal.tolist())),\n\n 'curvature': c\n\n })\n\n path.visit_at_interval(self.ds, visit_cb, self.trajectory_length)\n\n self.current_path = { \"chord_length\" : 0, \"path\": trajectory_points }\n\n# trajectory_points = [{'s': i * ds, 'speed': self.max_speed, 'curvature': geo.spline_distance_to_curvature(waypoint_spline, i*ds)} for i in range(30)]\n\n vmin = self.min_speed\n\n vmax = self.max_speed\n\n amax = self.max_acceleration\n\n\n\n def safe_speed(curvature, speed_neighbor, ds, accel = None):\n\n if accel is not None:\n\n return math.sqrt(speed_neighbor ** 2 + 2 * ds * accel)\n\n\n\n centripetal = curvature * speed_neighbor**2\n\n if centripetal >= amax:\n\n return max(vmin, min(vmax, math.sqrt(abs(amax / curvature))))\n\n remaining_acceleration = math.sqrt(amax**2 - centripetal**2)\n\n # see /Planning Motion Trajectories for Mobile Robots Using Splines/\n\n # (refered as Sprunk[2008] later) for more details (eq 3.21)\n\n v_this = math.sqrt(speed_neighbor ** 2 + 2 * ds * remaining_acceleration)\n\n return max(vmin, min(vmax, v_this))\n\n\n\n #print(geo.magnitude_vector(start_velocity))\n\n # trajectory_points[0]['speed'] = min(vmax, max(vmin, geo.magnitude_vector(start_velocity)))\n\n trajectory_points[0]['speed'] = geo.magnitude_vector(start_velocity)\n\n #print(trajectory_points[0]['speed'])\n\n num_traj = len(trajectory_points)\n\n for i in range(num_traj - 1): # iterate forwards, skipping first point which is fixed to current speed\n\n trajectory_points[i+1]['speed'] = safe_speed(trajectory_points[i+1]['curvature'], trajectory_points[i]['speed'], trajectory_points[i+1]['ds'])\n\n # skip the backward phase for 2 reason:\n\n # 1. we don't need a smooth stop. just complete the course\n\n # asap\n\n # 2. backward phase would change the start speed,\n\n # usually slower than the current speed. this\n\n # sudden change of speed would make the drone\n\n # \"jerking\" between trajectory switch.\n\n # for i in range(num_traj - 2):\n\n # j = num_traj - i - 2 # iterate backwards, skipping both end points\n\n # curvature = trajectory_points[j]['curvature']\n\n # min_neighbor_speed = min(trajectory_points[j-1]['speed'],trajectory_points[j+1]['speed'])\n\n # trajectory_points[j]['speed'] = safe_speed(curvature, min_neighbor_speed, trajectory_points[i+1]['ds'])\n\n\n\n # Set velocity based on speed and direction\n\n for point in trajectory_points:\n\n point['velocity'] = geo.scalar_multiply(point['speed'], point['speed_direction'])\n\n # the relationship between angular velocity and linear velocity is:\n\n # \\omega = r x v / || r ||^2\n\n # where r is the radius vector, v is linear velocity.\n\n # see: https://en.wikipedia.org/wiki/Angular_velocity#Particle_in_three_dimensions\n\n # note: with the anti-commutative law of cross product,\n\n # unit binormal B = v x (-r) / (||v|| * ||r||) = r x v / (||v|| * ||r||)\n\n # and curvature k = 1 / || r ||\n\n # so, omega = || v || * k * B \n\n omega = geo.scalar_multiply(geo.magnitude_vector(point['velocity']) * point['curvature'], point['unit_binormal'])\n\n point['omega'] = omega\n\n\n\n # Set time based on speed and distance\n\n trajectory_points[0]['time'] = 0.0\n\n for i in range(num_traj - 1):\n\n ds = trajectory_points[i+1]['ds']\n\n prev_time = trajectory_points[i]['time']\n\n # see Sprunk[2018] eq 3.20\n\n ave_speed = 0.5 * (trajectory_points[i]['speed'] + trajectory_points[i+1]['speed'])\n\n trajectory_points[i+1]['time'] = prev_time + ds / ave_speed\n\n\n\n # low pass filter on the designated speed.\n\n lpf = LowPassFilter(trajectory_points[0]['speed'], 5)\n\n for i in range(1, num_traj):\n\n trajectory_points[i]['speed'] = lpf.update(trajectory_points[i]['speed'], trajectory_points[i]['time'])\n\n \n\n # print(geo.magnitude_vector(start_velocity))\n\n # for pt in trajectory_points:\n\n # print(pt['speed'])\n\n # print(\"------\")\n\n\n\n # Set acceleration based on change in velocity\n\n # we're assuming constant accelerations between waypoints,\n\n # a is just \\delta V / \\delta t\n\n for i in range(num_traj - 1):\n\n t_current = trajectory_points[i]['time']\n\n t_next = trajectory_points[i + 1]['time']\n\n dt = t_next - t_current\n\n \n\n v_current = trajectory_points[i]['velocity']\n\n v_next = trajectory_points[i + 1]['velocity']\n\n dv = geo.vector_from_to(v_current, v_next)\n\n \n\n w_current = trajectory_points[i]['omega']\n\n w_next = trajectory_points[i]['omega']\n\n dw = geo.vector_from_to(w_current, w_next)\n\n \n\n trajectory_points[i]['acceleration'] = geo.scalar_multiply(1.0/dt, dv)\n\n trajectory_points[i]['acceleration_w'] = geo.scalar_multiply(1.0/dt, dw)\n\n trajectory_points[-1]['acceleration'] = trajectory_points[-2]['acceleration']\n\n trajectory_points[-1]['acceleration_w'] = trajectory_points[-2]['acceleration_w']\n\n\n\n trajectory = MultiDOFJointTrajectory()\n\n trajectory.header.frame_id=''\n\n trajectory.joint_names = ['base']\n\n for idx in range(len(trajectory_points)):\n\n point = trajectory_points[idx]\n\n point['time'] = trajectory_points[idx]['time']\n\n transform = Transform()\n\n transform.translation = point['point']\n\n transform.rotation = Quaternion(*(geo.vector_to_quat(point['velocity']).tolist()))\n\n velocity = Twist()\n\n velocity.linear = point['velocity']\n\n velocity.angular = point['omega']\n\n \n\n acceleration = Twist()\n\n acceleration.linear = point['acceleration']\n\n acceleration.angular = point['acceleration_w']\n\n \n\n trajectory.points.append(MultiDOFJointTrajectoryPoint([transform], [velocity], [acceleration], rospy.Duration(point['time'])))\n\n\n\n trajectory.header.stamp = rospy.Time.now()\n\n return trajectory\n\n\n\n # return MultiDOFJointTrajectory\n\n # joint_names=['uav']\n\n # points (type=MultiDOFJointTrajectoryPoint)\n\n # transforms (translation and rotation)\n\n # velocities (linear and angular)\n\n # accelerations (linear and angular)\n\n # time_from_start (duration, first point should have duration 0.0)\n\n #\n\n # http://docs.ros.org/api/trajectory_msgs/html/msg/MultiDOFJointTrajectory.html\n\n # https://github.com/ethz-asl/rotors_simulator/issues/510#issuecomment-414996170\n\n #\n\n # Note: The \"multi\" part is inappropriate, so lots of lists with one element each.\n\n\n\nif __name__ == '__main__':\n\n _node_name = 'spline_planner'\n\n _namespace = 'firefly'\n\n print('* {} starting... '.format(_node_name), end=\"\")\n\n rospy.init_node(_node_name)\n\n node = SplinePlanner(_node_name, _namespace)\n\n srv = Server(PlannerConfig, node.reconfigure_parameters)\n\n print('Ready.')\n\n node.start()\n\n rospy.spin()\n\n\n\n\"\"\"\n\nMisc planning references\n\n\n\nhttp://wiki.ros.org/base_local_planner\n\nhttp://docs.ros.org/melodic/api/nav_msgs/html/msg/OccupancyGrid.html\n\nhttp://wiki.ros.org/octomap\n\n\"\"\"\n\n\n", "file_path": "spline_planner/scripts/planner.py", "rank": 99, "score": 27584.94479796216 } ]
C++
ThirdParty-mod/java2cpp/java/io/LineNumberInputStream.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
#ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_DECL #define J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_DECL namespace j2cpp { namespace java { namespace io { class FilterInputStream; } } } namespace j2cpp { namespace java { namespace io { class InputStream; } } } #include <java/io/FilterInputStream.hpp> #include <java/io/InputStream.hpp> namespace j2cpp { namespace java { namespace io { class LineNumberInputStream; class LineNumberInputStream : public object<LineNumberInputStream> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) explicit LineNumberInputStream(jobject jobj) : object<LineNumberInputStream>(jobj) { } operator local_ref<java::io::FilterInputStream>() const; LineNumberInputStream(local_ref< java::io::InputStream > const&); jint available(); jint getLineNumber(); void mark(jint); jint read(); jint read(local_ref< array<jbyte,1> > const&, jint, jint); void reset(); void setLineNumber(jint); jlong skip(jlong); }; } } } #endif #else #ifndef J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_IMPL #define J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_IMPL namespace j2cpp { java::io::LineNumberInputStream::operator local_ref<java::io::FilterInputStream>() const { return local_ref<java::io::FilterInputStream>(get_jobject()); } java::io::LineNumberInputStream::LineNumberInputStream(local_ref< java::io::InputStream > const &a0) : object<java::io::LineNumberInputStream>( call_new_object< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(0), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } jint java::io::LineNumberInputStream::available() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(1), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(1), jint >(get_jobject()); } jint java::io::LineNumberInputStream::getLineNumber() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(2), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(2), jint >(get_jobject()); } void java::io::LineNumberInputStream::mark(jint a0) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(3), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject(), a0); } jint java::io::LineNumberInputStream::read() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(4), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(4), jint >(get_jobject()); } jint java::io::LineNumberInputStream::read(local_ref< array<jbyte,1> > const &a0, jint a1, jint a2) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(5), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject(), a0, a1, a2); } void java::io::LineNumberInputStream::reset() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(6), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(6), void >(get_jobject()); } void java::io::LineNumberInputStream::setLineNumber(jint a0) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(7), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject(), a0); } jlong java::io::LineNumberInputStream::skip(jlong a0) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(8), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(8), jlong >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::io::LineNumberInputStream,"java/io/LineNumberInputStream") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,0,"<init>","(Ljava/io/InputStream;)V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,1,"available","()I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,2,"getLineNumber","()I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,3,"mark","(I)V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,4,"read","()I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,5,"read","([BII)I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,6,"reset","()V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,7,"setLineNumber","(I)V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,8,"skip","(J)J") } #endif #endif
#ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_DECL #define J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_DECL namespace j2cpp { namespace java { namespace io { class FilterInputStream; } } } namespace j2cpp { namespace java { namespace io { class InputStream; } } } #include <java/io/FilterInputStream.hpp> #include <java/io/InputStream.hpp> namespace j2cpp { namespace java { namespace io { class LineNumberInputStream; class LineNumberInputStream : public object<LineNumberInputStream> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) explicit LineNumberInputStream(jobject jobj) : object<LineNumberInputStream>(jobj) { } operator local_ref<java::io::FilterInputStream>() const; LineNumberInputStream(local_ref< java::io::InputStream > const&); jint available(); jint getLineNumber(); void mark(jint); jint read(); jint read(local_ref< array<jbyte,1> > const&, jint, jint); void reset(); void setLineNumber(jint); jlong skip(jlong); }; } } } #endif #else #ifndef J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_IMPL #define J2CPP_JAVA_IO_LINENUMBERINPUTSTREAM_HPP_IMPL namespace j2cpp { java::io::LineNumberInputStream::operator local_ref<java::io::FilterInputStream>() const { return local_ref<java::io::FilterInputStream>(get_jobject()); } java::io::LineNumberInputStream::LineNumberInputStream(local_ref< java::io::InputStream > const &a0) : object<java::io::LineNumberInputStream>( call_new_object< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(0), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } jint java::io::LineNumberInputStream::available() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(1), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(1), jint >(get_jobject()); } jint java::io::LineNumberInputStream::getLineNumber() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(2), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(2), jint >(get_jobject()); } void java::io::LineNumberInputStrea
jint java::io::LineNumberInputStream::read() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(4), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(4), jint >(get_jobject()); } jint java::io::LineNumberInputStream::read(local_ref< array<jbyte,1> > const &a0, jint a1, jint a2) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(5), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject(), a0, a1, a2); } void java::io::LineNumberInputStream::reset() { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(6), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(6), void >(get_jobject()); } void java::io::LineNumberInputStream::setLineNumber(jint a0) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(7), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject(), a0); } jlong java::io::LineNumberInputStream::skip(jlong a0) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(8), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(8), jlong >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::io::LineNumberInputStream,"java/io/LineNumberInputStream") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,0,"<init>","(Ljava/io/InputStream;)V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,1,"available","()I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,2,"getLineNumber","()I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,3,"mark","(I)V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,4,"read","()I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,5,"read","([BII)I") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,6,"reset","()V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,7,"setLineNumber","(I)V") J2CPP_DEFINE_METHOD(java::io::LineNumberInputStream,8,"skip","(J)J") } #endif #endif
m::mark(jint a0) { return call_method< java::io::LineNumberInputStream::J2CPP_CLASS_NAME, java::io::LineNumberInputStream::J2CPP_METHOD_NAME(3), java::io::LineNumberInputStream::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject(), a0); }
function_block-function_prefixed
[ { "content": "\tclass Void;\n", "file_path": "ThirdParty-mod/java2cpp/java/lang/Void.hpp", "rank": 0, "score": 307452.9692886499 }, { "content": "\tclass Void\n\n\t\t: public object<Void>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit Void(jobject jobj)\n\n\t\t: object<Void>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/lang/Void.hpp", "rank": 1, "score": 307452.9692886499 }, { "content": "class ASSIMP_API IOStream : public Intern::AllocateFromAssimpHeap\n\n{\n\nprotected:\n\n\t/** Constructor protected, use IOSystem::Open() to create an instance. */\n\n\tIOStream(void);\n\n\n\npublic:\n\n\t// -------------------------------------------------------------------\n\n\t/** @brief Destructor. Deleting the object closes the underlying file, \n\n\t * alternatively you may use IOSystem::Close() to release the file. \n\n\t */\n\n\tvirtual ~IOStream();\n\n\n\n\t// -------------------------------------------------------------------\n\n\t/** @brief Read from the file\n\n\t *\n\n\t * See fread() for more details\n\n\t * This fails for write-only files */\n\n virtual size_t Read(void* pvBuffer, \n\n\t\tsize_t pSize, \n", "file_path": "utilities/ConvertToHQEngineMeshFile/Assimp/include/IOStream.h", "rank": 2, "score": 291400.2372448919 }, { "content": "class ASSIMP_API IOSystem : public Intern::AllocateFromAssimpHeap\n\n{\n\npublic:\n\n\n\n\t// -------------------------------------------------------------------\n\n\t/** @brief Default constructor.\n\n\t *\n\n\t * Create an instance of your derived class and assign it to an \n\n\t * #Assimp::Importer instance by calling Importer::SetIOHandler().\n\n\t */\n\n\tIOSystem();\n\n\n\n\t// -------------------------------------------------------------------\n\n\t/** @brief Virtual destructor.\n\n\t *\n\n\t * It is safe to be called from within DLL Assimp, we're constructed\n\n\t * on Assimp's heap.\n\n\t */\n\n\tvirtual ~IOSystem();\n\n\n", "file_path": "utilities/ConvertToHQEngineMeshFile/Assimp/include/IOSystem.h", "rank": 3, "score": 291400.23724489193 }, { "content": "\tclass InputStream\n\n\t\t: public object<InputStream>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\n\n\t\texplicit InputStream(jobject jobj)\n\n\t\t: object<InputStream>(jobj)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/InputStream.hpp", "rank": 4, "score": 283569.15788997256 }, { "content": "\tclass InputStream;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/InputStream.hpp", "rank": 5, "score": 283569.15788997256 }, { "content": "\tclass FilterInputStream\n\n\t\t: public object<FilterInputStream>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit FilterInputStream(jobject jobj)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilterInputStream.hpp", "rank": 6, "score": 276397.52693573793 }, { "content": "\tclass FilterInputStream;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilterInputStream.hpp", "rank": 7, "score": 276397.52693573793 }, { "content": "\tclass IOException;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/IOException.hpp", "rank": 10, "score": 260582.7359667247 }, { "content": "\tclass IOException\n\n\t\t: public object<IOException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit IOException(jobject jobj)\n\n\t\t: object<IOException>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Exception>() const;\n\n\n\n\n\n\t\tIOException();\n\n\t\tIOException(local_ref< java::lang::String > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/IOException.hpp", "rank": 11, "score": 260582.7359667247 }, { "content": "\tclass InterruptedIOException\n\n\t\t: public object<InterruptedIOException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit InterruptedIOException(jobject jobj)\n\n\t\t: object<InterruptedIOException>(jobj)\n\n\t\t, bytesTransferred(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::IOException>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/InterruptedIOException.hpp", "rank": 12, "score": 254264.81508473345 }, { "content": "\tclass InterruptedIOException;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/InterruptedIOException.hpp", "rank": 13, "score": 254264.81508473345 }, { "content": "\tclass InvalidClassException\n\n\t\t: public object<InvalidClassException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit InvalidClassException(jobject jobj)\n\n\t\t: object<InvalidClassException>(jobj)\n\n\t\t, classname(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::ObjectStreamException>() const;\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/InvalidClassException.hpp", "rank": 14, "score": 254046.8168031483 }, { "content": "\tclass ObjectStreamClass\n\n\t\t: public object<ObjectStreamClass>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit ObjectStreamClass(jobject jobj)\n\n\t\t: object<ObjectStreamClass>(jobj)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/ObjectStreamClass.hpp", "rank": 15, "score": 254046.8168031483 }, { "content": "\tclass ObjectStreamClass;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/ObjectStreamClass.hpp", "rank": 16, "score": 254046.8168031483 }, { "content": "\tclass InvalidClassException;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/InvalidClassException.hpp", "rank": 17, "score": 254046.8168031483 }, { "content": "\tclass PublicKey;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/PublicKey.hpp", "rank": 18, "score": 253076.04216929557 }, { "content": "\tclass PublicKey\n\n\t\t: public object<PublicKey>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit PublicKey(jobject jobj)\n\n\t\t: object<PublicKey>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::Key>() const;\n\n\n\n\n\n\t\tstatic static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jlong > serialVersionUID;\n\n\t}; //class PublicKey\n", "file_path": "ThirdParty-mod/java2cpp/java/security/PublicKey.hpp", "rank": 19, "score": 253076.04216929557 }, { "content": "class IOStream;\n\n\n\n// ---------------------------------------------------------------------------\n\n/** @brief CPP-API: Interface to the file system.\n\n *\n\n * Derive an own implementation from this interface to supply custom file handling\n\n * to the importer library. If you implement this interface, you also want to\n\n * supply a custom implementation for IOStream.\n\n *\n\n * @see Importer::SetIOHandler() */\n", "file_path": "utilities/ConvertToHQEngineMeshFile/Assimp/include/IOSystem.h", "rank": 20, "score": 250251.99479879646 }, { "content": "class HQShaderIncludeHandlerD3D11 : public ID3DInclude {\n\npublic:\n\n\tHQShaderIncludeHandlerD3D11();\n\n\tvoid SetFileManager(HQFileManager* includeFileManager) { this->includeFileManager = includeFileManager; }\n\n\tHQFileManager* GetFileManager() const { return includeFileManager; }\n\n\n\n\tSTDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes);\n\n\tSTDMETHOD(Close)(THIS_ LPCVOID pData);\n\nprivate:\n\n\tHQFileManager* includeFileManager;\n\n};\n\n\n\n#ifdef WIN32\n\n#\tpragma warning( push )\n\n#\tpragma warning( disable : 4250 )//dominance inheritance of HQBufferD3D11\n\n#endif\n\n\n\n/*-------------HQDrawIndirectBufferD3D11------------------*/\n", "file_path": "HQEngine/Source/HQRendererD3D11/HQShaderD3D11.h", "rank": 21, "score": 247862.0311051504 }, { "content": "\tclass HQEngineTexture : public ITexture\n\n\t{\n\n\tpublic:\n\n\t\tHQEngineTexture(const std::string& _name, HQEngineRenderManager* _manager);\n\n\t\tvirtual ~HQEngineTexture();\n\n\n\n\t\tvirtual const std::string& getName() const;\n\n\n\n\t\tvirtual void createManual(int _width, int _height, TextureUsage _usage, PixelFormat _format);\n\n\t\tvirtual void loadFromFile(const std::string& _filename);\n\n\t\tvirtual void saveToFile(const std::string& _filename) { }\n\n\n\n\t\tvirtual void destroy();\n\n\n\n\t\tvirtual ITexturePixelBuffer* lockPixelBuffer(TextureUsage _usage) ;\n\n\t\tvirtual void unlockPixelBuffer();\n\n\t\tvirtual bool isLockedPixelBuffer();\n\n\n\n\t\tvirtual int getWidth();\n\n\t\tvirtual int getHeight();\n", "file_path": "ThirdParty-mod/MyGUI/include/MyGUI_HQEngineTexture.h", "rank": 22, "score": 247851.0435155044 }, { "content": "\tclass UnsupportedOperationException;\n", "file_path": "ThirdParty-mod/java2cpp/java/lang/UnsupportedOperationException.hpp", "rank": 23, "score": 246406.27897643214 }, { "content": "\tclass UnsupportedOperationException\n\n\t\t: public object<UnsupportedOperationException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\n\n\t\texplicit UnsupportedOperationException(jobject jobj)\n\n\t\t: object<UnsupportedOperationException>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::RuntimeException>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/lang/UnsupportedOperationException.hpp", "rank": 24, "score": 246406.27897643214 }, { "content": "\tclass ReadOnlyBufferException;\n", "file_path": "ThirdParty-mod/java2cpp/java/nio/ReadOnlyBufferException.hpp", "rank": 25, "score": 246394.23709502482 }, { "content": "\tclass ReadOnlyBufferException\n\n\t\t: public object<ReadOnlyBufferException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\n\n\t\texplicit ReadOnlyBufferException(jobject jobj)\n\n\t\t: object<ReadOnlyBufferException>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::UnsupportedOperationException>() const;\n\n\n\n\n\n\t\tReadOnlyBufferException();\n\n\t}; //class ReadOnlyBufferException\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/nio/ReadOnlyBufferException.hpp", "rank": 26, "score": 246394.23709502482 }, { "content": "\tclass Widget;\n\n\ttypedef std::vector<Widget*> VectorWidgetPtr;\n\n\ttypedef std::map<std::string, Widget*> MapWidgetPtr;\n\n\ttypedef Enumerator<VectorWidgetPtr> EnumeratorWidgetPtr;\n\n\n\n} // namespace MyGUI\n\n\n\n#endif // __MYGUI_WIDGET_DEFINES_H__\n", "file_path": "ThirdParty-mod/MyGUI/include/MyGUI_WidgetDefines.h", "rank": 27, "score": 245001.38683669036 }, { "content": "\tclass Serializable;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Serializable.hpp", "rank": 28, "score": 244145.0197976975 }, { "content": "\tclass Writer\n\n\t\t: public object<Writer>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\t\tJ2CPP_DECLARE_METHOD(11)\n\n\t\tJ2CPP_DECLARE_METHOD(12)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Writer.hpp", "rank": 29, "score": 244145.0197976975 }, { "content": "\tclass Writer;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Writer.hpp", "rank": 30, "score": 244145.0197976975 }, { "content": "\tclass File;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/File.hpp", "rank": 31, "score": 244145.0197976975 }, { "content": "\tclass Flushable;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Flushable.hpp", "rank": 32, "score": 244145.0197976975 }, { "content": "\tclass Externalizable\n\n\t\t: public object<Externalizable>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit Externalizable(jobject jobj)\n\n\t\t: object<Externalizable>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::io::Serializable>() const;\n\n\n\n\n\n\t\tvoid readExternal(local_ref< java::io::ObjectInput > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Externalizable.hpp", "rank": 33, "score": 244145.0197976975 }, { "content": "\tclass Serializable\n\n\t\t: public object<Serializable>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\n\n\t\texplicit Serializable(jobject jobj)\n\n\t\t: object<Serializable>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\n\n\t}; //class Serializable\n\n\n\n} //namespace io\n\n} //namespace java\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Serializable.hpp", "rank": 34, "score": 244145.0197976975 }, { "content": "\tclass Reader\n\n\t\t: public object<Reader>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\t\tJ2CPP_DECLARE_METHOD(11)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Reader.hpp", "rank": 35, "score": 244145.0197976975 }, { "content": "\tclass Reader;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Reader.hpp", "rank": 36, "score": 244145.0197976975 }, { "content": "\tclass Closeable\n\n\t\t: public object<Closeable>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\n\n\t\texplicit Closeable(jobject jobj)\n\n\t\t: object<Closeable>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\n\n\n\n\t\tvoid close();\n\n\t}; //class Closeable\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Closeable.hpp", "rank": 37, "score": 244145.0197976975 }, { "content": "\tclass Closeable;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Closeable.hpp", "rank": 38, "score": 244145.01979769752 }, { "content": "\tclass File\n\n\t\t: public object<File>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\t\tJ2CPP_DECLARE_METHOD(11)\n\n\t\tJ2CPP_DECLARE_METHOD(12)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/File.hpp", "rank": 39, "score": 244145.0197976975 }, { "content": "\tclass Flushable\n\n\t\t: public object<Flushable>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\n\n\t\texplicit Flushable(jobject jobj)\n\n\t\t: object<Flushable>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\n\n\n\n\t\tvoid flush();\n\n\t}; //class Flushable\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Flushable.hpp", "rank": 40, "score": 244145.0197976975 }, { "content": "\tclass Externalizable;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/Externalizable.hpp", "rank": 41, "score": 244145.0197976975 }, { "content": "class HQBaseShaderManagerGL : public HQShaderManager, public HQResetable\n\n{\n\npublic:\n\n\t~HQBaseShaderManagerGL() {}\n\n\n\n\tvirtual void OnDraw() {}//this is called before drawing\n\n\tvirtual void OnLost() {}\n\n\tvirtual void OnReset() {}\n\n\n\n\t///\n\n\t///tạo shader từ mã đã compile\n\n\t///\n\n\tHQReturnVal CreateShaderFromByteCodeStream(HQShaderType type,\n\n\t\t\t\t\t\t\t\t\t HQDataReaderStream* dataStream,\n\n\t\t\t\t\t\t\t\t\t HQShaderObject** pID)\n\n\t{\n\n\t\treturn HQ_FAILED;\n\n\t}\n\n\n\n\t///\n", "file_path": "HQEngine/Source/HQRendererGL/HQShaderGL_Common.h", "rank": 42, "score": 244043.55244546512 }, { "content": "\tclass RSAPublicKey\n\n\t\t: public object<RSAPublicKey>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit RSAPublicKey(jobject jobj)\n\n\t\t: object<RSAPublicKey>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::PublicKey>() const;\n\n\t\toperator local_ref<java::security::interfaces::RSAKey>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/security/interfaces/RSAPublicKey.hpp", "rank": 43, "score": 243191.53429196042 }, { "content": "\tclass RSAPublicKey;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/interfaces/RSAPublicKey.hpp", "rank": 44, "score": 243191.53429196042 }, { "content": "\tclass DSAPublicKey;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/interfaces/DSAPublicKey.hpp", "rank": 45, "score": 243191.53429196042 }, { "content": "\tclass DSAPublicKey\n\n\t\t: public object<DSAPublicKey>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit DSAPublicKey(jobject jobj)\n\n\t\t: object<DSAPublicKey>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::interfaces::DSAKey>() const;\n\n\t\toperator local_ref<java::security::PublicKey>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/security/interfaces/DSAPublicKey.hpp", "rank": 46, "score": 243191.53429196042 }, { "content": "\tclass ECPublicKey\n\n\t\t: public object<ECPublicKey>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit ECPublicKey(jobject jobj)\n\n\t\t: object<ECPublicKey>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::PublicKey>() const;\n\n\t\toperator local_ref<java::security::interfaces::ECKey>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/security/interfaces/ECPublicKey.hpp", "rank": 47, "score": 243191.53429196042 }, { "content": "\tclass ECPublicKey;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/interfaces/ECPublicKey.hpp", "rank": 48, "score": 243191.53429196042 }, { "content": "\tclass ReadWriteLock\n\n\t\t: public object<ReadWriteLock>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit ReadWriteLock(jobject jobj)\n\n\t\t: object<ReadWriteLock>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\n\n\n\n\t\tlocal_ref< java::util::concurrent::locks::Lock > readLock();\n\n\t\tlocal_ref< java::util::concurrent::locks::Lock > writeLock();\n", "file_path": "ThirdParty-mod/java2cpp/java/util/concurrent/locks/ReadWriteLock.hpp", "rank": 49, "score": 240129.38676664265 }, { "content": "\t\tclass ReadLock\n\n\t\t\t: public object<ReadLock>\n\n\t\t{\n\n\t\tpublic:\n\n\n\n\t\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\t\tJ2CPP_DECLARE_METHOD(7)\n\n\n\n\t\t\texplicit ReadLock(jobject jobj)\n\n\t\t\t: object<ReadLock>(jobj)\n\n\t\t\t{\n\n\t\t\t}\n", "file_path": "ThirdParty-mod/java2cpp/java/util/concurrent/locks/ReentrantReadWriteLock.hpp", "rank": 50, "score": 240129.38676664265 }, { "content": "\tclass ReadWriteLock;\n", "file_path": "ThirdParty-mod/java2cpp/java/util/concurrent/locks/ReadWriteLock.hpp", "rank": 51, "score": 240129.38676664265 }, { "content": "\t\tclass ReadLock;\n", "file_path": "ThirdParty-mod/java2cpp/java/util/concurrent/locks/ReentrantReadWriteLock.hpp", "rank": 52, "score": 240129.38676664265 }, { "content": "class gzfilestream_common : virtual public ios {\n\n\n\n friend class gzifstream;\n\n friend class gzofstream;\n\n friend gzofstream &setcompressionlevel( gzofstream &, int );\n\n friend gzofstream &setcompressionstrategy( gzofstream &, int );\n\n\n\npublic:\n\n virtual ~gzfilestream_common();\n\n\n\n void attach( int fd, int io_mode );\n\n void open( const char *name, int io_mode );\n\n void close();\n\n\n\nprotected:\n\n gzfilestream_common();\n\n\n\nprivate:\n\n gzfilebuf *rdbuf();\n\n\n\n gzfilebuf buffer;\n\n\n\n};\n\n\n", "file_path": "HQEngine/Source/ImagesLoader/zlib-1.2.6/contrib/iostream/zfstream.h", "rank": 53, "score": 239933.2275571355 }, { "content": "\tclass HQEngineVertexBuffer : public IVertexBuffer\n\n\t{\n\n\tpublic:\n\n\t\tHQEngineVertexBuffer(HQEngineRenderManager* _pRenderManager);\n\n\t\tvirtual ~HQEngineVertexBuffer();\n\n\n\n\t\tvirtual void setVertexCount(size_t _count);\n\n\t\tvirtual size_t getVertexCount();\n\n\n\n\t\tvirtual Vertex* lock();\n\n\t\tvirtual void unlock();\n\n\n\n\tprivate:\n\n\t\tbool create();\n\n\t\tvoid destroy();\n\n\t\tvoid resize();\n\n\n\n\tprivate:\n\n\t\tHQEngineRenderManager*\tmManager;\n\n\t\tsize_t mVertexCount;\n\n\t\tsize_t mNeedVertexCount;\n\n\n\n\tpublic:\n\n\t\tHQVertexBuffer* mBuffer;\n\n\t};\n\n\n\n} // namespace MyGUI\n\n\n\n#endif // __MYGUI_HQEngine_VERTEX_BUFFER_H__\n", "file_path": "ThirdParty-mod/MyGUI/include/MyGUI_HQEngineVertexBuffer.h", "rank": 54, "score": 238361.33509966126 }, { "content": "\t\t//#########################################################################\n\n\t\t//! const reverse iterator for UString\n\n\tclass MYGUI_EXPORT _const_rev_iterator: public _base_iterator { /* i don't know why the beautifier is freaking out on this line */\n\n\t\tpublic:\n\n\t\t\t_const_rev_iterator();\n\n\t\t\t_const_rev_iterator( const _const_rev_iterator& i );\n\n\t\t\t_const_rev_iterator( const _rev_iterator& i );\n\n\t\t\t//! pre-increment\n\n\t\t\t_const_rev_iterator& operator++();\n\n\t\t\t//! post-increment\n\n\t\t\t_const_rev_iterator operator++( int );\n\n\n\n\t\t\t//! pre-decrement\n\n\t\t\t_const_rev_iterator& operator--();\n\n\t\t\t//! post-decrement\n\n\t\t\t_const_rev_iterator operator--( int );\n\n\n\n\t\t\t//! addition operator\n\n\t\t\t_const_rev_iterator operator+( difference_type n );\n\n\t\t\t//! subtraction operator\n\n\t\t\t_const_rev_iterator operator-( difference_type n );\n\n\n", "file_path": "ThirdParty-mod/MyGUI/include/MyGUI_UString.h", "rank": 55, "score": 237695.61398963825 }, { "content": "\t\t//#########################################################################\n\n\t\t//! const forward iterator for UString\n\n\tclass MYGUI_EXPORT _const_fwd_iterator: public _base_iterator { /* i don't know why the beautifier is freaking out on this line */\n\n\t\tpublic:\n\n\t\t\t_const_fwd_iterator();\n\n\t\t\t_const_fwd_iterator( const _const_fwd_iterator& i );\n\n\t\t\t_const_fwd_iterator( const _fwd_iterator& i );\n\n\n\n\t\t\t//! pre-increment\n\n\t\t\t_const_fwd_iterator& operator++();\n\n\t\t\t//! post-increment\n\n\t\t\t_const_fwd_iterator operator++( int );\n\n\n\n\t\t\t//! pre-decrement\n\n\t\t\t_const_fwd_iterator& operator--();\n\n\t\t\t//! post-decrement\n\n\t\t\t_const_fwd_iterator operator--( int );\n\n\n\n\t\t\t//! addition operator\n\n\t\t\t_const_fwd_iterator operator+( difference_type n );\n\n\t\t\t//! subtraction operator\n\n\t\t\t_const_fwd_iterator operator-( difference_type n );\n", "file_path": "ThirdParty-mod/MyGUI/include/MyGUI_UString.h", "rank": 56, "score": 237695.61398963825 }, { "content": "\tclass ECPublicKeySpec\n\n\t\t: public object<ECPublicKeySpec>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\n\n\t\texplicit ECPublicKeySpec(jobject jobj)\n\n\t\t: object<ECPublicKeySpec>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::spec::KeySpec>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/security/spec/ECPublicKeySpec.hpp", "rank": 57, "score": 237128.9125429335 }, { "content": "\tclass RSAPublicKeySpec\n\n\t\t: public object<RSAPublicKeySpec>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\n\n\t\texplicit RSAPublicKeySpec(jobject jobj)\n\n\t\t: object<RSAPublicKeySpec>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::spec::KeySpec>() const;\n\n\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/security/spec/RSAPublicKeySpec.hpp", "rank": 58, "score": 237128.9125429335 }, { "content": "\tclass ECPublicKeySpec;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/spec/ECPublicKeySpec.hpp", "rank": 59, "score": 237128.9125429335 }, { "content": "\tclass DSAPublicKeySpec;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/spec/DSAPublicKeySpec.hpp", "rank": 60, "score": 237128.9125429335 }, { "content": "\tclass RSAPublicKeySpec;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/spec/RSAPublicKeySpec.hpp", "rank": 61, "score": 237128.9125429335 }, { "content": "\tclass DSAPublicKeySpec\n\n\t\t: public object<DSAPublicKeySpec>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\n\n\t\texplicit DSAPublicKeySpec(jobject jobj)\n\n\t\t: object<DSAPublicKeySpec>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\t\toperator local_ref<java::security::spec::KeySpec>() const;\n", "file_path": "ThirdParty-mod/java2cpp/java/security/spec/DSAPublicKeySpec.hpp", "rank": 62, "score": 237128.9125429335 }, { "content": "class HQBaseRenderTargetManagerGL : public HQBaseRenderTargetManager, public HQResetable\n\n{\n\npublic:\n\n\tHQBaseRenderTargetManagerGL(hq_uint32 maxActiveRenderTargets, \n\n\t\t\t\t\t\t\t HQBaseTextureManager *pTexMan,\n\n\t\t\t\t\t\t\t HQLogStream* logFileStream , const char *logPrefix ,\n\n\t\t\t\t\t\t\t bool flushLog)\n\n\t\t:HQBaseRenderTargetManager(\n\n\t\t\tmaxActiveRenderTargets, pTexMan, \n\n\t\t\tlogFileStream, logPrefix, flushLog\n\n\t\t)\n\n\t{\n\n\t}\n\n\n\n\t//clear only first {numRTs} render targets\n\n\tvirtual HQReturnVal ClearRenderTargets(hquint32 numRTs) = 0;\n\n};\n\n\n\n/*----------frame buffer object implementation version---------------*/\n", "file_path": "HQEngine/Source/HQRendererGL/HQRenderTargetGL.h", "rank": 63, "score": 236966.41401866626 }, { "content": "\tclass FilterReader\n\n\t\t: public object<FilterReader>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit FilterReader(jobject jobj)\n\n\t\t: object<FilterReader>(jobj)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilterReader.hpp", "rank": 64, "score": 236389.9623191039 }, { "content": "\tclass FileReader\n\n\t\t: public object<FileReader>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\n\n\t\texplicit FileReader(jobject jobj)\n\n\t\t: object<FileReader>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::InputStreamReader>() const;\n\n\n\n\n\n\t\tFileReader(local_ref< java::io::File > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FileReader.hpp", "rank": 65, "score": 236389.9623191039 }, { "content": "\tclass FilenameFilter\n\n\t\t: public object<FilenameFilter>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\n\n\t\texplicit FilenameFilter(jobject jobj)\n\n\t\t: object<FilenameFilter>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n\n\n\n\n\n\t\tjboolean accept(local_ref< java::io::File > const&, local_ref< java::lang::String > const&);\n\n\t}; //class FilenameFilter\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilenameFilter.hpp", "rank": 66, "score": 236389.9623191039 }, { "content": "\tclass EOFException\n\n\t\t: public object<EOFException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit EOFException(jobject jobj)\n\n\t\t: object<EOFException>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::IOException>() const;\n\n\n\n\n\n\t\tEOFException();\n\n\t\tEOFException(local_ref< java::lang::String > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/EOFException.hpp", "rank": 67, "score": 236389.9623191039 }, { "content": "\tclass PushbackReader\n\n\t\t: public object<PushbackReader>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\t\tJ2CPP_DECLARE_METHOD(11)\n\n\t\tJ2CPP_DECLARE_METHOD(12)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/PushbackReader.hpp", "rank": 68, "score": 236389.9623191039 }, { "content": "\tclass PushbackReader;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/PushbackReader.hpp", "rank": 69, "score": 236389.9623191039 }, { "content": "\tclass FilterReader;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilterReader.hpp", "rank": 70, "score": 236389.9623191039 }, { "content": "\tclass FilenameFilter;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilenameFilter.hpp", "rank": 71, "score": 236389.9623191039 }, { "content": "\tclass OutputStream\n\n\t\t: public object<OutputStream>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\n\n\t\texplicit OutputStream(jobject jobj)\n\n\t\t: object<OutputStream>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::lang::Object>() const;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/OutputStream.hpp", "rank": 72, "score": 236389.9623191039 }, { "content": "\tclass FileWriter;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FileWriter.hpp", "rank": 73, "score": 236389.9623191039 }, { "content": "\tclass BufferedReader\n\n\t\t: public object<BufferedReader>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\n\n\t\texplicit BufferedReader(jobject jobj)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/BufferedReader.hpp", "rank": 74, "score": 236389.9623191039 }, { "content": "\tclass PipedWriter;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/PipedWriter.hpp", "rank": 75, "score": 236389.9623191039 }, { "content": "\tclass ObjectInput\n\n\t\t: public object<ObjectInput>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\n\n\t\texplicit ObjectInput(jobject jobj)\n\n\t\t: object<ObjectInput>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/ObjectInput.hpp", "rank": 76, "score": 236389.9623191039 }, { "content": "\tclass EOFException;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/EOFException.hpp", "rank": 77, "score": 236389.9623191039 }, { "content": "\tclass NotSerializableException;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/NotSerializableException.hpp", "rank": 78, "score": 236389.9623191039 }, { "content": "\tclass FilePermission;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilePermission.hpp", "rank": 79, "score": 236389.9623191039 }, { "content": "\tclass StringWriter\n\n\t\t: public object<StringWriter>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\t\tJ2CPP_DECLARE_METHOD(11)\n\n\t\tJ2CPP_DECLARE_METHOD(12)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/StringWriter.hpp", "rank": 80, "score": 236389.9623191039 }, { "content": "\tclass FileWriter\n\n\t\t: public object<FileWriter>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\n\n\t\texplicit FileWriter(jobject jobj)\n\n\t\t: object<FileWriter>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::OutputStreamWriter>() const;\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FileWriter.hpp", "rank": 81, "score": 236389.9623191039 }, { "content": "\tclass NotSerializableException\n\n\t\t: public object<NotSerializableException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit NotSerializableException(jobject jobj)\n\n\t\t: object<NotSerializableException>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::ObjectStreamException>() const;\n\n\n\n\n\n\t\tNotSerializableException();\n\n\t\tNotSerializableException(local_ref< java::lang::String > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/NotSerializableException.hpp", "rank": 82, "score": 236389.9623191039 }, { "content": "\tclass FilterWriter;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilterWriter.hpp", "rank": 83, "score": 236389.9623191039 }, { "content": "\tclass DataOutput;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/DataOutput.hpp", "rank": 84, "score": 236389.9623191039 }, { "content": "\tclass SerializablePermission;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/SerializablePermission.hpp", "rank": 85, "score": 236389.9623191039 }, { "content": "\tclass NotActiveException\n\n\t\t: public object<NotActiveException>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit NotActiveException(jobject jobj)\n\n\t\t: object<NotActiveException>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::io::ObjectStreamException>() const;\n\n\n\n\n\n\t\tNotActiveException();\n\n\t\tNotActiveException(local_ref< java::lang::String > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/NotActiveException.hpp", "rank": 86, "score": 236389.9623191039 }, { "content": "\tclass OutputStream;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/OutputStream.hpp", "rank": 87, "score": 236389.9623191039 }, { "content": "\tclass BufferedReader;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/BufferedReader.hpp", "rank": 88, "score": 236389.9623191039 }, { "content": "\tclass SerializablePermission\n\n\t\t: public object<SerializablePermission>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\n\n\t\texplicit SerializablePermission(jobject jobj)\n\n\t\t: object<SerializablePermission>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::security::BasicPermission>() const;\n\n\n\n\n\n\t\tSerializablePermission(local_ref< java::lang::String > const&);\n\n\t\tSerializablePermission(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);\n", "file_path": "ThirdParty-mod/java2cpp/java/io/SerializablePermission.hpp", "rank": 89, "score": 236389.9623191039 }, { "content": "\tclass FilePermission\n\n\t\t: public object<FilePermission>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\n\n\t\texplicit FilePermission(jobject jobj)\n\n\t\t: object<FilePermission>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\toperator local_ref<java::security::Permission>() const;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilePermission.hpp", "rank": 90, "score": 236389.9623191039 }, { "content": "\tclass PipedReader\n\n\t\t: public object<PipedReader>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\n\n\t\texplicit PipedReader(jobject jobj)\n\n\t\t: object<PipedReader>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/PipedReader.hpp", "rank": 91, "score": 236389.9623191039 }, { "content": "\tclass ObjectInput;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/ObjectInput.hpp", "rank": 92, "score": 236389.9623191039 }, { "content": "\tclass StringWriter;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/StringWriter.hpp", "rank": 93, "score": 236389.9623191039 }, { "content": "\tclass PipedReader;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/PipedReader.hpp", "rank": 94, "score": 236389.9623191039 }, { "content": "\tclass NotActiveException;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/NotActiveException.hpp", "rank": 95, "score": 236389.9623191039 }, { "content": "\tclass DataOutput\n\n\t\t: public object<DataOutput>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\t\tJ2CPP_DECLARE_METHOD(7)\n\n\t\tJ2CPP_DECLARE_METHOD(8)\n\n\t\tJ2CPP_DECLARE_METHOD(9)\n\n\t\tJ2CPP_DECLARE_METHOD(10)\n\n\t\tJ2CPP_DECLARE_METHOD(11)\n\n\t\tJ2CPP_DECLARE_METHOD(12)\n", "file_path": "ThirdParty-mod/java2cpp/java/io/DataOutput.hpp", "rank": 96, "score": 236389.9623191039 }, { "content": "\tclass FileReader;\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FileReader.hpp", "rank": 97, "score": 236389.9623191039 }, { "content": "\tclass FilterWriter\n\n\t\t: public object<FilterWriter>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_FIELD(0)\n\n\n\n\t\texplicit FilterWriter(jobject jobj)\n\n\t\t: object<FilterWriter>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/FilterWriter.hpp", "rank": 98, "score": 236389.9623191039 }, { "content": "\tclass PipedWriter\n\n\t\t: public object<PipedWriter>\n\n\t{\n\n\tpublic:\n\n\n\n\t\tJ2CPP_DECLARE_CLASS\n\n\n\n\t\tJ2CPP_DECLARE_METHOD(0)\n\n\t\tJ2CPP_DECLARE_METHOD(1)\n\n\t\tJ2CPP_DECLARE_METHOD(2)\n\n\t\tJ2CPP_DECLARE_METHOD(3)\n\n\t\tJ2CPP_DECLARE_METHOD(4)\n\n\t\tJ2CPP_DECLARE_METHOD(5)\n\n\t\tJ2CPP_DECLARE_METHOD(6)\n\n\n\n\t\texplicit PipedWriter(jobject jobj)\n\n\t\t: object<PipedWriter>(jobj)\n\n\t\t{\n\n\t\t}\n\n\n", "file_path": "ThirdParty-mod/java2cpp/java/io/PipedWriter.hpp", "rank": 99, "score": 236389.9623191039 } ]
C++
Funambol/source/common/http/DigestAuthentication.cpp
wbitos/funambol
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
#include <Funambol/base/Log.h> #include <Funambol/base/messages.h> #include <Funambol/base/util/utils.h> #include <Funambol/http/constants.h> #include <Funambol/http/errors.h> #include <Funambol/http/DigestAuthentication.h> #include <Funambol/event/FireEvent.h> USE_NAMESPACE DigestAuthentication::DigestAuthentication(const StringBuffer& user, const StringBuffer& pass) : HttpAuthentication(Digest, user, pass) { } StringBuffer DigestAuthentication::getAuthenticationHeaders(const char* authstr, URL url, const HashProvider *hashProvider) { processAuthInfo(authstr); return generateAuthResponseString(url, hashProvider); } StringBuffer DigestAuthentication::extractDigestProp(const char* authstr, const char* prop) { StringBuffer result = ""; const char* start; const char* end; const char* ptr; char * temp = new char[100]; sprintf(temp, "%s=\"", prop); start = strstr(authstr, temp); if (start == NULL) { return ""; } start = start + strlen(temp); end = start; delete [] temp; while ((ptr = strstr(end, "\"")) != NULL) { if (*(ptr-1) != '\\') { end = ptr; break; } } if (ptr == NULL) { end = start + strlen(start); } int len = (int)(end - start); result = ""; result.append(start); return result.substr(0, len); } void DigestAuthentication::processAuthInfo(const char* authstr) { if (strstr(authstr, "Digest") != authstr) { return; } this->realm = extractDigestProp(authstr, "realm"); this->qop = extractDigestProp(authstr, "qop"); this->nonce = extractDigestProp(authstr, "nonce"); this->opaque = extractDigestProp(authstr, "opaque"); } StringBuffer DigestAuthentication::generateAuthResponseString(URL url, const HashProvider *hashProvider) { if (!hashProvider) { return NULL; } StringBuffer nc = "00000001"; StringBuffer cnonce; StringBuffer ha1; StringBuffer ha2; StringBuffer finalhash; StringBuffer key = ""; key.sprintf("%d:%d", rand(), rand()); cnonce = hashProvider->getHash(key.c_str()); StringBuffer temp = ""; temp.append(this->username.c_str()).append(":") .append(this->realm).append(":") .append(this->password.c_str()); ha1 = hashProvider->getHash(temp.c_str()); temp = "POST:"; temp.append(url.resource); ha2 = hashProvider->getHash(temp.c_str()); StringBuffer tohash = ""; tohash.append(ha1).append(":") .append(this->nonce).append(":") .append(nc).append(":") .append(cnonce).append(":") .append(this->qop).append(":") .append(ha2); finalhash = hashProvider->getHash(tohash); StringBuffer response = ""; response.sprintf("Digest username=\"%s\", realm=\"%s\", " "nonce=\"%s\", uri=\"%s\", qop=\"%s\", nc=\"%s\", " "cnonce=\"%s\", response=\"%s\", opaque=\"%s\"", this->username.c_str(), this->realm.c_str(), this->nonce.c_str(), url.resource, this->qop.c_str(), nc.c_str(), cnonce.c_str(), finalhash.c_str(), this->opaque.c_str()); return response; }
#include <Funambol/base/Log.h> #include <Funambol/base/messages.h> #include <Funambol/base/util/utils.h> #include <Funambol/http/constants.h> #include <Funambol/http/errors.h> #include <Funambol/http/DigestAuthentication.h> #include <Funambol/event/FireEvent.h> USE_NAMESPACE DigestAuthentication::DigestAuthentication(const StringBuffer& user, const StringBuffer& pass) : HttpAuthentication(Digest, user, pass) { } StringBuffer DigestAuthentication::getAuthenticationHeaders(const char* authstr, URL url, const HashProvider *hashProvider) { processAuthInfo(authstr); return generateAuthResponseString(url, hashProvider); }
void DigestAuthentication::processAuthInfo(const char* authstr) { if (strstr(authstr, "Digest") != authstr) { return; } this->realm = extractDigestProp(authstr, "realm"); this->qop = extractDigestProp(authstr, "qop"); this->nonce = extractDigestProp(authstr, "nonce"); this->opaque = extractDigestProp(authstr, "opaque"); } StringBuffer DigestAuthentication::generateAuthResponseString(URL url, const HashProvider *hashProvider) { if (!hashProvider) { return NULL; } StringBuffer nc = "00000001"; StringBuffer cnonce; StringBuffer ha1; StringBuffer ha2; StringBuffer finalhash; StringBuffer key = ""; key.sprintf("%d:%d", rand(), rand()); cnonce = hashProvider->getHash(key.c_str()); StringBuffer temp = ""; temp.append(this->username.c_str()).append(":") .append(this->realm).append(":") .append(this->password.c_str()); ha1 = hashProvider->getHash(temp.c_str()); temp = "POST:"; temp.append(url.resource); ha2 = hashProvider->getHash(temp.c_str()); StringBuffer tohash = ""; tohash.append(ha1).append(":") .append(this->nonce).append(":") .append(nc).append(":") .append(cnonce).append(":") .append(this->qop).append(":") .append(ha2); finalhash = hashProvider->getHash(tohash); StringBuffer response = ""; response.sprintf("Digest username=\"%s\", realm=\"%s\", " "nonce=\"%s\", uri=\"%s\", qop=\"%s\", nc=\"%s\", " "cnonce=\"%s\", response=\"%s\", opaque=\"%s\"", this->username.c_str(), this->realm.c_str(), this->nonce.c_str(), url.resource, this->qop.c_str(), nc.c_str(), cnonce.c_str(), finalhash.c_str(), this->opaque.c_str()); return response; }
StringBuffer DigestAuthentication::extractDigestProp(const char* authstr, const char* prop) { StringBuffer result = ""; const char* start; const char* end; const char* ptr; char * temp = new char[100]; sprintf(temp, "%s=\"", prop); start = strstr(authstr, temp); if (start == NULL) { return ""; } start = start + strlen(temp); end = start; delete [] temp; while ((ptr = strstr(end, "\"")) != NULL) { if (*(ptr-1) != '\\') { end = ptr; break; } } if (ptr == NULL) { end = start + strlen(start); } int len = (int)(end - start); result = ""; result.append(start); return result.substr(0, len); }
function_block-full_function
[ { "content": " class URL {\n\n\n\n public:\n\n char* fullURL ;\n\n char* protocol;\n\n char* host ;\n\n char* resource;\n\n int port ;\n\n\n\n URL();\n\n URL(const URL &url);\n\n URL(const char* url);\n\n ~URL();\n\n\n\n void setURL(const URL& url);\n\n void setURL(const char* url);\n\n\n\n bool isSecure() const;\n\n\n\n URL& operator= (const URL& url);\n", "file_path": "Funambol/include/Funambol/http/URL.h", "rank": 0, "score": 146955.34165515288 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n#ifndef INCL_HTTP_URL\n\n #define INCL_HTTP_URL\n\n/** @cond DEV */\n\n\n\n #include <Funambol/base/globalsdef.h>\n\n #include <Funambol/base/fscapi.h>\n\n #include <Funambol/base/constants.h>\n\n #include <Funambol/http/constants.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n", "file_path": "Funambol/include/Funambol/http/URL.h", "rank": 1, "score": 104635.12678214896 }, { "content": " URL& operator= (const char* url);\n\n\n\n protected:\n\n void setURL(const char* u, const char* p, const char* h, const char* r, int port);\n\n };\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n\n\n", "file_path": "Funambol/include/Funambol/http/URL.h", "rank": 2, "score": 104633.35961490893 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/http/URL.h", "rank": 3, "score": 104619.0132921579 }, { "content": "WCHAR *toWideChar(const char *mb, const char *encoding = 0 );\n", "file_path": "Funambol/include/Funambol/base/util/utils.h", "rank": 4, "score": 91064.62940525108 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n\n\n#include <Funambol/base/util/utils.h>\n\n#include <Funambol/http/URL.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 5, "score": 52736.98835780264 }, { "content": "void URL::setURL(const char* url) {\n\n if ((url == NULL) || (strlen(url) == 0)) {\n\n return;\n\n }\n\n\n\n long size;\n\n\n\n char* s = NULL;\n\n char* q = NULL;\n\n\n\n //\n\n // protocol (mandatory)\n\n //\n\n s = strstr((char*)url, \"://\");\n\n if ((s == NULL) || (s == url)) {\n\n return;\n\n }\n\n\n\n size = s-url;\n\n char* p = new char[size+1];\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 6, "score": 52736.83573657426 }, { "content": " delete [] protocol; protocol = NULL;\n\n }\n\n\n\n if (host) {\n\n delete [] host; host = NULL;\n\n }\n\n\n\n if (resource) {\n\n delete [] resource; resource = NULL;\n\n }\n\n\n\n}\n\n\n\nvoid URL::setURL(const URL& url) {\n\n setURL(url.fullURL, url.protocol, url.host, url.resource, url.port);\n\n}\n\n\n\nvoid URL::setURL(const char*u, const char*p, const char*h, const char*r, int port) {\n\n if (fullURL) {\n\n delete [] fullURL; fullURL = NULL;\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 7, "score": 52736.51205602988 }, { "content": " port = (int)strtol(s+1, NULL, 10);\n\n *s = 0;\n\n }\n\n\n\n //\n\n // resource\n\n //\n\n size = q ? strlen(q) : 0;\n\n char* r = new char[size+1];\n\n if (size) strncpy(r, q, size); r[size] = 0;\n\n\n\n //\n\n // fullURL\n\n //\n\n size = strlen(url);\n\n char* u = new char[size+1];\n\n strcpy(u, url);\n\n\n\n setURL(u, p, h, r, port);\n\n\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 8, "score": 52736.151325325576 }, { "content": " //\n\n // frees all pointer\n\n //\n\n if (p != NULL)\n\n delete [] p;\n\n if (u != NULL)\n\n delete [] u;\n\n if (h != NULL)\n\n delete [] h;\n\n if (r != NULL)\n\n delete [] r;\n\n\n\n\n\n}\n\n\n\nURL& URL::operator= (const URL& url) {\n\n setURL(url); return *this;\n\n}\n\n\n\nURL& URL::operator= (const char* url) {\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 9, "score": 52735.081748928875 }, { "content": " setURL(url); return *this;\n\n}\n\n\n\nbool URL::isSecure() const {\n\n char* t = strtolower(protocol);\n\n\n\n bool ret = (strcmp(t, \"https\") == 0);\n\n\n\n delete [] t; t = NULL;\n\n\n\n return ret;\n\n}\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 10, "score": 52734.679026491685 }, { "content": "USE_NAMESPACE\n\n\n\n\n\n/*\n\n * Creates a new URL object from a string representation of the URL. The URL\n\n * must be in the form:\n\n *\n\n * <protocol>://<hostname>[:<port>]/<resource>\n\n *\n\n * If a parsing error occurs, fullURL is set to an empty string (\"\").\n\n *\n\n * @param url the URL\n\n */\n\nURL::URL(const char* url) : fullURL(NULL), protocol(NULL), host(NULL), resource(NULL), port(0){\n\n setURL(url);\n\n}\n\n\n\n/*\n\n * Default constructs\n\n */\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 11, "score": 52734.61636468878 }, { "content": " strncpy(p, url, size); p[size] = 0;\n\n\n\n //\n\n // server (mandatory)\n\n // and\n\n // port (optional)\n\n //\n\n s += 3;\n\n q = strstr(s, \"/\");\n\n if (q == NULL) {\n\n size = strlen(s);\n\n } else {\n\n size = q-s;\n\n }\n\n char* h = new char[size+1];\n\n strncpy(h, s, size); h[size] = 0;\n\n\n\n unsigned int port = (unsigned int)-1;\n\n s = strstr(h, \":\");\n\n if (s) {\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 12, "score": 52733.795558855374 }, { "content": "URL::URL() : fullURL(NULL), protocol(NULL), host(NULL), resource(NULL), port(0) {\n\n}\n\n\n\n/*\n\n * Copy constructor\n\n */\n\nURL::URL(const URL& url) {\n\n this->fullURL = stringdup(url.fullURL);\n\n this->host = stringdup(url.host);\n\n this->port = url.port;\n\n this->protocol = stringdup(url.protocol);\n\n this->resource = stringdup(url.resource);\n\n}\n\n\n\nURL::~URL() {\n\n if (fullURL) {\n\n delete [] fullURL; fullURL = NULL;\n\n }\n\n\n\n if (protocol) {\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 13, "score": 52729.86209459732 }, { "content": " }\n\n\n\n if (u) {\n\n fullURL = stringdup(u);\n\n }\n\n\n\n if (protocol) {\n\n delete [] protocol; protocol = NULL;\n\n }\n\n\n\n if (p) {\n\n protocol = stringdup(p);\n\n }\n\n\n\n if (host) {\n\n delete [] host; host = NULL;\n\n }\n\n\n\n if (h) {\n\n host = stringdup(h);\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 14, "score": 52727.74553356432 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 15, "score": 52721.997301832336 }, { "content": " }\n\n\n\n if (resource) {\n\n delete [] resource; resource = NULL;\n\n }\n\n\n\n if (r) {\n\n resource = stringdup(r);\n\n }\n\n\n\n if (port == -1) {\n\n //\n\n // use default ports\n\n //\n\n this->port = isSecure() ? 443 : 80;\n\n } else {\n\n this->port = port;\n\n }\n\n}\n\n\n", "file_path": "Funambol/source/common/http/URL.cpp", "rank": 16, "score": 52721.997301832336 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef _BASE64_H\n\n#define _BASE64_H\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/fscapi.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\nint b64_encode(char *dest, const void *src, int len);\n\nint b64_decode(void *dest, const char *src);\n\n\n", "file_path": "Funambol/include/Funambol/base/base64.h", "rank": 17, "score": 50601.22470187173 }, { "content": "#include <Funambol/spdm/ManagementNode.h>\n\n#include <Funambol/spdm/DMTreeFactory.h>\n\n#include <Funambol/spdm/DMTree.h>\n\n#include <Funambol/base/util/utils.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n\n\n\n#include <Funambol/updater/UpdaterConfig.h>\n\n#include <Funambol/updater/UpdaterUI.h>\n\n\n\n#define UP_URL_COMPONENT \"component=\"\n\n#define UP_URL_VERSION \"version=\"\n\n#define UP_URL_FORMAT \"format=\"\n\n\n\n#define UP_TYPE \"type=\"\n\n#define UP_ACTIVATION_DATE \"activation-date=\"\n\n#define UP_SIZE \"size=\"\n\n#define UP_VERSION \"version=\"\n\n#define UP_URL_UPDATE \"url=\"\n\n#define UP_URL_COMMENT \"url_description=\"\n\n\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 18, "score": 50601.15950967836 }, { "content": " /**\n\n * Return true if this is the last chunk;\n\n */\n\n bool isLast();\n\n void setLast(bool v);\n\n \n\n /**\n\n * Return the length of the data in this chunk\n\n */\n\n unsigned long getDataSize();\n\n \n\n /**\n\n * Set the data inside the chunk\n\n */\n\n void setData(const char* value);\n\n\n\n /**\n\n * Return a pointer to the internal data without any new allocation\n\n */\n\n const char* getData();\n", "file_path": "Funambol/include/Funambol/spds/Chunk.h", "rank": 19, "score": 50599.505757813204 }, { "content": " * @param shortTime a time string including just the local time of day in\n\n * the preferred time format according to the current locale\n\n * @param utcTime a time string including just the UTC time of day in \"hh:mm:ss UTC\" format\n\n * @param level the severity of the report\n\n * @param levelPrefix a string representing the severity (may differ from level, e.g. for Log::developer())\n\n * @param line the actual message string\n\n */\n\n virtual void printLine(bool firstLine,\n\n time_t time,\n\n const char *fullTime,\n\n const char *shortTime,\n\n const char *utcTime,\n\n LogLevel level,\n\n const char *levelPrefix,\n\n const char *line);\n\n\n\n private:\n\n FILE* logFile;\n\n bool logFileStdout;\n\n StringBuffer logName;\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 20, "score": 50598.77399799951 }, { "content": "\n\n virtual void setLogPath(const char* configLogPath);\n\n virtual void setLogName(const char* configLogName);\n\n virtual void error(const char* msg, ...);\n\n virtual void info(const char* msg, ...);\n\n virtual void developer(const char* msg, ...);\n\n virtual void debug(const char* msg, ...);\n\n virtual void reset(const char* title = NULL);\n\n virtual size_t getLogSize();\n\n\n\n protected:\n\n//\tchar htmlFormatLine[1024];\n\n /**\n\n * Prints a single line to the current log file.\n\n * Can be overridden by derived class to also print\n\n * in a different way.\n\n *\n\n * @param firstLine true if this is the first line of a new message\n\n * @param time unformatted time stamp for line\n\n * @param fullTime a time string including date and GMT offset\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 21, "score": 50597.84306145863 }, { "content": " * The encoding of this chunk\n\n */\n\n StringBuffer encoding;\n\n\n\n unsigned long totalDataSize;\n\n \n\npublic:\n\n\n\n // Constructor\n\n Chunk(); \n\n Chunk(const char* value); \n\n\n\n ~Chunk(); \n\n \n\n /**\n\n * Return true if this is the first chunk;\n\n */\n\n bool isFirst();\n\n void setFirst(bool v);\n\n \n", "file_path": "Funambol/include/Funambol/spds/Chunk.h", "rank": 22, "score": 50597.35847828081 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n\n\n#ifndef INCL_MAIL\n\n#define INCL_MAIL\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/fscapi.h>\n\n#include <Funambol/base/util/ArrayElement.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n\n#include <Funambol/spds/MailMessage.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n", "file_path": "Funambol/include/Funambol/spds/Email.h", "rank": 23, "score": 50597.33378985648 }, { "content": " virtual bool isLoggable(LogLevel level) { return level <= logLevel; }\n\n\n\n /**\n\n * error(), info(), developer(), debug() all print one message,\n\n * using printf() style formatting. Whether the message is really\n\n * written into the log file depends on the current log level\n\n * (see LogLevel above).\n\n *\n\n * Which of these calls is the right one for a certain message\n\n * is a somewhat subjective choice. Here is a definition how they\n\n * are supposed to be used:\n\n * - error: severe problem which the user and developer have to\n\n * know about\n\n * - info: information about a sync session which the user\n\n * will want to read during/after each sync session\n\n * - developer: information about a sync session that is not\n\n * interesting for a user (for example, because it\n\n * is constant and already known) but which should\n\n * be in each log because developers need to know\n\n * it. Messages logged with this calls will be included\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 24, "score": 50597.30193732027 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n#ifndef INCL_HTTP_PROXY\n\n#define INCL_HTTP_PROXY\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/fscapi.h>\n\n#include <Funambol/base/constants.h>\n\n#include <Funambol/http/constants.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\n\n", "file_path": "Funambol/include/Funambol/http/Proxy.h", "rank": 25, "score": 50597.22456210631 }, { "content": " * Updater configuration. \n\n * Note: it's owned externally!\n\n */\n\n UpdaterConfig& config;\n\n\n\n /** UI abstraction to interact with the user */\n\n UpdaterUI* ui;\n\n\n\nprivate:\n\n\n\n /**\n\n * It checks if it is needed to check via url or locally only.\n\n * If locally only, there is no other stuff to do. Otherwise the data\n\n * are overwritten in the Updateconfig and then persisted\n\n */\n\n int32_t requestUpdate();\n\n \n\n /**\n\n * Used to ask the server. Parse the message from the server and populate \n\n * the UpdateConfig\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 26, "score": 50596.9293648405 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_UPDATER\n\n#define INCL_UPDATER\n\n\n\n#include <Funambol/base/globalsdef.h>\n\n#include <Funambol/base/fscapi.h>\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 27, "score": 50596.567655578096 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n\n\n#ifndef INCL_LISTENER\n\n#define INCL_LISTENER\n\n#include <Funambol/base/globalsdef.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n", "file_path": "Funambol/include/Funambol/event/Listener.h", "rank": 28, "score": 50596.510374470294 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_ALLCLAUSE\n\n#define INCL_ALLCLAUSE\n\n/** @cond DEV */\n\n\n\n#include <Funambol/filter/Clause.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n", "file_path": "Funambol/include/Funambol/filter/AllClause.h", "rank": 29, "score": 50596.45377932522 }, { "content": " * previously postponed (later option).\n\n * The method returns true iff the check discovers a new version.\n\n */\n\n bool start();\n\n\n\n /**\n\n * This method forces the process of installing a new version. It does not\n\n * check if a new version is really available, but it calls the UI with\n\n * the last update URL (which may be invalid). It is responsability of the\n\n * caller to make sure it makes sense to invoke this method.\n\n */\n\n void forceUpdate();\n\n\n\n /**\n\n * Returns true if a new version is known to be available for upgrade. This\n\n * method does not query the upgrade server, but it uses the information\n\n * available.\n\n */\n\n bool isNewVersionAvailable();\n\n\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 30, "score": 50596.1652724311 }, { "content": " /**\n\n * Adds a fixed string to each following line of output. NULL\n\n * removes the prefix again. Some logging implementations\n\n * might ignore the prefix. The prefix is copied by the\n\n * implementation, i.e. the caller can free it after this\n\n * call.\n\n */\n\n virtual void setPrefix(const char *prefix) {\n\n // Avoid compiler warning\n\n prefix = NULL;\n\n }\n\n\n\n /**\n\n * Returns the log file size [bytes].\n\n */\n\n virtual size_t getLogSize() = 0;\n\n\n\n bool rotateLogFile(unsigned int maxSize, unsigned int maxCount) ;\n\n };\n\n\n\n# define LOG Log::instance()\n\n\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 31, "score": 50595.88441387349 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_WHERECLAUSE\n\n#define INCL_WHERECLAUSE\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/fscapi.h>\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 32, "score": 50595.334975087804 }, { "content": " *\n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite\n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n *\n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n *\n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably\n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_CHUNK\n\n#define INCL_CHUNK\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/fscapi.h>\n", "file_path": "Funambol/include/Funambol/spds/Chunk.h", "rank": 33, "score": 50595.334975087804 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_LOG\n\n #define INCL_LOG\n\n/** @cond DEV */\n\n\n\n #include <Funambol/base/fscapi.h>\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 34, "score": 50595.334975087804 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_CLAUSE\n\n#define INCL_CLAUSE\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/util/ArrayElement.h>\n", "file_path": "Funambol/include/Funambol/filter/Clause.h", "rank": 35, "score": 50595.272046886545 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_POSIX_LOG\n\n# define INCL_POSIX_LOG\n\n/** @cond DEV */\n\n\n\n#include <Funambol/base/fscapi.h>\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 36, "score": 50595.272046886545 }, { "content": "#include <Funambol/base/Log.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n\n\n\n#include <stdio.h>\n\n#include <time.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\n/**\n\n * extended API, can only be used if it is certain that\n\n * Log::instance() returns a POSIXLog\n\n */\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 37, "score": 50593.9214565347 }, { "content": "\n\n bool getForwarded() { return forwarded; }\n\n void setForwarded(bool v) { forwarded=v; }\n\n\n\n bool getReplied() { return replied; }\n\n void setReplied(bool r) { replied=r; }\n\n\n\n const char * getReceived() { return received; }\n\n void setReceived(const char * v) { received=v; }\n\n\n\n const char * getCreated() { return created; }\n\n void setCreated(const char * v) { created=v; }\n\n\n\n const char * getModified() { return modified; }\n\n void setModified(const char * v) { modified=v; }\n\n\n\n bool getDeleted() { return deleted; }\n\n void setDeleted(bool v) { deleted=v; }\n\n\n\n bool getFlagged() { return flagged; }\n", "file_path": "Funambol/include/Funambol/spds/Email.h", "rank": 38, "score": 50593.59605995038 }, { "content": "#include <Funambol/base/constants.h>\n\n#include <Funambol/base/globalsdef.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\n/**\n\n * Class representing a chunk of a SyncItem. It is filled by the ItemReader and it is\n\n * considered by the SyncManager as its interface instead of the SyncItem directly.\n\n */\n", "file_path": "Funambol/include/Funambol/spds/Chunk.h", "rank": 39, "score": 50593.4819938634 }, { "content": " /**\n\n * This method handles a new version. It takes care of asking the user\n\n * what he intends to do and take the proper actions.\n\n * The onlyMandatoryExpired is usually false because the method is in the flow\n\n * of the udpate. Putting the onlyMandatoryExpired to true, means that the check\n\n * with the stored info is done only if the updateType is mandatory and the \n\n * expiration date is done. It is useful for some check that can be done before starting \n\n * the sync.\n\n * \n\n * @param onlyMandatoryExpired - false to check everything during the whole process\n\n * true continue to check only if the mandatory udpate is expired\n\n *\n\n * @return true if the user has selected something. False if no action was performed by the \n\n * user.\n\n */\n\n bool newVersionAvailable(bool onlyMandatoryExpired = false);\n\n\n\n /**\n\n * Set the ui for calling bck when user actions are required. If this value\n\n * is not set, the update changes the config but does not need any user\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 40, "score": 50593.46709452984 }, { "content": "#include <Funambol/filter/Clause.h>\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\ntypedef enum {\n\n EQ = 0,\n\n NE = 1,\n\n GT = 2,\n\n LT = 3,\n\n GE = 4,\n\n LE = 5,\n\n CONTAIN = 6,\n\n NCONTAIN = 7,\n\n UNKNOWN = -1\n\n} WhereClauseOperator;\n\n\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 41, "score": 50593.17661180782 }, { "content": " */\n\n void setValue(const char* v);\n\n\n\n\n\n /*\n\n * getvalue\n\n *\n\n */\n\n const char* getValue();\n\n\n\n\n\n /*\n\n * getOperator\n\n *\n\n */\n\n WhereClauseOperator getOperator();\n\n\n\n\n\n /*\n\n * setOperator\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 42, "score": 50593.08129701854 }, { "content": " /*\n\n * setProperty\n\n *\n\n * @param p0\n\n */\n\n void setProperty(const char* p);\n\n\n\n\n\n /*\n\n * getProperty\n\n *\n\n */\n\n const char* getProperty();\n\n\n\n\n\n\n\n /*\n\n * setValue\n\n *\n\n * @param p0\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 43, "score": 50593.06335881749 }, { "content": " * at LOG_LEVEL_INFO, therefore messages should be small and\n\n * not recur so that the log file size remains small.\n\n * - debug: most detailed logging, messages may be arbitrarily large\n\n *\n\n * Here is a decision tree which helps to pick the right level:\n\n * - an error: => error()\n\n * - it changes during each sync or marks important steps\n\n * in the sync: info()\n\n * - small, non-recurring message which is important for developers\n\n * who read a log produced at LOG_LEVEL_INFO: developer()\n\n * - everything else: debug()\n\n */\n\n virtual void error(const char* msg, ...) = 0;\n\n virtual void info(const char* msg, ...) = 0;\n\n virtual void developer(const char* msg, ...) = 0;\n\n virtual void debug(const char* msg, ...) = 0;\n\n\n\n /** clients can use #ifdef to detect this new feature */\n\n# define LOG_HAVE_DEVELOPER 1\n\n\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 44, "score": 50593.061188340565 }, { "content": " WhereClause();\n\n\n\n\n\n /*\n\n * WhereClause constructor\n\n *\n\n * @param property\n\n * @param value\n\n * @param o\n\n * @param s\n\n */\n\n WhereClause(const char* property, const char* value, WhereClauseOperator o, bool p3);\n\n\n\n\n\n /*\n\n * WhereClause destructor\n\n *\n\n */\n\n ~WhereClause();\n\n\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 45, "score": 50592.99259125272 }, { "content": " /**\n\n * Sets the directory where the log file will be created,\n\n * which is done in reset() or any of the logging functions.\n\n */\n\n virtual void setLogPath(const char* configLogPath) = 0;\n\n\n\n /**\n\n * Sets the file name of the log file without creating it;\n\n * that is done in reset() or any of the logging functions.\n\n */\n\n virtual void setLogName(const char* configLogName) = 0;\n\n\n\n /**\n\n * creates the log file under the selected name and path,\n\n * optionally logging the given title\n\n */\n\n virtual void reset(const char* title = NULL) = 0;\n\n\n\n virtual void setLevel(LogLevel level) { logLevel = level; }\n\n virtual LogLevel getLevel() { return logLevel; }\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 46, "score": 50592.787992716825 }, { "content": " #include <Funambol/base/util/StringBuffer.h>\n\n\n\n /** prefix for error messages */\n\n #define LOG_ERROR \"ERROR\"\n\n /** prefix for informational messages */\n\n #define LOG_INFO \"INFO\"\n\n /** prefix for debug or developer messages */\n\n #define LOG_DEBUG \"DEBUG\"\n\n\n\n /** default is to create this file in the current directory */\n\n #define LOG_NAME \"synclog.html\"\n\n#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\n /**\n\n * valid parameters for setLevel()\n\n */\n\n typedef enum {\n\n /**\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 47, "score": 50592.72524090937 }, { "content": " void setFlagged(bool v) { flagged=v; }\n\n\n\n MailMessage& getMailMessage() { return emailItem; }\n\n void setMailMessage(const MailMessage& v) { emailItem = v; }\n\n\n\n // ---------------------------------------------------------- Public Methods\n\n int parse(const char *syncmlData) { return 0; } // TODO\n\n char *format() { return wcsdup(\"\"); } // TODO\n\n\n\n ArrayElement* clone() { return new Email(*this); }\n\n\n\n};\n\n\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n\n\n", "file_path": "Funambol/include/Funambol/spds/Email.h", "rank": 48, "score": 50592.67662431049 }, { "content": " * logging to stdout\n\n * @param redirectStderr if true, then file descriptor 2 (stderr)\n\n * will also be redirected into the log file;\n\n * the original stderr is preserved and will be\n\n * restored when turning this redirection off\n\n */\n\n virtual void setLogFile(const char *path, const char* name, bool redirectStderr = false);\n\n\n\n /**\n\n * returns active log file or NULL if none set (e.g. if logging to stdout directly)\n\n */\n\n virtual FILE *getLogFile() { return logFile; }\n\n\n\n /**\n\n * if a client developer wants to ignore the prefix, he can\n\n * derive his own Log implementation from POSIXLog, override this\n\n * call and then install his implementation via Log::setLogger()\n\n */\n\n virtual void setPrefix(const char *prefix) { this->prefix = prefix ? prefix : \"\"; }\n\n virtual const StringBuffer &getPrefix() const { return prefix; }\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 49, "score": 50592.65958830982 }, { "content": " StringBuffer logPath;\n\n bool logRedirectStderr;\n\n\n\n /** a copy of stderr before it was redirected */\n\n int fderr;\n\n\n\n /**\n\n * additional prefix for each line\n\n */\n\n StringBuffer prefix;\n\n\n\n void printMessage(LogLevel level, const char* levelPrefix, const char* msg, va_list argList);\n\n};\n\n\n\n#define POSIX_LOG ((POSIXLog &)Log::instance())\n\n\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 50, "score": 50592.61405688245 }, { "content": "#include <Funambol/base/globalsdef.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\ntypedef enum {\n\n CLAUSE = 0,\n\n LOGICAL_CLAUSE = 1,\n\n WHERE_CLAUSE = 2,\n\n ALL_CLAUSE = 3,\n\n FIELD_CLAUSE = 4,\n\n FILTER_CLAUSE = 5\n\n} ClauseType;\n\n\n", "file_path": "Funambol/include/Funambol/filter/Clause.h", "rank": 51, "score": 50592.26793027066 }, { "content": "\n\n void setDataEncoding(const char* enc) { encoding = enc; }\n\n StringBuffer getDataEncoding() { return encoding; }\n\n\n\n \n\n void setTotalDataSize(unsigned long size);\n\n\n\n unsigned long getTotalDataSize();\n\n\n\n};\n\n\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n", "file_path": "Funambol/include/Funambol/spds/Chunk.h", "rank": 52, "score": 50591.77807630715 }, { "content": " * log level not configured: if used in setLevel(), then only\n\n * error messages will be printed\n\n */\n\n LOG_LEVEL_NONE = 0,\n\n /**\n\n * errors and info messages for users and developers\n\n * will be printed: use this to keep the log consise and\n\n * small\n\n */\n\n LOG_LEVEL_INFO = 1,\n\n /**\n\n * all messages will be printed: the log can become very large!\n\n */\n\n LOG_LEVEL_DEBUG = 2,\n\n } LogLevel;\n\n\n\n /**\n\n *\n\n */\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 53, "score": 50591.74625563178 }, { "content": " /**\n\n * Build a numerical representation of a software version string. This\n\n * representation is suitable for comparison (>,<,==). Versions must be\n\n * triplets for this method to work properly.\n\n */\n\n int32_t buildVersionID(const StringBuffer& version);\n\n \n\npublic:\n\n \n\n /** \n\n * Construct an update with the given component name, version and configuration.\n\n */\n\n Updater(const StringBuffer& component, const StringBuffer& version, UpdaterConfig& c);\n\n \n\n ~Updater();\n\n\n\n /**\n\n * Start the update check progress. This may result in connecting to the\n\n * update server, check if a new version is available. If this is not\n\n * required, we can still notify the user of a new version which was\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 54, "score": 50591.361279974095 }, { "content": " /*\n\n * Creates a new instance of this Clause\n\n *\n\n * @return the clone\n\n */\n\n ArrayElement* clone();\n\n\n\n\n\n};\n\n\n\n\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 55, "score": 50586.62105279838 }, { "content": " * interaction.\n\n */\n\n void setUI(UpdaterUI* ui);\n\n\n\n /**\n\n * check the update on the server. If it is necessary set a value to 1\n\n * return false if there is no action to do\n\n * return true if there is something to download\n\n */\n\n bool checkIsToUpdate();\n\n \n\n /**\n\n * Check if the stored info are Mandatory update and the activation date has been exceeded. \n\n * It checks between the activation date stored in the settings and the current date \n\n * in the system plus the updateType that must be mandatory...\n\n *\n\n * @return true if it is a mandatory and the activation date exceeded, false otherwise\n\n */\n\n bool isMandatoryUpdateActivationDateExceeded();\n\n\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n#endif\n\n\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 56, "score": 50586.62105279838 }, { "content": "\n\nBEGIN_NAMESPACE\n\n/** @cond DEV */\n\n\n\n\n\n/**\n\n * The base class for all Listeners. This has to be derived by all types of\n\n * listeners.\n\n */\n\n\n", "file_path": "Funambol/include/Funambol/event/Listener.h", "rank": 57, "score": 50586.62105279838 }, { "content": " * Grants access to the singleton which implements logging.\n\n * The implementation of this function and thus the Log\n\n * class itself is platform specific: if no Log instance\n\n * has been set yet, then this call has to create one.\n\n */\n\n static Log &instance();\n\n\n\n /**\n\n * Overrides the default Log implementation. The Log class\n\n * itself will never delete the active logger.\n\n *\n\n * @param logger will be used for all future logging activities;\n\n * NULL is allowed and implies that the default\n\n * Log implementation will be created if needed\n\n */\n\n static void setLogger(Log *logger) { Log::logger = logger; }\n\n\n\n /** clients can use #ifdef to detect this new feature */\n\n# define LOG_HAVE_SET_LOGGER 1\n\n\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 58, "score": 50586.62105279838 }, { "content": "// To get data in the properties format (otherwise \"JSON\" is default)\n\n#define UP_PROPERTIES \"properties\"\n\n\n\n// Update types:\n\n#define UP_TYPE_OPTIONAL \"optional\"\n\n#define UP_TYPE_RECOMMENDED \"recommended\" // This is the default\n\n#define UP_TYPE_MANDATORY \"mandatory\"\n\n\n\n\n\nBEGIN_NAMESPACE\n\n\n\n/**\n\n * This class is responsible to handle the update procedure of the client.\n\n * It contains all the action that has to be done in order to handle the udpate.\n\n */\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 59, "score": 50586.62105279838 }, { "content": " */\n\n int32_t parseMessage(StringBuffer message);\n\n \n\n /**\n\n * utility to convert an unsigned long into a string\n\n */\n\n StringBuffer long2string(uint32_t v) ;\n\n \n\n /**\n\n * utility to convert a string into an unsigned long\n\n */\n\n uint32_t string2long(const StringBuffer& v) ;\n\n\n\n /**\n\n * Get all the strings in the server message\n\n */\n\n void getListedString(ArrayList& allString, const StringBuffer& s,\n\n const StringBuffer& separator);\n\n\n\n\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 60, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/base/posixlog.h", "rank": 61, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2008 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/updater/Updater.h", "rank": 62, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/spds/Email.h", "rank": 63, "score": 50586.62105279838 }, { "content": " *\n\n * @param o\n\n */\n\n void setOperator(WhereClauseOperator o);\n\n\n\n\n\n /*\n\n * isCaseSensitive\n\n *\n\n */\n\n bool isCaseSensitive();\n\n\n\n\n\n /*\n\n * setCaseSensitive\n\n *\n\n * @param s\n\n */\n\n void setCaseSensitive(bool s);\n\n\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 64, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/base/Log.h", "rank": 65, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/event/Listener.h", "rank": 66, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/base/base64.h", "rank": 67, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/http/Proxy.h", "rank": 68, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/filter/Clause.h", "rank": 69, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/filter/WhereClause.h", "rank": 70, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc. \n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n * \n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission \n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n * \n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n * \n\n * You should have received a copy of the GNU Affero General Public License \n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/filter/AllClause.h", "rank": 71, "score": 50586.62105279838 }, { "content": "/*\n\n * Funambol is a mobile platform developed by Funambol, Inc.\n\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n\n *\n\n * This program is free software; you can redistribute it and/or modify it under\n\n * the terms of the GNU Affero General Public License version 3 as published by\n\n * the Free Software Foundation with the addition of the following permission\n\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE\n\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n\n *\n\n * This program is distributed in the hope that it will be useful, but WITHOUT\n\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n\n * details.\n\n *\n\n * You should have received a copy of the GNU Affero General Public License\n\n * along with this program; if not, see http://www.gnu.org/licenses or write to\n\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\n * MA 02110-1301 USA.\n", "file_path": "Funambol/include/Funambol/spds/Chunk.h", "rank": 72, "score": 50586.62105279838 }, { "content": " MSUManager(const char* url, const char* user_agent);\n\n ~MSUManager();\n\n \n\n EMSUStatusCode login(const char* username, const char* password);\n\n EMSUStatusCode getCaptchaUrl(char** captchaUrl);\n\n EMSUStatusCode getCaptcha(const char* captchaRequestUrl, unsigned char** captchaImage, int *captchaImageSize);\n\n \n\n /**\n\n * Executes the mobile signup process (HTTP POST) for a new user, providing the passed captcha token.\n\n * The new userId and password must be passed as parameters, and are included in the JSON body request.\n\n * The sessionID saved during the getCaptcha request is used, if existing.\n\n *\n\n * @param username the new user id (the phone number)\n\n * @param password the password for the new user\n\n * @param token the captcha token inserted manually by the user\n\n * @param deviceIfo the device information required to fill the JSON body for the HTTP request\n\n * @return the result of the signup process, one of EMSUStatusCode.\n\n */\n\n EMSUStatusCode signup(const char* username, const char* password, const char *token, MSUDeviceInfo* deviceInfo);\n\n \n\n const char* getJsonErrorDescription() const { return jsonMessage->getErrorMessage().c_str(); }\n\n const char* getJsonErrorCode() const { return jsonMessage->getErrorCode().c_str(); }\n\n};\n\n \n\nEND_FUNAMBOL_NAMESPACE\n\n\n\n#endif // __MSU_MANAGER_H__\n", "file_path": "Funambol/include/Funambol/msu/MSUManager.h", "rank": 73, "score": 49387.80168316343 }, { "content": " * @param pass The corresponding password\n\n */\n\n HttpAuthentication(AuthType authType, const StringBuffer& user, const StringBuffer& pass) \n\n : type(authType), username(user), password(pass) {}\n\n \n\n virtual ~HttpAuthentication() {}\n\n\n\n virtual void setUsername(const StringBuffer& user) { username = user; }\n\n virtual void setPassword(const StringBuffer& pass) { password = pass; }\n\n virtual void setType (const AuthType typ) { type = typ; }\n\n \n\n virtual StringBuffer getUsername() { return username; }\n\n virtual StringBuffer getPassword() { return password; }\n\n virtual AuthType getType() { return type; }\n\n\n\n /**\n\n * Return generated authentication headers for the current username and password.\n\n *\n\n * @param authstr The authentication string from which the headers are generated\n\n * @param url The URL to authenticate against\n", "file_path": "Funambol/include/Funambol/http/HttpAuthentication.h", "rank": 74, "score": 49387.684053775876 }, { "content": "\n\n virtual const char* getUserAgent();\n\n\n\n /**\n\n * Set MIME type of the received message.\n\n *\n\n * @param mime mime type of the received response\n\n */\n\n void setResponseMime(const char *mime);\n\n\n\n /**\n\n * Returns MIME type of the response message.\n\n *\n\n * Returned string should be deleted.\n\n */\n\n const char* getResponseMime();\n\n\n\n /**\n\n * Returns property of the response message\n\n *\n", "file_path": "Funambol/include/Funambol/http/TransportAgent.h", "rank": 75, "score": 49378.46584701671 }, { "content": " *\n\n * @param proxyPassword the new proxyPassword value\n\n */\n\n void setProxyPassword(const char* proxyPassword);\n\n\n\n /**\n\n * Returns the syncURL value. If the URL does not start with http://\n\n * (or HTTP://) or https:// (or HTTPS://), http:// is prepended to the\n\n * given string.\n\n */\n\n const char* getSyncURL() const;\n\n\n\n /**\n\n * Sets a new the syncURL value. The given data are copied in an internal\n\n * buffer so that the caller is assured that the given address can be\n\n * released after the call.\n\n *\n\n * @param syncURL the new syncURL value\n\n */\n\n void setSyncURL(const char* syncURL);\n", "file_path": "Funambol/include/Funambol/spds/AccessConfig.h", "rank": 76, "score": 49378.15595419602 }, { "content": " * Returned string should be deleted.\n\n */\n\n const char* getResponseProperty(const char *pname);\n\n\n\n /**\n\n * Returns size of the server response (header size not included)\n\n */\n\n unsigned int getResponseSize();\n\n\n\n /**\n\n * Sets response code\n\n */\n\n void setResponseCode(int respCode);\n\n\n\n /**\n\n * Returns response code\n\n */\n\n int getResponseCode();\n\n\n\n /**\n", "file_path": "Funambol/include/Funambol/http/TransportAgent.h", "rank": 77, "score": 49377.8377186181 }, { "content": " /// Adds the passed dataStore (if nt NULL) to the array of dataStores.\n\n void addDataStore(DataStore* dataStore);\n\n\n\n /**\n\n * Returns a specific DataStore, given its name (sourceRef).\n\n * If not found, returns NULL.\n\n */\n\n DataStore* getDataStore(const char* sourceRef);\n\n\n\n /// Returns the value of dirty flag.\n\n unsigned int getDirty() const;\n\n\n\n /// Returns true if the passed flags are dirty for this object.\n\n bool isDirty(const unsigned int flags);\n\n\n\n /// Sets the dirty flag to the passed value. With flags=0 resets the dirty flag.\n\n void setDirty(const unsigned int flags);\n\n\n\n /**\n\n * Sets the values of this object with with the values from the given\n", "file_path": "Funambol/include/Funambol/spds/DeviceConfig.h", "rank": 78, "score": 49377.01319293842 }, { "content": "\t * Declared in the interface HttpAuthentication. Just calls getAuthenticationHeaders() with no params.\n\n\t * @see getAuthenticationHeaders()\n\n\t */ \n\n\tStringBuffer getAuthenticationHeaders(const char* authstr, URL url, const HashProvider *hashProvider) {\n\n\t return getAuthenticationHeaders();\n\n\t}\n\n\t\n\n};\n\n\n\nEND_FUNAMBOL_NAMESPACE\n\n#endif\n\n\n", "file_path": "Funambol/include/Funambol/http/BasicAuthentication.h", "rank": 79, "score": 49376.78456531314 }, { "content": " * @param hashProvider An object that provides a hashing function in order to hash the response\n\n * \n\n * @return The authentication response headers\n\n */\n\n virtual StringBuffer getAuthenticationHeaders(const char* authStr, URL url, const HashProvider *hashProvider) = 0;\n\n\n\n /**\n\n * Return generated authentication headers for the current username and password.\n\n * Just calls getAuthenticationHeaders() with no params.\n\n\t * @see getAuthenticationHeaders(const char*, URL, const HashProvider*)\n\n */\n\n virtual StringBuffer getAuthenticationHeaders() {\n\n return getAuthenticationHeaders(NULL, NULL, NULL);\n\n }\n\n \n\n \n\nprotected:\n\n \n\n /// The authentication type, one of enum AuthType.\n\n AuthType type;\n", "file_path": "Funambol/include/Funambol/http/HttpAuthentication.h", "rank": 80, "score": 49376.601698914455 }, { "content": " /// Compose and return the destination URL for the upload.\n\n StringBuffer composeURL();\n\n\n\n /// Sets all the headers for the http request.\n\n void setRequestHeaders(const StringBuffer& luid, HttpConnection& httpConnection, InputStream& inputStream);\n\n\n\n /**\n\n * Returns a new allocated HttpConnection.\n\n * It's used by the upload() method, the returned object is then deleted.\n\n */\n\n virtual HttpConnection* getHttpConnection() {\n\n return new HttpConnection(userAgent);\n\n }\n\n};\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n\n\n", "file_path": "Funambol/include/Funambol/http/HttpUploader.h", "rank": 81, "score": 49375.74672380207 }, { "content": " */\n\n virtual int sync(AbstractSyncConfig& config, char** sourceNames = NULL);\n\n\n\n /*\n\n * Returns a pointer to the internal syncReport.\n\n * Used to get detailed results on the executed synchronization.\n\n * Must be called after sync() method.\n\n */\n\n SyncReport* getSyncReport();\n\n\n\n /**\n\n * Sets a defined TransportAgent to be used during sync.\n\n * Note: the passed pointer will be owned and deleted by the APIs, so \n\n * it MUST NOT be deleted by the caller.\n\n */\n\n void setTransportAgent(TransportAgent* t);\n\n\n\n /**\n\n * Sets the last sync results in the passed config, and the last source resupt\n\n * for all active sources in SyncReport. The values are read from\n", "file_path": "Funambol/include/Funambol/client/SyncClient.h", "rank": 82, "score": 49374.72965290334 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_DIGEST_AUTHENTICATION\n\n#define INCL_DIGEST_AUTHENTICATION\n\n\n\n#include <Funambol/base/fscapi.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n\n#include <Funambol/http/URL.h>\n\n#include <Funambol/http/Proxy.h>\n\n#include <Funambol/http/HashProvider.h>\n\n#include <Funambol/http/HttpAuthentication.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n", "file_path": "Funambol/include/Funambol/http/DigestAuthentication.h", "rank": 83, "score": 49374.665770034924 }, { "content": " * \n\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n\n * 305, Redwood City, CA 94063, USA, or at email address [email protected].\n\n * \n\n * The interactive user interfaces in modified source and object code versions\n\n * of this program must display Appropriate Legal Notices, as required under\n\n * Section 5 of the GNU Affero General Public License version 3.\n\n * \n\n * In accordance with Section 7(b) of the GNU Affero General Public License\n\n * version 3, these Appropriate Legal Notices must retain the display of the\n\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n\n * feasible for technical reasons, the Appropriate Legal Notices must display\n\n * the words \"Powered by Funambol\".\n\n */\n\n\n\n#ifndef INCL_HTTP_AUTHENTICATION\n\n#define INCL_HTTP_AUTHENTICATION\n\n\n\n#include <Funambol/base/util/StringBuffer.h>\n\n#include <Funambol/http/HashProvider.h>\n\n#include <Funambol/http/URL.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\n\n", "file_path": "Funambol/include/Funambol/http/HttpAuthentication.h", "rank": 84, "score": 49374.291946095334 }, { "content": " unsigned long maxMsgSize ;\n\n unsigned long readBufferSize ;\n\n char* userAgent ;\n\n bool checkConn ;\n\n unsigned int responseTimeout ;\n\n bool compression ;\n\n\n\n /**\n\n * Dirty flag.\n\n * Used to execute the save operations only when really necessary.\n\n */\n\n unsigned int dirty;\n\n\n\n /**\n\n * Sets the given buffer with the given value, dealing correctly with\n\n * NULL values. If a NULL value is passed, the empty string is used.\n\n *\n\n * @param buf the destination buffer\n\n * @param v the new value (CAN BE NULL)\n\n */\n", "file_path": "Funambol/include/Funambol/spds/AccessConfig.h", "rank": 85, "score": 49374.04391125358 }, { "content": " * @param t the new msx msg size in bytes\n\n */\n\n virtual void setMaxMsgSize(unsigned int t);\n\n\n\n /**\n\n * Returns the max msg size\n\n */\n\n virtual unsigned int getMaxMsgSize();\n\n\n\n /**\n\n * Sets the buffer size\n\n *\n\n * @param t the buffer size size in bytes\n\n */\n\n virtual void setReadBufferSize(unsigned int t);\n\n\n\n virtual void setUserAgent(const char* ua);\n\n\n\n virtual void setCompression(bool newCompression);\n\n virtual bool getCompression();\n", "file_path": "Funambol/include/Funambol/http/TransportAgent.h", "rank": 86, "score": 49373.86987630997 }, { "content": "#include <Funambol/base/fscapi.h>\n\n#include <Funambol/base/constants.h>\n\n#include <Funambol/http/constants.h>\n\n#include <Funambol/base/Log.h>\n\n#include <Funambol/base/util/StringBuffer.h>\n\n#include <Funambol/inputStream/InputStream.h>\n\n#include <Funambol/inputStream/StringOutputStream.h>\n\n#include <Funambol/http/URL.h>\n\n#include <Funambol/http/HttpConnection.h>\n\n\n\nBEGIN_NAMESPACE\n\n\n\n\n\n#define UPLOAD_URL_RESOURCE \"sapi/media\"\n\n\n\n/**\n\n * This module is used to upload a given amount of data via an HTTP POST.\n\n * The destination URL is fixed, it's composed based on the params set:\n\n * \"http://<serverURL>[:port]/upload/<sourceURI>?LUID=<luid>\"\n\n * The params username and password are used for the HTTP Basic Authentication:\n\n * \"Authorization: Basic <b64(username:password)>\"\n\n * The deviceID is added in the http headers: \"deviceId: <deviceID>\"\n\n * All the params MUST be set before calling upload() method.\n\n *\n\n * This class used by MediaSyncSource, to upload media files at the end of the sync.\n\n */\n", "file_path": "Funambol/include/Funambol/http/HttpUploader.h", "rank": 87, "score": 49373.42684691696 }, { "content": " /*\n\n * Returns the url.\n\n */\n\n virtual URL& getURL();\n\n\n\n /**\n\n * Sets the connection timeout\n\n *\n\n * @param t the new timeout in seconds\n\n */\n\n virtual void setTimeout(unsigned int t);\n\n\n\n /**\n\n * Returns the connection timeout\n\n */\n\n virtual unsigned int getTimeout();\n\n\n\n /**\n\n * Sets the max msg size\n\n *\n", "file_path": "Funambol/include/Funambol/http/TransportAgent.h", "rank": 88, "score": 49373.16753454856 }, { "content": "\t\t/**\n\n\t\t * Returns mark\n\n\t\t *\n\n\t\t * @return mark\n\n\t\t */\n\n\t\tconst char* getMark();\n\n\n\n\t\t/**\n\n\t\t * Sets mark\n\n\t\t *\n\n\t\t * @param mark the new mark value\n\n\t\t */\n\n\t\tvoid setMark(const char* mark);\n\n\n\n\t\t/**\n\n\t\t * Returns version\n\n\t\t *\n\n\t\t * @return version\n\n\t\t */\n\n\t\tconst char* getVersion();\n", "file_path": "Funambol/include/Funambol/syncml/core/Meta.h", "rank": 89, "score": 49373.07911254498 }, { "content": "\n\n bool newReturnedData;\n\n long size;\n\n const char* username;\n\n const char* password;\n\n const char* sourceName;\n\n\n\n TransformationInfo() : newReturnedData(false)\n\n , size(-1)\n\n , username(NULL)\n\n , password(NULL)\n\n , sourceName(NULL) {}\n\n\n\n };\n\n\n", "file_path": "Funambol/include/Funambol/spds/DataTransformer.h", "rank": 90, "score": 49372.9871220039 }, { "content": "\n\n /**\n\n * Returns the proxyUsername value.\n\n */\n\n const char* getProxyUsername() const;\n\n\n\n /**\n\n * Sets a new proxyUsername value.\n\n *\n\n * @param proxyUsername the new proxyUsername value\n\n */\n\n void setProxyUsername(const char* proxyUsername);\n\n\n\n /**\n\n * Returns the proxyPassword value.\n\n */\n\n const char* getProxyPassword() const;\n\n\n\n /**\n\n * Sets a new proxyPassword value.\n", "file_path": "Funambol/include/Funambol/spds/AccessConfig.h", "rank": 91, "score": 49372.603168359514 }, { "content": " /**\n\n * set/get method for ctpReady parameter\n\n */\n\n int getCtpReady() { return ctpReady; }\n\n void setCtpReady(int v) { ctpReady = v; }\n\n \n\n\n\n /**\n\n * set/get method for nonce parameter: it's the 'accessConfig::clientNonce' so\n\n * we ridirect to that property.\n\n */\n\n const char* getCtpNonce() { return accessConfig.getClientNonce(); }\n\n void setCtpNonce(const char* v) { accessConfig.setClientNonce(v); }\n\n\n\n /**\n\n * set/get method for urlTo parameter\n\n */\n\n StringBuffer& getUrlTo() { return urlTo; }\n\n void setUrlTo(StringBuffer v) { urlTo = v; }\n\n\n", "file_path": "Funambol/include/Funambol/push/CTPConfig.h", "rank": 92, "score": 49372.562897285345 }, { "content": "#if defined(FUN_IPHONE)\n\n#include <SystemConfiguration/SystemConfiguration.h>\n\n#include <SystemConfiguration/SCNetworkReachability.h>\n\n#include <CFNetwork/CFNetwork.h>\n\n#else\n\n#include <Foundation/Foundation.h>\n\n#include <CoreFoundation/CoreFoundation.h>\n\n#endif\n\n\n\n#include <Funambol/http/URL.h>\n\n#include <Funambol/http/Proxy.h>\n\n#include <Funambol/http/TransportAgent.h>\n\n#include <Funambol/base/Log.h>\n\n#include <Funambol/http/HttpAuthentication.h>\n\n#include <Funambol/http/AbstractHttpConnection.h>\n\n#include <Funambol/inputStream/AppleInputStream.h>\n\n\n\n#define ERR_HTTP_TIME_OUT ERR_TRANSPORT_BASE+ 7\n\n#define ERR_HTTP_NOT_FOUND ERR_TRANSPORT_BASE+60\n\n#define ERR_HTTP_REQUEST_TIMEOUT ERR_TRANSPORT_BASE+61\n\n#define ERR_HTTP_INFLATE ERR_TRANSPORT_BASE+70\n\n#define ERR_HTTP_DEFLATE ERR_TRANSPORT_BASE+71\n\n#define ERR_HTTP_INVALID_URL ERR_TRANSPORT_BASE+72\n\n\n\nBEGIN_FUNAMBOL_NAMESPACE\n\n\n", "file_path": "Funambol/include/Funambol/http/HttpConnection.h", "rank": 93, "score": 49372.54453948664 }, { "content": " */\n\n void setSources(ArrayList* sources);\n\n\n\n /**\n\n * Returns the preferred language\n\n *\n\n * @return the preferred language\n\n *\n\n */\n\n const char* getLang();\n\n\n\n /**\n\n * Sets the preferred language\n\n *\n\n * @param lang the preferred language\n\n */\n\n void setLang(const char* lang);\n\n\n\n /**\n\n * Returns data\n", "file_path": "Funambol/include/Funambol/syncml/core/Search.h", "rank": 94, "score": 49372.519687382664 }, { "content": "\t\tconst char* getVerDTD() const ;\n\n void setVerDTD(const char* v) ;\n\n\n\n bool getSendDevInfo() const ;\n\n void setSendDevInfo(bool) ;\n\n\n\n bool getForceServerDevInfo() const ;\n\n void setForceServerDevInfo(bool) ;\n\n\n\n const char* getServerLastSyncURL() const;\n\n void setServerLastSyncURL(const char *v);\n\n\n\n bool getMediaHttpUpload() const;\n\n void setMediaHttpUpload(bool v);\n\n\n\n const char* getNoFieldLevelReplace() const;\n\n void setNoFieldLevelReplace(const char *v);\n\n\n\n /**\n\n * Specifies the array of DataStores supported by Server (used only by ServerConfig).\n", "file_path": "Funambol/include/Funambol/spds/DeviceConfig.h", "rank": 95, "score": 49372.41000359789 }, { "content": " */\n\n void setSource(Source* source);\n\n\n\n /**\n\n * Returns the item targetParent\n\n *\n\n * @return the item target parent\n\n */\n\n const char* getTargetParent();\n\n\n\n /**\n\n * Sets the item targetParent\n\n *\n\n * @param parent the target parent\n\n *\n\n */\n\n void setTargetParent(const char* parent);\n\n\n\n /**\n\n * Returns the item sourceParent\n", "file_path": "Funambol/include/Funambol/syncml/core/Item.h", "rank": 96, "score": 49372.31721595238 }, { "content": " NextNonce* getNextNonce();\n\n\n\n void setNextNonce(NextNonce* nextNonce);\n\n /**\n\n * Returns the authentication type\n\n *\n\n * @return authentication type.\n\n */\n\n const char* getType();\n\n\n\n /**\n\n * Returns the authentication format\n\n *\n\n * @return format the authentication format\n\n */\n\n const char* getFormat();\n\n\n\n /**\n\n * Creates a basic authentication challange.\n\n * This will have type = Cred.AUTH_TYPE_BASIC and\n", "file_path": "Funambol/include/Funambol/syncml/core/Chal.h", "rank": 97, "score": 49372.21837704906 }, { "content": " * it return 0\n\n */\n\n int getHostPort(StringBuffer syncUrl);\n\n \n\nprivate:\n\n char* decodePassword(const char* password);\n\n StringBuffer encodePassword(const char* password);\n\n};\n\n\n\n\n\n\n\nEND_NAMESPACE\n\n\n\n/** @endcond */\n\n#endif\n", "file_path": "Funambol/include/Funambol/push/CTPConfig.h", "rank": 98, "score": 49372.17463589447 }, { "content": " */\n\n virtual char* createFullName();\n\n\n\n /**\n\n * Returns the node name itself without the context.\n\n */\n\n virtual const char *getName();\n\n\n\n // ---------------------------------------------------- Abstract methods\n\n\n\n /*\n\n * Find how many children are defined for this node in the underlying\n\n * config system.\n\n */\n\n virtual int getChildrenMaxCount() = 0;\n\n\n\n /* Returns the names of the children nodes, in a new-allocated\n\n * string array\n\n *\n\n * @return NULL on failure\n", "file_path": "Funambol/include/Funambol/spdm/ManagementNode.h", "rank": 99, "score": 49372.12108597447 } ]
C++
bus/map_test.cpp
UndefeatedSunny/sc-platform
5897c460bf7a4b9694324f09d2492f5e157a3955
#include "bus/memory_map.hpp" #include "report/report.hpp" #include "report/summary.hpp" #include "common/common.hpp" #include <string> #include <list> #include <vector> #include <map> using namespace std; using namespace sc_core; namespace { const char * const MSGID{ "/Doulos/Example/map_test" }; } Port_t decode_address ( Addr_t address, Addr_t& masked_address ); uint64_t reconstruct_address ( Addr_t address, Port_t port, bool bias_upwards ); void build_port_map ( void ); void dump_port_map ( int level ); void check_port_map_and_update_configuration( void ); string name( string name = "" ) { static string m_name{ "top.cpu" }; if( name.length() > 0 ) m_name = name; return m_name; } string kind( string kind = "" ) { static string m_kind{ "Cpu_name" }; if( kind.length() > 0 ) m_kind = kind; return m_kind; } struct Command { string m_initiator; string m_bus; string m_target; string m_yaml; Addr_t m_addr; bool m_processing{ true }; list<string> m_cmds; Address_map m_addr_map; bool processing( void ) const { return not m_processing; } void process( void ); void add( initializer_list<string> cmds ) { m_cmds.splice( m_cmds.end(), cmds ); } size_t size( void ) const { return m_cmds.size(); } } command; void Command::process( void ) { while( not m_cmds.empty() ) { string cmd = m_cmds.front(); string arg; if( cmd == "yaml" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); } else if( cmd == "init" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "targ" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "bus" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "findaddr" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "decode" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "quit" ) { m_cmds.pop_front(); m_processing = false; break; } else if( m_cmds.size() == 1 ) { break; } } } int sc_main( int argc, char* argv[]) { Addr_t address = 0x1000ull; if( sc_argc() < 2 ) { command.add( { "yaml", "memory_map.yaml" , "init", "top.cpu" , "targ", "top.ram" , "bus", "top.bus" , "findaddr", "top.ram" , "decode", "0x1000" , "quit" }); } for( int i=1; i<sc_argc(); ++i ) { string arg( sc_argv()[i] ); if( arg == "-yaml" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"yaml", arg}); } else if( arg == "-init" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"init", arg}); } else if( arg == "-bus" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"bus", arg}); } else if( arg == "-targ" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"targ", arg}); } else if( arg == "-kind" and (i+1) < sc_argc() ) { arg = kind(sc_argv()[++i]); } } if( command.size() ) { command.process(); } while( command.processing() ) { char line[256]; std::cin.getline(line,256); istringstream is(line); string word; while( not is.eof() ) { is >> word; command.add({word}); } command.process(); } return Summary::report(); } Addr_t find_address ( string path ) { INFO( DEBUG, "Searching for address from " << name() << " to " << path ); list<string> device_path = { name(), path }; auto target_info = Memory_map::get_target_path_info( device_path ); sc_assert( target_info.base != BAD_ADDR ); MESSAGE( "Found address " << STREAM_HEX << target_info.base ); MESSAGE( " from " << name() << " to " << path ); MEND( DEBUG ); return target_info.base; } Port_t decode_address ( Addr_t address, Addr_t& masked_address ) { if( address == BAD_ADDR ) { REPORT( ERROR, "Unable to decode BAD_ADDR" ); return BAD_PORT; } INFO( DEBUG, "Decoding address " << STREAM_HEX << address ); Addr_t base = BAD_ADDR; masked_address = BAD_ADDR; auto lookup = m_addr_map.lower_bound( address ); if( lookup == m_addr_map.end() ) { REPORT( WARNING, "No address => port match found!" ); return BAD_PORT; } base = lookup->first; if( base == MAX_ADDR || base == BAD_ADDR ) { REPORT( WARNING, "No address => port match found! Unintialized entry." ); return BAD_PORT; } if( address > lookup->second.last ) { REPORT( WARNING, "No address => port match found. Goes beyond closest port's maximum." ); return BAD_PORT; } masked_address = address - base; return lookup->second.port; } Addr_t reconstruct_address( Addr_t address, Port_t port, bool bias_upwards ) { Addr_t base{ BAD_ADDR }; Addr_t last; Addr_t min_address{ MAX_ADDR}; Addr_t max_address{ 0 }; Addr_t reconstructed{ BAD_ADDR }; for( const auto& mapping : m_addr_map ) { if( mapping.second.port != port ) continue; base = mapping.second.base; last = mapping.second.last; if( base < min_address ) min_address = base; if( last > max_address ) max_address = last; if( base <= address and address <= last ) { reconstructed = base + address; break; } } if( reconstructed == BAD_ADDR ) { if( address < max_address ) address = max_address; if( bias_upwards ) { } else { } } return reconstructed; } void build_port_map( void ) { string config_name; string config_kind; Depth_t config_size; INFO( DEBUG, "Mapping port " << port << " " << config_name ); size_t matches{ 0 }; for( auto& mapping : m_addr_map ) { Addr_t addr{ mapping.first }; Target_info& mapped{ mapping.second }; INFO( DEBUG, "Target mapped: " << mapped ); if( mapped.name == config_name ) { ++matches; INFO( DEBUG, "Found port match at " << STREAM_HEX << addr ); mapped.port = port; mapped.kind = config_kind; if( config_size == UNASSIGNED ) { config_size = mapped.size; } else { mapped.size = config_size; } if( config_size == 0 ) { REPORT( ERROR, "Configured size of " << config_name << " is zero!" ); } mapped.last = mapped.base + config_size - 1; } } if( matches == 0 ) { REPORT( ERROR, "No matches on port " << config_name << " => connectivity mismatch!" ); } } void dump_port_map( int level ) { MESSAGE( "Port map for " << name() << ":\n" ); for( auto rit = m_addr_map.rbegin(); rit!=m_addr_map.rend(); ++rit ) { const Addr_t& addr{ rit->first }; const Target_info& info{ rit->second }; MESSAGE( STREAM_HEX << " - {" << " base: " << setw(10) << info.base << " last: " << setw(10) << info.last << " size: " << setw(6) << info.size << " port: " << setw(2) << STREAM_DEC << info.port << " name: " << info.name << " kind: " << info.kind << " }\n"; ); } MEND( NONE + level ); } void check_port_map_and_update_configuration( void ) { dump_port_map( SC_DEBUG ); INFO( MEDIUM, "Checking port map for " << name() ); Addr_t min_address{ MAX_ADDR }; Addr_t max_address{ 0 }; size_t mapping_errors { 0 }; for( const auto& mapping : m_addr_map ) { const Addr_t addr{ mapping.first }; const Target_info& info{ mapping.second }; if( info.base == BAD_ADDR ) { if( mapping_errors++ == 0 ) { MESSAGE( "Port map errors detected:" ); } MESSAGE( "\n - Address " << addr << " from " << info.kind << " " << info.name << " " << "doesn't match contained address" ); continue; } if( info.last < info.base ) { if( mapping_errors++ == 0 ) { MESSAGE( "Port map errors detected:" ); } MESSAGE( "\n - Address " << addr << " from " << info.kind << " " << info.name << " " << "address range wraps around 64 bits!" ); continue; } if( info.base < min_address ) { min_address = info.base; } if( info.last > max_address ) { max_address = info.last; } for( const auto& next_mapping : m_addr_map ) { const Addr_t next_addr{ next_mapping.first }; const Target_info& next_info{ next_mapping.second }; if( next_addr <= addr ) { continue; } if( next_addr <= info.last ) { if( mapping_errors++ == 0 ) { MESSAGE( "Port map errors detected:" ); } MESSAGE( "\n - Overlapping regions in Bus address map: " << STREAM_HEX << info.kind << " " << info.name << " " << addr << ".." << info.last << " and " << next_info.kind << " " << next_info.name << " " << next_info.base << ".." << next_info.last ); } } } if( mapping_errors > 0 ) { REPORT( ERROR, "\n\nTotal of " << mapping_errors << " mapping errors detected for " << name()); } else { INFO( MEDIUM, "Port map valid for " << name() ); } m_configuration.set( "name", string( name() ) ); m_configuration.set( "kind", string( kind() ) ); m_configuration.set( "object_ptr", uintptr_t( this ) ); m_configuration.set( "target_base", min_address ); m_configuration.set( "target_size", Depth_t( max_address - min_address ) ); INFO( DEBUG, "Bus configuration:\n" << m_configuration ); }
#include "bus/memory_map.hpp" #include "report/report.hpp" #include "report/summary.hpp" #include "common/common.hpp" #include <string> #include <list> #include <vector> #include <map> using namespace std; using namespace sc_core; namespace { const char * const MSGID{ "/Doulos/Example/map_test" }; } Port_t decode_address ( Addr_t address, Addr_t& masked_address ); uint64_t reconstruct_address ( Addr_t address, Port_t port, bool bias_upwards ); void build_port_map ( void ); void dump_port_map ( int level ); void check_port_map_and_update_configuration( void ); string name( string name = "" ) { static string m_name{ "top.cpu" }; if( name.length() > 0 ) m_name = name; return m_name; } string kind( string kind = "" ) { static string m_kind{ "Cpu_name" }; if( kind.length() > 0 ) m_kind = kind; return m_kind; } struct Command { string m_initiator; string m_bus; string m_target; string m_yaml; Addr_t m_addr; bool m_processing{ true }; list<string> m_cmds; Address_map m_addr_map; bool processing( void ) const { return not m_processing; } void process( void ); void add( initializer_list<string> cmds ) { m_cmds.splice( m_cmds.end(), cmds ); } size_t size( void ) const { return m_cmds.size(); } } command; void Command::process( void ) { while( not m_cmds.empty() ) { string cmd = m_cmds.front(); string arg; if( cmd == "yaml" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); } else if( cmd == "init" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "targ" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "bus" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "findaddr" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "decode" and m_cmds.size() > 1 ) { m_cmds.pop_front(); arg = m_cmds.front(); m_cmds.pop_front(); NOT_YET_IMPLEMENTED(); } else if( cmd == "quit" ) { m_cmds.pop_front(); m_processing = false; break; } else if( m_cmds.size() == 1 ) { break; } } } int sc_main( int argc, char* argv[]) { Addr_t address = 0x1000ull; if( sc_argc() < 2 ) { command.add( { "yaml", "memory_map.yaml" , "init", "top.cpu" , "targ", "top.ram" , "bus", "top.bus" , "findaddr", "top.ram" , "decode", "0x1000" , "quit" }); } for( int i=1; i<sc_argc(); ++i ) { string arg( sc_argv()[i] ); if( arg == "-yaml" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"yaml", arg}); } else if( arg == "-init" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"init", arg}); } else if( arg == "-bus" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"bus", arg}); } else if( arg == "-targ" and (i+1) < sc_argc() ) { arg = name(sc_argv()[++i]); command.add({"targ", arg}); } else if( arg == "-kind" and (i+1) < sc_argc() ) { arg = kind(sc_argv()[++i]); } } if( command.size() ) { command.process(); } while( command.processing() ) { char line[256]; std::cin.getline(line,256); istringstream is(line); string word; while( not is.eof() ) { is >> word; command.add({word}); } command.process(); } return Summary::report(); } Addr_t find_address ( string path ) { INFO( DEBUG, "Searching for address from " << name() << " to " << path ); list<string> device_path = { name(), path }; auto target_info = Memory_map::get_target_path_info( device_path ); sc_assert( target_info.base != BAD_ADDR ); MESSAGE( "Found address " << STREAM_HEX << target_info.base ); MESSAGE( " from " << name() << " to " << path ); MEND( DEBUG ); return target_info.base; } Port_t decode_address ( Addr_t address, Addr_t& masked_address ) { if( address == BAD_ADDR ) { REPORT( ERROR, "Unable to decode BAD_ADDR" ); return BAD_PORT; } INFO( DEBUG, "Decoding address " << STREAM_HEX << address ); Addr_t base = BAD_ADDR; masked_address = BAD_ADDR; auto lookup = m_addr_map.lower_bound( address ); if( lookup == m_addr_map.end() ) { REPORT( WARNING, "No address => port match found!" ); return BAD_PORT; } base = lookup->first; if( base == MAX_ADDR || base == BAD_ADDR ) { REPORT( WARNING, "No address => port match found! Unintialized entry." ); return BAD_PORT; } if( address > lookup->second.last ) { REPORT( WARNING, "No address => port match found. Goes beyond closest port's maximum." ); return BAD_PORT; } masked_address = address - base; return lookup->second.port; }
void build_port_map( void ) { string config_name; string config_kind; Depth_t config_size; INFO( DEBUG, "Mapping port " << port << " " << config_name ); size_t matches{ 0 }; for( auto& mapping : m_addr_map ) { Addr_t addr{ mapping.first }; Target_info& mapped{ mapping.second }; INFO( DEBUG, "Target mapped: " << mapped ); if( mapped.name == config_name ) { ++matches; INFO( DEBUG, "Found port match at " << STREAM_HEX << addr ); mapped.port = port; mapped.kind = config_kind; if( config_size == UNASSIGNED ) { config_size = mapped.size; } else { mapped.size = config_size; } if( config_size == 0 ) { REPORT( ERROR, "Configured size of " << config_name << " is zero!" ); } mapped.last = mapped.base + config_size - 1; } } if( matches == 0 ) { REPORT( ERROR, "No matches on port " << config_name << " => connectivity mismatch!" ); } } void dump_port_map( int level ) { MESSAGE( "Port map for " << name() << ":\n" ); for( auto rit = m_addr_map.rbegin(); rit!=m_addr_map.rend(); ++rit ) { const Addr_t& addr{ rit->first }; const Target_info& info{ rit->second }; MESSAGE( STREAM_HEX << " - {" << " base: " << setw(10) << info.base << " last: " << setw(10) << info.last << " size: " << setw(6) << info.size << " port: " << setw(2) << STREAM_DEC << info.port << " name: " << info.name << " kind: " << info.kind << " }\n"; ); } MEND( NONE + level ); } void check_port_map_and_update_configuration( void ) { dump_port_map( SC_DEBUG ); INFO( MEDIUM, "Checking port map for " << name() ); Addr_t min_address{ MAX_ADDR }; Addr_t max_address{ 0 }; size_t mapping_errors { 0 }; for( const auto& mapping : m_addr_map ) { const Addr_t addr{ mapping.first }; const Target_info& info{ mapping.second }; if( info.base == BAD_ADDR ) { if( mapping_errors++ == 0 ) { MESSAGE( "Port map errors detected:" ); } MESSAGE( "\n - Address " << addr << " from " << info.kind << " " << info.name << " " << "doesn't match contained address" ); continue; } if( info.last < info.base ) { if( mapping_errors++ == 0 ) { MESSAGE( "Port map errors detected:" ); } MESSAGE( "\n - Address " << addr << " from " << info.kind << " " << info.name << " " << "address range wraps around 64 bits!" ); continue; } if( info.base < min_address ) { min_address = info.base; } if( info.last > max_address ) { max_address = info.last; } for( const auto& next_mapping : m_addr_map ) { const Addr_t next_addr{ next_mapping.first }; const Target_info& next_info{ next_mapping.second }; if( next_addr <= addr ) { continue; } if( next_addr <= info.last ) { if( mapping_errors++ == 0 ) { MESSAGE( "Port map errors detected:" ); } MESSAGE( "\n - Overlapping regions in Bus address map: " << STREAM_HEX << info.kind << " " << info.name << " " << addr << ".." << info.last << " and " << next_info.kind << " " << next_info.name << " " << next_info.base << ".." << next_info.last ); } } } if( mapping_errors > 0 ) { REPORT( ERROR, "\n\nTotal of " << mapping_errors << " mapping errors detected for " << name()); } else { INFO( MEDIUM, "Port map valid for " << name() ); } m_configuration.set( "name", string( name() ) ); m_configuration.set( "kind", string( kind() ) ); m_configuration.set( "object_ptr", uintptr_t( this ) ); m_configuration.set( "target_base", min_address ); m_configuration.set( "target_size", Depth_t( max_address - min_address ) ); INFO( DEBUG, "Bus configuration:\n" << m_configuration ); }
Addr_t reconstruct_address( Addr_t address, Port_t port, bool bias_upwards ) { Addr_t base{ BAD_ADDR }; Addr_t last; Addr_t min_address{ MAX_ADDR}; Addr_t max_address{ 0 }; Addr_t reconstructed{ BAD_ADDR }; for( const auto& mapping : m_addr_map ) { if( mapping.second.port != port ) continue; base = mapping.second.base; last = mapping.second.last; if( base < min_address ) min_address = base; if( last > max_address ) max_address = last; if( base <= address and address <= last ) { reconstructed = base + address; break; } } if( reconstructed == BAD_ADDR ) { if( address < max_address ) address = max_address; if( bias_upwards ) { } else { } } return reconstructed; }
function_block-full_function
[ { "content": "#define UNASSIGNED 0\n\n#define UNLIMITED 0\n\nstruct Target_info {\n\n // Initial values chosen to force initialization discovery if need be\n\n Port_t port { BAD_PORT }; // get from probe\n\n Addr_t base { BAD_ADDR }; // get from YAML\n\n Addr_t last { 0 }; // computed\n\n Depth_t size { UNASSIGNED }; // YAML unless 0\n\n int irq { UNASSIGNED }; // get from YAML\n\n std::string name { \"\" }; // get from YAML\n\n std::string kind { \"\" }; // get from probe\n\n};\n\nstd::ostream& operator<<( std::ostream& os, const Target_info& rhs );\n\nusing Address_map = std::map< Addr_t, Target_info, std::greater<Addr_t> >;\n\n\n", "file_path": "bus/memory_map.hpp", "rank": 1, "score": 151738.70565032083 }, { "content": "#include <systemcc>\n\n#include <tlmc>\n\n#include <string>\n\n#include <sstream>\n\n#include <iomanip>\n\nstruct Report {\n\n static std::ostringstream mout;\n\n};\n\n#define STREAM_HEX std::hex << std::showbase\n\n#define STREAM_DEC std::dec << std::noshowbase << std::setfill(' ')\n\n\n\n#ifdef __SYNTHESIS__\n\n #define REPORT(type,stream)\n\n #define ASSERT(expr,stream)\n\n #define SC_ALWAYS SC_NONE\n\n #define SC_NEVER (1<<14)\n\n #define SC_HYPER 1024\n\n #define DEVID (std::string(\"(\")+name()+\")\").c_str()\n\n #define NOINFO(level,stream)\n\n #define INFO(level,stream)\n\n #define DEBUG(level,stream)\n\n #define MESSAGE(stream)\n\n #define MEND(level)\n\n #define RULER(c)\n\n #define TODO(stream)\n", "file_path": "report/report.hpp", "rank": 2, "score": 140854.4232285769 }, { "content": "struct DELETE_THIS\n\n{\n\n DELETE_THIS( char const * const filename, int lineno, char const * const message )\n\n {\n\n ::sc_core::sc_report_handler::report( \\\n\n ::sc_core::SC_WARNING, \"Code incomplete\", message, filename, lineno );\n\n }\n\n};\n\n#define DELETE_THIS_LINE(lno,message) const DELETE_THIS lno{ __FILE__, __LINE__, #message }\n\n\n\nstd::string to_string( tlm::tlm_command command );\n\nstd::string to_string( uint8_t const * const data, uint32_t len );\n\nstd::string verbosity2str(const int& level);\n\n// Output the contents of a vector\n\ntemplate<typename T>\n\nstd::ostream& operator<<( std::ostream& os, const std::vector<T>& vec );\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n// Implementation\n\ntemplate<typename T>\n", "file_path": "report/report.hpp", "rank": 3, "score": 110509.27822090153 }, { "content": "struct Top_module: sc_core::sc_module\n\n{\n\n Top_module( sc_core::sc_module_name instance )\n\n : sc_module( instance )\n\n {\n\n }\n\n};\n\n\n\nusing namespace sc_core;\n\n\n\nint sc_main( int argc, char* argv[] )\n\n{\n\n return 0;\n\n}\n", "file_path": "report/report_test.cpp", "rank": 4, "score": 103909.8808383395 }, { "content": "// Singleton class\n\nstruct Memory_map\n\n{\n\n // Local types\n\n using Target_ptr = std::unique_ptr<Target_info>;\n\n enum { BAD_TARG = -1 };\n\n using Targ_t = int;\n\n using Target_map = std::map< std::string, Target_info >;\n\n using Target_ptr_map = std::map< std::string, Target_info* >;\n", "file_path": "bus/memory_map.hpp", "rank": 5, "score": 103378.04171130952 }, { "content": "struct Commandline\n\n{\n\n // Return index if a command-line argument beginning with opt exists; otherwise, zero\n\n inline static size_t has_opt( std::string opt )\n\n {\n\n for( int i = 1; i < sc_core::sc_argc(); ++i ) {\n\n std::string arg{ sc_core::sc_argv()[ i ] };\n\n if( arg.find( opt ) == 0 ) return i;\n\n }\n\n return 0;\n\n }\n\nprivate:\n\n [[maybe_unused]]inline constexpr static char const * const\n\n MSGID{ \"/Doulos/Example/Commandline\" };\n\n};\n", "file_path": "report/commandline.hpp", "rank": 6, "score": 99619.88085667908 }, { "content": "struct Summary {\n\n static int report( void );\n\n static int errors( void );\n\n // For tracking errors and warnings not reported with SC_REPORT_*:\n\n static void increment_errors(void) { ++s_errors; }\n\n static void increment_warnings(void) { ++s_warnings; }\n\n // For establishing timing points\n\n static void starting_elaboration( void );\n\n static void starting_simulation( void );\n\n static void finished_simulation( void );\n\nprivate:\n\n static double s_elaboration_time;\n\n static double s_starting_time;\n\n static double s_finished_time;\n\n static unsigned int s_errors;\n\n static unsigned int s_warnings;\n\n};\n\n\n\n#endif /*SUMMARY_HPP*/\n", "file_path": "report/summary.hpp", "rank": 7, "score": 99619.88085667908 }, { "content": "struct Interrupt_debug_if\n\n: virtual sc_core::sc_interface\n\n{\n\n virtual const sc_core::sc_event& event( void ) const = 0;\n\n // Interrupts needing immediate service at the current simulation time\n\n virtual size_t pending ( void ) const = 0;\n\n // Total scheduled interrupts\n\n virtual size_t outstanding ( void ) const = 0;\n\n};\n\n\n\n#endif /*INTERRUPT_IF_HPP*/\n", "file_path": "interrupt/interrupt_if.hpp", "rank": 8, "score": 95761.36365893157 }, { "content": "#define ASYNC_KIND_KEY(_a) _a,\n\nenum class Async_kind : int {\n\n ASYNC_KIND_ENUMS(ASYNC_KIND_KEY)\n\n};\n\n#undef ASYNC_KIND_KEY\n\n\n\nstd::string async_kind_str( const Async_kind& elt );\n\nbool is_Async_kind( const std::string& str ) noexcept;\n\nAsync_kind to_Async_kind( const std::string& str );\n\nstd::ostream& operator<<( std::ostream& os, const Async_kind& rhs );\n\nstd::istream& operator>>( std::istream& is, Async_kind& rhs );\n\ninline Async_kind operator++(Async_kind& x) {\n\n return x = (Async_kind)(std::underlying_type<Async_kind>::type(x) + 1); \n\n}\n\ninline Async_kind operator*(Async_kind c) {\n\n return c;\n\n}\n\ninline Async_kind begin(Async_kind r) {\n\n return (Async_kind)std::underlying_type<Async_kind>::type(0);\n\n}\n\ninline Async_kind end(Async_kind r) {\n\n return Async_kind::end;\n\n}\n\n\n\n#endif /*ASYNC_KIND_HPP*/\n", "file_path": "async/async_kind.hpp", "rank": 9, "score": 92755.00028711773 }, { "content": "struct Async_rx_base_if\n\n: virtual sc_core::sc_interface\n\n{\n\n virtual void wait_unless_available( void ) = 0; // Blocks if no events are available\n\n virtual bool is_empty( void ) const = 0; //< Returns true if no events waiting\n\n virtual size_t available( void ) const = 0; //< Returns # of events available\n\n virtual const sc_core::sc_event& default_event( void ) const = 0; // Only valid for SystemC side.\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "async/async_if.hpp", "rank": 10, "score": 92161.42487582436 }, { "content": "struct Uart_module: sc_core::sc_module\n\n{\n\n // Type definitions to improve readability\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Uart_module>;\n\n using Uart_txslow_port_t = sc_port<sc_core::sc_signal_out_if<bool> ,0,SC_ZERO_OR_MORE_BOUND>;\n\n using Uart_rxslow_port_t = sc_port<sc_core::sc_signal_in_if <bool> ,0,SC_ZERO_OR_MORE_BOUND>;\n\n using Uart_txfast_port_t = sc_port<sc_core::sc_fifo_out_if<uint8_t>,0,SC_ZERO_OR_MORE_BOUND>;\n\n using Uart_rxfast_port_t = sc_port<sc_core::sc_fifo_in_if <uint8_t>,0,SC_ZERO_OR_MORE_BOUND>;\n\n using Intrq_port_t = sc_port<Interrupt_send_if,0,SC_ZERO_OR_MORE_BOUND>;\n\n\n", "file_path": "uart/uart.hpp", "rank": 11, "score": 64605.72440437479 }, { "content": "struct Timer_module: sc_core::sc_module\n\n{\n\n\n\n //----------------------------------------------------------------------------\n\n // Types\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Timer_module>;\n\n\n\n //----------------------------------------------------------------------------\n\n // Ports\n\n tlm_utils::simple_target_socket<Timer_module> targ_socket{ \"targ_socket\" };\n\n sc_core::sc_port<Interrupt_send_if,0,sc_core::SC_ZERO_OR_MORE_BOUND> intrq_port { \"intrq_port\" };\n\n sc_core::sc_port<sc_core::sc_signal_out_if<bool>,0,sc_core::SC_ZERO_OR_MORE_BOUND> pulse_port { \"pulse_port\" };\n\n\n\n //----------------------------------------------------------------------------\n\n // Fundamentals\n\n Timer_module //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , size_t timer_quantity\n", "file_path": "timer/timer.hpp", "rank": 12, "score": 64605.72440437479 }, { "content": "struct Gpio_module: sc_core::sc_module\n\n{\n\n static constexpr int const PINS { 64 };\n\n\n\n // Type definitions to improve readability\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Gpio_module>;\n\n using Gpio_signal_t = sc_core::sc_signal_resolved;\n\n using Gpio_export_t = sc_export<sc_signal_inout_if<sc_dt::sc_logic>>;\n\n using Intrq_port_t = sc_core::sc_port<Interrupt_send_if,0,sc_core::SC_ZERO_OR_MORE_BOUND>;\n\n\n\n // Sockets, ports and exports\n\n tlm_utils::simple_target_socket<Gpio_module> targ_socket { \"targ_socket\" };\n\n sc_vector<Gpio_export_t> gpio_xport { \"gpio_export\", PINS };\n\n Intrq_port_t intrq_port { \"intrq_port\" };\n\n\n\n Gpio_module //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , uint32_t addr_clocks = 1\n", "file_path": "gpio/gpio.hpp", "rank": 13, "score": 64605.72440437479 }, { "content": "struct Memory_module: sc_core::sc_module\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Memory_module>;\n\n tlm_utils::simple_target_socket<Memory_module> targ1_socket{ \"targ1_socket\" };\n\n tlm_utils::simple_target_socket<Memory_module> targ2_socket{ \"targ2_socket\" };\n\n\n\n Memory_module //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , Depth_t target_size = 0/*bytes*/\n\n , Addr_t target_base = 0\n\n , Access access = Access::none\n\n , size_t max_burst = 8/*bytes*/\n\n , size_t alignment = 4/*bytes*/\n\n , Feature dmi_allowed = DMI::none\n\n , Feature byte_enables = Byte_enables::none\n\n , uint32_t addr_clocks = 1\n\n , uint32_t read_clocks = 2\n\n , uint32_t write_clocks = 3\n", "file_path": "mailbox/mailbox.hpp", "rank": 14, "score": 64605.72440437479 }, { "content": "struct Mmu_module: sc_core::sc_module\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_accessor_t = tlm_utils::instance_specific_extension_accessor;\n\n tlm_utils::multi_passthrough_target_socket<Mmu_module> targ_socket;\n\n tlm_utils::multi_passthrough_initiator_socket<Mmu_module> init_socket;\n\n\n\n SC_CTOR( Mmu_module );\n\n virtual ~Mmu_module( void );\n\n const char* kind( void ) const override { return \"Mmu_module\"; }\n\n\n\n // Forward interface\n\n void b_transport( int id, tlm_payload_t& trans, sc_core::sc_time& delay );\n\n tlm::tlm_sync_enum nb_transport_fw( int id, tlm_payload_t& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay );\n\n bool get_direct_mem_ptr( int id, tlm_payload_t& trans, tlm::tlm_dmi& dmi_data);\n\n unsigned int transport_dbg( int id, tlm_payload_t& trans );\n\n\n\n // Backward interface\n\n tlm::tlm_sync_enum nb_transport_bw( int id, tlm_payload_t& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay );\n\n void invalidate_direct_mem_ptr( int id, sc_dt::uint64 start_range, sc_dt::uint64 end_range );\n", "file_path": "mmu/mmu.hpp", "rank": 15, "score": 64605.72440437479 }, { "content": "struct Bus_module: sc_core::sc_module\n\n{\n\n // Local types\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_accessor_t = tlm_utils::instance_specific_extension_accessor;\n\n\n\n // Ports\n\n tlm_utils::multi_passthrough_target_socket<Bus_module> targ_socket { \"targ_socket\" };\n\n tlm_utils::multi_passthrough_initiator_socket<Bus_module> init_socket { \"init_socket\" };\n\n\n\n // Basics\n\n SC_CTOR( Bus_module );\n\n virtual ~Bus_module( void );\n\n const char* kind( void ) const override { return \"Bus_module\"; }\n\n void start_of_simulation( void ) override;\n\n\n\n // Forward interface\n\n void b_transport( int id, tlm_payload_t& trans, sc_core::sc_time& delay );\n\n tlm::tlm_sync_enum nb_transport_fw( int id, tlm_payload_t& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay );\n\n bool get_direct_mem_ptr( int id, tlm_payload_t& trans, tlm::tlm_dmi& dmi_data);\n", "file_path": "bus/bus.hpp", "rank": 16, "score": 64605.72440437479 }, { "content": "struct Stub_module: sc_core::sc_module\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Stub_module>;\n\n tlm_utils::simple_target_socket<Stub_module> targ_socket{ \"targ_socket\" };\n\n\n\n Stub_module //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , Depth_t target_size = 64/*bytes*/\n\n , Access access = Access::none\n\n , size_t max_burst = 8/*bytes*/\n\n , size_t alignment = 4/*bytes*/\n\n , Feature dmi_allowed = DMI::none\n\n , Feature byte_enables = Byte_enables::none\n\n , uint32_t addr_clocks = 1\n\n , uint32_t read_clocks = 1\n\n , uint32_t write_clocks = 1\n\n );\n\n ~Stub_module( void ); //< Destructor\n", "file_path": "top/stub.hpp", "rank": 17, "score": 64605.72440437479 }, { "content": "struct Cpu_module: sc_core::sc_module\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Cpu_module>;\n\n // Ports\n\n tlm_utils::simple_initiator_socket<Cpu_module> init_socket { \"init_socket\" };\n\n sc_core::sc_export<Interrupt_send_if> intrq_xport { \"intrq_xport\" };\n\n no_clock& clk { no_clock::global( \"system_clock\" ) };\n\n\n\n // Local channels\n\n Interrupt_channel intrq_chan { \"intrq_signal\" };\n\n sc_signal<bool> intrq_enabled { \"intrq_enabled\" };\n\n\n\n // Fundamentals\n\n SC_CTOR( Cpu_module );\n\n ~Cpu_module( void ){}\n\n const char* kind( void ) const override { return \"Cpu_module\"; }\n\n\n\n // Processes\n", "file_path": "cpu/cpu.hpp", "rank": 18, "score": 64605.72440437479 }, { "content": "struct Memory_module: sc_core::sc_module\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Memory_module>;\n\n tlm_utils::simple_target_socket<Memory_module> targ_socket{ \"targ_socket\" };\n\n\n\n Memory_module //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , Depth_t target_size = 0/*bytes*/\n\n , Access access = Access::none\n\n , size_t max_burst = 8/*bytes*/\n\n , size_t alignment = 4/*bytes*/\n\n , Feature dmi_allowed = DMI::none\n\n , Feature byte_enables = Byte_enables::none\n\n , uint32_t addr_clocks = 1\n\n , uint32_t read_clocks = 2\n\n , uint32_t write_clocks = 3\n\n );\n\n ~Memory_module( void ); //< Destructor\n", "file_path": "memory/memory.hpp", "rank": 19, "score": 64605.72440437479 }, { "content": "struct Dma_module: sc_core::sc_module\n\n{\n\n tlm_utils::simple_initiator_socket<Dma_module> init_socket{ \"init_socket\" };\n\n tlm_utils::simple_target_socket<Dma_module> targ_socket{ \"targ_socket\" };\n\n\n\n Dma_module\n\n ( sc_core::sc_module_name instance\n\n );\n\n virtual ~Dma_module( void );\n\n // Processes\n\n virtual void dma_thread( void );\n\n // Forward interface\n\n virtual void b_transport( tlm::tlm_generic_payload& trans, sc_core::sc_time& delay );\n\n #if 0\n\n virtual tlm::tlm_sync_enum nb_transport_fw( tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay );\n\n virtual bool get_direct_mem_ptr( tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data )\n\n virtual unsigned int transport_dbg( tlm::tlm_generic_payload& trans );\n\n #endif\n\n #if 0\n\n // Backward interface\n", "file_path": "dma/dma.hpp", "rank": 20, "score": 64605.72440437479 }, { "content": "struct Pic_module: sc_core::sc_module\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n using tlm_phase_t = tlm::tlm_phase;\n\n using tlm_peq_t = tlm_utils::peq_with_cb_and_phase<Pic_module>;\n\n\n\n // Ports\n\n tlm_utils::simple_target_socket<Pic_module> targ_socket { \"targ_socket\" };\n\n sc_core::sc_export<Interrupt_send_if> irq_recv_xport { \"irq_recv_xport\" };\n\n sc_core::sc_port<Interrupt_send_if,0> irq_send_port { \"irq_send_port\" };\n\n\n\n // Local channels\n\n Interrupt_channel irq_channel { \"irq_channel\" };\n\n\n\n Pic_module //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , uint32_t addr_clocks = 1\n\n , uint32_t read_clocks = 1\n\n , uint32_t write_clocks = 1\n\n );\n", "file_path": "interrupt/pic.hpp", "rank": 21, "score": 64605.72440437479 }, { "content": "void error( char* msg )\n\n{\n\n perror( msg );\n\n exit( 1 );\n", "file_path": "tcpip/server.c", "rank": 22, "score": 62605.79812337101 }, { "content": "void error( char *msg )\n\n{\n\n perror( msg );\n\n exit( 0 );\n", "file_path": "tcpip/client.c", "rank": 23, "score": 62605.79812337101 }, { "content": "// Singleton class\n\nstruct Options\n\n{\n\n static Options& instance( void );\n\n Platform get_configuration( void ) const { return m_configuration; }\n\n const std::set<PlatformTest>& get_test_set( void ) const { return m_test_set; }\n\n static bool has_flag ( std::string );\n\n static std::string get_flag ( std::string );\n\nprivate:\n\n\n\n Options( void ); //< Default constructor\n\n \n\n // Attribbutes\n\n using flag_map_t = std::map<std::string, std::string>;\n\n Platform m_configuration;\n\n flag_map_t m_flag_map;\n\n std::set<PlatformTest> m_test_set;\n\n Signal m_interrupt{ Signal::INTERRUPT };\n\n\n\n};\n\n\n\n#endif /*OPTIONS_HPP*/\n", "file_path": "top/options.hpp", "rank": 24, "score": 61348.725043511775 }, { "content": "struct Fanout\n\n: sc_core::sc_channel\n\n, private sc_signal_inout_if<T1>\n\n{\n\n using ZERO_OR_MORE = sc_core::SC_ZERO_OR_MORE_BOUND;\n\n\n\n // Ports\n\n sc_core::sc_export< sc_signal_inout_if<T1> > xport;\n\n sc_core::sc_vector< sc_port< sc_signal_inout_if<T2, 1, ZERO_OR_MORE> > port;\n\n\n\n Fanout( sc_core::sc_module_name instance, size_t width )\n\n {\n\n xport.bind( *this );\n\n SC_HAS_PROCESS( Fanout );\n\n SC_THREAD( fanout_thread );\n\n }\n\n\n\nprivate:\n\n\n\n void fanout_thread( void )\n", "file_path": "utility/fanout.hpp", "rank": 25, "score": 61348.725043511775 }, { "content": "struct News\n\n{\n\n News(void);\n\n static void report_handler( const sc_report& the_report, const sc_actions& the_actions );\n\n static const std::string compose_report(const sc_report& the_report);\n\n static void add_tag( const std::string& tag );\n\n static size_t get_tag_count( const std::string& tag );\n\nprivate:\n\n static bool initialized;\n\n static std::map<std::string,size_t> tag_map;\n\n};\n\n\n\n#endif /*NEWS_HPP*/\n", "file_path": "top/news.hpp", "rank": 26, "score": 61348.725043511775 }, { "content": "struct Signal {\n\n enum { STOP=-1, ABORT=-2, INTERRUPT=-3 };\n\n using Handler_t = void (*)( int );\n\n Signal( int sig, Handler_t sighandler = nullptr );\n\n ~Signal( void );\n\n void install( void );\n\n void remove( void );\n\nprivate:\n\n void revert( void );\n\n void add( int sig, Handler_t sighandler );\n\n int m_sig;\n\n Handler_t m_sighandler{ nullptr };\n\n std::forward_list<int> m_siglist;\n\n static std::forward_list<Signal*> s_handlers;\n\n};\n\n\n\n#endif /*SIGNAL_HPP*/\n", "file_path": "utility/signal.hpp", "rank": 27, "score": 61348.725043511775 }, { "content": "struct Ansi\n\n{\n\n static constexpr char const * const reset { \"\\033[00m\" };\n\n static constexpr char const * const bright { \"\\033[01m\" };\n\n static constexpr char const * const dim { \"\\033[02m\" };\n\n static constexpr char const * const bold { \"\\033[03m\" };\n\n static constexpr char const * const underline { \"\\033[04m\" };\n\n static constexpr char const * const blink { \"\\033[05m\" };\n\n static constexpr char const * const reverse { \"\\033[06m\" };\n\n static constexpr char const * const hide { \"\\033[07m\" };\n\n static constexpr char const * const fg_black { \"\\033[30m\" };\n\n static constexpr char const * const fg_red { \"\\033[31m\" };\n\n static constexpr char const * const fg_green { \"\\033[32m\" };\n\n static constexpr char const * const fg_yellow { \"\\033[33m\" };\n\n static constexpr char const * const fg_blue { \"\\033[34m\" };\n\n static constexpr char const * const fg_magenta { \"\\033[35m\" };\n\n static constexpr char const * const fg_cyan { \"\\033[36m\" };\n\n static constexpr char const * const fg_white { \"\\033[37m\" };\n\n static constexpr char const * const bg_black { \"\\033[40m\" };\n\n static constexpr char const * const bg_red { \"\\033[41m\" };\n", "file_path": "utility/ansi.hpp", "rank": 28, "score": 61348.725043511775 }, { "content": "struct Netlist\n\n{\n\n // Gang of six\n\n Netlist( void ); // Constructor\n\n virtual ~Netlist( void ) = default; // Destructor\n\nprivate:\n\n Netlist( const Netlist& rhs ) = delete; // Copy constructor\n\n Netlist( Netlist&& rhs ) = delete; // Move constructor\n\n Netlist& operator=( const Netlist& rhs ) = delete; // Copy assignment\n\n Netlist& operator=( Netlist&& rhs ) = delete; // Move assignment\n\n};\n\n\n\n#endif /*NETLIST_HPP*/\n", "file_path": "top/netlist.hpp", "rank": 29, "score": 61348.725043511775 }, { "content": "struct Parity\n\n {\n\n Parity( void )\n\n {\n\n for( auto v=0u; v!=256u; ++v )\n\n {\n\n odd_table[ v ] = odd( v );\n\n }\n\n }\n\n inline bool odd( uint8_t v )\n\n {\n\n static bool odd4[16] \n\n { false, true, true, false, true, false, false, true\n\n , true, false, false, true, false, true, true, false\n\n };\n\n return odd4[ v>> 4 ] ^ odd4[ v&0xf ];\n\n }\n\n bool odd_table[256];\n\n } parity;\n\n};\n", "file_path": "uart/parity.cpp", "rank": 30, "score": 61348.725043511775 }, { "content": "struct no_clock_if\n\n: virtual sc_core::sc_interface\n\n{\n\n virtual void set_frequency ( double frequency ) = 0;\n\n virtual void set_period_time ( sc_core::sc_time period ) = 0;\n\n virtual void set_offset_time ( sc_core::sc_time offset ) = 0;\n\n virtual void set_duty_cycle ( double duty ) = 0;\n\n virtual void set_sample_time ( sc_core::sc_time sample ) = 0;\n\n virtual void set_setedge_time ( sc_core::sc_time setedge ) = 0;\n\n virtual const char* clock_name ( void ) const = 0;\n\n virtual sc_core::sc_time period ( Clock_count_t cycles = 0U ) const = 0;\n\n virtual double duty ( void ) const = 0;\n\n virtual double frequency ( void ) const = 0;\n\n // Special conveniences\n\n virtual Clock_count_t cycles ( void ) const = 0; // Number of clock cycles since start\n\n virtual Clock_count_t cycles ( sc_core::sc_time t ) const = 0;\n\n virtual Clock_count_t frequency_changes ( void ) const = 0; // Number of times frequency was changed\n\n // Calculate the delay till... (use for temporal offset)...may return SC_ZERO_TIME if already on the edge\n\n virtual sc_core::sc_time until_posedge ( Clock_count_t cycles = 0U ) const = 0;\n\n virtual sc_core::sc_time until_negedge ( Clock_count_t cycles = 0U ) const = 0;\n", "file_path": "no_clock/no_clock_if.hpp", "rank": 31, "score": 61348.725043511775 }, { "content": "struct no_clock\n\n: sc_core::sc_prim_channel\n\n, no_clock_if\n\n{\n\n no_clock //< Constructor (enhanced)\n\n ( const char* clock_instance\n\n , const sc_core::sc_time& tPERIOD\n\n , double duty\n\n , const sc_core::sc_time& tOFFSET\n\n , const sc_core::sc_time& tSAMPLE\n\n , const sc_core::sc_time& tSETEDGE\n\n , bool positive\n\n );\n\n no_clock //< Constructor (original)\n\n ( const char* clock_instance\n\n , const sc_core::sc_time& tPERIOD\n\n , double duty = 0.5\n\n , const sc_core::sc_time& tOFFSET = sc_core::SC_ZERO_TIME\n\n , bool positive = true\n\n );\n", "file_path": "no_clock/no_clock.hpp", "rank": 32, "score": 61348.725043511775 }, { "content": "struct Configuration\n\n{\n\n\n\n Configuration( bool use_defaults = true ); //< Constructor\n\n\n\n Configuration( const Configuration& rhs ); // Copy constructor\n\n Configuration& operator=( const Configuration& rhs ); // Copy assignment\n\n virtual ~Configuration( void ) = default;\n\n bool operator==( const Configuration& rhs ) const;\n\n\n\n //----------------------------------------------------------------------------\n\n using Printer_t = std::function<void( std::ostream&, const boost::any& )>;\n\n using Equal_t = std::function<bool( const boost::any&, const boost::any& )>;\n\n using Assign_t = std::function<void( const std::string&, boost::any&, const boost::any& )>;\n\n struct Function_t \n\n {\n\n Function_t\n\n ( Printer_t p\n\n , Equal_t e\n\n , Assign_t a\n", "file_path": "config/configuration.hpp", "rank": 33, "score": 61348.725043511775 }, { "content": "struct Cpu_if : virtual sc_core::sc_interface\n\n{\n\n virtual void write32 ( Addr_t address, uint32_t data ) = 0;\n\n virtual void read32 ( Addr_t address, uint32_t& data ) = 0;\n\n virtual void write16 ( Addr_t address, uint16_t data ) = 0;\n\n virtual void read16 ( Addr_t address, uint16_t& data ) = 0;\n\n virtual void write8 ( Addr_t address, uint8_t data ) = 0;\n\n virtual void read8 ( Addr_t address, uint8_t& data ) = 0;\n\n virtual void write ( Addr_t address, uint8_t* data, Depth_t length ) = 0;\n\n virtual void read ( Addr_t address, uint8_t* data, Depth_t length ) = 0;\n\n virtual void put( Addr_t address, std::vector<uint8_t>& vec ) = 0;\n\n virtual void get( Addr_t address, Depth_t depth, std::vector<uint8_t>& vec ) = 0;\n\n};\n\n#endif /*CPU_IF_HPP*/\n", "file_path": "cpu/cpu_if.hpp", "rank": 34, "score": 60361.40904247635 }, { "content": "struct Timer\n\n: sc_core::sc_module\n\n{\n\n using sc_module_name = sc_core::sc_module_name;\n\n using sc_time = sc_core::sc_time;\n\n using sc_event = sc_core::sc_event;\n\n\n\n Timer( sc_module_name nm ); //< Constructor\n\n ~Timer( void ); //< Destructor\n\n\n\n // Processes\n\n void trigger_thread( void );\n\n\n\n // Inline accessors\n\n void set_load_delay ( sc_time t ) { m_load_delay = t; }\n\n //id set_start_time ( sc_time t ) { m_start_time = t; }\n\n void set_pulse_delay ( sc_time t ) { m_pulse_delay = t; }\n\n //id set_trigger_time( sc_time t ) { m_trigger_time = t; }\n\n sc_time get_load_delay ( void ) const { return m_load_delay; }\n\n sc_time get_start_time ( void ) const { return m_start_time; }\n", "file_path": "timer/timer_beh.hpp", "rank": 35, "score": 59360.215779886275 }, { "content": "struct Top_module\n\n: sc_core::sc_module\n\n{\n\n // Constructor\n\n Top_module(sc_core::sc_module_name instance_name);\n\n ~Top_module(void); // Destructor\n\n const char* kind( void ) const override { return \"Top_module\"; }\n\n void end_of_elaboration( void ) override;\n\n void start_of_simulation( void ) override;\n\n void end_of_simulation( void ) override;\n\n struct Impl;\n\n std::unique_ptr<Impl> pImpl;\n\n\n\n // Processes - NONE\n\n\n\n};//end Top_module\n\n#endif/*TOP_H*/\n\n///////////////////////////////////////////////////////////////////////////////\n\n//END $Id$\n", "file_path": "top/top.hpp", "rank": 36, "score": 59360.215779886275 }, { "content": "struct Async_rx_if\n\n: virtual sc_core::sc_interface\n\n, Async_rx_base_if\n\n{\n\n // Copy out data -- returns false if queue empty. Sets data_len to 0 if no data. Removes entry from queue if successful.\n\n virtual bool nb_read( Async_payload<T>& the_payload ) = 0;\n\n // Blocking call -- waits for data. Sets data_len to 0 if no data. Removes entry from queue.\n\n virtual void read( Async_payload<T>& the_payload ) = 0;\n\n // Get reference to data -- returns false if queue empty. Does NOT complete transaction.\n\n virtual bool nb_peek( Async_payload<T>*& payload_ptr ) const = 0;\n\n // Blocking call to get pointer to data -- waits for data. Does NOT complete transaction.\n\n virtual void peek( Async_payload<T>*& payload_ptr ) const = 0;\n\n // Toss the payload at the head of the queue. Completes the transaction.\n\n virtual void drop( void ) = 0;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "async/async_if.hpp", "rank": 37, "score": 59360.215779886275 }, { "content": "struct PowerSetting\n\n{\n\n enum Level : uint8_t\n\n { off=0\n\n , gated=1\n\n , low\n\n , medium\n\n , full\n\n } level { full };\n\n sc_core::sc_object* root;\n\n};\n\n\n", "file_path": "power/power.hpp", "rank": 38, "score": 59360.215779886275 }, { "content": "struct Task_manager\n\n{\n\n using Task_body_t = void (*)(void);\n\n using Task_obj_t = sc_core::sc_object;\n\n using Task_map_t = std::map<std::string,Task_body_t>;\n\n\n\n struct Task_list\n\n {\n\n Task_obj_t* boss_ptr{nullptr};\n\n Task_map_t task;\n\n };\n\n\n\n // Task boss constructor\n\n Task_manager(std::string boss_name, Task_obj_t* boss_ptr);\n\n // Task worker constructor\n\n Task_manager(std::string boss_name, std::string task_name, Task_body_t task_body);\n\n const Task_map_t& tasks( void );\n\n Task_obj_t* obj(void);\n\n\n\nprivate:\n\n std::string m_boss_name;\n\n std::string m_task_name;\n\n static std::map<std::string,Task_list> s_tasks;\n\n};\n\n\n\n#endif /*TASK_HPP*/\n", "file_path": "cpu/task.hpp", "rank": 39, "score": 59360.215779886275 }, { "content": "struct Interrupt_channel\n\n: private Interrupt_send_if\n\n, private Interrupt_recv_if\n\n, private Interrupt_debug_if\n\n, sc_core::sc_object\n\n{\n\n // Exported interfaces\n\n sc_core::sc_export< Interrupt_send_if> send_if { \"send_if\" };\n\n sc_core::sc_export< Interrupt_recv_if> recv_if { \"recv_if\" };\n\n sc_core::sc_export< Interrupt_debug_if> debug_if { \"debug_if\" };\n\n\n\n //----------------------------------------------------------------------------\n\n // Constructor\n\n Interrupt_channel( const std::string& instance_name )\n\n : sc_core::sc_object( instance_name.c_str() )\n\n {\n\n send_if.bind ( *this );\n\n recv_if.bind ( *this );\n\n debug_if.bind( *this );\n\n }\n", "file_path": "interrupt/interrupt.hpp", "rank": 40, "score": 59360.215779886275 }, { "content": "struct Async_tx_if\n\n: virtual sc_core::sc_interface\n\n{\n\n // Safely add entry to queue and return success status (in case queue full)\n\n virtual bool notify( const Async_payload<T>& the_payload ) = 0;\n\n};\n\n\n", "file_path": "async/async_if.hpp", "rank": 41, "score": 59360.215779886275 }, { "content": "struct Interrupt_recv_if\n\n: virtual sc_core::sc_interface\n\n{\n\n // Wait for an event. *** Does NOT wait if already available ***\n\n virtual void wait ( void ) = 0;\n\n // Take an event off the queue and return the name of the source\n\n virtual char* get_next ( void ) = 0;\n\n // Combination of wait & get_next\n\n virtual void wait_n_get ( char** source ) = 0;\n\n // Empty the entire queue (e.g. for reset\n\n virtual void clearall ( void ) = 0;\n\n // Number of calls to notify\n\n virtual size_t sent ( void ) const = 0;\n\n // Number of calls to get\n\n virtual size_t taken ( void ) const = 0;\n\n // Interrupts are pending immediate service at the current simulation time\n\n virtual bool has_pending ( void ) const = 0;\n\n};\n\n\n", "file_path": "interrupt/interrupt_if.hpp", "rank": 42, "score": 59360.215779886275 }, { "content": "struct Interrupt_send_if\n\n: virtual sc_core::sc_interface\n\n{\n\n // Send an event using the current module instance as source\n\n virtual void notify( void ) = 0; //< immediate\n\n virtual void notify( const sc_core::sc_time& delay ) = 0;\n\n // Send an event from the specified source\n\n virtual void notify( const char* source ) = 0; //< immediate\n\n virtual void notify( const char* source, const sc_core::sc_time& delay ) = 0;\n\n};\n\n\n", "file_path": "interrupt/interrupt_if.hpp", "rank": 43, "score": 59360.215779886275 }, { "content": "struct PowerDomain\n\n: sc_core::sc_object\n\n{\n\n using Power_map_t = std::unordered_map< const char*, PowerSetting* >;\n\n virtual ~PowerDomain( void ); // Destructor\n\n static Power_map_t::iterator create( const std::string& domain, Power_t level );\n\n PowerSetting state( void );\n\n void reset( void );\n\n const sc_core::sc_event& event( void ) { return m_event; }\n\nprivate:\n\n PowerDomain( const std::string& domain ); // Constructor\n\n std::vector<sc_core::sc_object*> get_processes( sc_core::sc_object* root );\n\n static PowerSetting get_state( const std::string& domain );\n\n static clock_map_t s_level;\n\n std::string m_domain;\n\n sc_core::sc_event m_event;\n\n};\n\n\n\n#endif /*POWER_HPP*/\n", "file_path": "power/power.hpp", "rank": 44, "score": 59360.215779886275 }, { "content": "struct Route_extn\n\n: tlm_utils::instance_specific_extension<Route_extn>\n\n{\n\n int id;\n\n};\n\n\n\n#endif /*ROUTE_EXTN_HPP*/\n", "file_path": "bus/route_extn.hpp", "rank": 45, "score": 57569.35823991404 }, { "content": "struct Cpuid_extn\n\n: tlm::tlm_extension<Cpuid_extn>\n\n{\n\n Cpuid_extn( sc_core::sc_module* cpu = nullptr );\n\n virtual tlm_extension_base* clone( void ) const;\n\n virtual void copy_from( tlm_extension_base const& extn );\n\n const char* name( void ) const;\n\n void set_module_ptr( sc_core::sc_module* cpu );\n\n sc_core::sc_module* get_module_ptr( void ) const;\n\nprivate:\n\n sc_core::sc_module* m_cpu_ptr;\n\n};\n\n\n\n#endif/*CPUID_EXTN_HPP*/\n", "file_path": "cpu/cpuid_extn.hpp", "rank": 46, "score": 57569.35823991404 }, { "content": "struct Config_extn\n\n: tlm::tlm_extension<Config_extn>\n\n{\n\n Config_extn( void );\n\n virtual ~Config_extn( void ) = default;\n\n virtual tlm::tlm_extension_base* clone( void ) const override;\n\n virtual void copy_from(tlm::tlm_extension_base const& extn) override;\n\n Configuration configuration;\n\n};\n\n\n\n#endif /*CONFIG_EXTN_HPP*/\n", "file_path": "config/config_extn.hpp", "rank": 47, "score": 57569.35823991404 }, { "content": "struct RgbLED_module\n\n: sc_core::sc_module\n\n{\n\n // Ports\n\n sc_core::sc_in_resolved r, g, b;\n\n\n\n // Constructor\n\n RgbLED_module( sc_core::sc_module_name instance_name );\n\n\n\n // Destructor\n\n virtual ~RgbLED_module( void );\n\n\n\n // Processes\n\n void rgbled_method( void );\n\n\n\nprivate:\n\n // Local methods - NONE\n\n\n\n // Local channels\n\n\n\n // Attributes - NONE\n\n\n\n};//end RgbLED_module\n\n\n\n#endif/*RGBLED_HPP*/\n", "file_path": "gpio/rgbled.hpp", "rank": 48, "score": 57569.35823991404 }, { "content": "struct Tcpip_tx_if\n\n: tlm::tlm_put_if<Async_payload>\n\n{\n\n};\n\n\n\n#endif/*TCPIP_TX_IF_HPP\n\n\n\n//------------------------------------------------------------------------------\n\n// Copyright 2019 by Doulos. All rights reserved.\n\n// For licensing information concerning this document see LICENSE-APACHE.txt.\n\n//END tcpip_if.hpp @(#)$Id$\n", "file_path": "tcpip/tcpip_tx_if.hpp", "rank": 49, "score": 57569.35823991404 }, { "content": "struct Excl_filt\n\n: sc_core::sc_module\n\n, tlm::tlm_bw_transport_if<>\n\n, tlm::tlm_fw_transport_if<>\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n\n\n // Ports\n\n tlm::tlm_initiator_socket<> init_socket;\n\n tlm::tlm_target_socket<> targ_socket;\n\n\n\n Excl_filt //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , Depth_t excl_locks = 1\n\n , Depth_t excl_size = 4/*bytes*/\n\n , Excl_filt* global = nullptr;\n\n );\n\n virtual ~Excl_filt( void );\n\n const char* kind( void ) const override { return \"Excl_filt\"; }\n\n\n", "file_path": "exclusive/excl_filt.hpp", "rank": 50, "score": 57569.35823991404 }, { "content": "struct Dmi_extn\n\n: tlm::tlm_extension<Dmi_extn>\n\n{\n\n Dmi_extn( void );\n\n virtual ~Dmi_extn( void ) = default;\n\n virtual tlm::tlm_extension_base* clone( void );\n\n virtual void copy_from( tlm::tlm_extension_base const& ext );\n\n virtual void free( void );\n\n};\n\n\n\n#endif /*DMI_EXTN_HPP*/\n", "file_path": "dmi/dmi_extn.hpp", "rank": 51, "score": 57569.35823991404 }, { "content": "struct Tcpip_rx_if\n\n: tlm::tlm_get_if<Async_payload>\n\n{\n\n};\n\n\n\n#endif/*TCPIP_RX_IF_HPP\n\n\n\n//------------------------------------------------------------------------------\n\n// Copyright 2019 by Doulos. All rights reserved.\n\n// For licensing information concerning this document see LICENSE-APACHE.txt.\n\n//END tcpip_if.hpp @(#)$Id$\n", "file_path": "tcpip/tcpip_rx_if.hpp", "rank": 52, "score": 57569.35823991404 }, { "content": "struct Secure_extn\n\n: tlm::tlm_extension<Secure_extn>\n\n{\n\n Secure_extn( void );\n\n virtual ~Secure_extn( void ) = default;\n\n virtual tlm::tlm_extension_base* clone( void ) const override;\n\n virtual void copy_from(tlm::tlm_extension_base const& extn) override;\n\n int level { 1 };\n\n};\n\n\n\n#endif /*SECURE_EXTN_HPP*/\n", "file_path": "secure/secure_extn.hpp", "rank": 53, "score": 57569.35823991404 }, { "content": "struct Timer_api\n\n{\n\n // Constructor\n\n Timer_api(Cpu_module& cpu, Addr_t base, int timer=-1 )\n\n : m_cpu( cpu )\n\n , m_base( base )\n\n , m_timer( (timer<0)?nTimer():timer )\n\n {\n\n INFO( MEDIUM, \"Referencing timer \" << m_timer );\n\n }\n\n\n\n ~Timer_api( void ) = default;\n\n\n\n // Convenience\n\n int timer( void ) const { return m_timer; }\n\n void setup( uint32_t timer_count=0, uint32_t scale=1 )\n\n {\n\n Addr_t timer_addr = m_base + m_timer*TIMER_REGS_SIZE;\n\n m_cpu.write32( timer_addr + TIMER_LOAD_LO_REG, timer_count );\n\n m_cpu.write32( timer_addr + TIMER_CTRLCLR_REG, TIMER_FLAGS_MASK | TIMER_SCALE_MASK );\n", "file_path": "timer/timer_api.hpp", "rank": 54, "score": 57569.35823991404 }, { "content": "struct Config_proxy\n\n: sc_core::sc_module\n\n, tlm::tlm_bw_transport_if<>\n\n, tlm::tlm_fw_transport_if<>\n\n{\n\n using tlm_payload_t = tlm::tlm_generic_payload;\n\n\n\n // Ports\n\n tlm::tlm_initiator_socket<> init_socket{ \"init_socket\" };\n\n tlm::tlm_target_socket<> targ_socket{ \"targ_socket\" };\n\n\n\n Config_proxy //< Constructor\n\n ( sc_core::sc_module_name instance_name\n\n , Depth_t target_size = 0/*bytes*/\n\n , Access access = Access::none\n\n , size_t max_burst = 8/*bytes*/\n\n , size_t alignment = 4/*bytes*/\n\n , uint32_t addr_clocks = 1\n\n , uint32_t read_clocks = 2\n\n , uint32_t write_clocks = 3\n", "file_path": "config/config_proxy.hpp", "rank": 55, "score": 57569.35823991404 }, { "content": "struct Cache_extn\n\n: tlm::tlm_extension<Cache_extn>\n\n{\n\n // Local types\n\n using Cache_id_t = uint_least8_t;\n", "file_path": "cache/cache_extn.hpp", "rank": 56, "score": 57569.35823991404 }, { "content": "struct sc_freq\n\n{\n\n\n\n // Constructors\n\n sc_freq( void ) : m_value(0.0), m_units( SC_HZ ) {}\n\n explicit sc_freq( double value, sc_freq_units units = SC_HZ )\n\n : m_value( value ), m_units( units ) {}\n\n sc_freq( const sc_freq& ) = default;\n\n sc_freq( sc_freq&& ) = default;\n\n ~sc_freq( void ) = default;\n\n\n\n // Assignment\n\n sc_freq& operator=( const sc_freq& rhs ) = default;\n\n sc_freq& operator=( sc_freq&& rhs ) = default;\n\n\n\n // Utility\n\n static double magnitude( sc_freq_units units );\n\n static std::string str( sc_freq_units units );\n\n\n\n // Accessors & conversion\n", "file_path": "scx/sc_freq.hpp", "rank": 57, "score": 57569.35823991404 }, { "content": "struct Pic_api\n\n{\n\n // Constructor\n\n Pic_api(Cpu_module& cpu, Addr_t base )\n\n : m_cpu( cpu )\n\n , m_base( base )\n\n {\n\n }\n\n\n\n ~Pic_api( void ) = default;\n\n\n\n // Convenience\n\n uint32_t get_ident( void );\n\n void setup( void );\n\n uint16_t get_source_count( void );\n\n uint16_t get_target_count( void );\n\n uint32_t get_targetid( void );\n\n uint32_t get_target( void );\n\n void set_target( void );\n\n void set_mask( uint8_t level );\n", "file_path": "interrupt/pic_api.hpp", "rank": 58, "score": 57569.35823991404 }, { "content": "struct Mmu_extn\n\n: tlm::tlm_extension<Mmu_extn>\n\n{\n", "file_path": "mmu/mmu_extn.hpp", "rank": 59, "score": 57569.35823991404 }, { "content": "struct Async_payload\n\n{\n\n static const uint64_t UNDEFINED = ~uint64_t(0);\n\n // Constructor\n\n Async_payload\n\n ( Async_kind kind\n\n , const Data_t& data\n\n , uint64_t dest=UNDEFINED\n\n , uint64_t orig=UNDEFINED\n\n , uint64_t time=UNDEFINED\n\n )\n\n : m_id ( next() )\n\n , m_orig ( orig )\n\n , m_dest ( dest )\n\n , m_time ( time )\n\n , m_kind ( kind )\n\n , m_data ( data )\n\n , m_has_data( true )\n\n , m_has_kind( true )\n\n {\n", "file_path": "async/async_payload.hpp", "rank": 60, "score": 57569.35823991404 }, { "content": "struct Excl_extn\n\n: tlm::tlm_extension<Excl_extn>\n\n{\n\n Excl_extn( void );\n\n virtual ~Excl_extn( void ) = default;\n\n virtual tlm::tlm_extension_base* clone( void ) const override;\n\n virtual void copy_from(tlm::tlm_extension_base const& extn) override;\n\n bool exclusive( const tlm::tlm_generic_payload& trans, bool& open );\n\n void succeeded( void ) const { return m_success; }\n\nprivate:\n\n bool m_success { false };\n\n};\n\n\n\n#endif /*EXCL_EXTN_HPP*/\n", "file_path": "exclusive/excl_extn.hpp", "rank": 61, "score": 57569.35823991404 }, { "content": "struct Async_tx_channel\n\n: sc_core::sc_prim_channel\n\n, Async_if<T>\n\n{\n\n // Constructor\n\n Async_tx_channel( const std::string& instance_name )\n\n : sc_core::sc_prim_channel( instance_name.c_str() )\n\n {\n\n REPORT_INFO( \"Constructed outgoing \" << name() );\n\n }\n\n\n\n // Destructor\n\n ~Async_tx_channel( void )\n\n {\n\n REPORT_INFO( \"Destroyed outgoing \" << name() );\n\n }\n\n\n\n // Safely add entry to queue and return success status (in case queue full)\n\n bool notify( const Async_payload<T>& the_payload ) override\n\n {\n", "file_path": "async/async_tx.hpp", "rank": 62, "score": 55948.078682545936 }, { "content": "struct Tcpip_tx_channel\n\n: sc_core::sc_channel\n\n, Tcpip_tx_if\n\n{\n\n // Constructor\n\n Tcpip_tx_channel( sc_core::sc_module_name instance_name, uint32_t port )\n\n : m_tx_port( port )\n\n {\n\n }\n\n\n\n // Destructor\n\n virtual ~Tcpip_tx_channel( void )\n\n {\n\n }\n\n\n\n void start_of_simulation()\n\n {\n\n // Launch thread\n\n m_tx_osthread = std::thread( tx_osthread );\n\n }\n", "file_path": "tcpip/tcpip_tx.hpp", "rank": 63, "score": 55948.078682545936 }, { "content": "struct Tcpip_rx_channel\n\n: sc_core::sc_channel\n\n, Tcpip_rx_if\n\n{\n\n // Constructor\n\n Tcpip_rx_channel( sc_core::sc_module_name instance_name )\n\n {\n\n }\n\n\n\n // Destructor\n\n virtual ~Tcpip_rx_channel( void )\n\n {\n\n }\n\n\n\n void start_of_simulation()\n\n {\n\n // Launch thread\n\n }\n\n\n\n // Processes\n", "file_path": "tcpip/tcpip_rx.hpp", "rank": 64, "score": 55948.078682545936 }, { "content": "struct Async_rx_channel\n\n: sc_core::sc_prim_channel\n\n, Async_if<T>\n\n{\n\n Async_rx_channel( const std::string& instance_name ); ///< Constructor\n\n ~Async_rx_channel( void ); ///< Destructor\n\n\n\n // Safely add entry to queue and return success status (in case queue full)\n\n bool notify( const Async_payload<T>& the_payload ) override;\n\n\n\n // Performs the transfer during SystemC update phase\n\n // *** Do NOT call this directly ***\n\n void update( void );\n\n `\n\n // Determines if there is anything waiting to be read\n\n bool is_empty( void ) const override;\n\n\n\n // Block if no events are available\n\n void wait_unless_available( void ) const override;\n\n\n", "file_path": "async/async_rx.hpp", "rank": 65, "score": 55948.078682545936 }, { "content": "///////////////////////////////////////////////////////////////////////////////\n\n// Private implementation\n\nstruct Top_module::Impl\n\n{\n\n\n\n // Clock\n\n no_clock& clk { no_clock::global( \"system_clock\", 100_MHz ) };\n\n\n\n // Modules\n\n std::unique_ptr< Cpu_module > cpu;\n\n std::unique_ptr< Bus_module > nth;\n\n std::unique_ptr< Bus_module > sth;\n\n std::unique_ptr< Memory_module > rom;\n\n std::unique_ptr< Memory_module > ram;\n\n std::unique_ptr< Memory_module > ddr;\n\n std::unique_ptr< Gpio_module > gio;\n\n std::unique_ptr< RgbLED_module > led1;\n\n std::unique_ptr< Timer_module > tmr;\n\n std::unique_ptr< Pic_module > pic;\n\n std::unique_ptr< Uart_module > ser;\n\n std::unique_ptr< Stub_module > dma;\n\n\n", "file_path": "top/top.cpp", "rank": 66, "score": 53807.40434889887 }, { "content": "struct Memory_manager: tlm::tlm_mm_interface, sc_core::sc_object\n\n{\n\n\n\n // Methods\n\n //----------------------------------------------------------------------------\n\n static Memory_manager& instance( void );\n\n //----------------------------------------------------------------------------\n\n T* allocate( void );\n\n //----------------------------------------------------------------------------\n\n T* allocate_acquire( void );\n\n //----------------------------------------------------------------------------\n\n T* allocate_acquire_and_set\n\n ( tlm::tlm_command command = tlm::TLM_IGNORE_COMMAND\n\n , sc_dt::uint64 address = ~0ull\n\n , unsigned char* data_ptr = nullptr\n\n , uint32_t data_length = 0\n\n , uint32_t streaming_width = ~0u\n\n , unsigned char* byte_enable_ptr = nullptr\n\n , uint32_t byte_enable_length = 0\n\n );\n", "file_path": "utility/memory_manager.hpp", "rank": 67, "score": 51741.17394240173 }, { "content": "#define PLATFORM_KEY(_a) _a,\n\nenum class Platform : int {\n\n PLATFORM_ENUMS(PLATFORM_KEY)\n\n };\n\n#undef PLATFORM_KEY\n\n\n\nstd::string platform_str( const Platform& elt );\n\nbool is_Platform( const std::string& str ) noexcept;\n\nPlatform to_Platform( const std::string& str );\n\nstd::ostream& operator<< ( std::ostream& os, const Platform& rhs );\n\nstd::istream& operator>> ( std::istream& is, Platform& rhs );\n\ninline Platform operator++(Platform& x) {\n\n return x = (Platform)(std::underlying_type<Platform>::type(x) + 1); \n\n}\n\ninline Platform operator*(Platform c) {\n\n return c;\n\n}\n\ninline Platform begin([[maybe_unused]]Platform r) {\n\n return (Platform)std::underlying_type<Platform>::type(0);\n\n}\n\ninline Platform end([[maybe_unused]]Platform r) {\n\n return Platform::end;\n\n}\n\n\n\n#endif /*PLATFORM_ENUM_HPP*/\n", "file_path": "top/platform_enum.hpp", "rank": 68, "score": 51072.90154972252 }, { "content": "#include <sstream>\n\n#include <string>\n\n#include <systemcc>\n\n#include <tlmc>\n\nusing namespace sc_core;\n\nusing namespace std;\n\nusing namespace tlm;\n\n\n\nstd::ostringstream Report::mout;\n\n\n\n/**\n\n * @func convert tlm_command enum to string\n\n */\n\nstring to_string( tlm_command command )\n\n{\n\n switch( command )\n\n {\n\n case TLM_WRITE_COMMAND: return \"TLM_WRITE_COMMAND\";\n\n case TLM_READ_COMMAND: return \"TLM_READ_COMMAND\";\n\n case TLM_IGNORE_COMMAND: return \"TLM_IGNORE_COMMAND\";\n", "file_path": "report/report.cpp", "rank": 69, "score": 51004.50079177463 }, { "content": " } \\\n\n} while(0)\n\n#endif\n\n#define MESSAGE(stream) do { Report::mout << stream; } while(0)\n\n#define MEND(level) do { \\\n\n if( sc_core::sc_report_handler::get_verbosity_level() >= (sc_core::SC_##level) ) {\\\n\n Report::mout << std::ends; \\\n\n std::string str = Report::mout.str(); Report::mout.str(\"\"); \\\n\n SC_REPORT_INFO_VERB( MSGID, str.c_str(), (sc_core::SC_##level)); \\\n\n } \\\n\n} while (0)\n\n#define RULER(c) MESSAGE( std::string( 80, c ) << \"\\n\" )\n\n\n\n#define TODO(stream) REPORT( WARNING, \"TODO: \" << stream )\n\n#define NOT_YET_IMPLEMENTED() REPORT( WARNING, __func__ << \" is not yet implemented.\" )\n\n\n", "file_path": "report/report.hpp", "rank": 70, "score": 51000.79807231827 }, { "content": " #define NOT_YET_IMPLEMENTED()\n\n #define DELETE_THIS_LINE(lno,message)\n\n#else\n\n// For type: WARNING, ERROR, FATAL (use INFO() for INFO level messages)\n\n#define REPORT(type,stream) \\\n\ndo { \\\n\n Report::mout << STREAM_DEC << stream << std::ends; \\\n\n auto str = Report::mout.str(); Report::mout.str(\"\"); \\\n\n SC_REPORT_##type( MSGID, str.c_str() ); \\\n\n} while (0)\n\n\n\n// Use the following to (A) add more information in the event of failure, and\n\n// and (B) control sc_assert behavior (i.e. not unconditional abort on failure).\n\n#ifndef NDEBUG\n\n#define ASSERT(expr,stream) do {\\\n\n if(!(expr)) REPORT(FATAL, \"Assertion failed: \" << # expr << \". \" << stream );\\\n\n} while (0)\n\n#else\n\n#define ASSERT(expr,stream)\n\n#endif\n", "file_path": "report/report.hpp", "rank": 71, "score": 51000.73630239096 }, { "content": " size_t p0=id.find(\"/\"),p1=id.find_last_of(\"/\"); \\\n\n if(p1!=std::string::npos) id.erase(p0,p1-p0+1); \\\n\n auto str = Report::mout.str(); Report::mout.str(\"\"); \\\n\n SC_REPORT_INFO_VERB( id.c_str(), str.c_str(), (sc_core::SC_##level) ); \\\n\n } else { \\\n\n auto str = Report::mout.str(); Report::mout.str(\"\"); \\\n\n SC_REPORT_INFO_VERB( MSGID, str.c_str(), (sc_core::SC_##level) ); \\\n\n } \\\n\n } \\\n\n} while (0)\n\n\n\n#ifdef NDEBUG\n\n#define DEBUG()\n\n#else\n\n#include \"report/commandline.hpp\"\n\n#define DEBUG(stream) do { \\\n\n if( sc_core::sc_report_handler::get_verbosity_level() >= sc_core::SC_DEBUG \\\n\n and ( Commandline::has_opt(\"-debugall\") \\\n\n or Commandline::has_opt(\"-debug=\"s + basename() ) ) ) { \\\n\n INFO(DEBUG,stream); \\\n", "file_path": "report/report.hpp", "rank": 72, "score": 50999.05020919601 }, { "content": "\n\n/**\n\n * @func Convert verbosity to string\n\n */\n\nstd::string verbosity2str(const int & level)\n\n{\n\n std::ostringstream os;\n\n switch( level ) {\n\n case SC_NONE : os << \"NONE\"; break;\n\n case SC_LOW : os << \"LOW\"; break;\n\n case SC_MEDIUM : os << \"MEDIUM\"; break;\n\n case SC_HIGH : os << \"HIGH\"; break;\n\n case SC_FULL : os << \"FULL\"; break;\n\n case SC_DEBUG : os << \"DEBUG\"; break;\n\n default:\n\n if( level < SC_LOW ) { os << std::to_string( int( level - SC_NONE ) ) << \"% LOW\" ; }\n\n else if( level < SC_MEDIUM ) { os << std::to_string( int( level - SC_LOW ) ) << \"% MEDIUM\" ; }\n\n else if( level < SC_HIGH ) { os << std::to_string( int( level - SC_MEDIUM ) ) << \"% HIGH\" ; }\n\n else if( level < SC_FULL ) { os << std::to_string( int( level - SC_HIGH ) ) << \"% FULL\" ; }\n\n else if( level < SC_DEBUG ) { os << std::to_string( int( level - SC_FULL ) ) << \"% DEBUG\" ; }\n\n else { os << \"DEBUG + \" << std::to_string( int( level - SC_DEBUG ) ) ; }\n\n }//endswitch\n\n return os.str();\n\n}\n\n\n", "file_path": "report/report.cpp", "rank": 73, "score": 50996.77781679159 }, { "content": "std::ostream& operator<<( std::ostream& os, const std::vector<T>& vec )\n\n{\n\n static const int threshold{8};\n\n os << \"{ \";\n\n size_t i = 0;\n\n\n\n for ( auto& v : vec ) {\n\n if ( i != 0 ) {\n\n os << \", \";\n\n }\n\n\n\n if ( i+1 == vec.size() and vec.size() > threshold ) {\n\n os << \" ...\";\n\n }\n\n\n\n if ( i < threshold or i+1 == vec.size() ) {\n\n os << i++ << \":\" << v;\n\n }\n\n\n\n }\n\n\n\n os << \" }\";\n\n return os;\n\n}\n\n\n\n#endif/*__SYNTHESIS__*/\n\n\n\n#endif/*REPORT_HPP*/\n", "file_path": "report/report.hpp", "rank": 74, "score": 50994.38348459118 }, { "content": "\n\n#define SC_ALWAYS SC_NONE\n\n#define SC_NEVER 16*KB\n\n#define SC_HYPER 1024\n\n#define DEVID (std::string(\"(\")+name()+\")\").c_str()\n\n#define NOINFO(level,stream)\n\n// For level: NONE, LOW, MEDIUM, HIGH, DEBUG\n\n#define INFO(level,stream) \\\n\ndo { \\\n\n if( sc_core::sc_report_handler::get_verbosity_level() \\\n\n >= (sc_core::SC_##level) ) { \\\n\n Report::mout << STREAM_DEC << stream; \\\n\n if( auto now = sc_core::sc_time_stamp(); now > sc_core::SC_ZERO_TIME \\\n\n or sc_core::sc_get_status() >= sc_core::SC_START_OF_SIMULATION ) { \\\n\n Report::mout << STREAM_DEC << \" at \" << now; \\\n\n } \\\n\n Report::mout << std::ends; \\\n\n if( (sc_core::SC_##level) > sc_core::SC_DEBUG ) { \\\n\n std::string id{\"DEBUG(\"}; \\\n\n id+=__FILE__ ; id+=\":\"; id+=std::to_string(__LINE__)+\")\"; \\\n", "file_path": "report/report.hpp", "rank": 75, "score": 50994.01297009093 }, { "content": " default: return \"!UKNOWN_COMMAND!\";\n\n }\n\n}\n\n\n\n/**\n\n * @func output an array of bytes\n\n */\n\nstring to_string( uint8_t const * const data, uint32_t len )\n\n{\n\n static char const * const hexdigit = \"0123456789ABCDEF\";\n\n string result( len+2, '0' );\n\n result[1] = 'x';\n\n for( int i=2; len > 0; ) {\n\n --len;\n\n uint8_t d = data[len];\n\n result[i++] = hexdigit[ d >> 4 ];\n\n result[i++] = hexdigit[ d & 0xF ];\n\n }\n\n return result;\n\n}\n", "file_path": "report/report.cpp", "rank": 76, "score": 50989.38389444511 }, { "content": "#ifndef REPORT_HPP\n\n#define REPORT_HPP\n\n////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// ##### ##### ##### #### ##### ####### \n\n// # # # # # # # # # # \n\n// # # # # # # # # # # \n\n// ##### ##### ##### # # ##### # \n\n// # # # # # # # # # \n\n// # # # # # # # # # \n\n// # # ##### # #### # # # \n\n//\n\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n\n * @file report.hpp\n\n * @brief Improve reporting with macros, more overloads on `operator<<`,\n\n * and other enhancements to `sc_report_handler`.\n\n *\n\n * See `ABOUT_REPORT.md` for more information.\n\n */\n\n#include <systemcc>\n\n#include <tlmc>\n\n#include <string>\n\n#include <sstream>\n\n#include <iomanip>\n", "file_path": "report/report.hpp", "rank": 77, "score": 50981.51633994998 }, { "content": "#include \"report.hpp\"\n\n\n", "file_path": "report/report_test.cpp", "rank": 78, "score": 49170.20374994695 }, { "content": "#define TEST_KEY(_a) _a,\n\nenum class PlatformTest : int {\n\n TEST_ENUMS(TEST_KEY)\n\n };\n\n#undef TEST_KEY\n\n\n\nstd::string platformtest_str( const PlatformTest& elt );\n\nbool is_PlatformTest( const std::string& str ) noexcept;\n\nPlatformTest to_PlatformTest( const std::string& str );\n\nstd::ostream& operator<<( std::ostream& os, const PlatformTest& rhs );\n\nstd::istream& operator>>( std::istream& is, PlatformTest& rhs );\n\ninline PlatformTest operator++(PlatformTest& x) {\n\n return x = (PlatformTest)(std::underlying_type<PlatformTest>::type(x) + 1); \n\n}\n\ninline PlatformTest operator*(PlatformTest c) {\n\n return c;\n\n}\n\ninline PlatformTest begin([[maybe_unused]]PlatformTest r) {\n\n return (PlatformTest)std::underlying_type<PlatformTest>::type(0);\n\n}\n\ninline PlatformTest end([[maybe_unused]]PlatformTest r) {\n\n return PlatformTest::end;\n\n}\n\n\n\n#endif /*TEST_ENUM_HPP*/\n", "file_path": "unit_test/test_enum.hpp", "rank": 79, "score": 48223.70021030772 }, { "content": "struct Async_if: Async_rx_if<T>, Async_tx_if<T> { }\n\n\n\n#endif/*ASYNC_IF_HPP\n\n\n\n//------------------------------------------------------------------------------\n\n// Copyright 2019 by Doulos. All rights reserved.\n\n// For licensing information concerning this document see LICENSE-{:LICENSE:}.txt.\n\n//END async_if.hpp @(#)$Id$\n", "file_path": "async/async_if.hpp", "rank": 80, "score": 41749.650204637386 }, { "content": "struct Tcpip_if: Tcpip_rx_if<T>, Tcpip_tx_if<T> { }\n\n\n\n#endif/*TCPIP_IF_HPP\n\n\n\n//------------------------------------------------------------------------------\n\n// Copyright 2019 by Doulos. All rights reserved.\n\n// For licensing information concerning this document see LICENSE-APACHE.txt.\n\n//END tcpip_if.hpp @(#)$Id$\n", "file_path": "tcpip/tcpip_if.hpp", "rank": 81, "score": 41749.650204637386 }, { "content": "#include \"report/summary.hpp\"\n\n#include <systemcc>\n\n#define REQUIRES_CPP 14\n\n#define REQUIRES_SYSTEMC 233\n\n#include \"common/require_version.hpp\"\n\n#include \"report/report.hpp\"\n\n#include \"top/wallclock.hpp\"\n\n#include <string>\n\nusing namespace std;\n\nusing namespace sc_core;\n\nnamespace {\n\n const char * const MSGID{ \"/Doulos/Example/summary\" };\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// Static allocations\n\ndouble Summary::s_elaboration_time = -1.0;\n\ndouble Summary::s_starting_time = -1.0;\n\ndouble Summary::s_finished_time = -1.0;\n\nunsigned int Summary::s_errors = 0;\n", "file_path": "report/summary.cpp", "rank": 82, "score": 40543.720910180884 }, { "content": " MESSAGE( \" Compiled using: Microsoft Visual Studio version \" << _MSC_FULL_VER << \"\\n\" );\n\n #elif defined(__PGI)\n\n MESSAGE( \" Compiled using: Portland Group PGCC/PGCPP version \" << __PGIC__ << \".\" << __PGIC_MINOR__ << \".\" << __PGIC_PATCHLEVEL__ << \"\\n\" );\n\n #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)\n\n MESSAGE( \" Compiled using: Oracle Solaris Studio version \" << std::hex << __SUNPRO_CC << \"\\n\" );\n\n #elif defined(__cppcheck__)\n\n MESSAGE( \" Cppcheck version \" << __cppcheck__ << \"\\n \" );\n\n #else\n\n MESSAGE( \" Unknown compiler?\" << \"\\n\" );\n\n ++s_warnings;\n\n warn = true;\n\n #endif\n\n MEND( ALWAYS );\n\n if( warn ) {\n\n REPORT( WARNING, \" Please inform Doulos of your compiler and how to check for its existence.\" );\n\n }\n\n }\n\n string kind = \"Simulation\";\n\n\n\n if ( s_starting_time < 0.0 ) {\n", "file_path": "report/summary.cpp", "rank": 83, "score": 40535.00063787336 }, { "content": " if( first_time ) {\n\n s_finished_time = get_cpu_time();\n\n }\n\n first_time = false;\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\nint Summary::errors( void )\n\n{\n\n return sc_report_handler::get_count( SC_ERROR )\n\n + s_errors\n\n + sc_report_handler::get_count( SC_FATAL );\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n// Summarize results\n\nint Summary::report( void )\n\n{\n\n {\n\n bool warn{ false };\n", "file_path": "report/summary.cpp", "rank": 84, "score": 40531.3416750174 }, { "content": " kind = \"Elaboration\";\n\n s_starting_time = s_finished_time = get_cpu_time();\n\n }\n\n\n\n if ( s_finished_time < 0.0 ) {\n\n s_finished_time = get_cpu_time();\n\n }\n\n\n\n MESSAGE( \"\\n\" );\n\n RULER( '-' );\n\n MESSAGE( \"Summary for \" << sc_argv()[0] << \":\\n\" );\n\n MESSAGE( \" CPU elaboration time \" << setprecision( 4 ) << ( s_starting_time - s_elaboration_time ) << \" sec\\n\" );\n\n MESSAGE( \" CPU simulation time \" << setprecision( 4 ) << ( s_finished_time - s_starting_time ) << \" sec\\n\" );\n\n MESSAGE( \" \" << setw( 2 ) << sc_report_handler::get_count( SC_WARNING ) << \" warnings\" << \"\\n\" );\n\n MESSAGE( \" \" << setw( 2 ) << sc_report_handler::get_count( SC_ERROR ) + s_errors << \" errors\" << \"\\n\" );\n\n MESSAGE( \" \" << setw( 2 ) << sc_report_handler::get_count( SC_FATAL ) << \" fatals\" << \"\\n\" );\n\n MESSAGE( \"\\n\" );\n\n RULER( '#' );\n\n MESSAGE( kind << \" \" << ( errors() ? \"FAILED\" : \"PASSED\" ) );\n\n MEND( ALWAYS );\n\n return ( errors() ? 1 : 0 );\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n// Copyright 2018 by Doulos. All rights reserved.\n\n// END $Id: summary.cpp,v 1.0 2018/11/19 05:18:14 dcblack Exp $\n", "file_path": "report/summary.cpp", "rank": 85, "score": 40531.28995459698 }, { "content": "unsigned int Summary::s_warnings = 0;\n\n\n\n//------------------------------------------------------------------------------\n\nvoid Summary::starting_elaboration( void )\n\n{\n\n s_elaboration_time = get_cpu_time();\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\nvoid Summary::starting_simulation( void )\n\n{\n\n // Last call wins...\n\n s_starting_time = get_cpu_time();\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\nvoid Summary::finished_simulation( void )\n\n{\n\n // First call wins...\n\n static bool first_time = true;\n", "file_path": "report/summary.cpp", "rank": 86, "score": 40527.960782129754 }, { "content": " MESSAGE( \"\\n\" );\n\n RULER( '#' );\n\n MESSAGE( \"Compilation information for \" << sc_argv()[0] << \":\\n\" );\n\n MESSAGE( \" C++ std version: \" << __cplusplus << \" (ISO/IEC 14882:\" <<CPP_VERSION << \")\" << \"\\n\" );\n\n MESSAGE( \" SystemC version: \" << SYSTEMC_VERSION << \"\\n\" );\n\n MESSAGE( \" TLM version: \" << TLM_VERSION << \"\\n\" );\n\n #ifdef BOOST_LIB_VERSION\n\n MESSAGE( \" BOOST version: \" << BOOST_LIB_VERSION << \"\\n\" );\n\n #endif\n\n #if defined(__clang__)\n\n MESSAGE( \" Compiled using: Clang/LLVM version \" << __clang_major__ << \".\" << __clang_minor__ << \".\" << __clang_patchlevel__ << \"\\n\" );\n\n #elif defined(__ICC) || defined(__INTEL_COMPILER)\n\n MESSAGE( \" Compiled using: Intel ICC/ICPC version \" << __ICC << \"\\n\" );\n\n #elif defined(__GNUC__) || defined(__GNUG__)\n\n MESSAGE( \" Compiled using: GNU GCC/G++ version \" << __GNUC__ << \".\" << __GNUC_MINOR__ << \".\" << __GNUC_PATCHLEVEL__ << \"\\n\" );\n\n #elif defined(__HP_cc) || defined(__HP_aCC)\n\n MESSAGE( \" Compiled using: Hewlett-Packard C/aC++ version \" << __HP_cc << \"\\n\" );\n\n #elif defined(__IBMC__) || defined(__IBMCPP__)\n\n MESSAGE( \" Compiled using: IBM XL C/C++ version \" << __IBMCPP__ << \"\\n\" );\n\n #elif defined(_MSC_VER)\n", "file_path": "report/summary.cpp", "rank": 87, "score": 40519.97770999096 }, { "content": "#pragma once\n\n\n\n#include <systemcc>\n\n#include <string>\n\n\n", "file_path": "report/commandline.hpp", "rank": 88, "score": 40516.6636341017 }, { "content": "#ifndef SUMMARY_HPP\n\n#define SUMMARY_HPP\n\n\n", "file_path": "report/summary.hpp", "rank": 89, "score": 40506.44490685754 }, { "content": "#include \"async/async_kind.hpp\"\n\n#include <algorithm>\n\n#include <exception>\n\n\n\n#define ASYNC_KIND_KEY(_a) #_a,\n\nnamespace {\n\nusing cstr = const char * const;\n\ncstr s_async_kind_str[] = {\n\n ASYNC_KIND_ENUMS(ASYNC_KIND_KEY)\n\n};\n\n}\n\n#undef KEY\n\n\n\n//------------------------------------------------------------------------------\n\nstd::string async_kind_str( const Async_kind& elt )\n\n{\n\n return s_async_kind_str[ static_cast<int>( elt ) ];\n\n}\n\n\n\n//------------------------------------------------------------------------------\n", "file_path": "async/async_kind.cpp", "rank": 90, "score": 38400.91822912832 }, { "content": " return static_cast<Async_kind>( ptr - begin );\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\nstd::istream& operator>>( std::istream& is, Async_kind& rhs )\n\n{\n\n std::string str;\n\n is >> str;\n\n rhs = to_Async_kind( str );\n\n return is;\n\n}\n\n\n\n#ifdef ASYNC_KIND_ENUM_EXAMPLE\n\n#include <sstream>\n\n#include <iomanip>\n\nint main( void )\n\n{\n\n std::string input;\n\n std::istringstream is;\n\n Async_kind vu, v0, v1, v2{ Async_kind::packet };\n", "file_path": "async/async_kind.cpp", "rank": 91, "score": 38399.610920280786 }, { "content": "std::ostream& operator<<( std::ostream& os, const Async_kind& rhs )\n\n{\n\n os << async_kind_str( rhs );\n\n return os;\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\nbool is_Async_kind( const std::string& str ) noexcept\n\n{\n\n int size = sizeof( s_async_kind_str ) / sizeof( char* );\n\n cstr* begin = s_async_kind_str;\n\n cstr* end = begin + size;\n\n cstr* ptr = find( begin, end, str );\n\n return (ptr != end);\n\n}\n\n\n\nnamespace {\n", "file_path": "async/async_kind.cpp", "rank": 92, "score": 38398.26247926201 }, { "content": "#ifndef ASYNC_KIND_HPP\n\n#define ASYNC_KIND_HPP\n\n\n\n#if __cplusplus < 201103L\n\n #error Requires C++11 or better\n\n#endif\n\n\n\n#include <cstdint>\n\n#include <string>\n\n#include <iostream>\n\n\n\n#define ASYNC_KIND_ENUMS(ENUM)\\\n\n ENUM( command )\\\n\n ENUM( stream )\\\n\n ENUM( parallel )\\\n\n ENUM( packet )\\\n\n ENUM( graphic )\\\n\n ENUM( audio )\\\n\n ENUM( debug )\\\n\n ENUM( shutdown )\\\n\n ENUM( end ) //< required\n\n\n\n#define ASYNC_KIND_KEY(_a) _a,\n", "file_path": "async/async_kind.hpp", "rank": 93, "score": 38393.6514771874 }, { "content": " std::cout << \"v1=\" << v1 << std::endl;\n\n std::cout << \"v2=\" << v2 << std::endl;\n\n input = to_string( v2 );\n\n is.str( input );\n\n is >> v0;\n\n is.str(\"bad entry\");\n\n is.seekg( 0, is.beg );\n\n try {\n\n is >> v0;\n\n }\n\n catch( std::exception& e ) {\n\n std::cout << \"Successfully caught \" << e.what() << std::endl;\n\n }\n\n std::cout << \"Async_kinds:\" << std::endl;\n\n for( auto elt : Async_kind() ) {\n\n std::cout << \" \" << elt << std::endl;\n\n }\n\n // User testing\n\n do {\n\n std::cout << \"Enter an enum name ('q' to quit): \" << std::flush;\n", "file_path": "async/async_kind.cpp", "rank": 94, "score": 38393.33733808343 }, { "content": " std::cin >> input;\n\n size_t pos;\n\n if( not is_Async_kind( input ) ) {\n\n if( input != \"\" ) std::cout << \"Not a Async_kind\" << std::endl;\n\n continue;\n\n }\n\n is.str( input );\n\n is.seekg( 0, is.beg );\n\n v0 = vu;\n\n try {\n\n is >> v0;\n\n }\n\n catch( std::exception& e ) {\n\n std::cout << \"Caught \" << e.what() << std::endl;\n\n }\n\n std::cout << \"Converted result of '\" << input << \"' is Async_kind::\" << v0 << std::endl;\n\n } while ( input != \"q\" );\n\n return 0;\n\n}\n\n#endif\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n// Copyright 2019 by Doulos. All rights reserved.\n\n//END async_kind.cpp @(#)$Id$\n", "file_path": "async/async_kind.cpp", "rank": 95, "score": 38382.54410838403 } ]
C++
code/BDataPersonName.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
#include "precompiled.h" #include "BDataPersonName.h" #include "ConstantsDatabase.h" #include "BDoc.h" #include "UI.h" #include "NeoMem.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif IMPLEMENT_SERIAL(BDataPersonName, BData, VERSIONABLE_SCHEMA | versionFileStructure) BDataPersonName::BDataPersonName() : m_bCacheValid (FALSE) { } BDataPersonName::~BDataPersonName() { } BOOL BDataPersonName::SetBDataText(const CString& str, BObject* pobjPropertyDef , BOOL bShowErrorMessage ) { ASSERT_VALID(this); m_strTitle.Empty(); m_strFirst.Empty(); m_strMiddle.Empty(); m_strLast.Empty(); m_strNickname.Empty(); m_strSuffix.Empty(); int n = str.Find(','); if (n != -1) { m_strLast = str.Left(n); m_strFirst = str.Mid(n+1); m_strFirst.TrimLeft(); } else { int n = str.ReverseFind(' '); if (n == -1) { m_strLast = str; } else { m_strFirst = str.Left(n); m_strLast = str.Mid(n+1); } } m_bCacheValid = FALSE; return TRUE; } CString BDataPersonName::GetBDataText(BDoc* pDoc, ULONG lngPropertyID, BOOL bMachineVersion) { ASSERT_VALID(this); ASSERT_VALID(pDoc); if (m_bCacheValid) return m_strText; m_strText.Empty(); switch (app.m_nNameFormat) { case nfLastFirst: { LPCTSTR pszGap = ""; if (!m_strLast.IsEmpty()) { m_strText = m_strLast; pszGap = g_strCommaSpace; } if (!m_strTitle.IsEmpty()) { m_strText += pszGap + m_strTitle + g_strSpace; pszGap = "";} if (!m_strFirst.IsEmpty()) { m_strText += pszGap + m_strFirst + g_strSpace; pszGap = "";} if (!m_strMiddle.IsEmpty()) { m_strText += pszGap + m_strMiddle + g_strSpace; pszGap = "";} if (!m_strNickname.IsEmpty()) { m_strText += pszGap + g_strQuote + m_strNickname + g_strQuoteSpace; pszGap = "";} if (!m_strSuffix.IsEmpty()) { m_strText += pszGap + m_strSuffix; pszGap = "";} break; } case nfFirstLast: default: if (!m_strTitle.IsEmpty()) m_strText = m_strTitle + g_strSpace; if (!m_strFirst.IsEmpty()) m_strText += m_strFirst + g_strSpace; if (!m_strMiddle.IsEmpty()) m_strText += m_strMiddle + g_strSpace; if (!m_strNickname.IsEmpty()) m_strText += g_strQuote + m_strNickname + g_strQuoteSpace; if (!m_strLast.IsEmpty()) m_strText += m_strLast; if (!m_strSuffix.IsEmpty()) m_strText += g_strCommaSpace + m_strSuffix; break; } m_strText.TrimRight(); m_bCacheValid = TRUE; return m_strText; } BOOL BDataPersonName::UIEditValue(CUI& ui, BObject* pobj, BObject* pobjPropertyDef) { ASSERT_VALID(this); if (ui.EditName(m_strTitle, m_strFirst, m_strMiddle, m_strNickname, m_strLast, m_strSuffix)) { m_bCacheValid = FALSE; return TRUE; } return FALSE; } void BDataPersonName::Serialize(CArchive& ar) { BData::Serialize(ar); if (ar.IsStoring()) { ar << m_strTitle; ar << m_strFirst; ar << m_strMiddle; ar << m_strLast; ar << m_strNickname; ar << m_strSuffix; } else { ar >> m_strTitle; ar >> m_strFirst; ar >> m_strMiddle; ar >> m_strLast; ar >> m_strNickname; ar >> m_strSuffix; } } BData* BDataPersonName::CreateCopy() { ASSERT_VALID(this); BDataPersonName* pdatCopy = new BDataPersonName(); ASSERT_VALID(pdatCopy); pdatCopy->m_strTitle = m_strTitle; pdatCopy->m_strFirst = m_strFirst; pdatCopy->m_strLast = m_strLast; pdatCopy->m_strMiddle = m_strMiddle; pdatCopy->m_strNickname = m_strNickname; pdatCopy->m_strSuffix = m_strSuffix; return pdatCopy; } BOOL BDataPersonName::FindReferences(BObject* pobjFind) { return FALSE; } ULONG BDataPersonName::GetMemoryUsed(BOOL bRecursive) { ASSERT_VALID(this); ULONG nBytes = sizeof(BDataPersonName); nBytes += m_strTitle.GetLength() * sizeof(TCHAR); nBytes += m_strFirst.GetLength() * sizeof(TCHAR); nBytes += m_strLast.GetLength() * sizeof(TCHAR); nBytes += m_strMiddle.GetLength() * sizeof(TCHAR); nBytes += m_strNickname.GetLength() * sizeof(TCHAR); nBytes += m_strSuffix.GetLength() * sizeof(TCHAR); return nBytes; } void BDataPersonName::ResetData() { m_bCacheValid = FALSE; }
#include "precompiled.h" #include "BDataPersonName.h" #include "ConstantsDatabase.h" #include "BDoc.h" #include "UI.h" #include "NeoMem.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif IMPLEMENT_SERIAL(BDataPersonName, BData, VERSIONABLE_SCHEMA | versionFileStructure) BDataPersonName::BDataPersonName() : m_bCacheValid (FALSE) { } BDataPersonName::~BDataPersonName() { } BOOL BDataPersonName::SetBDataText(const CString& str, BObject* pobjPropertyDef , BOOL bShowErrorMessage ) { ASSERT_VALI
rFirst = str.Mid(n+1); m_strFirst.TrimLeft(); } else { int n = str.ReverseFind(' '); if (n == -1) { m_strLast = str; } else { m_strFirst = str.Left(n); m_strLast = str.Mid(n+1); } } m_bCacheValid = FALSE; return TRUE; } CString BDataPersonName::GetBDataText(BDoc* pDoc, ULONG lngPropertyID, BOOL bMachineVersion) { ASSERT_VALID(this); ASSERT_VALID(pDoc); if (m_bCacheValid) return m_strText; m_strText.Empty(); switch (app.m_nNameFormat) { case nfLastFirst: { LPCTSTR pszGap = ""; if (!m_strLast.IsEmpty()) { m_strText = m_strLast; pszGap = g_strCommaSpace; } if (!m_strTitle.IsEmpty()) { m_strText += pszGap + m_strTitle + g_strSpace; pszGap = "";} if (!m_strFirst.IsEmpty()) { m_strText += pszGap + m_strFirst + g_strSpace; pszGap = "";} if (!m_strMiddle.IsEmpty()) { m_strText += pszGap + m_strMiddle + g_strSpace; pszGap = "";} if (!m_strNickname.IsEmpty()) { m_strText += pszGap + g_strQuote + m_strNickname + g_strQuoteSpace; pszGap = "";} if (!m_strSuffix.IsEmpty()) { m_strText += pszGap + m_strSuffix; pszGap = "";} break; } case nfFirstLast: default: if (!m_strTitle.IsEmpty()) m_strText = m_strTitle + g_strSpace; if (!m_strFirst.IsEmpty()) m_strText += m_strFirst + g_strSpace; if (!m_strMiddle.IsEmpty()) m_strText += m_strMiddle + g_strSpace; if (!m_strNickname.IsEmpty()) m_strText += g_strQuote + m_strNickname + g_strQuoteSpace; if (!m_strLast.IsEmpty()) m_strText += m_strLast; if (!m_strSuffix.IsEmpty()) m_strText += g_strCommaSpace + m_strSuffix; break; } m_strText.TrimRight(); m_bCacheValid = TRUE; return m_strText; } BOOL BDataPersonName::UIEditValue(CUI& ui, BObject* pobj, BObject* pobjPropertyDef) { ASSERT_VALID(this); if (ui.EditName(m_strTitle, m_strFirst, m_strMiddle, m_strNickname, m_strLast, m_strSuffix)) { m_bCacheValid = FALSE; return TRUE; } return FALSE; } void BDataPersonName::Serialize(CArchive& ar) { BData::Serialize(ar); if (ar.IsStoring()) { ar << m_strTitle; ar << m_strFirst; ar << m_strMiddle; ar << m_strLast; ar << m_strNickname; ar << m_strSuffix; } else { ar >> m_strTitle; ar >> m_strFirst; ar >> m_strMiddle; ar >> m_strLast; ar >> m_strNickname; ar >> m_strSuffix; } } BData* BDataPersonName::CreateCopy() { ASSERT_VALID(this); BDataPersonName* pdatCopy = new BDataPersonName(); ASSERT_VALID(pdatCopy); pdatCopy->m_strTitle = m_strTitle; pdatCopy->m_strFirst = m_strFirst; pdatCopy->m_strLast = m_strLast; pdatCopy->m_strMiddle = m_strMiddle; pdatCopy->m_strNickname = m_strNickname; pdatCopy->m_strSuffix = m_strSuffix; return pdatCopy; } BOOL BDataPersonName::FindReferences(BObject* pobjFind) { return FALSE; } ULONG BDataPersonName::GetMemoryUsed(BOOL bRecursive) { ASSERT_VALID(this); ULONG nBytes = sizeof(BDataPersonName); nBytes += m_strTitle.GetLength() * sizeof(TCHAR); nBytes += m_strFirst.GetLength() * sizeof(TCHAR); nBytes += m_strLast.GetLength() * sizeof(TCHAR); nBytes += m_strMiddle.GetLength() * sizeof(TCHAR); nBytes += m_strNickname.GetLength() * sizeof(TCHAR); nBytes += m_strSuffix.GetLength() * sizeof(TCHAR); return nBytes; } void BDataPersonName::ResetData() { m_bCacheValid = FALSE; }
D(this); m_strTitle.Empty(); m_strFirst.Empty(); m_strMiddle.Empty(); m_strLast.Empty(); m_strNickname.Empty(); m_strSuffix.Empty(); int n = str.Find(','); if (n != -1) { m_strLast = str.Left(n); m_st
function_block-random_span
[ { "content": "#define HID_STATIC 0x1FFFF\n", "file_path": "help/HTMLDefines.h", "rank": 0, "score": 83671.20184086818 }, { "content": "#define HIDD_NEW_FILE 0x2031E\n", "file_path": "help/HTMLDefines.h", "rank": 1, "score": 80391.89517914159 }, { "content": "#define HID_POPUP_BDATA_STOP 0x12AF7\n", "file_path": "help/HTMLDefines.h", "rank": 2, "score": 77397.33029743686 }, { "content": "#define HID_POPUP_BDATA_START 0x12710\n", "file_path": "help/HTMLDefines.h", "rank": 3, "score": 77397.33029743686 }, { "content": "#define HIDD_NEW_LINK_SOURCE 0x2032A\n", "file_path": "help/HTMLDefines.h", "rank": 4, "score": 77369.13990118417 }, { "content": "#define HID_HELP_WHATS_NEW 0x1C3F6\n", "file_path": "help/HTMLDefines.h", "rank": 5, "score": 77369.13990118417 }, { "content": "class CStaticEx : public CStatic\n\n{\n\n// Construction\n\npublic:\n\n\tCStaticEx();\n\n\t~CStaticEx();\n\n\n\n// Operations\n\npublic:\n\n\tBOOL Create(\n\n\t\t\t\t\tLPCTSTR szText, \n\n\t\t\t\t\tCRect &r, \n\n\t\t\t\t\tCWnd* pParentWnd, \n\n\t\t\t\t\tUINT nCommandID = 0,\n\n\t\t\t\t\tBOOL bAutosize = TRUE, \n\n\t\t\t\t\tUINT nFormat = DT_LEFT | DT_BOTTOM,\n\n\t\t\t\t\tUINT nFlags = 0);\n\n//\tvoid SetColors(BOOL bOpaque = TRUE, COLORREF clrText = -1, COLORREF clrBackground = -1, \n\n//\t\t\t\t\t\t\tCOLORREF clrHighlight = -1, COLORREF clrBackground2 = -1);\n\n\tvoid SetColors(BOOL bOpaque = TRUE);\n", "file_path": "code/StaticEx.h", "rank": 6, "score": 62441.60055885982 }, { "content": "\n\n// CStaticEx\n\n// This class extends the CStatic class, letting you make labels into buttons, change \n\n// background color, foreground color, font, etc.\n\n//-----------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n#pragma once\n\n\n\n#include \"FontEx.h\"\n\n\n\n\n\n\n", "file_path": "code/StaticEx.h", "rank": 7, "score": 52683.62329260523 }, { "content": "\tUINT m_nFormat;\n\n\tCString m_strLink;\n\n\tCString m_strEmail;\n\n\tint m_nSound;\n\n\tBOOL m_bOpaque;\n\n\tHCURSOR m_hCursor;\n\n\n\n\tCRect m_rMargins;\n\n\tCRect m_rControlSize; // textsize + margins\n\n\tCRect m_rPos;\n\n\tCRect m_rDraw; // control size + margin top left\n\n\n\n\tCFontEx m_font;\n\n\tint m_nBkMode;\n\n\tUINT m_nTimer;\n\n\tUINT m_nFlags;\n\n\n\n\n\n\n\n// Overrides\n", "file_path": "code/StaticEx.h", "rank": 8, "score": 52681.4570909131 }, { "content": "\t// ClassWizard generated virtual function overrides\n\n\t//{{AFX_VIRTUAL(CStaticEx)\n\n\tprotected:\n\n\tvirtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);\n\n\t//}}AFX_VIRTUAL\n\n\n\n// Generated message map functions\n\nprotected:\n\n\t//{{AFX_MSG(CStaticEx)\n\n\tafx_msg void OnPaint();\n\n\tafx_msg void OnClicked();\n\n\tafx_msg void OnSize(UINT nType, int cx, int cy);\n\n\tafx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);\n\n\tafx_msg void OnMouseMove(UINT nFlags, CPoint point);\n\n\tafx_msg void OnSysColorChange();\n\n\t//}}AFX_MSG\n\n\n\n\tDECLARE_MESSAGE_MAP()\n\n};\n\n\n\n\n", "file_path": "code/StaticEx.h", "rank": 9, "score": 52681.37017883133 }, { "content": "\tvoid SetFontEx(LPCTSTR szFontName = \"Arial\", float sngFontSize = 8.0, BOOL bFontBold = FALSE, \n\n\t\t\t\t\t\tBOOL bFontItalic = FALSE);\n\n\tint SetWidthGetHeight(int nWidth);\n\n\n\n\n\n// Public Attributes\n\npublic:\n\n\tCOLORREF m_clrText;\n\n\tCOLORREF m_clrHighlight;\n\n\tCOLORREF m_clrBackground;\n\n\tCOLORREF m_clrBackground2;\n\n\tCRect m_rTextSize;\n\n\tenum eFlags {flagNone = 0, flagUnderline = 1};\n\n\n\n// Attributes\n\nprivate:\n\n\tBOOL m_bAutosize;\n\n\tBOOL m_bHighlight;\n\n\n\n\tint m_nCommandID;\n", "file_path": "code/StaticEx.h", "rank": 10, "score": 52678.233500889706 }, { "content": "class CDialogNewFile : public CDialog\n\n{\n\n// Construction\n\npublic:\n\n\tCDialogNewFile(CWnd* pParent = NULL); // standard constructor\n\n\n\n// Public Attributes\n\npublic:\n\n\tCImageList m_iml;\n\n\n\n// Dialog Data\n\n\t//{{AFX_DATA(CDialogNewFile)\n\n\tenum { IDD = IDD_NEW_FILE };\n\n\tCListCtrlEx\tm_lvw;\n\n\tCStatic\tm_lblInstructions;\n\n\t//}}AFX_DATA\n\n\n\n// Overrides\n\n\t// ClassWizard generated virtual function overrides\n\n\t//{{AFX_VIRTUAL(CDialogNewFile)\n", "file_path": "code/DialogNewFile.h", "rank": 11, "score": 52124.92318824641 }, { "content": "\n\n// CStaticEx\n\n\n\n\n\n\n\n#include \"precompiled.h\"\n\n#include \"NeoMem.h\"\n\n#include \"StaticEx.h\"\n\n\n\n\n\n#ifdef _DEBUG\n\n#define new DEBUG_NEW\n\n#undef THIS_FILE\n\nstatic char THIS_FILE[] = __FILE__;\n\n#endif\n\n\n\n\n\n\n\n/*\n\n//, could set different default tab stop - this is 1/2 inch\n", "file_path": "code/StaticEx.cpp", "rank": 12, "score": 50143.904673908415 }, { "content": "\tm_font.CreateStockObject(ANSI_VAR_FONT);\n\n\n\n\tm_nFlags = 0;\n\n}\n\n\n\nCStaticEx::~CStaticEx()\n\n{\n\n//\tif (m_nTimer)\n\n//\t\tKillTimer(m_nTimer);\n\n}\n\n\n\n\n\n\n\n//---------------------------------------------------------------------------------------------------------\n\n\n\n\n\nvoid CStaticEx::SetFontEx(LPCTSTR szFontName /* = \"Arial\" */, float sngFontSize /* = 8.0 */, \n\n\t\t\t\t\t\t\t\t\t\tBOOL bFontBold /* = FALSE */, BOOL bFontItalic /* = FALSE */)\n\n{\n\n\t// Create and set font\n", "file_path": "code/StaticEx.cpp", "rank": 13, "score": 50126.381737858894 }, { "content": "\n\n\n\n\n\nvoid CStaticEx::OnMouseMove(UINT nFlags, CPoint point) \n\n{\n\n\t//trace(\"CStaticEx::OnMouseMove %d %d\\n\", point.x, point.y);\n\n\n\n\t// Show status bar text if this label has it.\n\n\t// Gets status string from string table (resource ID should match command ID).\n\n\tif (m_nCommandID)\n\n\t{\n\n\t\tCString str;\n\n\t\tif (str.LoadString(m_nCommandID))\n\n\t\t\tapp.SetStatusBarText(str);\n\n\t\telse\n\n\t\t\tapp.SetStatusBarText();\n\n\t}\n\n\telse\n\n\t\tapp.SetStatusBarText();\n\n\tCStatic::OnMouseMove(nFlags, point);\n", "file_path": "code/StaticEx.cpp", "rank": 14, "score": 50126.139958952226 }, { "content": "\t// modify the right side of the rectangle so that it bounds the last character in the line. \n\n\t// In either case, DrawText returns the height of the formatted text, but does not draw the text.\n\n\tCString strText;\n\n\tGetWindowText(strText);\n\n\tCRect r;\n\n\tr.SetRect(0, 0, nWidth, 0);\n\n\tCFont* poldfont = dc.SelectObject(&m_font);\n\n//\tint nHeight = dc.DrawText(m_strText, r, m_nFormat | DT_CALCRECT);\n\n\tint nHeight = dc.DrawText(strText, r, m_nFormat | DT_CALCRECT);\n\n\tdc.SelectObject(poldfont);\n\n\n\n\treturn nHeight;\n\n}\n\n\n\n\n\n\n\nvoid CStaticEx::OnClicked() \n\n{\n\n\t//trace(\"CStaticEx::OnClicked\\n\");\n\n\tif (m_nCommandID)\n", "file_path": "code/StaticEx.cpp", "rank": 15, "score": 50125.43827876348 }, { "content": "\t}\n\n\n\n\t// Draw text\n\n\tCFont* poldfont = dc.SelectObject(&m_font);\n\n//\tdc.DrawText(m_strText, m_rDraw, m_nFormat);\n\n\tCString strText;\n\n\tGetWindowText(strText);\n\n\tdc.DrawText(strText, m_rDraw, m_nFormat);\n\n\tdc.SelectObject(poldfont);\n\n\n\n\t// Draw underline if specified\n\n\tif (m_nFlags && flagUnderline)\n\n\t{\n\n\t\tint x = m_rControlSize.right;\n\n\t\tint y = m_rControlSize.bottom;\n\n//\t\tCPen* pPen = new CPen(PS_SOLID, 0, m_clrText);\n\n\t\tCPen* pPen = new CPen(PS_SOLID, 0, clrForeground);\n\n\t\tCPen* pOldPen = dc.SelectObject(pPen);\n\n\t\tdc.MoveTo(0, y);\n\n\t\tdc.LineTo(x, y);\n", "file_path": "code/StaticEx.cpp", "rank": 16, "score": 50125.138921749014 }, { "content": "\t\tdc.SelectObject(pOldPen);\n\n\t\tdelete pPen;\n\n\t}\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nBOOL CStaticEx::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) \n\n{\n\n\tif (m_hCursor)\n\n\t{\n\n\t\t::SetCursor(m_hCursor);\n\n\t\treturn TRUE;\n\n\t}\n\n\n\n\treturn CStatic::OnSetCursor(pWnd, nHitTest, message);\n\n}\n", "file_path": "code/StaticEx.cpp", "rank": 17, "score": 50125.01528582438 }, { "content": "\t{\n\n\t\tCWaitCursor cw;\n\n\t\tGetParent()->SendMessage(WM_COMMAND, m_nCommandID);\n\n\t}\n\n}\n\n\n\n\n\nBOOL CStaticEx::OnCommand(WPARAM wParam, LPARAM lParam) \n\n{\n\n\t// On receiving a command, pass it on to this label's parent, as\n\n\t// it might have a child label which is sending it this message.\n\n\tGetParent()->SendMessage(WM_COMMAND, wParam);\n\n\treturn TRUE; // message has been processed\n\n\n\n//\treturn CStatic::OnCommand(wParam, lParam);\n\n}\n\n\n\n\n\n\n\nvoid CStaticEx::OnSysColorChange() \n\n{\n\n\tCStatic::OnSysColorChange();\n\n\t\n\n\t// TODO: Add your message handler code here\n\n\t\t\n\n}\n\n\n\n\n", "file_path": "code/StaticEx.cpp", "rank": 18, "score": 50124.55200349405 }, { "content": "// ideally, let user pick one\n\n// unless...\n\n// could read default font info here\n\n\tCString strPrefix = \n\n\t\t\"{\\\\rtf1\\\\ansi\\\\deff0\\\\deftab720\\\\deflang1033\"\n\n\t\t\"{\\\\fonttbl{\\\\f0\\\\fswiss Tahoma;}}\\n\"\n\n\t\t\"{\\\\colortbl\\\\red0\\\\green0\\\\blue0;}\\n\"\n\n\t\t\"\\\\pard\"\n\n//\t\t\"\\\\tx360\\\\tx720\\\\tx1080\\\\tx1440\\\\tx1800\\\\tx2160\\\\tx2520\\\\tx2880\\\\tx3240\\\\tx3600\\\\tx3960\\\\tx4320\\\\tx4680\\\\tx5040\\\\tx5400\\\\tx5760\\\\tx6120\\\\tx6480\"\n\n\t\t\"\\\\plain\\\\f0\\\\fs16 \"; // fs16 means to use 8 pt font!\n\n*/\n\n\n\n\n\n\n\n\n\n//---------------------------------------------------------------------------------------------------------\n\n\n\n\n\nBEGIN_MESSAGE_MAP(CStaticEx, CStatic)\n\n\t//{{AFX_MSG_MAP(CStaticEx)\n", "file_path": "code/StaticEx.cpp", "rank": 19, "score": 50123.89815171414 }, { "content": "{\n\n\t// Get background drawing mode\n\n\tm_bOpaque = bOpaque;\n\n\tm_nBkMode = m_bOpaque ? OPAQUE : TRANSPARENT;\n\n\n\n\t// Get colors\n\n//\tm_clrText = (clrText == -1) ? ::GetSysColor(COLOR_TEXT) : clrText;\n\n//\tm_clrBackground = (clrBackground == -1) ? ::GetSysColor(COLOR_WINDOW) : clrBackground;\n\n//\tm_clrHighlight = (clrHighlight == -1) ? ::GetSysColor(COLOR_HIGHLIGHTTEXT) : clrHighlight;\n\n//\tm_clrBackground2 = (clrBackground2 == -1) ? ::GetSysColor(COLOR_TEXT) : clrText;\n\n\n\n}\n\n\n\n\n\nBOOL CStaticEx::Create(\t\t\n\n\t\t\t\t\t\t\t\t\t\t\tLPCTSTR szText, \n\n\t\t\t\t\t\t\t\t\t\t\tCRect &r, \n\n\t\t\t\t\t\t\t\t\t\t\tCWnd* pParentWnd, \n\n\t\t\t\t\t\t\t\t\t\t\tUINT nCommandID /* = 0 */, \n\n\t\t\t\t\t\t\t\t\t\t\tBOOL bAutosize /* = TRUE */, \n", "file_path": "code/StaticEx.cpp", "rank": 20, "score": 50122.64591522046 }, { "content": "\t\t\t\t\t\t\t\t\t\t\tUINT nFormat /* = DT_LEFT | DT_BOTTOM */,\n\n\t\t\t\t\t\t\t\t\t\t\tUINT nFlags /* = 0 */\n\n\t\t\t\t\t\t\t\t\t\t)\n\n{\n\n\t// Call base class to create window\n\n\tif (!CStatic::Create(szText, WS_CHILD | WS_VISIBLE | SS_NOTIFY, r, pParentWnd, nCommandID))\n\n//\tif (!CStatic::Create(szText, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | SS_NOTIFY, r, pParentWnd, nCommandID))\n\n\t\treturn FALSE;\n\n\n\n\t// Save parameters\n\n//\tm_strText = szText;\n\n\tm_nCommandID = nCommandID;\n\n\tm_bAutosize = bAutosize;\n\n\tif (nFormat & DT_TOP || nFormat & DT_BOTTOM || nFormat & DT_VCENTER)\n\n\t\tnFormat |= DT_SINGLELINE;\n\n\tm_nFormat = nFormat;\n\n\n\n\t// If font has not been specified yet, use the default font\n\n//\tif (m_font.m_hObject == 0)\n\n//\t\tm_font.CreateStockObject(ANSI_VAR_FONT);\n", "file_path": "code/StaticEx.cpp", "rank": 21, "score": 50122.30993416597 }, { "content": "}\n\n\n\n\n\n\n\n\n\n// Set the width of the label and get the height necessary to fit all the text\n\nint CStaticEx::SetWidthGetHeight(int nWidth)\n\n{\n\n\tCClientDC dc(this);\n\n\n\n//\tCSize sz = dc.GetTextExtent(m_strHeader);\n\n//\tCSize sz = dc.GetTextExtent(\"OP\", 2);\n\n//\tm_nHeaderHeight = (int) ((float) sz.cy * 1.2f); // 30\n\n//\tCSize sz = dc.GetTextExtent(m_strText);\n\n//\tint y = (r.bottom - sz.cy) / 2;\n\n\n\n\t// Get height using DrawText\n\n\t// DT_CALCRECT Determines the width and height of the rectangle. If there are multiple lines of \n\n\t// text, DrawText will use the width of the rectangle pointed to by lpRect and extend the base \n\n\t// of the rectangle to bound the last line of text. If there is only one line of text, DrawText will \n", "file_path": "code/StaticEx.cpp", "rank": 22, "score": 50122.02648918308 }, { "content": "\tVERIFY(m_font.DeleteObject()); // delete existing font\n\n\tint nPointSizeTimes10 = (int) (sngFontSize * 10);\n\n\tVERIFY(m_font.CreatePointFont2(nPointSizeTimes10, szFontName, bFontBold, bFontItalic));\n\n//\tLOGFONT lf;\n\n//\tm_font.GetLogFont(&lf);\n\n\t// Set font if window has been created\n\n\tif (::IsWindow(m_hWnd))\n\n\t\tSetFont(&m_font);\n\n}\n\n\n\n\n\nvoid CStaticEx::SetColors(BOOL bOpaque /* = TRUE */\n\n//\t\t\t\t\t\t\t\t\t\tint nText /* = COLOR_TEXT */\n\n//\t\t\t\t\t\t\t\t\t\tint nTextBack /* = COLOR_3DFACE */\n\n//\t\t\t\t\t\t\t\t\t\tint nHot /* = \n\n//\t\t\t\t\t\t\t\t\t\tCOLORREF clrText /* = -1 */\n\n//\t\t\t\t\t\t\t\t\t\tCOLORREF clrBackground /* = -1 */\n\n//\t\t\t\t\t\t\t\t\t\tCOLORREF clrHighlight /* = -1 */\n\n//\t\t\t\t\t\t\t\t\t\tCOLORREF clrBackground2 /* = -1 */\n\n\t\t\t\t\t\t\t\t\t\t)\n", "file_path": "code/StaticEx.cpp", "rank": 23, "score": 50121.17058353848 }, { "content": "\tON_WM_PAINT()\n\n\tON_CONTROL_REFLECT(BN_CLICKED, OnClicked)\n\n\tON_WM_SIZE()\n\n\tON_WM_SETCURSOR()\n\n\tON_WM_MOUSEMOVE()\n\n\tON_WM_SYSCOLORCHANGE()\n\n\t//}}AFX_MSG_MAP\n\nEND_MESSAGE_MAP()\n\n\n\n\n\n\n\n\n\nCStaticEx::CStaticEx()\n\n{\n\n\tm_bAutosize = TRUE;\n\n//\tm_bHighlight = FALSE;\n\n\n\n\tm_nCommandID = 0;\n\n\n\n\tm_bOpaque = TRUE;\n", "file_path": "code/StaticEx.cpp", "rank": 24, "score": 50120.36970334684 }, { "content": "\t}\n\n\n\n\t// Save flags\n\n\tm_nFlags = nFlags;\n\n\n\n\treturn TRUE;\n\n}\n\n\n\n\n\n\n\n\n\nvoid CStaticEx::OnSize(UINT nType, int cx, int cy) \n\n{\n\n\tCStatic::OnSize(nType, cx, cy);\n\n\t\n\n\t// Save width and height of control\n\n\tm_rControlSize.SetRect(0, 0, cx, cy);\n\n\n\n\tm_rDraw = m_rControlSize;\n\n\tm_rDraw.DeflateRect(&m_rMargins);\n", "file_path": "code/StaticEx.cpp", "rank": 25, "score": 50120.244323402236 }, { "content": "\tSetFont(&m_font, FALSE);\n\n\n\n\t// Get size of text\n\n\tCString strText = szText;\n\n\tCDC* pdc = GetDC();\n\n//\tCSize sz = pdc->GetTextExtent(m_strText);\n\n\tCSize sz = pdc->GetTextExtent(strText);\n\n\tm_rTextSize.SetRect(0, 0, sz.cx, sz.cy);\n\n\n\n\t// Get size and position\n\n\tif (m_bAutosize)\n\n\t{\n\n\t\tm_rMargins.SetRect(0, 0, 0, 0);\n\n\t\tm_rControlSize = m_rTextSize + m_rMargins;\n\n\t\t// Set window width and height\n\n\t\t// this will trigger OnSize\n\n\t\tSetWindowPos(0, 0, 0, m_rControlSize.right, m_rControlSize.bottom, SWP_NOMOVE | SWP_NOZORDER);\n\n//\t\tm_rDraw = m_rControlSize;\n\n\t}\n\n\telse\n", "file_path": "code/StaticEx.cpp", "rank": 26, "score": 50119.96502846489 }, { "content": "\n\n}\n\n\n\n\n\n\n\nvoid CStaticEx::OnPaint() \n\n{\n\n\t// Do not call CStatic::OnPaint() for painting messages\n\n\tCPaintDC dc(this); // device context for painting\n\n\n\n\tCOLORREF clrBackground = (m_clrBackground == -1) ? Library::clrWindow : m_clrBackground;\n\n\tCOLORREF clrForeground = (m_clrText == -1) ? Library::clrWindowText : m_clrText;\n\n\n\n//\tdc.SetTextColor(m_clrText);\n\n//\tdc.SetBkColor(m_clrBackground);\n\n\tdc.SetTextColor(clrForeground);\n\n\tdc.SetBkColor(clrBackground);\n\n//\tdc.SetBkMode(m_nBkMode); // opaque or transparent, for drawtext\n\n\tdc.SetBkMode(TRANSPARENT); \n\n\n", "file_path": "code/StaticEx.cpp", "rank": 27, "score": 50119.27086508285 }, { "content": "\t// Fill background if in opaque mode\n\n//\tif (m_bOpaque)\n\n\tif (m_clrBackground != -1)\n\n\t{\n\n\t\tdc.FillSolidRect(m_rControlSize, m_clrBackground);\n\n\t}\n\n\n\n\t// Fill with even line color also if specified\n\n\tif (m_clrBackground2 != -1)\n\n\t{\n\n\t\t// walk through and color even lines\n\n\t\tCPen* pPen = new CPen(PS_SOLID, 0, m_clrBackground2);\n\n\t\tCPen* pOldPen = dc.SelectObject(pPen);\n\n\t\tfor (int y = 0; y < m_rControlSize.bottom; y += 2)\n\n\t\t{\n\n\t\t\tdc.MoveTo(0, y);\n\n\t\t\tdc.LineTo(m_rControlSize.right, y);\n\n\t\t}\n\n\t\tdc.SelectObject(pOldPen);\n\n\t\tdelete pPen;\n", "file_path": "code/StaticEx.cpp", "rank": 28, "score": 50118.07958477511 }, { "content": "\n\n// CDialogNewFile\n\n// This dialog will let the user create a new file based on a selected template, etc.\n\n//-----------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n#pragma once\n\n\n\n\n\n#include \"ListCtrlEx.h\"\n\n#include \"resource.h\"\n\n\n\n\n", "file_path": "code/DialogNewFile.h", "rank": 29, "score": 50114.39733886005 }, { "content": "\t{\n\n//\t\tm_rDraw.SetRect(m_rMargins.left, m_rMargins.top, m_rTextSize.right + m_rMargins.left + m_rMargins.right,\n\n//\t\t\t\t\t\t\t\t\tm_rTextSize.bottom + m_rMargins.top + m_rMargins.bottom);\n\n\t}\n\n\n\n\t// Turn on highlight timer\n\n\t//...... better if we just have one global timer that checks if mouse is over same window\n\n\t// otherwise would bog program down\n\n\t//. actually could start the timer when mouse moves over label, if one hasn't already been started,\n\n\t// and if at the timeout period the mouse is no longer over the label, unhighlight it\n\n//\tif (m_nCommand)\n\n//\t{\n\n//\t\tm_nTimer = SetTimer(\n\n//\t}\n\n\n\n\t// Use hand cursor if command ID specified (ie it's a button)\n\n\tif (m_nCommandID)\n\n\t{\n\n//\t\tm_hCursor = AfxGetApp()->LoadCursor(IDC_CURSOR_HAND);\n\n\t\tm_hCursor = app.m_hCursorHand;\n", "file_path": "code/StaticEx.cpp", "rank": 30, "score": 50114.35624263255 }, { "content": "\tm_nBkMode = OPAQUE;\n\n//\tm_clrText = ::GetSysColor(COLOR_WINDOWTEXT);\n\n//\tm_clrBackground = ::GetSysColor(COLOR_3DFACE);\n\n//\tm_clrText = g_clrWindowText;\n\n\tm_clrText = -1; // use windows system color\n\n//\tm_clrBackground = g_clr3dFace;\n\n\tm_clrBackground = -1; // none\n\n\tm_clrBackground2 = -1; // none\n\n//\tm_clrHighlight = ::GetSysColor(COLOR_HIGHLIGHT);\n\n//\tm_clrHighlight = g_clrHighlight;\n\n\tm_clrHighlight = -1; // use windows system color\n\n\n\n\tm_hCursor = 0;\n\n\tm_nSound = 0;\n\n\tm_nTimer = 0;\n\n\tm_rMargins.SetRect(2, 1, 2, 1);\n\n\tm_rPos.SetRectEmpty();\n\n\tm_rTextSize.SetRectEmpty();\n\n//\tm_rDraw.SetRectEmpty();\n\n\n", "file_path": "code/StaticEx.cpp", "rank": 31, "score": 50114.35624263255 }, { "content": "\tprotected:\n\n\tvirtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n\n\t//}}AFX_VIRTUAL\n\n\n\n// Implementation\n\nprotected:\n\n\t// Generated message map functions\n\n\t//{{AFX_MSG(CDialogNewFile)\n\n\tvirtual BOOL OnInitDialog();\n\n\t//}}AFX_MSG\n\n\tDECLARE_MESSAGE_MAP()\n\n};\n\n\n", "file_path": "code/DialogNewFile.h", "rank": 32, "score": 50110.82382506631 }, { "content": "class CDialogNewLinkSource : public CDialog\n\n{\n\n// Construction\n\npublic:\n\n\tCDialogNewLinkSource(CWnd* pParent = NULL); // standard constructor\n\n\n\n// Public Attributes\n\npublic:\n\n\tBDoc* m_pDoc;\n\n\n\n\tULONG m_lngClassID; // [out]\n\n\tCString m_strFolderName; // [out]\n\n\n\n// Dialog Data\n\n\t//{{AFX_DATA(CDialogNewLinkSource)\n\n\tenum { IDD = IDD_NEW_LINK_SOURCE };\n\n\tCButton\tm_btnHelp;\n\n\tCEdit\tm_txtFolderName;\n\n\tCStatic\tm_lblFolder;\n\n\tCStatic\tm_lblClass;\n", "file_path": "code/DialogNewLinkSource.h", "rank": 33, "score": 49618.44487454444 }, { "content": "\n\n// CDialogNewFile\n\n\n\n\n\n#include \"precompiled.h\"\n\n\n\n#include \"NeoMem.h\"\n\n#include \"DialogNewFile.h\"\n\n\n\n#include \"BDoc.h\"\n\n\n\n\n\n#ifdef _DEBUG\n\n#define new DEBUG_NEW\n\n#undef THIS_FILE\n\nstatic char THIS_FILE[] = __FILE__;\n\n#endif\n\n\n\n\n\n\n", "file_path": "code/DialogNewFile.cpp", "rank": 34, "score": 47810.61940761378 }, { "content": "\n\n// CDialogNewLinkSource\n\n// This dialog lets the user create a new Link Source folder.\n\n//-----------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\n#pragma once\n\n\n\n\n\n#include \"resource.h\"\n\n#include \"XComboBoxEx.h\"\n", "file_path": "code/DialogNewLinkSource.h", "rank": 35, "score": 47794.48142705669 }, { "content": "\t\n\n\t// Fill listview with files in the Templates folder\n\n\tCFileFind ff;\n\n\tBOOL bWorking = ff.FindFile(\"*.neo\"); //, get from string table\n\n\tint nItem = 0;\n\n\twhile (bWorking)\n\n\t{\n\n\t\tbWorking = ff.FindNextFile();\n\n\t\tCString strName = ff.GetFileName();\n\n\t\tm_lvw.InsertItem(nItem, strName, nImage);\n\n\t\tnItem++;\n\n\t}\n\n\n\n\n\n\treturn TRUE; // return TRUE unless you set the focus to a control\n\n\t // EXCEPTION: OCX Property Pages should return FALSE\n\n}\n\n\n\n\n\nvoid CDialogNewFile::DoDataExchange(CDataExchange* pDX)\n\n{\n\n\tCDialog::DoDataExchange(pDX);\n\n\t//{{AFX_DATA_MAP(CDialogNewFile)\n\n\tDDX_Control(pDX, IDC_LVW, m_lvw);\n\n\tDDX_Control(pDX, IDC_INSTRUCTIONS, m_lblInstructions);\n\n\t//}}AFX_DATA_MAP\n\n}\n\n\n", "file_path": "code/DialogNewFile.cpp", "rank": 36, "score": 47793.71968428165 }, { "content": "\n\nBEGIN_MESSAGE_MAP(CDialogNewFile, CDialog)\n\n\t//{{AFX_MSG_MAP(CDialogNewFile)\n\n\t//}}AFX_MSG_MAP\n\nEND_MESSAGE_MAP()\n\n\n\n\n\nCDialogNewFile::CDialogNewFile(CWnd* pParent /*=NULL*/)\n\n\t: CDialog(CDialogNewFile::IDD, pParent)\n\n{\n\n\t//{{AFX_DATA_INIT(CDialogNewFile)\n\n\t\t// NOTE: the ClassWizard will add member initialization here\n\n\t//}}AFX_DATA_INIT\n\n}\n\n\n\n\n\n\n\nBOOL CDialogNewFile::OnInitDialog() \n\n{\n\n\t// Call base class\n", "file_path": "code/DialogNewFile.cpp", "rank": 37, "score": 47792.159253480124 }, { "content": "\tCButton\tm_btnNewClass;\n\n\tXComboBoxEx m_cboClass;\n\n\t//}}AFX_DATA\n\n\n\n// Overrides\n\n\t// ClassWizard generated virtual function overrides\n\n\t//{{AFX_VIRTUAL(CDialogNewLinkSource)\n\n\tprotected:\n\n\tvirtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n\n\t//}}AFX_VIRTUAL\n\n\n\n// Implementation\n\nprotected:\n\n\t// Generated message map functions\n\n\t//{{AFX_MSG(CDialogNewLinkSource)\n\n\tvirtual BOOL OnInitDialog();\n\n\tafx_msg void OnBtnNewClass();\n\n\tafx_msg void OnSelChangeCboClass();\n\n\tafx_msg void OnBtnHelp();\n\n\tvirtual void OnOK();\n\n\t//}}AFX_MSG\n\n\tDECLARE_MESSAGE_MAP()\n\n};\n\n\n\n\n\n\n", "file_path": "code/DialogNewLinkSource.h", "rank": 38, "score": 47790.870803112266 }, { "content": "\tCDialog::OnInitDialog();\n\n\n\n\t// Get document\n\n//\tm_pDoc = BDoc::GetDoc();\n\n//\tASSERT_VALID(m_pDoc);\n\n\n\n\t// Set image list\n\n//\tCImageList* pImageList = m_pDoc->GetImageList();\n\n//\tASSERT_VALID(pImageList);\n\n//\tm_lvw.SetImageList(pImageList, LVSIL_SMALL);\n\n//\tm_lvw.SetImageList(app.GetImageList(), LVSIL_NORMAL);\n\n\n\n\t// Create image list containing file icon\n\n\tm_iml.Create(32, 32, ILC_MASK | ILC_COLOR24, 1, 1);\n\n\tint nImage = m_iml.Add(app.LoadIcon(IDR_NEOMEM_TYPE));\n\n\n\n\tm_lvw.SetImageList(&m_iml, LVSIL_NORMAL);\n\n\n\n\t// Switch to large icon view\n\n\tm_lvw.ModifyStyle(LVS_REPORT, LVS_ICON);\n", "file_path": "code/DialogNewFile.cpp", "rank": 39, "score": 47781.522414535575 }, { "content": "#undef THIS_FILE\n\nstatic char THIS_FILE[] = __FILE__;\n\n#endif\n\n\n\n\n\n\n\n\n\nBEGIN_MESSAGE_MAP(CDialogNewLinkSource, CDialog)\n\n\t//{{AFX_MSG_MAP(CDialogNewLinkSource)\n\n\tON_BN_CLICKED(IDC_BTN_NEW_CLASS, OnBtnNewClass)\n\n\tON_CBN_SELCHANGE(IDC_CBO_CLASS, OnSelChangeCboClass)\n\n\tON_BN_CLICKED(IDC_BTN_HELP, OnBtnHelp)\n\n\t//}}AFX_MSG_MAP\n\nEND_MESSAGE_MAP()\n\n\n\n\n\n\n\nCDialogNewLinkSource::CDialogNewLinkSource(CWnd* pParent /*=NULL*/)\n\n\t: CDialog(CDialogNewLinkSource::IDD, pParent)\n\n{\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 40, "score": 45684.10723698261 }, { "content": "\n\n// CDialogNewLinkSource\n\n\n\n\n\n\n\n#include \"precompiled.h\"\n\n\n\n#include \"DialogNewLinkSource.h\"\n\n#include \"DialogEditName.h\"\n\n#include \"NeoMem.h\"\n\n#include \"Constants.h\"\n\n#include \"HelpIDs.h\"\n\n\n\n#include \"ConstantsDatabase.h\"\n\n#include \"BDoc.h\"\n\n\n\n\n\n\n\n#ifdef _DEBUG\n\n#define new DEBUG_NEW\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 41, "score": 45681.47134923341 }, { "content": "\t\tm_txtFolderName.GetWindowText(m_strFolderName);\n\n\t}\n\n\n\n}\n\n\n\n\n\n\n\n\n\n// Add a new class (just need name really)\n\nvoid CDialogNewLinkSource::OnBtnNewClass() \n\n{\n\n\tCDialogEditName dlg;\n\n\tdlg.m_strCaption = _T(\"Add Link Class\");\n\n\tdlg.m_strInstructions = _T(\"Enter the name for the new link class:\");\n\n\tdlg.m_strName = _T(\"New Link Class\");\n\n\tif (dlg.DoModal() == IDOK)\n\n\t{\n\n\t\t// Create the new class\n\n//\t\tCString strClassName = dlg.m_strName;\n\n//\t\tHOBJECT hobjNewClass = m_pDoc->CreateClass(strClassName);\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 42, "score": 45680.803799805115 }, { "content": "// or just let user type it all in themselves for now\n\nvoid CDialogNewLinkSource::OnSelChangeCboClass() \n\n{\n\n}\n\n\n\n\n\n\n\n\n\n// Bring up help for this dialog\n\nvoid CDialogNewLinkSource::OnBtnHelp() \n\n{\n\n\tapp.WinHelp(HID_BASE_RESOURCE + IDD_NEW_LINK_SOURCE);\n\n}\n\n\n\n\n\nvoid CDialogNewLinkSource::OnOK() \n\n{\n\n\tm_txtFolderName.GetWindowText(m_strFolderName);\n\n\tm_strFolderName.TrimLeft();\n\n\tif (m_strFolderName.IsEmpty())\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 43, "score": 45679.32647048191 }, { "content": "\t//{{AFX_DATA_INIT(CDialogNewLinkSource)\n\n\t\t// NOTE: the ClassWizard will add member initialization here\n\n\t//}}AFX_DATA_INIT\n\n}\n\n\n\n\n\n\n\n\n\nBOOL CDialogNewLinkSource::OnInitDialog() \n\n{\n\n\t// Call base class (calls DoDataExchange)\n\n\tCDialog::OnInitDialog();\n\n\n\n\t// Get document\n\n\tm_pDoc = BDoc::GetDoc();\n\n\n\n\t// Set bold font\n\n\tm_lblClass.SetFont(&app.m_fontControlsBold);\n\n\tm_lblFolder.SetFont(&app.m_fontControlsBold);\n\n\t\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 44, "score": 45675.85160004911 }, { "content": "\n\n\t\tBObject& objClass = BObject::New(*m_pDoc, classClass, dlg.m_strName, rootClass);\n\n\n\n//,\t\tobjClass.SetPropertyString(propDescription, strDescription, FALSE, FALSE);\n\n\n\n\t\t// Add to combo and select it\n\n\t\t//. test\n\n\t\tBObject* pobjParent = objClass.GetParent();\n\n\t\tint nItem = m_cboClass.AddObject(&objClass, pobjParent);\n\n\t\tm_cboClass.SetCurSel(nItem);\n\n\t}\n\n\n\n\t// Set focus back to combo\n\n\tm_cboClass.SetFocus();\n\n}\n\n\n\n\n\n\n\n// Different class selected - modify the folder name if not already modified by user.\n\n// Eg for class Category, folder name would be Categorys (just add an s to the end).\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 45, "score": 45675.16409182394 }, { "content": "\t{\n\n\t\tAfxMessageBox(\"Please enter a name for the new folder.\", MB_ICONINFORMATION);\n\n\t\tm_txtFolderName.SetFocus();\n\n\t}\n\n\telse\n\n\t{\n\n\t\tCDialog::OnOK();\n\n\t}\n\n}\n\n\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 46, "score": 45672.20946745344 }, { "content": "\t//{{AFX_DATA_MAP(CDialogNewLinkSource)\n\n\tDDX_Control(pDX, IDC_BTN_HELP, m_btnHelp);\n\n\tDDX_Control(pDX, IDC_TXT_FOLDER_NAME, m_txtFolderName);\n\n\tDDX_Control(pDX, IDC_LBL_FOLDER, m_lblFolder);\n\n\tDDX_Control(pDX, IDC_LBL_CLASS, m_lblClass);\n\n\tDDX_Control(pDX, IDC_BTN_NEW_CLASS, m_btnNewClass);\n\n\tDDX_Control(pDX, IDC_CBO_CLASS, m_cboClass);\n\n\t//}}AFX_DATA_MAP\n\n\t\n\n\tif (!pDX->m_bSaveAndValidate) // Load\n\n\t{\n\n\t}\n\n\telse // Save\n\n\t{\n\n\t\t// Get class\n\n\t\tBObject* pobjClass = (BObject*) m_cboClass.GetSelectedItemData();\n\n\t\tASSERT_VALID(pobjClass);\n\n\t\tm_lngClassID = pobjClass->GetObjectID();\n\n\n\n\t\t// Get folder name\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 47, "score": 45672.17352787508 }, { "content": "\t// Fill combo with classes\n\n\tm_cboClass.SetImageList(m_pDoc->GetImageList());\n\n\tBObject* pobjClassFolder = m_pDoc->GetObject(rootClass);\n\n\tm_cboClass.AddObjects(pobjClassFolder, app.m_lngExcludeFlags, FALSE, TRUE);\n\n\t\n\n\t// Select default class (paper)\n\n\tBObject* pobjDefaultClass = m_pDoc->GetObject(classPaper);\n\n\tm_cboClass.SelectItemData((DWORD) pobjDefaultClass);\n\n\n\n\tm_txtFolderName.SetWindowText(\"New Folder\");\n\n\n\n\treturn TRUE; // return TRUE unless you set the focus to a control\n\n\t // EXCEPTION: OCX Property Pages should return FALSE\n\n}\n\n\n\n\n\n\n\nvoid CDialogNewLinkSource::DoDataExchange(CDataExchange* pDX)\n\n{\n\n\tCDialog::DoDataExchange(pDX);\n", "file_path": "code/DialogNewLinkSource.cpp", "rank": 48, "score": 45671.4246599159 }, { "content": "#define ID_STATIC 65535\n", "file_path": "resources/resource.h", "rank": 49, "score": 43742.69079776813 }, { "content": "#include \"resource.h\"\n\n#include \"XComboBoxEx.h\"\n\nclass BDoc;\n\n\n\n\n", "file_path": "code/DialogNewLinkSource.h", "rank": 50, "score": 43738.53369520699 }, { "content": "#define IDI_NEW 730\n", "file_path": "resources/resource.h", "rank": 51, "score": 43731.48036274369 }, { "content": "; Alias File written automatically by HHPMod Version 3.2.2\n", "file_path": "help/NewAliases.h", "rank": 52, "score": 43731.48036274369 }, { "content": "; Alias File written automatically by HHPMod Version 3.2.2\n", "file_path": "help/NewAliases.h", "rank": 53, "score": 43731.48036274369 }, { "content": "; Automatic aliases for normal topics ;;;;;;;;;;;;;;;;;;;;;;;;;;\n", "file_path": "help/NewAliases.h", "rank": 54, "score": 43731.48036274369 }, { "content": "#define HIDD_ABOUT 0x20064\n", "file_path": "help/HTMLDefines.h", "rank": 55, "score": 43474.566807497285 }, { "content": "#define HID_WHAT_IS_THIS 0x18052\n", "file_path": "help/HTMLDefines.h", "rank": 56, "score": 43474.566807497285 }, { "content": "#define IDC_OPT_NEW 1163\n", "file_path": "resources/resource.h", "rank": 57, "score": 41953.45761490886 }, { "content": "; Alias File written automatically by HHPMod Version 3.2.2\n", "file_path": "help/NewAliases.h", "rank": 58, "score": 41953.45761490886 }, { "content": "#define IDD_NEW_FILE 798\n", "file_path": "resources/resource.h", "rank": 59, "score": 41953.45761490886 }, { "content": "#define IDC_BTN_NEW 1101\n", "file_path": "resources/resource.h", "rank": 60, "score": 41953.45761490886 }, { "content": "ULONG const iconNew = 5015; // new row icon (triangle) used in contents view\n", "file_path": "code/ConstantsDatabase.h", "rank": 61, "score": 41953.45761490886 }, { "content": "#define HIDR_FORV2 0x203B4\n", "file_path": "help/HTMLDefines.h", "rank": 62, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50037 0x1C375\n", "file_path": "help/HTMLDefines.h", "rank": 63, "score": 41706.98958178213 }, { "content": "#define HID_CANCEL 0x1807D\n", "file_path": "help/HTMLDefines.h", "rank": 64, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50196 0x1C414\n", "file_path": "help/HTMLDefines.h", "rank": 65, "score": 41706.98958178213 }, { "content": "#define HID_NAVIGATE_UP 0x180E9\n", "file_path": "help/HTMLDefines.h", "rank": 66, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50181 0x1C405\n", "file_path": "help/HTMLDefines.h", "rank": 67, "score": 41706.98958178213 }, { "content": "#define HID_SYMBOL_2 0x1C3BD\n", "file_path": "help/HTMLDefines.h", "rank": 68, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50199 0x1C417\n", "file_path": "help/HTMLDefines.h", "rank": 69, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50145 0x1C3E1\n", "file_path": "help/HTMLDefines.h", "rank": 70, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50198 0x1C416\n", "file_path": "help/HTMLDefines.h", "rank": 71, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50149 0x1C3E5\n", "file_path": "help/HTMLDefines.h", "rank": 72, "score": 41706.98958178213 }, { "content": "#define HIDR_DIALOG_ABOUT 0x203BF\n", "file_path": "help/HTMLDefines.h", "rank": 73, "score": 41706.98958178213 }, { "content": "#define HIDR_COMPANY 0x200CA\n", "file_path": "help/HTMLDefines.h", "rank": 74, "score": 41706.98958178213 }, { "content": "#define HID_SYMBOL_1 0x1C36D\n", "file_path": "help/HTMLDefines.h", "rank": 75, "score": 41706.98958178213 }, { "content": "#define HIDR_OPTIONS 0x203C0\n", "file_path": "help/HTMLDefines.h", "rank": 76, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50029 0x1C36D\n", "file_path": "help/HTMLDefines.h", "rank": 77, "score": 41706.98958178213 }, { "content": "#define HID_TAB_ABOUT 0x1C409\n", "file_path": "help/HTMLDefines.h", "rank": 78, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50041 0x1C379\n", "file_path": "help/HTMLDefines.h", "rank": 79, "score": 41706.98958178213 }, { "content": "#define HID_TEST 0x1C3C1\n", "file_path": "help/HTMLDefines.h", "rank": 80, "score": 41706.98958178213 }, { "content": "#define HIDR_SYSTRAY 0x203B3\n", "file_path": "help/HTMLDefines.h", "rank": 81, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50148 0x1C3E4\n", "file_path": "help/HTMLDefines.h", "rank": 82, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50147 0x1C3E3\n", "file_path": "help/HTMLDefines.h", "rank": 83, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50197 0x1C415\n", "file_path": "help/HTMLDefines.h", "rank": 84, "score": 41706.98958178213 }, { "content": "#define HID_HELP_WHAT_IS 0x1C3AA\n", "file_path": "help/HTMLDefines.h", "rank": 85, "score": 41706.98958178213 }, { "content": "#define HID_ACCEL50200 0x1C418\n", "file_path": "help/HTMLDefines.h", "rank": 86, "score": 41706.98958178213 }, { "content": "#define HIDR_WHAT_IS_THIS_MENU 0x200FB\n", "file_path": "help/HTMLDefines.h", "rank": 87, "score": 41706.98958178213 }, { "content": "#define HIDR_OBSOLETE 0x200CC\n", "file_path": "help/HTMLDefines.h", "rank": 88, "score": 41706.98958178213 }, { "content": "#define HIDR_ACCELERATOR1 0x200D0\n", "file_path": "help/HTMLDefines.h", "rank": 89, "score": 41706.98958178213 }, { "content": "#define HIDD_ERROR 0x2006B\n", "file_path": "help/HTMLDefines.h", "rank": 90, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50030 0x1C36E\n", "file_path": "help/HTMLDefines.h", "rank": 91, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50146 0x1C3E2\n", "file_path": "help/HTMLDefines.h", "rank": 92, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50059 0x1C38B\n", "file_path": "help/HTMLDefines.h", "rank": 93, "score": 41706.98958178213 }, { "content": "#define HIDR_TEXTFILE1 0x20306\n", "file_path": "help/HTMLDefines.h", "rank": 94, "score": 41706.98958178213 }, { "content": "#define HIDR_TOOLBAR_OTHER 0x203AE\n", "file_path": "help/HTMLDefines.h", "rank": 95, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50144 0x1C3E0\n", "file_path": "help/HTMLDefines.h", "rank": 96, "score": 41706.98958178213 }, { "content": "#define HIDR_MAINFRAME 0x200C8\n", "file_path": "help/HTMLDefines.h", "rank": 97, "score": 41706.98958178213 }, { "content": "#define HID_NAVIGATE_DOWN 0x180EA\n", "file_path": "help/HTMLDefines.h", "rank": 98, "score": 41706.98958178213 }, { "content": "#define HID_BUTTON50153 0x1C3E9\n", "file_path": "help/HTMLDefines.h", "rank": 99, "score": 41706.98958178213 } ]
C++
examples/fft2d/fft2d.cpp
brycelelbach/upcxx
9a3f3b18a631d8e924298e621729ef302636908d
#include <upcxx.h> #include <forkjoin.h> #include "myfft.h" #include <cstdlib> #include <iostream> #include <vector> #include <cassert> #include <time.h> #include <sys/time.h> #define VERIFY using namespace upcxx; #include <cstdlib> size_t NX_default = 1024; size_t NY_default = 1024; global_ptr<complex_t> *Input, *Output; double mysecond() { struct timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + ((double) tv.tv_usec / 1000000); } template<typename T> static inline void print_matrix(std::ostream &out, T *A, size_t nrows, size_t ncols) { size_t i,j; for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { out << "(" << A[i*ncols+j].real << " + " << A[i*ncols+j].imag << "i)\t "; } out << "\n"; } } void init_array(complex_t *A, size_t sz, double val=0.0) { assert(A != NULL); for (size_t i = 0; i < sz; i++) { A[i].real = (double)i + val; A[i].imag = 0; } } static inline double random_double(void) { long long tmp; tmp = rand(); tmp = (tmp << 32) | rand(); return (double)tmp; } static inline complex_t random_complex(void) { complex_t tmp; tmp.real = random_double(); tmp.real = random_double(); return tmp; } template<typename T> void alltoall(global_ptr<T> src[], global_ptr<T> dst[], size_t count[], int np) { int i; int myid = myrank(); for (i=0; i<np; i++) { int j = (myid+i) % np; #ifdef DEBUG fprintf(stderr, "myid %d: i %d, j %d ", myid, i, j); cerr << "src[j] " << src[j] << " dst[j] " << dst[j] << " count[j] " << count[j] << "\n"; #endif async_copy(src[j], dst[j], count[j]); } async_copy_fence(); barrier(); } template<typename T> static inline void local_transpose(T *A, size_t N, size_t row_stride, size_t col_stride) { size_t i, j; T tmp; for (i=0; i<N; i++) { for (j=i+1; j<N; j++) { tmp = A[i*row_stride + j*col_stride]; A[i*row_stride + j*col_stride] = A[j*row_stride + i*col_stride]; A[j*row_stride + i*col_stride] = tmp; } } } template<typename T> static inline void local_transpose1(T *A, size_t N) { size_t i, j; T tmp; for (i=0; i<N; i++) { for (j=i+1; j<N; j++) { tmp = A[i*N+j]; A[i*N+j] = A[j*N+i]; A[j*N+i] = tmp; } } } template<typename T> static inline void local_transpose2(T *A, T *B, size_t n, size_t m) { size_t i, j; T tmp; #ifdef DEBUG int myid = my_cpu_place.id(); cerr << "myid " << myid << " A: " << A << " B: " << B << "\n"; #endif for (i=0; i<n; i++) { for (j=0; j<m; j++) { B[j*n+i] = A[i*m+j]; } } } template<typename T> void blockize(T *in, T *out, size_t nx, size_t ny, size_t blk_nx, size_t blk_ny) { size_t x, y, row_major_offset, blk_cyclic_offset; size_t blk_offset_x, blk_offset_y, blk_grid_x, blk_grid_y; assert(in != out); assert(in != NULL); assert(out != NULL); for (x = 0; x < nx; x++) { for (y = 0; y < ny; y++) { blk_offset_x = x % blk_nx; blk_offset_y = y % blk_ny; blk_grid_x = x / blk_nx; blk_grid_y = y / blk_ny; row_major_offset = x * ny + y; blk_cyclic_offset = blk_grid_x * (blk_nx * ny) + blk_grid_y * (blk_nx * blk_ny) + blk_offset_x * blk_ny + blk_offset_y; out[blk_cyclic_offset] = in[row_major_offset]; } } } template<typename T> static inline void transpose(T *in, T *out, global_ptr< global_ptr<T> > all_Ws, size_t nx, size_t ny, int nprocs) { global_ptr<T> *src = new global_ptr<T> [nprocs]; assert(src != NULL); global_ptr<T> *dst = new global_ptr<T> [nprocs]; assert(dst != NULL); size_t count[nprocs]; int i; size_t msgsz_per_p = (nx/nprocs) * (ny/nprocs); size_t nx_per_p = nx / nprocs; int myid = myrank(); global_ptr<T> tmp_in; global_ptr<T> *W = new global_ptr<T> [nprocs]; assert(W != NULL); assert(nx == ny); upcxx::copy(all_Ws, global_ptr< global_ptr<T> >(W), nprocs); #ifdef DEBUG for (int i=0; i<nprocs; i++) { fprintf(stderr, "transpose: myid %d, W[%d] ", myid, i); cerr << W[i] << "\n"; } #endif tmp_in = allocate<T>(myid, nx_per_p * ny); assert(tmp_in.raw_ptr() != NULL); #ifdef DEBUG printf("P%d transpose: Before local_transpose2 (row-major storage):\n", myid); print_matrix<T>(cout, in, nx_per_p, ny); #endif local_transpose2<T>(in, tmp_in.raw_ptr(), nx_per_p, ny); #ifdef DEBUG printf("P%d transpose: After local_transpose2 (should be column-major):\n", myid); print_matrix<T>(cout, (T *)tmp_in.raw_ptr(), ny, nx_per_p); #endif for (i = 0; i < nprocs; i++) { local_transpose1<T>((tmp_in + msgsz_per_p * i).raw_ptr(), nx_per_p); } #ifdef DEBUG printf("P%d transpose: After local_transpose1 (should be block-cyclic):\n", myid); print_matrix<T>(cout, (T *)tmp_in.raw_ptr(), ny, nx_per_p); #endif for (i=0; i<nprocs; i++) { src[i] = tmp_in + (i*msgsz_per_p) ; dst[i] = W[i] + (myid*msgsz_per_p); count[i] = msgsz_per_p; #ifdef DEBUG fprintf(stderr, "transpose: myid %d, i %d ", myid, i); cerr << "W[i] " << W[i] << " src[i] "<< src[i] << " dst[i] " << dst[i] << "\n"; #endif } alltoall(src, dst, count, nprocs); #ifdef DEBUG for (i=0; i<nprocs; i++) { if (myid == i) { printf("P%d transpose: After alltoall:\n", myid); print_matrix<T>(cout, (T *)W[myid].raw_ptr(), ny, nx_per_p); } barrier(); } #endif local_transpose2<T>((T *)W[myid].raw_ptr(), out, ny, nx_per_p); #ifdef DEBUG for (i=0; i<nprocs; i++) { if (myid == i) { printf("P%d transpose: After the second local_transpose2:\n", myid); print_matrix<T>(cout, out, nx_per_p, ny); } barrier(); } #endif delete [] src; delete [] dst; } void verify(complex_t *X, complex_t *Z, int nx, int ny) { complex_t *Y, *tmp; size_t failed = 0; double epsilon = 1e-7; Y = (complex_t *)malloc(nx * ny * sizeof(complex_t)); assert(Y != NULL); tmp = (complex_t *)malloc(nx * ny * sizeof(complex_t)); assert(tmp != NULL); fft2(tmp, X, nx, ny); local_transpose2(tmp, Y, nx, ny); #ifdef DEBUG1 printf("verify: X: \n"); print_matrix(cout, X, nx, ny); printf("verify: Y: \n"); print_matrix(cout, Y, nx, ny); printf("verify: Z: \n"); print_matrix(cout, Z, nx, ny); #endif double max_diff = 0.0; for (size_t i = 0; i < nx*ny; i++) { double diff_real = Y[i].real - Z[i].real; double diff_imag = Y[i].imag - Z[i].imag; double abs_diff = sqrt(diff_real * diff_real + diff_imag * diff_imag); double abs_y = sqrt(Y[i].real * Y[i].real + Y[i].real * Y[i].real); if (abs_diff / abs_y > epsilon * log((double)nx*ny)) { failed++; if (abs_diff > max_diff) { max_diff = abs_diff; } } } free(Y); free(tmp); if (failed) { printf("FFT2D verification failed: %lu elements are different, max_diff: %g.\n", failed, max_diff); } else { printf("FFT2D verification passed.\n"); } } void fft2d(complex_t *my_A, complex_t *my_Z, complex_t *my_W, size_t nx, size_t ny, global_ptr<global_ptr<complex_t> > all_Ws) { int nprocs = ranks(); complex_t *tmp; fft_plan_t planX, planY; int myid = myrank(); size_t nx_per_p = nx / nprocs; size_t ny_per_p = ny / nprocs; size_t size_per_p = nx_per_p * ny; assert(nx == ny); fft_init(); std::generate(my_A, &my_A[nx_per_p * ny], random_complex); init_array(my_A, size_per_p, myid * size_per_p); complex_t *pIn = my_A; complex_t *pOut = my_W; fft_plan_1d(FFT_FORWARD, ny, nx_per_p, pOut, 1, ny, pIn, 1, ny, &planY); fft_plan_1d(FFT_FORWARD, nx, ny_per_p, pOut, 1, nx, pIn, 1, nx, &planX); run_1d_fft(my_Z, my_A, &planY); tmp = (complex_t *)malloc(sizeof(complex_t) * (nx*ny/nprocs)); assert(tmp != NULL); transpose<complex_t>(my_Z, tmp, all_Ws, nx, ny, nprocs); run_1d_fft(my_Z, tmp, &planY); free(tmp); #ifdef DEBUG for (int i=0; i<nprocs; i++) { if (myid == i) { printf("myid %d: A: \n", myid); print_matrix(cout, (complex_t *)my_A, nx_per_p, ny); printf("myid %d: Z: \n", myid); print_matrix(cout, (complex_t *)my_Z, nx_per_p, ny); } barrier(); } #endif #ifdef VERIFY if (myid == 0) { global_ptr<complex_t> all_in, all_out; all_in = allocate<complex_t>(myid, nx * ny); all_out = allocate<complex_t>(myid, nx * ny); for (int i = 0; i < nprocs; i++) { async_copy(Input[i], all_in + i * size_per_p, size_per_p); async_copy(Output[i], all_out + i * size_per_p, size_per_p); } async_copy_fence(); verify(all_in.raw_ptr(), all_out.raw_ptr(), (int)nx, (int)ny); } barrier(); #endif } int main(int argc, char **argv) { double starttime; int i; int nprocs = ranks(); Input = new global_ptr<complex_t> [nprocs]; Output = new global_ptr<complex_t> [nprocs]; size_t nx, ny; global_ptr<global_ptr<complex_t> > all_Ws; all_Ws = allocate< global_ptr<complex_t> > (myrank(), nprocs); global_ptr<complex_t> *W = (global_ptr<complex_t> *)all_Ws.raw_ptr(); int tmp = 0; if (argc > 1) { tmp = atoi(argv[1]); } nx = (tmp < 2) ? NX_default : tmp; ny = nx; size_t nx_per_p = nx / nprocs; for (i=0; i<nprocs; i++) { Input[i] = allocate<complex_t>(i, nx_per_p * ny); Output[i] = allocate<complex_t>(i, nx_per_p * ny); W[i] = allocate<complex_t>(i, nx_per_p * ny); } #ifdef DEBUG for (i=0; i<nprocs; i++) { fprintf(stderr, "W[%d] ", i); cerr << W[i] << "\n"; } #endif starttime = mysecond(); for (i=0; i<nprocs; i++) { async(i)(fft2d, Input[i].raw_ptr(), Output[i].raw_ptr(), W[i].raw_ptr(), nx, ny, all_Ws); } upcxx::async_wait(); double elapsedtime = mysecond() - starttime; printf("fft2d (nx %lu, ny %lu), np %d, time = %f s\n", nx, ny, nprocs, elapsedtime); for (i=0; i<nprocs; i++) { upcxx::deallocate(Input[i]); upcxx::deallocate(Output[i]); upcxx::deallocate(W[i]); } delete [] Input; delete [] Output; return 0; }
#include <upcxx.h> #include <forkjoin.h> #include "myfft.h" #include <cstdlib> #include <iostream> #include <vector> #include <cassert> #include <time.h> #include <sys/time.h> #define VERIFY using namespace upcxx; #include <cstdlib> size_t NX_default = 1024; size_t NY_default = 1024; global_ptr<complex_t> *Input, *Output; double mysecond() { struct timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + ((double) tv.tv_usec / 1000000); } template<typename T> static inline void print_matrix(std::ostream &out, T *A, size_t nrows, size_t ncols) { size_t i,j; for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { out << "(" << A[i*ncols+j].real << " + " << A[i*ncols+j].imag << "i)\t "; } out << "\n"; } } void init_array(complex_t *A, size_t sz, double val=0.0) { assert(A != NULL); for (size_t i = 0; i < sz; i++) { A[i].real = (double)i + val; A[i].imag = 0; } } static inline double random_double(void) { long long tmp; tmp = rand(); tmp = (tmp << 32) | rand(); return (double)tmp; } static inline complex_t random_complex(void) { complex_t tmp; tmp.real = random_double(); tmp.real = random_double(); return tmp; } template<typename T> void alltoall(global_ptr<T> src[], global_ptr<T> dst[], size_t count[], int np) { int i; int myid = myrank(); for (i=0; i<np; i++) { int j = (myid+i) % np; #ifdef DEBUG fprintf(stderr, "myid %d: i %d, j %d ", myid, i, j); cerr << "src[j] " << src[j] << " dst[j] " << dst[j] << " count[j] " << count[j] << "\n"; #endif async_copy(src[j], dst[j], count[j]); } async_copy_fence(); barrier(); } template<typename T> static inline void local_transpose(T *A, size_t N, size_t row_stride, size_t col_stride) { size_t i, j; T tmp; for (i=0; i<N; i++) { for (j=i+1; j<N; j++) { tmp = A[i*row_stride + j*col_stride]; A[i*row_stride + j*col_stride] = A[j*row_stride + i*col_stride]; A[j*row_stride + i*col_stride] = tmp; } } } template<typename T> static inline void local_transpose1(T *A, size_t N) { size_t i, j; T tmp; for (i=0; i<N; i++) { for (j=i+1; j<N; j++) { tmp = A[i*N+j]; A[i*N+j] = A[j*N+i]; A[j*N+i] = tmp; } } } template<typename T> static inline void local_transpose2(T *A, T *B, size_t n, size_t m) { size_t i, j; T tmp; #ifdef DEBUG int myid = my_cpu_place.id(); cerr << "myid " << myid << " A: " << A << " B: " << B << "\n"; #endif for (i=0; i<n; i++) { for (j=0; j<m; j++) { B[j*n+i] = A[i*m+j]; } } } template<typename T> void blockize(T *in, T *out, size_t nx, size_t ny, size_t blk_nx, size_t blk_ny) { size_t x, y, row_major_offset, blk_cyclic_offset; size_t blk_offset_x, blk_offset_y, blk_grid_x, blk_grid_y; assert(in != out); assert(in != NULL); assert(out != NULL); for (x = 0; x < nx; x++) { for (y = 0; y < ny; y++) { blk_offset_x = x % blk_nx; blk_offset_y = y % blk_ny; blk_grid_x = x / blk_nx; blk_grid_y = y / blk_ny; row_major_offset = x * ny + y; blk_cyclic_offset = blk_grid_x * (blk_nx * ny) + blk_grid_y * (blk_nx * blk_ny) + blk_offset_x * blk_ny + blk_offset_y; out[blk_cyclic_offset] = in[row_major_offset]; } } } template<typename T> static inline void transpose(T *in, T *out, global_ptr< global_ptr<T> > all_Ws, size_t nx, size_t ny, int nprocs) { global_ptr<T> *src = new global_ptr<T> [nprocs]; assert(src != NULL); global_ptr<T> *dst = new global_ptr<T> [nprocs]; assert(dst != NULL); size_t count[nprocs]; int i; size_t msgsz_per_p = (nx/nprocs) * (ny/nprocs); size_t nx_per_p = nx / nprocs; int myid = myrank(); global_ptr<T> tmp_in; global_ptr<T> *W = new global_ptr<T> [nprocs]; assert(W != NULL); assert(nx == ny); upcx
nx_per_p); } barrier(); } #endif local_transpose2<T>((T *)W[myid].raw_ptr(), out, ny, nx_per_p); #ifdef DEBUG for (i=0; i<nprocs; i++) { if (myid == i) { printf("P%d transpose: After the second local_transpose2:\n", myid); print_matrix<T>(cout, out, nx_per_p, ny); } barrier(); } #endif delete [] src; delete [] dst; } void verify(complex_t *X, complex_t *Z, int nx, int ny) { complex_t *Y, *tmp; size_t failed = 0; double epsilon = 1e-7; Y = (complex_t *)malloc(nx * ny * sizeof(complex_t)); assert(Y != NULL); tmp = (complex_t *)malloc(nx * ny * sizeof(complex_t)); assert(tmp != NULL); fft2(tmp, X, nx, ny); local_transpose2(tmp, Y, nx, ny); #ifdef DEBUG1 printf("verify: X: \n"); print_matrix(cout, X, nx, ny); printf("verify: Y: \n"); print_matrix(cout, Y, nx, ny); printf("verify: Z: \n"); print_matrix(cout, Z, nx, ny); #endif double max_diff = 0.0; for (size_t i = 0; i < nx*ny; i++) { double diff_real = Y[i].real - Z[i].real; double diff_imag = Y[i].imag - Z[i].imag; double abs_diff = sqrt(diff_real * diff_real + diff_imag * diff_imag); double abs_y = sqrt(Y[i].real * Y[i].real + Y[i].real * Y[i].real); if (abs_diff / abs_y > epsilon * log((double)nx*ny)) { failed++; if (abs_diff > max_diff) { max_diff = abs_diff; } } } free(Y); free(tmp); if (failed) { printf("FFT2D verification failed: %lu elements are different, max_diff: %g.\n", failed, max_diff); } else { printf("FFT2D verification passed.\n"); } } void fft2d(complex_t *my_A, complex_t *my_Z, complex_t *my_W, size_t nx, size_t ny, global_ptr<global_ptr<complex_t> > all_Ws) { int nprocs = ranks(); complex_t *tmp; fft_plan_t planX, planY; int myid = myrank(); size_t nx_per_p = nx / nprocs; size_t ny_per_p = ny / nprocs; size_t size_per_p = nx_per_p * ny; assert(nx == ny); fft_init(); std::generate(my_A, &my_A[nx_per_p * ny], random_complex); init_array(my_A, size_per_p, myid * size_per_p); complex_t *pIn = my_A; complex_t *pOut = my_W; fft_plan_1d(FFT_FORWARD, ny, nx_per_p, pOut, 1, ny, pIn, 1, ny, &planY); fft_plan_1d(FFT_FORWARD, nx, ny_per_p, pOut, 1, nx, pIn, 1, nx, &planX); run_1d_fft(my_Z, my_A, &planY); tmp = (complex_t *)malloc(sizeof(complex_t) * (nx*ny/nprocs)); assert(tmp != NULL); transpose<complex_t>(my_Z, tmp, all_Ws, nx, ny, nprocs); run_1d_fft(my_Z, tmp, &planY); free(tmp); #ifdef DEBUG for (int i=0; i<nprocs; i++) { if (myid == i) { printf("myid %d: A: \n", myid); print_matrix(cout, (complex_t *)my_A, nx_per_p, ny); printf("myid %d: Z: \n", myid); print_matrix(cout, (complex_t *)my_Z, nx_per_p, ny); } barrier(); } #endif #ifdef VERIFY if (myid == 0) { global_ptr<complex_t> all_in, all_out; all_in = allocate<complex_t>(myid, nx * ny); all_out = allocate<complex_t>(myid, nx * ny); for (int i = 0; i < nprocs; i++) { async_copy(Input[i], all_in + i * size_per_p, size_per_p); async_copy(Output[i], all_out + i * size_per_p, size_per_p); } async_copy_fence(); verify(all_in.raw_ptr(), all_out.raw_ptr(), (int)nx, (int)ny); } barrier(); #endif } int main(int argc, char **argv) { double starttime; int i; int nprocs = ranks(); Input = new global_ptr<complex_t> [nprocs]; Output = new global_ptr<complex_t> [nprocs]; size_t nx, ny; global_ptr<global_ptr<complex_t> > all_Ws; all_Ws = allocate< global_ptr<complex_t> > (myrank(), nprocs); global_ptr<complex_t> *W = (global_ptr<complex_t> *)all_Ws.raw_ptr(); int tmp = 0; if (argc > 1) { tmp = atoi(argv[1]); } nx = (tmp < 2) ? NX_default : tmp; ny = nx; size_t nx_per_p = nx / nprocs; for (i=0; i<nprocs; i++) { Input[i] = allocate<complex_t>(i, nx_per_p * ny); Output[i] = allocate<complex_t>(i, nx_per_p * ny); W[i] = allocate<complex_t>(i, nx_per_p * ny); } #ifdef DEBUG for (i=0; i<nprocs; i++) { fprintf(stderr, "W[%d] ", i); cerr << W[i] << "\n"; } #endif starttime = mysecond(); for (i=0; i<nprocs; i++) { async(i)(fft2d, Input[i].raw_ptr(), Output[i].raw_ptr(), W[i].raw_ptr(), nx, ny, all_Ws); } upcxx::async_wait(); double elapsedtime = mysecond() - starttime; printf("fft2d (nx %lu, ny %lu), np %d, time = %f s\n", nx, ny, nprocs, elapsedtime); for (i=0; i<nprocs; i++) { upcxx::deallocate(Input[i]); upcxx::deallocate(Output[i]); upcxx::deallocate(W[i]); } delete [] Input; delete [] Output; return 0; }
x::copy(all_Ws, global_ptr< global_ptr<T> >(W), nprocs); #ifdef DEBUG for (int i=0; i<nprocs; i++) { fprintf(stderr, "transpose: myid %d, W[%d] ", myid, i); cerr << W[i] << "\n"; } #endif tmp_in = allocate<T>(myid, nx_per_p * ny); assert(tmp_in.raw_ptr() != NULL); #ifdef DEBUG printf("P%d transpose: Before local_transpose2 (row-major storage):\n", myid); print_matrix<T>(cout, in, nx_per_p, ny); #endif local_transpose2<T>(in, tmp_in.raw_ptr(), nx_per_p, ny); #ifdef DEBUG printf("P%d transpose: After local_transpose2 (should be column-major):\n", myid); print_matrix<T>(cout, (T *)tmp_in.raw_ptr(), ny, nx_per_p); #endif for (i = 0; i < nprocs; i++) { local_transpose1<T>((tmp_in + msgsz_per_p * i).raw_ptr(), nx_per_p); } #ifdef DEBUG printf("P%d transpose: After local_transpose1 (should be block-cyclic):\n", myid); print_matrix<T>(cout, (T *)tmp_in.raw_ptr(), ny, nx_per_p); #endif for (i=0; i<nprocs; i++) { src[i] = tmp_in + (i*msgsz_per_p) ; dst[i] = W[i] + (myid*msgsz_per_p); count[i] = msgsz_per_p; #ifdef DEBUG fprintf(stderr, "transpose: myid %d, i %d ", myid, i); cerr << "W[i] " << W[i] << " src[i] "<< src[i] << " dst[i] " << dst[i] << "\n"; #endif } alltoall(src, dst, count, nprocs); #ifdef DEBUG for (i=0; i<nprocs; i++) { if (myid == i) { printf("P%d transpose: After alltoall:\n", myid); print_matrix<T>(cout, (T *)W[myid].raw_ptr(), ny,
random
[ { "content": " int barrier();\n", "file_path": "include/upcxx/upcxx_runtime.h", "rank": 0, "score": 169134.43952992093 }, { "content": " static inline uint32_t myrank() {\n\n if (is_init() == false) return 0xFFFFFFFF; // return a special value if not inited\n\n return team::current_team()->myrank();\n", "file_path": "include/upcxx/team.h", "rank": 1, "score": 167479.50578351872 }, { "content": " group(int sz, int i) : _size(sz), _index(i)\n\n { }\n\n\n", "file_path": "include/upcxx/group.h", "rank": 2, "score": 167476.27486042457 }, { "content": " _myrank = other->_myrank;\n", "file_path": "include/upcxx/team.h", "rank": 3, "score": 136435.14019989956 }, { "content": " void *_am_dst; // active message dst buffer\n", "file_path": "include/upcxx/async_impl.h", "rank": 4, "score": 132764.63759847396 }, { "content": " void *_am_src; // active message src buffer\n", "file_path": "include/upcxx/async_impl.h", "rank": 5, "score": 132075.84876053332 }, { "content": "namespace upcxx \n\n{\n\n /// \\cond SHOW_INTERNAL\n\n struct alloc_am_t\n\n {\n\n size_t nbytes;\n\n void **ptr_addr;\n\n event *cb_event;\n\n };\n\n\n\n struct alloc_reply_t\n\n {\n\n void **ptr_addr;\n\n void *ptr;\n\n event *cb_event;\n\n };\n\n\n\n struct free_am_t\n\n {\n\n void *ptr;\n\n };\n\n\n\n struct inc_am_t\n\n {\n\n void *ptr;\n\n };\n\n /// \\endcond SHOW_INTERNAL\n\n\n\n /**\n\n * \\ingroup internal\n\n * Advance the outgoing task queue by processing local tasks\n\n *\n\n * Note that some local tasks may take\n\n *\n\n * \\param max_dispatched the maximum number of tasks to be processed\n\n *\n\n * \\return the number of tasks that have been processed\n\n */\n\n int advance_out_task_queue(queue_t *outq, int max_dispatched);\n\n\n\n inline int advance_out_task(int max_dispatched = MAX_DISPATCHED_OUT)\n\n {\n\n return advance_out_task_queue(out_task_queue, max_dispatched);\n\n }\n\n\n\n /*\n\n * \\ingroup internal\n\n * Advance the incoming task queue by sending out remote task requests\n\n *\n\n * Note that advance_out_task_queue() shouldn't be be called in\n\n * any GASNet AM handlers because it calls gasnet_AMPoll() and\n\n * may result in a deadlock.\n\n *\n\n * \\param max_dispatched the maximum number of tasks to send\n\n *\n\n * \\return the number of tasks that have been sent\n\n */\n\n int advance_in_task_queue(queue_t *inq, int max_dispatched);\n\n\n\n inline int advance_in_task(int max_dispatched = MAX_DISPATCHED_IN)\n\n {\n\n return advance_in_task_queue(in_task_queue, max_dispatched);\n\n }\n\n \n\n // AM handler functions\n\n void async_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n void async_done_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n void alloc_cpu_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n void alloc_gpu_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n void alloc_reply_handler(gasnet_token_t token, void *reply, size_t nbytes);\n\n void free_cpu_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n void free_gpu_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n void inc_am_handler(gasnet_token_t token, void *am, size_t nbytes);\n\n\n\n MEDIUM_HANDLER_DECL(copy_and_signal_request, 4, 8);\n\n SHORT_HANDLER_DECL(copy_and_signal_reply, 2, 4);\n\n\n\n enum {\n\n gasneti_handleridx(copy_and_signal_request) = COPY_AND_SIGNAL_REQUEST, \n\n gasneti_handleridx(copy_and_signal_reply) = COPY_AND_SIGNAL_REPLY, \n\n };\n\n \n\n //typedef struct {\n\n // void *addr;\n\n // uintptr_t size;\n\n //} gasnet_seginfo_t;\n\n\n\n // int gasnet_getSegmentInfo (gasnet_seginfo_t *seginfo table, int numentries);\n\n\n\n // This may need to be a thread-private data if GASNet supports per-thread segment in the future\n\n extern gasnet_seginfo_t *all_gasnet_seginfo;\n\n extern gasnet_seginfo_t *my_gasnet_seginfo;\n\n extern mspace _gasnet_mspace;\n\n extern gasnet_nodeinfo_t *all_gasnet_nodeinfo;\n\n extern gasnet_nodeinfo_t *my_gasnet_nodeinfo;\n\n extern gasnet_node_t my_gasnet_supernode;\n\n\n\n\n\n extern int env_use_am_for_copy_and_set; // defined in upcxx_runtime.cpp\n\n extern int env_use_dmapp; // defined in upcxx_runtime.cpp\n\n\n\n\n\n static inline void init_gasnet_seg_mspace()\n\n {\n\n all_gasnet_seginfo =\n\n (gasnet_seginfo_t *)malloc(sizeof(gasnet_seginfo_t) * gasnet_nodes());\n\n assert(all_gasnet_seginfo != NULL);\n\n\n\n int rv = gasnet_getSegmentInfo(all_gasnet_seginfo, gasnet_nodes());\n\n assert(rv == GASNET_OK);\n\n\n\n my_gasnet_seginfo = &all_gasnet_seginfo[gasnet_mynode()];\n\n\n\n _gasnet_mspace = create_mspace_with_base(my_gasnet_seginfo->addr,\n\n my_gasnet_seginfo->size, 1);\n\n assert(_gasnet_mspace != 0);\n\n\n\n // Set the mspace limit to the gasnet segment size so it won't go outside.\n\n mspace_set_footprint_limit(_gasnet_mspace, my_gasnet_seginfo->size);\n\n }\n\n\n\n void gasnet_seg_free(void *p);\n\n void *gasnet_seg_memalign(size_t nbytes, size_t alignment);\n\n void *gasnet_seg_alloc(size_t nbytes);\n\n\n\n // Return the supernode of node n in GASNet\n\n static inline gasnet_node_t gasnet_supernode_of(gasnet_node_t n)\n\n {\n\n assert(all_gasnet_seginfo != NULL);\n\n return all_gasnet_nodeinfo[n].supernode;\n\n }\n\n\n\n#if GASNET_PSHM\n\n static inline uintptr_t gasnet_pshm_offset(gasnet_node_t n)\n\n {\n\n assert(all_gasnet_nodeinfo != NULL);\n\n return all_gasnet_nodeinfo[n].offset;\n\n }\n\n#endif\n\n \n\n void init_pshm_teams(const gasnet_nodeinfo_t *nodeinfo_from_gasnet,\n\n uint32_t num_nodes);\n", "file_path": "include/upcxx/upcxx_internal.h", "rank": 6, "score": 130302.26230651347 }, { "content": "namespace upcxx\n\n{\n\n typedef uint32_t rank_t;\n\n\n\n /**\n\n * \\defgroup initgroup Job initialization and query\n\n * This group of API is for initialization and self-query.\n\n */\n\n\n\n /**\n\n * \\ingroup initgroup\n\n * Initialize the GASNet runtime, which should be called\n\n * only once at the beginning of the client program.\n\n *\n\n * \\param argc the pointer to the number of arguments\n\n * \\param argv the pointer to the values of the arguments\n\n *\n\n * \\see hello.cpp\n\n */\n\n int init(int *argc, char ***argv);\n\n\n\n /**\n\n * \\ingroup initgroup\n\n * Finalize the GASNet runtime, which should be called only\n\n * once at the end of the client program.\n\n */\n\n int finalize();\n\n\n\n bool is_init();\n\n\n\n rank_t global_ranks();\n\n\n\n rank_t global_myrank();\n\n\n\n extern queue_t *in_task_queue;\n\n\n\n extern queue_t *out_task_queue;\n\n\n\n /**\n\n * Default maximum number of task to dispatch for every time\n\n * the incoming task queue is polled/advanced.\n\n */\n\n #define MAX_DISPATCHED_IN 10\n\n\n\n /**\n\n * Default maximum number of task to dispatch for every time\n\n * the outgoing task queue is polled/advanced.\n\n */\n\n #define MAX_DISPATCHED_OUT 10\n\n\n\n /**\n\n * \\ingroup asyncgroup\n\n * Advance both the incoming and outgoing task queues\n\n * Note that advance() shouldn't be be called in any GASNet AM\n\n * handlers because it calls gasnet_AMPoll() and may result in\n\n * a deadlock.\n\n *\n\n * \\param max_in maximum number of incoming tasks to be processed before returning\n\n * \\param max_out maximum number of outgoing tasks to be processed before returning\n\n *\n\n * \\return the total number of tasks that have been processed in the incoming\n\n * and outgoing task queues\n\n */\n\n int advance(int max_in = MAX_DISPATCHED_IN, int max_out = MAX_DISPATCHED_OUT);\n\n\n\n // An alias of the advance function for backward compatibility.\n\n // The advance function is recommended.\n\n inline int progress() { return advance(); }\n\n\n\n // drain() is superseded by advance(), provided for backward compatibility.\n\n // The advance function is recommended.\n\n inline int drain(int max_dispatched = 0)\n\n {\n\n return advance(max_dispatched, max_dispatched);\n", "file_path": "include/upcxx/upcxx_runtime.h", "rank": 7, "score": 130302.26230651347 }, { "content": "namespace upcxx {\n\n typedef uint64_t flag_t;\n\n\n\n const flag_t UPCXX_FLAG_VAL_SET = 1;\n\n const flag_t UPCXX_FLAG_VAL_UNSET = 0;\n", "file_path": "include/upcxx/upcxx_types.h", "rank": 8, "score": 130302.26230651347 }, { "content": "namespace upcxx {\n\n#ifdef UPCXX_HAVE_CXX11\n\n // Apply a function to a list of arguments stored in a std::tuple\n\n template<size_t N>\n\n struct applier {\n\n template<typename Function, typename... Ts, typename... Ts2>\n\n static auto call(Function k, const std::tuple<Ts...>& t, Ts2... as) ->\n\n decltype(applier<N-1>::call(k, t, std::get<N-1>(t), as...)) {\n\n return applier<N-1>::call(k, t, std::get<N-1>(t), as...);\n\n }\n\n };\n\n\n\n template<>\n\n struct applier<0> {\n\n template<typename Function, typename... Ts, typename... Ts2>\n\n static auto call(Function k, const std::tuple<Ts...>& t, Ts2... as) ->\n\n decltype(k(as...)) {\n\n return k(as...);\n\n }\n\n };\n\n\n\n template<typename Function, typename... Ts>\n\n auto apply(Function k, const std::tuple<Ts...>& t) ->\n\n decltype(applier<sizeof...(Ts)>::call(k, t)) {\n\n return applier<sizeof...(Ts)>::call(k, t);\n\n }\n\n\n\n namespace util {\n\n template<int ...>\n\n struct seq { };\n\n\n\n template<int N, int ...S>\n\n struct gens : gens<N-1, N-1, S...> { };\n\n\n\n template<int ...S>\n\n struct gens<0, S...> {\n\n typedef seq<S...> type;\n\n };\n", "file_path": "include/upcxx/utils.h", "rank": 9, "score": 129334.86226198668 }, { "content": "namespace upcxx {\n\n\n\n struct f_scope {\n\n int done;\n\n event e;\n\n inline f_scope():done(0)\n\n {\n\n push_event(&e);\n\n }\n\n inline ~f_scope() \n\n {\n\n assert(peek_event() == &e);\n\n pop_event();\n\n e.wait();\n\n }\n", "file_path": "include/upcxx/finish.h", "rank": 10, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n struct team;\n\n\n\n extern std::vector<team *> *_team_stack;\n\n\n\n struct ts_scope;\n\n\n\n struct team {\n\n team() : _mychild(NULL) {\n\n if (_team_stack != NULL && _team_stack->size() > 0) {\n\n const team *other = current_team();\n\n _parent = other->_parent;\n\n _size = other->_size;\n\n _myrank = other->_myrank;\n\n _color = other->_color;\n\n _team_id = other->_team_id;\n\n _gasnet_team = other->_gasnet_team;\n\n }\n\n }\n\n\n\n team(const team *other) : _mychild(NULL) {\n\n _parent = other->_parent;\n\n _size = other->_size;\n\n _myrank = other->_myrank;\n\n _color = other->_color;\n\n _team_id = other->_team_id;\n\n _gasnet_team = other->_gasnet_team;\n\n }\n\n \n\n ~team()\n\n {\n\n // YZ: free the underlying gasnet team?\n\n // if (_gasnet_team != NULL) {\n\n // gasnete_coll_team_free(_gasnet_team);\n\n // }\n\n }\n\n\n\n inline uint32_t myrank() const { return _myrank; }\n\n \n\n inline uint32_t size() const { return _size; }\n\n \n\n inline uint32_t team_id() const { return _team_id; }\n\n \n\n inline team *parent() const { return _parent; }\n\n\n\n inline team *mychild() const { return _mychild; }\n\n\n\n inline uint32_t color() const { return _color; }\n\n\n\n inline gasnet_team_handle_t gasnet_team() const {\n\n return _gasnet_team;\n\n }\n\n\n\n inline bool is_team_all() const\n\n {\n\n return (_team_id == 0); // team_all has team_id 0\n\n }\n\n\n\n // void create_gasnet_team();\n\n int split(uint32_t color, uint32_t relrank, team *&new_team);\n\n int split(uint32_t color, uint32_t relrank);\n\n \n\n inline int barrier() const\n\n {\n\n int rv;\n\n assert(_gasnet_team != NULL);\n\n gasnet_coll_barrier_notify(_gasnet_team, 0,\n\n GASNET_BARRIERFLAG_ANONYMOUS);\n\n while ((rv=gasnet_coll_barrier_try(_gasnet_team, 0,\n\n GASNET_BARRIERFLAG_ANONYMOUS))\n\n == GASNET_ERR_NOT_READY) {\n\n if (advance() < 0) { // process the async task queue\n\n return UPCXX_ERROR;\n\n }\n\n }\n\n assert(rv == GASNET_OK);\n\n return UPCXX_SUCCESS;\n\n\n\n }\n\n\n\n inline int bcast(void *src, void *dst, size_t nbytes, uint32_t root) const\n\n {\n\n assert(_gasnet_team != NULL);\n\n gasnet_coll_broadcast(_gasnet_team, dst, root, src, nbytes,\n\n UPCXX_GASNET_COLL_FLAG);\n\n return UPCXX_SUCCESS;\n\n }\n\n \n\n inline int gather(void *src, void *dst, size_t nbytes, uint32_t root) const\n\n {\n\n assert(_gasnet_team != NULL);\n\n gasnet_coll_gather(_gasnet_team, root, dst, src, nbytes, \n\n UPCXX_GASNET_COLL_FLAG);\n\n return UPCXX_SUCCESS;\n\n }\n\n\n\n inline int scatter(void *src, void *dst, size_t nbytes, uint32_t root) const\n\n {\n\n assert(_gasnet_team != NULL);\n\n gasnet_coll_scatter(_gasnet_team, dst, root, src, nbytes,\n\n UPCXX_GASNET_COLL_FLAG);\n\n return UPCXX_SUCCESS;\n\n }\n\n\n\n inline int allgather(void *src, void *dst, size_t nbytes) const\n\n {\n\n assert(_gasnet_team != NULL);\n\n // YZ: gasnet_coll_gather_all is broken with Intel compiler on Linux!\n\n /*\n\n gasnet_coll_gather_all(_gasnet_team, dst, src, nbytes, \n\n UPCXX_GASNET_COLL_FLAG);\n\n */\n\n void *temp = allocate(nbytes * size());\n\n assert(temp != NULL);\n\n gather(src, temp, nbytes, 0);\n\n bcast(temp, dst, nbytes * size(), 0);\n\n deallocate(temp);\n\n return UPCXX_SUCCESS;\n\n }\n\n\n\n inline void alltoall(void *src, void *dst, size_t nbytes) const\n\n {\n\n gasnet_coll_exchange(_gasnet_team, dst, src, nbytes,\n\n UPCXX_GASNET_COLL_FLAG);\n\n }\n\n\n\n template<class T>\n\n int reduce(T *src, T *dst, size_t count, uint32_t root,\n\n upcxx_op_t op) const\n\n {\n\n // We infer the data type from T by datatype_wrapper\n\n assert(_gasnet_team != NULL);\n\n gasnet_coll_reduce(_gasnet_team, root, dst, src, 0, 0, sizeof(T),\n\n count, datatype_wrapper<T>::value, op,\n\n UPCXX_GASNET_COLL_FLAG);\n\n return UPCXX_SUCCESS;\n\n }\n\n \n\n /**\n\n * Translate a rank in a team to its global rank\n\n */\n\n inline uint32_t team_rank_to_global(uint32_t team_rank) const\n\n {\n\n return gasnete_coll_team_rank2node(_gasnet_team, team_rank);\n\n }\n\n \n\n inline uint32_t global_rank_to_team(uint32_t global_rank) const\n\n {\n\n return gasnete_coll_team_node2rank(_gasnet_team, global_rank);\n\n }\n\n\n\n static uint32_t new_team_id();\n\n\n\n static team *current_team() { return _team_stack->back(); }\n\n\n\n static team *global_team() { return (*_team_stack)[0]; }\n\n\n\n friend int init(int *pargc, char ***pargv);\n\n friend struct ts_scope;\n\n\n\n private:\n\n team *_parent, *_mychild;\n\n uint32_t _size, _myrank, _color;\n\n uint32_t _team_id;\n\n gasnet_team_handle_t _gasnet_team;\n\n\n\n team(team *parent, int size, int rank, int color,\n\n gasnet_team_handle_t handle) : _parent(parent),\n\n _mychild(NULL), _size(size), _myrank(rank), _color(color),\n\n _team_id(new_team_id()), _gasnet_team(handle) {}\n\n\n\n void init_global_team() {\n\n _parent = NULL;\n\n _size = gasnet_nodes();\n\n _myrank = gasnet_mynode();\n\n _color = 0;\n\n _team_id = 0;\n\n _gasnet_team = GASNET_TEAM_ALL;\n\n // add to top of team stack\n\n if (_team_stack->size() == 0)\n\n _team_stack->push_back(this);\n\n }\n\n\n\n static gasnet_hsl_t _tid_lock;\n\n // static std::vector<team *> _team_stack;\n\n\n\n static void descend_team(team *t) {\n\n if (t->_parent->_team_id != current_team()->_team_id) {\n\n std::cerr << \"team is not a subteam of current team\\n\";\n\n abort();\n\n }\n\n _team_stack->push_back(t);\n\n }\n\n\n\n static void ascend_team() {\n\n _team_stack->pop_back();\n\n }\n", "file_path": "include/upcxx/team.h", "rank": 11, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n // Defined in team.cpp but we don't want to include team.h here due to\n\n // cyclic include dependencies\n\n extern gasnet_team_handle_t current_gasnet_team();\n\n\n\n template<class T>\n\n void reduce(T *src, T *dst, size_t count, uint32_t root,\n\n upcxx_op_t op, upcxx_datatype_t dt)\n\n {\n\n // YZ: check consistency of T and dt\n\n UPCXX_CALL_GASNET(gasnet_coll_reduce(current_gasnet_team(), root, dst, src, 0, 0,\n\n sizeof(T), count, dt, op,\n\n UPCXX_GASNET_COLL_FLAG));\n\n }\n\n #define upcxx_reduce upcxx::reduce\n\n \n\n void init_collectives();\n\n \n\n static inline void bcast(void *src, void *dst, size_t nbytes, uint32_t root)\n\n {\n\n UPCXX_CALL_GASNET(gasnet_coll_broadcast(current_gasnet_team(), dst, root, src,\n\n nbytes, UPCXX_GASNET_COLL_FLAG));\n\n }\n\n #define upcxx_bcast upcxx::bcast\n\n \n\n static inline void gather(void *src, void *dst, size_t nbytes, uint32_t root)\n\n {\n\n UPCXX_CALL_GASNET(gasnet_coll_gather(current_gasnet_team(), root, dst, src, nbytes,\n\n UPCXX_GASNET_COLL_FLAG));\n\n }\n\n #define upcxx_gather upcxx::gather\n\n \n\n static inline void allgather(void *src, void *dst, size_t nbytes)\n\n {\n\n // gasnet_coll_gather_all(current_gasnet_team(), dst, src, nbytes,\n\n // UPCXX_GASNET_COLL_FLAG);\n\n void *temp = (void *)allocate(nbytes * gasnete_coll_team_size(current_gasnet_team()));\n\n assert(temp != NULL);\n\n upcxx::gather(src, temp, nbytes, 0);\n\n upcxx::bcast(temp, dst, nbytes * gasnete_coll_team_size(current_gasnet_team()), 0);\n\n deallocate(temp);\n\n }\n\n #define upcxx_allgather upcxx::allgather\n\n \n\n static inline void alltoall(void *src, void *dst, size_t nbytes)\n\n {\n\n UPCXX_CALL_GASNET(gasnet_coll_exchange(current_gasnet_team(), dst, src, nbytes,\n\n UPCXX_GASNET_COLL_FLAG));\n\n }\n\n #define upcxx_alltoall upcxx::alltoall\n", "file_path": "include/upcxx/collective.h", "rank": 12, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n\n\n /**\n\n * \\ingroup asyncgroup\n\n *\n\n * Asynchronous function execution\n\n * Optionally signal the event \"ack\" for task completion\n\n *\n\n * ~~~~~~~~~~~~~~~{.cpp}\n\n * async(rank_t rank, event *ack)(function, arg1, arg2, ...);\n\n * ~~~~~~~~~~~~~~~\n\n * \\see test_async.cpp\n\n *\n\n */\n\n inline gasnet_launcher<rank_t> async(rank_t rank,\n\n event *e = peek_event())\n\n {\n\n return gasnet_launcher<rank_t>(rank, e);\n\n }\n\n\n\n /**\n\n * \\ingroup asyncgroup\n\n *\n\n * Asynchronous function execution\n\n *\n\n * ~~~~~~~~~~~~~~~{.cpp}\n\n * async(range ranks)(function, arg1, arg2, ...);\n\n * ~~~~~~~~~~~~~~~\n\n * \\see test_am_bcast.cpp\n\n *\n\n */\n\n inline gasnet_launcher<range> async(range r,\n\n event *e = peek_event())\n\n {\n\n gasnet_launcher<range> launcher(r, e);\n\n launcher.set_group(group(r.count(), -1));\n\n return launcher;\n\n }\n\n\n\n /**\n\n * \\ingroup asyncgroup\n\n *\n\n * Conditional asynchronous function execution\n\n * The task will be automatically enqueued for execution after\n\n * the event \"after\" is signaled.\n\n * Optionally signal the event \"ack\" for task completion\n\n *\n\n * ~~~~~~~~~~~~~~~{.cpp}\n\n * async_after(uint32_t rank, event *after, event *ack)(function, arg1, arg2, ...);\n\n * ~~~~~~~~~~~~~~~\n\n * \\see test_async.cpp\n\n *\n\n */\n\n inline gasnet_launcher<rank_t> async_after(rank_t rank, event *after,\n\n event *ack = peek_event())\n\n {\n\n return gasnet_launcher<rank_t>(rank, ack, after);\n\n }\n\n\n\n \n\n /**\n\n * \\ingroup asyncgroup\n\n *\n\n * async for Active Message style communication\n\n * ~~~~~~~~~~~~~~~{.cpp}\n\n * async(uint32_t rank, void *src, size_t nbytes, event *ack)\n\n (function, arg1, arg2, ...);\n\n * ~~~~~~~~~~~~~~~\n\n * \\see test_async_am.cpp\n\n *\n\n */\n\n inline gasnet_launcher<rank_t> async(uint32_t rank,\n\n void *am_dst,\n\n void *am_src,\n\n size_t nbytes,\n\n event *ack)\n\n {\n\n return gasnet_launcher<rank_t>(rank, ack, NULL);\n\n }\n\n\n\n template<>\n\n void gasnet_launcher<rank_t>::launch(generic_fp fp,\n\n void *async_args,\n\n size_t arg_sz);\n\n\n\n template<>\n\n void gasnet_launcher<range>::launch(generic_fp fp,\n\n void *async_args,\n\n size_t arg_sz);\n\n\n", "file_path": "include/upcxx/async.h", "rank": 13, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n void signal_exit(); \n\n void wait_for_incoming_tasks();\n", "file_path": "include/upcxx/forkjoin.h", "rank": 14, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n struct async_task; // defined in async_gasnet.h\n\n\n\n // extern gasnet_hsl_t async_lock;\n\n // extern queue_t *async_task_queue;\n\n extern upcxx_mutex_t in_task_queue_lock;\n\n extern queue_t *in_task_queue;\n\n extern upcxx_mutex_t out_task_queue_lock;\n\n extern queue_t *out_task_queue;\n\n extern upcxx_mutex_t all_events_lock;\n\n\n\n#define MAX_NUM_DONE_CB 16\n\n\n\n#define USE_EVENT_LOCK\n\n\n\n /**\n\n * \\addtogroup asyncgroup Asynchronous task execution and Progress\n\n * @{\n\n * Events are used to notify asynch task completion and invoke callback functions.\n\n */\n\n struct event {\n\n volatile int _count; // outstanding number of tasks.\n\n int owner;\n\n std::vector<gasnet_handle_t> _gasnet_handles;\n\n#ifdef UPCXX_USE_DMAPP\n\n std::vector<dmapp_syncid_handle_t> _dmapp_handles;\n\n#endif\n\n int _num_done_cb;\n\n async_task *_done_cb[MAX_NUM_DONE_CB]; \n\n // std::vector<async_task &> _cont_tasks;\n\n\n\n inline event() : _count(0), _num_done_cb(0), owner(0)\n\n {\n\n }\n\n\n\n inline ~event()\n\n {\n\n this->wait();\n\n }\n\n\n\n inline int count() const { return _count; }\n\n\n\n void _enqueue_cb();\n\n\n\n inline bool isdone() const\n\n {\n\n assert(_count >= 0);\n\n return (_count == 0);\n\n }\n\n \n\n // Increment the reference counter for the event\n\n void incref(uint32_t c=1)\n\n {\n\n upcxx_mutex_lock(&all_events_lock);\n\n _incref(c);\n\n upcxx_mutex_unlock(&all_events_lock);\n\n }\n\n\n\n\n\n // Decrement the reference counter for the event\n\n inline void decref(uint32_t c=1)\n\n {\n\n upcxx_mutex_lock(&all_events_lock);\n\n _decref(c);\n\n upcxx_mutex_unlock(&all_events_lock);\n\n }\n\n\n\n inline void add_gasnet_handle(gasnet_handle_t h)\n\n {\n\n upcxx_mutex_lock(&all_events_lock);\n\n _add_gasnet_handle(h);\n\n upcxx_mutex_unlock(&all_events_lock);\n\n }\n\n\n\n void _add_gasnet_handle(gasnet_handle_t h);\n\n\n\n#ifdef UPCXX_USE_DMAPP\n\n void add_dmapp_handle(dmapp_syncid_handle_t h);\n\n#endif\n\n\n\n inline int num_done_cb() const { return _num_done_cb; }\n\n\n\n void _add_done_cb(async_task *task);\n\n\n\n inline void add_done_cb(async_task *task)\n\n {\n\n upcxx_mutex_lock(&all_events_lock);\n\n _add_done_cb(task);\n\n upcxx_mutex_unlock(&all_events_lock);\n\n }\n\n\n\n /**\n\n * Wait for the asynchronous event to complete\n\n */\n\n void wait(); \n\n\n\n /**\n\n * Return 1 if the task is done; return 0 if not\n\n */\n\n inline int async_try()\n\n {\n\n if (upcxx_mutex_trylock(&all_events_lock) != 0) {\n\n return isdone(); // somebody else is holding the lock\n\n }\n\n int rv = _async_try();\n\n upcxx_mutex_unlock(&all_events_lock);\n\n return rv;\n\n }\n\n\n\n inline int test() { return async_try(); }\n\n\n\n private:\n\n void _decref(uint32_t c=1);\n\n void _incref(uint32_t c=1);\n\n int _async_try();\n\n friend int advance(int max_in, int max_out);\n\n };\n\n /// @}\n\n\n\n void event_incref(event *e, uint32_t c=1);\n\n void event_decref(event *e, uint32_t c=1);\n\n\n\n typedef struct event future;\n\n\n\n inline\n\n std::ostream& operator<<(std::ostream& out, const event& e)\n\n {\n\n return out << \"event: count \" << e.count()\n\n << \", # of callback tasks \" << e.num_done_cb()\n\n << \"\\n\";\n\n }\n\n\n\n extern event *system_event; // defined in upcxx.cpp\n\n extern std::list<event *> *outstanding_events;\n\n\n\n /* event stack interface used by finish */\n\n void push_event(event *);\n\n void pop_event();\n\n event *peek_event();\n\n\n\n struct event_stack {\n\n std::vector<event *> stack;\n\n inline event_stack() {\n\n stack.push_back(system_event);\n\n }\n\n };\n\n extern event_stack *events;\n\n\n\n inline void async_wait(event *e)\n\n {\n\n if (e != NULL) {\n\n e->wait();\n\n }\n\n }\n\n\n\n void async_wait();\n\n\n\n int async_try(event *e = peek_event());\n\n\n", "file_path": "include/upcxx/event.h", "rank": 15, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n struct group {\n\n int _size;\n\n int _index;\n\n\n\n group(int sz, int i) : _size(sz), _index(i)\n\n { }\n\n\n\n inline int index() const { return _index; }\n\n inline int size() const { return _size; }\n", "file_path": "include/upcxx/group.h", "rank": 16, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief allocate memory in the global address space of a rank (process)\n\n *\n\n * \\return the pointer to the allocated pace\n\n * \\param nbytes the number of element to be copied\n\n * \\param rank the rank_t where the memory space should be allocated\n\n */\n\n global_ptr<void> allocate(rank_t rank, size_t nbytes);\n\n\n\n static inline void* allocate(size_t nbytes) \n\n {\n\n return allocate(global_myrank(), nbytes).raw_ptr();\n\n }\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief allocate memory in the global address space at a specific rank_t\n\n *\n\n * \\tparam T type of the element\n\n *\n\n * \\return the pointer to the allocated pace\n\n * \\param count the number of element to be copied\n\n * \\param rank the rank_t where the memory space should be allocated\n\n */\n\n template<typename T>\n\n global_ptr<T> allocate(rank_t rank, size_t count)\n\n {\n\n size_t nbytes = count * sizeof(T);\n\n return global_ptr<T>(allocate(rank, nbytes));\n\n }\n\n\n\n template<typename T>\n\n T* allocate(size_t count)\n\n {\n\n size_t nbytes = count * sizeof(T);\n\n return (T*)allocate(nbytes);\n\n }\n\n\n\n void deallocate(global_ptr<void> ptr);\n\n\n\n void deallocate(void *ptr);\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief free memory in the global address space\n\n *\n\n * \\tparam T type of the element\n\n *\n\n * \\param ptr the pointer to which the memory space should be freed\n\n */\n\n template<typename T>\n\n void deallocate(global_ptr<T> ptr)\n\n {\n\n deallocate(global_ptr<void>(ptr));\n", "file_path": "include/upcxx/allocate.h", "rank": 17, "score": 129334.86226198668 }, { "content": "namespace upcxx {\n\n template<bool enable, class T> struct enable_if {\n\n typedef T type;\n\n };\n\n\n\n template<class T> struct enable_if<false, T> {\n\n };\n\n\n\n /* Check if two types are the same. Can be used with enable_if to\n\n * implement an interface, as in the following:\n\n * typedef enable_if<is_same<L, local>::value, T> local_elem_type;\n\n */\n\n template<class T, class U> struct is_same {\n\n enum { value = 0 };\n\n };\n\n\n\n template<class T> struct is_same<T, T> {\n\n enum { value = 1 };\n\n };\n\n\n\n /* Combination of enable_if and is_same */\n\n#ifdef UPCXX_HAVE_CXX11\n\n template<class T, class U, class V>\n\n using enable_if_same = enable_if<is_same<T, U>::value, V>;\n\n#else\n\n template<class T, class U, class V> struct enable_if_same {\n\n };\n\n\n\n template<class T, class V> struct enable_if_same<T, T, V> {\n\n typedef V type;\n\n };\n\n#endif\n", "file_path": "include/upcxx/interfaces.h", "rank": 18, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n template<typename T>\n\n struct atomic {\n\n public:\n\n inline atomic(const T& data) : _data(data)\n\n { }\n\n\n\n inline atomic() : _data()\n\n { }\n\n\n\n inline T load() { return _data; }\n\n inline void store(const T& val) { _data = val; }\n\n\n\n inline T fetch_add(const T& add_val)\n\n {\n\n // no threading\n\n T old = _data;\n\n _data += add_val;\n\n return old;\n\n }\n\n \n\n private:\n\n T _data;\n\n // mutex\n\n };\n\n\n\n template<typename T>\n\n struct fetch_add_am_t {\n\n atomic<T> *obj;\n\n T add_val;\n\n T* old_val_addr;\n\n event* cb_event;\n\n };\n\n\n\n template<typename T>\n\n struct fetch_add_reply_t {\n\n T old_val;\n\n T* old_val_addr;\n\n event* cb_event;\n\n };\n\n\n\n #ifdef UPCXX_HAVE_CXX11\n\n template<typename T = uint64_t>\n\n #else\n\n template<typename T>\n\n #endif\n\n static void fetch_add_am_handler(gasnet_token_t token, void *buf, size_t nbytes)\n\n {\n\n fetch_add_am_t<T> *am = (fetch_add_am_t<T> *)buf;\n\n fetch_add_reply_t<T> reply;\n\n\n\n // if no threading\n\n reply.old_val = am->obj->fetch_add(am->add_val);\n\n reply.old_val_addr = am->old_val_addr;\n\n reply.cb_event = am->cb_event; // callback event on the src rank\n\n // YZ: should use a different GASNet AM handler id for different type T\n\n GASNET_SAFE(gasnet_AMReplyMedium0(token, FETCH_ADD_U64_REPLY,\n\n &reply, sizeof(reply)));\n\n }\n\n\n\n #ifdef UPCXX_HAVE_CXX11\n\n template<typename T = uint64_t>\n\n #else\n\n template<typename T>\n\n #endif\n\n static void fetch_add_reply_handler(gasnet_token_t token, void *buf, size_t nbytes)\n\n {\n\n fetch_add_reply_t<T> *reply = (fetch_add_reply_t<T> *)buf;\n\n\n\n *reply->old_val_addr = reply->old_val;\n\n reply->cb_event->decref();\n\n }\n\n\n\n /**\n\n * Atomic fetch-and-add: atomically add val to the atomic obj and\n\n * then return the old value of the atomic object\n\n */\n\n inline\n\n uint64_t fetch_add(global_ptr<atomic<uint64_t> > obj, uint64_t add_val)\n\n {\n\n event e;\n\n uint64_t old_val;\n\n fetch_add_am_t<uint64_t> am;\n\n\n\n gasnet_AMPoll(); // process other AMs to be fair\n\n\n\n am.obj = obj.raw_ptr();\n\n am.add_val = add_val;\n\n am.old_val_addr = &old_val;\n\n am.cb_event = &e;\n\n e.incref();\n\n \n\n // YZ: should use a different GASNet AM handler id for different type T\n\n GASNET_SAFE(gasnet_AMRequestMedium0(obj.where(), FETCH_ADD_U64_AM, &am, sizeof(am)));\n\n e.wait();\n\n\n\n gasnet_AMPoll(); // process other AMs to be fair\n\n\n\n return old_val;\n\n }\n", "file_path": "include/upcxx/atomic.h", "rank": 19, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n /**\n\n * \\brief data structure for describing a range of integers\n\n *\n\n * UPC++ range is left-closed and right-open: the first (begin)\n\n * element is inclusive while the last (end) element is exclusive.\n\n * For example, range(0, 5, 1) = {0, 1, 2, 3, 4};\n\n */\n\n struct range {\n\n\n\n typedef int iterator;\n\n typedef const int const_iterator;\n\n\n\n int _begin;\n\n int _end;\n\n int _step;\n\n \n\n public:\n\n inline range() :\n\n _begin(0), _end(1), _step(1)\n\n { }\n\n \n\n inline range(int end) :\n\n _begin(0), _end(end), _step(1)\n\n {\n\n assert (end > 0);\n\n }\n\n \n\n inline range(int begin, int end, int step = 1) :\n\n _begin(begin), _end(end), _step(step)\n\n {\n\n if (end > begin) {\n\n assert(step > 0);\n\n } else {\n\n if (begin > end) {\n\n assert(step < 0);\n\n }\n\n }\n\n }\n\n \n\n inline int count() const\n\n {\n\n return (_end - _begin + (_step -1)) / _step;\n\n }\n\n \n\n inline int size() const\n\n {\n\n return count();\n\n }\n\n\n\n inline int begin() const\n\n {\n\n return _begin;\n\n }\n\n \n\n inline int end() const\n\n {\n\n return _end;\n\n }\n\n \n\n inline int step() const\n\n {\n\n return _step;\n\n }\n\n \n\n int operator [] (int i) const\n\n {\n\n assert(i < this->count());\n\n return (_begin + i * _step);\n\n }\n\n \n\n range operator + (int i)\n\n {\n\n // assert(i <= count());\n\n return range(_begin, _end + i * _step, _step);\n\n }\n\n \n\n range operator - (int i)\n\n {\n\n assert(count() > i);\n\n return range(_begin, _end - i * _step, _step);\n\n }\n\n \n\n range operator / (int i)\n\n {\n\n return range(_begin, _begin + count() / i * _step, _step);\n\n }\n\n \n\n bool contains(int i)\n\n {\n\n if ((i >= _begin) && (i < _end) &&\n\n ((i-_begin)%_step == 0))\n\n return true;\n\n \n\n return false;\n\n }\n", "file_path": "include/upcxx/range.h", "rank": 20, "score": 129334.86226198668 }, { "content": "namespace upcxx {\n\n template<class T>\n\n UPCXXI_GLOBALIZE_TYPE(T) broadcast(T val, int root) {\n\n UPCXXI_GLOBALIZE_TYPE(T) sval = (UPCXXI_GLOBALIZE_TYPE(T)) val;\n\n UPCXXI_GLOBALIZE_TYPE(T) result;\n\n upcxx::bcast(&sval, &result, sizeof(UPCXXI_GLOBALIZE_TYPE(T)),\n\n root);\n\n return result;\n\n }\n\n\n\n template<class T> void broadcast(UPCXXI_NONGLOBALIZE_TYPE(T) * src,\n\n T *dst, size_t count, int root) {\n\n upcxx::bcast(src, dst, count*sizeof(T), root);\n\n }\n\n\n\n template<class Array>\n\n void broadcast(Array src, Array dst, int root,\n\n UPCXXI_ARRAY_NG_TYPE(Array) * = 0) {\n\n upcxx::bcast(src.storage_ptr(), dst.storage_ptr(),\n\n src.size()*sizeof(UPCXXI_ARRAY_ELEM_TYPE(Array)),\n\n root);\n\n }\n", "file_path": "include/upcxx/broadcast.h", "rank": 21, "score": 129334.86226198668 }, { "content": "namespace upcxx\n\n{\n\n /*\n\n * Todo: shared_lock variables can only be defined in the file\n\n * scope statically due to limitations in the current\n\n * implementation.\n\n */\n\n\n\n /**\n\n * \\ingroup syncgroup\n\n * global address space lock implemented by active messages and local handler-safe locks.\n\n */\n\n struct shared_lock {\n\n private:\n\n volatile int _locked; /**< lock state: 1 - locked, 0 - unlocked */\n\n rank_t _owner; /**< the owner of the lock */\n\n rank_t _holder; /**< the current holder of the lock */\n\n shared_lock *myself;\n\n\n\n#if defined(UPCXX_THREAD_SAFE) || defined(GASNET_PAR)\n\n upcxx_mutex_t _mutex; /**< local handler-safe lock for thread/signal safety */\n\n#endif\n\n\n\n public:\n\n inline shared_lock(rank_t owner=0)\n\n {\n\n _locked = 0;\n\n _owner = owner;\n\n _holder = _owner;\n\n\n\n myself = this;\n\n#if defined(UPCXX_THREAD_SAFE) || defined(GASNET_PAR)\n\n upcxx_mutex_init(&_mutex);\n\n#endif\n\n }\n\n\n\n /**\n\n * Try to acquire the lock without blocking. return 1 if the\n\n * lock is acquired; return 0 otherwise.\n\n */\n\n int trylock();\n\n\n\n /**\n\n * Acquire the lock and would wait until succeed\n\n */\n\n void lock();\n\n\n\n /**\n\n * Release the lock\n\n */\n\n void unlock();\n\n\n\n // Make lock AM handler functions as member functions so that\n\n // they can access private data\n\n\n\n /// \\cond SHOW_INTERNAL\n\n\n\n /**\n\n * \\return 1 if the lock is hold by the calling process\n\n */\n\n int islocked();\n\n\n\n inline rank_t get_owner() { return _owner; }\n\n inline void set_owner(gasnet_node_t o) { _owner = o; }\n\n\n\n inline rank_t get_holder() { return _holder; }\n\n inline void set_holder(rank_t r) { _holder = r; }\n\n\n\n static void lock_am_handler(gasnet_token_t token, void *buf, size_t nbytes);\n\n static void lock_reply_handler(gasnet_token_t token, void *buf, size_t nbytes);\n\n static void unlock_am_handler(gasnet_token_t token, void *buf, size_t nbytes);\n\n\n\n /// \\endcond\n", "file_path": "include/upcxx/lock.h", "rank": 22, "score": 129334.86226198668 }, { "content": " size_t _arg_sz;\n", "file_path": "include/upcxx/async_impl.h", "rank": 23, "score": 129279.66106148798 }, { "content": " this->_arg_sz = arg_sz;\n", "file_path": "include/upcxx/async_impl.h", "rank": 24, "score": 129274.27685397147 }, { "content": "namespace upcxx\n\n{\n\n extern std::vector<void*> *pending_array_inits;\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief shared 1-D array with 1-D block-cyclic distribution\n\n *\n\n * In the current implementation, the application needs to call\n\n * the init() member function for each shared array object after\n\n * calling upcxx::init(). For example, sa.init(total_sz, blk_sz);\n\n *\n\n * In UPC++, the block size (blk_sz) can be changed at runtime\n\n * by set_blk_sz().\n\n */\n\n template<typename T, size_t BLK_SZ = 1>\n\n struct shared_array\n\n {\n\n T *_data;\n\n T **_alldata;\n\n size_t _blk_sz; // blocking factor\n\n size_t _local_size;\n\n size_t _size;\n\n size_t _type_size;\n\n\n\n void global2local(const size_t global_index,\n\n size_t &local_index,\n\n rank_t &rank)\n\n {\n\n rank_t nplaces = ranks();\n\n size_t block_id = global_index / _blk_sz;\n\n size_t phase = global_index % _blk_sz;\n\n local_index = (block_id / nplaces) * _blk_sz + phase ;\n\n rank = block_id % nplaces;\n\n }\n\n\n\n shared_array(size_t size=0, size_t blk_sz=BLK_SZ)\n\n {\n\n#ifdef UPCXX_DEBUG\n\n printf(\"In shared_array constructor, size %lu\\n\", size);\n\n#endif\n\n _data = NULL;\n\n _alldata = NULL;\n\n _blk_sz = blk_sz;\n\n _local_size = 0;\n\n _size = size;\n\n _type_size = sizeof(T);\n\n if (size != 0)\n\n init(size, blk_sz);\n\n }\n\n\n\n /**\n\n * Return the total size of the shared array.\n\n * This value is not runtime changeable.\n\n */\n\n inline size_t size() { return _size; }\n\n\n\n /**\n\n * Get the current block size (a.k.a. blocking factor in UPC)\n\n */\n\n inline size_t get_blk_sz() { return _blk_sz; }\n\n\n\n /**\n\n * Set the current block size (a.k.a. blocking factor in UPC)\n\n */\n\n inline void set_blk_sz(size_t blk_sz) { _blk_sz = blk_sz; }\n\n\n\n /**\n\n * Initialize the shared array, which should be done after upcxx::init().\n\n * This is a collective function and all ranks should agree on the same\n\n * shared array size (sz) and the blocking factor (blk_sz) or the shared\n\n * array allocated would have undefined behavior (e.g., segmentation fault\n\n * due to insufficient memory allocated on some ranks).\n\n *\n\n * \\param sz total size (# of elements) of the shared array\n\n * \\param blk_sz the blocking factor (# of elements per block)\n\n */\n\n void init(size_t sz, size_t blk_sz)\n\n {\n\n if (!upcxx::is_init()) {\n\n std::cerr << \"error: attempt to create shared_array before \"\n\n << \"initializing UPC++\" << std::endl;\n\n abort();\n\n }\n\n\n\n if (sz == 0) return;\n\n\n\n if (_alldata == NULL) {\n\n _alldata = (T **)malloc(ranks() * sizeof(T*));\n\n assert(_alldata != NULL);\n\n }\n\n\n\n if (_data != NULL) deallocate(_data);\n\n\n\n rank_t np = ranks();\n\n _size = sz;\n\n if (blk_sz != 0)\n\n _blk_sz = blk_sz;\n\n else\n\n _blk_sz = (sz + np - 1) / np;\n\n _local_size = ((_size+_blk_sz -1)/_blk_sz + np - 1) / np * _blk_sz;\n\n\n\n // allocate the data space in bytes\n\n _data = (T*)allocate(myrank(), _local_size * _type_size).raw_ptr();\n\n assert(_data != NULL);\n\n\n\n // \\Todo _data allocated in this way is not aligned!!\n\n gasnet_coll_handle_t h;\n\n h = gasnet_coll_gather_all_nb(GASNET_TEAM_ALL, _alldata, &_data, sizeof(T*),\n\n UPCXX_GASNET_COLL_FLAG);\n\n while(gasnet_coll_try_sync(h) != GASNET_OK) {\n\n advance(); // need to keep polling the task queue while waiting\n\n }\n\n#ifdef UPCXX_DEBUG\n\n printf(\"my rank %d, size %lu, blk_sz %lu, local_sz %lu, type_sz %lu, _data %p\\n\",\n\n myrank(), size(), get_blk_sz(), _local_size, _type_size, _data);\n\n for (int i=0; i<np; i++) {\n\n printf(\"_alldata[%d]=%p \", i, _alldata[i]);\n\n }\n\n printf(\"\\n\");\n\n#endif\n\n }\n\n\n\n void init()\n\n {\n\n init(size(), get_blk_sz());\n\n }\n\n\n\n void init(size_t sz)\n\n {\n\n init(sz, get_blk_sz());\n\n }\n\n\n\n void finalize()\n\n {\n\n barrier();\n\n if (_alldata) free(_alldata);\n\n if (_data != NULL)\n\n deallocate(_data); // _data is from the global address space\n\n }\n\n\n\n /**\n\n * Collectively allocate a shared array of nblocks with blk_sz elements\n\n * per block. This is similar to init() except that init takes the total\n\n * number of elements as argument whereas all_alloc takes the total number\n\n * of blocks as argument (similar to upc_all_alloc).\n\n *\n\n * \\param nblocks total number of blocks\n\n * \\param blk_sz the blocking factor (# of elements per block)\n\n */\n\n void all_alloc(size_t nblocks, size_t blk_sz=BLK_SZ)\n\n {\n\n this->init(nblocks*blk_sz, blk_sz);\n\n }\n\n\n\n global_ref<T> operator [] (size_t global_index)\n\n {\n\n // address translation\n\n size_t local_index;\n\n rank_t rank;\n\n global2local(global_index, local_index, rank);\n\n\n\n // assert(_data != NULL);\n\n // assert(_alldata != NULL);\n\n\n\n#ifdef UPCXX_DEBUG\n\n printf(\"shared_array [], gi %lu, li %lu, rank %u\\n\",\n\n global_index, local_index, rank);\n\n#endif\n\n // only works with statically declared (and presumably aligned) data\n\n return global_ref<T>(rank, &_alldata[rank][local_index]);\n", "file_path": "include/upcxx/shared_array.h", "rank": 25, "score": 127207.0515064521 }, { "content": "namespace upcxx \n\n{ \n\n typedef void (*generic_fp)(void *);\n\n\n\n#define MAX_AM_BCAST_PACKET_SIZE 4096\n\n\n\n /// \\cond SHOW_INTERNAL\n\n /**\n\n * \\ingroup internalgroup Internal API\n\n * This group of API is intended for internal use within the UPCXX lib.\n\n * @{\n\n */\n\n\n\n /**\n\n *\n\n * Initiate Active Message Broadcast\n\n *\n\n * \\param [in] target the set of target nodes\n\n * \\param [in] ack the acknowledgment event\n\n * \\param [in] fp the pointer to the function to be executed\n\n * \\param [in] arg_sz the size of the function arguments in bytes\n\n * \\param [in] args the pointer to the function arguments\n\n * \\param [in] after the dependent event\n\n * \\param [in] root_index the node id of the AM bcast root\n\n */\n\n void am_bcast(range target,\n\n event *ack,\n\n generic_fp fp,\n\n size_t arg_sz,\n\n void * args,\n\n event *after,\n\n int root_index);\n\n\n\n /** @} */ // end of internalgroup\n\n /// \\endcond\n", "file_path": "include/upcxx/active_coll.h", "rank": 26, "score": 127201.86594860218 }, { "content": "namespace upcxx\n\n{\n\n /*************************************/\n\n /* Active Message argument templates */\n\n /*************************************/\n\n\n\n\n\n template <typename Function>\n\n struct generic_arg0 {\n\n Function kernel;\n\n\n\n\n\n generic_arg0(Function k) :\n\n kernel(k) { }\n\n };\n\n\n\n template <typename Function, typename T1>\n\n struct generic_arg1 {\n\n Function kernel;\n\n T1 arg1;\n\n\n\n generic_arg1(Function k, T1 a1) :\n\n kernel(k), arg1(a1) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2>\n\n struct generic_arg2 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n\n\n generic_arg2(Function k, T1 a1, T2 a2) :\n\n kernel(k), arg1(a1), arg2(a2) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2, typename T3>\n\n struct generic_arg3 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n T3 arg3;\n\n\n\n generic_arg3(Function k, T1 a1, T2 a2, T3 a3) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2, typename T3,\n\n typename T4>\n\n struct generic_arg4 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n T3 arg3;\n\n T4 arg4;\n\n\n\n generic_arg4(Function k, T1 a1, T2 a2, T3 a3, T4 a4) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3), arg4(a4) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2, typename T3,\n\n typename T4, typename T5>\n\n struct generic_arg5 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n T3 arg3;\n\n T4 arg4;\n\n T5 arg5;\n\n\n\n generic_arg5(Function k, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3), arg4(a4), arg5(a5) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2, typename T3,\n\n typename T4, typename T5, typename T6>\n\n struct generic_arg6 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n T3 arg3;\n\n T4 arg4;\n\n T5 arg5;\n\n T6 arg6;\n\n\n\n generic_arg6(Function k, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3), arg4(a4), arg5(a5), arg6(a6) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2, typename T3,\n\n typename T4, typename T5, typename T6, typename T7>\n\n struct generic_arg7 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n T3 arg3;\n\n T4 arg4;\n\n T5 arg5;\n\n T6 arg6;\n\n T7 arg7;\n\n\n\n generic_arg7(Function k, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3), arg4(a4), arg5(a5), arg6(a6),\n\n arg7(a7) { }\n\n };\n\n\n\n template <typename Function, typename T1, typename T2, typename T3,\n\n typename T4, typename T5, typename T6, typename T7, typename T8>\n\n struct generic_arg8 {\n\n Function kernel;\n\n T1 arg1;\n\n T2 arg2;\n\n T3 arg3;\n\n T4 arg4;\n\n T5 arg5;\n\n T6 arg6;\n\n T7 arg7;\n\n T8 arg8;\n\n\n\n generic_arg8(Function k, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7,\n\n T8 a8) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3), arg4(a4), arg5(a5), arg6(a6),\n\n arg7(a7), arg8(a8) { }\n", "file_path": "include/upcxx/async_templates.h", "rank": 27, "score": 127190.88321816837 }, { "content": "namespace upcxx\n\n{\n\n // begin progress thread execution (executes progress_helper())\n\n void progress_thread_start();\n\n\n\n // signal to stop the progress thread and wait on it\n\n void progress_thread_stop();\n", "file_path": "include/upcxx/progress_thread.h", "rank": 28, "score": 127190.88321816837 }, { "content": "namespace upcxx\n\n{\n\n#ifdef UPCXX_HAVE_CXX11\n\n\n\n\n\n template<typename Function, typename... Ts>\n\n struct generic_arg {\n\n Function kernel;\n\n std::tuple<Ts...> args;\n\n\n\n generic_arg(const Function& k, const Ts&... as) :\n\n kernel(k), args{as...} {}\n\n\n\n#ifdef UPCXX_APPLY_IMPL1\n\n inline void apply() {\n\n upcxx::apply(kernel, args);\n\n }\n\n#else // UPCXX_APPLY_IMPL2\n\n template<int ...S>\n\n inline void call(util::seq<S...>)\n\n {\n\n kernel(std::get<S>(args) ...);\n\n }\n\n\n\n inline void apply()\n\n {\n\n call(typename util::gens<sizeof...(Ts)>::type());\n\n }\n\n#endif // UPCXX_APPLY_IMPL1\n\n }; // end of struct generic_arg\n\n\n\n /* Active Message wrapper function */\n\n template <typename Function, typename... Ts>\n\n void async_wrapper(void *args) {\n\n generic_arg<Function, Ts...> *a =\n\n (generic_arg<Function, Ts...> *) args;\n\n\n\n a->apply();\n\n }\n\n#endif\n\n\n\n#define MAX_ASYNC_ARG_COUNT 16 // max number of arguments\n\n#define MAX_ASYNC_ARG_SIZE 512 // max size of all arguments (in nbytes)\n\n \n\n /// \\cond SHOW_INTERNAL\n\n struct async_task {\n\n rank_t _caller; // the place where async is called, for reply\n\n rank_t _callee; // the place where the task should be executed\n\n event *_ack; // Acknowledgment event pointer on caller node\n\n generic_fp _fp;\n\n void *_am_src; // active message src buffer\n\n void *_am_dst; // active message dst buffer\n\n size_t _arg_sz;\n\n char _args[MAX_ASYNC_ARG_SIZE];\n\n \n\n inline async_task()\n\n : _caller(0), _callee(0), _ack(NULL), _fp(NULL),\n\n _am_src(NULL), _am_dst(NULL), _arg_sz(0) { };\n\n\n\n inline void init_async_task(rank_t caller,\n\n rank_t callee,\n\n event *ack,\n\n generic_fp fp,\n\n size_t arg_sz,\n\n void *async_args)\n\n {\n\n assert(arg_sz <= MAX_ASYNC_ARG_SIZE);\n\n // set up the task message\n\n // Increase the event reference at submission\n\n /*\n\n if (ack != NULL) {\n\n ack->incref();\n\n }\n\n */\n\n this->_caller = caller;\n\n this->_callee = callee;\n\n this->_ack = ack;\n\n this->_fp = fp;\n\n this->_arg_sz = arg_sz;\n\n if (arg_sz > 0) {\n\n memcpy(&this->_args, async_args, arg_sz);\n\n }\n", "file_path": "include/upcxx/async_impl.h", "rank": 29, "score": 127190.88321816837 }, { "content": "namespace upcxx\n\n{\n\n // **************************************************************************\n\n // Implement global address space shared variable template \n\n // **************************************************************************\n\n \n\n extern std::vector<void *> *pending_shared_var_inits;\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief globally shared variable\n\n *\n\n * shared_var variables can only be defined in the file scope\n\n * (not inside a function). Global data reside on CPU place 0\n\n * (node 0). It only supports contiguous data types that can\n\n * use direct data memcpy (shallow copy) for assignment operations\n\n * without a customized copy function (deep copy) because the\n\n * system doesn't have a general mechanism to perform deep copy\n\n * across nodes.\n\n *\n\n * Example usage: \n\n * shared_var<int> x=123;\n\n *\n\n * void foo() { // can be executed on any cpu place\n\n * int y = x.get();\n\n * x = 456;\n\n * }\n\n *\n\n * std::cout << x;\n\n * printf(\"x=%d\\n\", (int)x); // explicit casting is needed for printf\n\n */\n\n template<typename T>\n\n struct shared_var\n\n {\n\n private:\n\n global_ptr<T> _ptr;\n\n size_t _type_size;\n\n T _val;\n\n\n\n public:\n\n shared_var() : _type_size(sizeof(T))\n\n {\n\n if (upcxx::is_init()) {\n\n init();\n\n } else {\n\n enqueue_init();\n\n }\n\n }\n\n \n\n inline shared_var(const T &val) : _type_size(sizeof(T)), _val(val)\n\n {\n\n if (upcxx::is_init()) {\n\n init();\n\n } else {\n\n enqueue_init();\n\n }\n\n }\n\n\n\n // copy constructor\n\n inline\n\n shared_var(const shared_var<T> &g) : _type_size(g._type_size), _val(g._val)\n\n {\n\n if (upcxx::is_init()) {\n\n init();\n\n } else {\n\n enqueue_init();\n\n }\n\n }\n\n\n\n // init is a collective operation\n\n inline void init(rank_t where=0)\n\n {\n\n // allocate the data space in bytes\n\n if (myrank() == where) {\n\n _ptr = allocate(where, _type_size);\n\n }\n\n\n\n gasnet_coll_handle_t h;\n\n h = gasnet_coll_broadcast_nb(GASNET_TEAM_ALL, &_ptr, where, &_ptr, sizeof(_ptr),\n\n UPCXX_GASNET_COLL_FLAG);\n\n while(gasnet_coll_try_sync(h) != GASNET_OK) {\n\n advance(); // need to keep polling the task queue while waiting\n\n }\n\n#ifdef UPCXX_HAVE_CXX11\n\n assert(_ptr != nullptr);\n\n#else\n\n assert(_ptr.raw_ptr() != NULL);\n\n#endif\n\n\n\n#ifdef UPCXX_DEBUG\n\n std::cout << myrank() << \": _ptr \" << _ptr << \"\\n\";\n\n#endif\n\n }\n\n\n\n inline void enqueue_init()\n\n {\n\n if (pending_shared_var_inits== NULL)\n\n pending_shared_var_inits = new std::vector<void*>;\n\n assert(pending_shared_var_inits!= NULL);\n\n pending_shared_var_inits->push_back((void *)this);\n\n }\n\n\n\n T& get()\n\n {\n\n // gasnet_get(&_val, 0, (char *)shared_var_addr+_my_offset, sizeof(T));\n\n copy<T>(_ptr, &_val, 1);\n\n return _val;\n\n }\n\n \n\n void put(const T &val)\n\n {\n\n _val = val;\n\n // gasnet_put(0, (char *)shared_var_addr+_my_offset, &_val, sizeof(T));\n\n copy<T>(&_val, _ptr, 1);\n\n }\n\n \n\n shared_var<T>& operator =(const T &val)\n\n {\n\n put(val);\n\n return *this;\n\n }\n\n\n\n#define UPCXX_SHARED_VAR_ASSIGN_OP(OP) \\\n\n shared_var<T>& operator OP(const T &a) \\\n\n { \\\n\n /* gasnet_get(&_val, 0, (char *)shared_var_addr+_my_offset, sizeof(T)); */ \\\n\n copy<T>(_ptr, &_val, 1); \\\n\n _val OP a; \\\n\n put(_val); \\\n\n return *this; \\\n\n }\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(+=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(-=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(*=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(/=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(%=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(^=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(|=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(&=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(<<=)\n\n\n\n UPCXX_SHARED_VAR_ASSIGN_OP(>>=)\n\n\n\n //////\n\n\n\n // copy assignment \n\n shared_var<T>& operator =(shared_var<T> &g)\n\n {\n\n if (this != &g) {\n\n put(g.get());\n\n }\n\n return *this;\n\n }\n\n \n\n // type conversion operator\n\n operator T() \n\n { \n\n return get();\n\n }\n\n\n\n inline global_ptr<T> operator &()\n\n {\n\n return global_ptr<T>(&_val, 0);\n\n }\n\n\n\n }; // struct shared_var\n\n\n\n static inline void run_pending_shared_var_inits()\n\n {\n\n#ifdef UPCXX_DEBUG\n\n printf(\"Running shared_var::run_pending_inits(). pending_inits sz %lu\\n\",\n\n pending_inits->size());\n\n#endif\n\n\n\n#ifdef UPCXX_HAVE_CXX11\n\n for (auto it = pending_shared_var_inits->begin();\n\n it != pending_shared_var_inits->end(); ++it) {\n\n#else\n\n for (std::vector<void*>::iterator it = pending_shared_var_inits->begin();\n\n it != pending_shared_var_inits->end(); ++it) {\n\n#endif\n\n shared_var<char> *current = (shared_var<char> *)*it;\n\n#ifdef UPCXX_DEBUG\n\n printf(\"Rank %u: Init shared_var %p, size %lu\\n\",\n\n myrank(), current, current->_type_size);\n\n#endif\n\n current->init();\n\n }\n\n }\n", "file_path": "include/upcxx/shared_var.h", "rank": 30, "score": 127190.88321816837 }, { "content": "namespace upcxx {\n\n template<class T, int N> struct globalize_result {\n\n typedef T type;\n\n };\n\n\n\n template<class T, int N> struct globalize_result<T *, N> {\n\n typedef global_ptr<T> type;\n", "file_path": "include/upcxx/interfaces_internal.h", "rank": 31, "score": 127190.88321816837 }, { "content": "namespace upcxx\n\n{\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief transfer data between processes\n\n *\n\n * \\tparam T type of the element\n\n * \\param src the pointer of src data\n\n * \\param dst the pointer of dst data\n\n * \\param nbytes the number of bytes to be transferred\n\n *\n\n */\n\n int copy(global_ptr<void> src, global_ptr<void> dst, size_t nbytes);\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief transfer data between processes\n\n *\n\n * \\tparam T type of the element\n\n * \\param src the pointer of src data\n\n * \\param dst the pointer of dst data\n\n * \\param count the number of element to be transferred\n\n *\n\n * \\see test_global_ptr.cpp\n\n */\n\n template<typename T>\n\n int copy(global_ptr<T> src, global_ptr<T> dst, size_t count)\n\n {\n\n size_t nbytes = count * sizeof(T);\n\n return copy((global_ptr<void>)src, (global_ptr<void>)dst, nbytes);\n\n }\n\n\n\n template<typename T>\n\n inline int copy(global_ptr<T> src, T* dst, size_t count)\n\n {\n\n return copy(src, global_ptr<T>(dst), count);\n\n }\n\n\n\n template<typename T>\n\n inline int copy(T* src, global_ptr<T> dst, size_t count)\n\n {\n\n return copy(global_ptr<T>(src), dst, count);\n\n }\n\n\n\n int async_copy(global_ptr<void> src,\n\n global_ptr<void> dst,\n\n size_t bytes,\n\n event *done_event = peek_event());\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief Non-blocking transfer data between processes\n\n *\n\n * \\tparam T type of the element\n\n * \\param src the pointer of src data\n\n * \\param dst the pointer of dst data\n\n * \\param count the number of element to be copied\n\n * \\param done_event the event to be signaled after transfer completion \n\n */\n\n template<typename T>\n\n int async_copy(global_ptr<T> src,\n\n global_ptr<T> dst,\n\n size_t count,\n\n event *done_event = peek_event())\n\n {\n\n size_t nbytes = count * sizeof(T);\n\n return async_copy((global_ptr<void>)src,\n\n (global_ptr<void>)dst,\n\n nbytes,\n\n done_event);\n\n }\n\n\n\n template<typename T>\n\n inline int async_copy(global_ptr<T> src, T* dst, size_t count,\n\n event *done_event = peek_event())\n\n {\n\n return async_copy(src, global_ptr<T>(dst), count, done_event);\n\n }\n\n\n\n template<typename T>\n\n inline int async_copy(T* src, global_ptr<T> dst, size_t count,\n\n event *done_event = peek_event())\n\n {\n\n return async_copy(global_ptr<T>(src), dst, count, done_event);\n\n }\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief Non-blocking signaling copy, which first performs an async copy\n\n * and then signal an event on the destination rank\n\n *\n\n * The remote rank can wait on the event to check if the corresponding\n\n * async_copy data have arrived.\n\n *\n\n * \\tparam T type of the element\n\n * \\param src the pointer of src data\n\n * \\param dst the pointer of dst data\n\n * \\param nbytes the number of bytes to be transferred\n\n * \\param signal_event the event to be signaled on the dst rank after transfer\n\n * \\param local_completion sender event when the local buffer can be reused\n\n * \\param remote_completion sender event when the dst buffer is written\n\n */\n\n int async_copy_and_signal(global_ptr<void> src,\n\n global_ptr<void> dst,\n\n size_t nbytes,\n\n event *signal_event,\n\n event *local_completion,\n\n event *remote_completion = peek_event());\n\n\n\n /**\n\n * \\ingroup gasgroup\n\n * \\brief Non-blocking signaling copy, which first performs an async copy\n\n * and then signal an event on the destination rank\n\n *\n\n * The remote rank can wait on the event to check if the corresponding\n\n * async_copy data have arrived.\n\n *\n\n * The remote rank can wait on the flag to check if the corresponding\n\n * async_copy data have arrived.\n\n *\n\n * \\tparam T type of the element\n\n * \\param src the pointer of src data\n\n * \\param dst the pointer of dst data\n\n * \\param count the number of element to be transferred\n\n * \\param signal_event the event to be signaled on the dst rank\n\n * \\param done_event the event to be signaled after copy completion\n\n */\n\n template<typename T>\n\n int async_copy_and_signal(global_ptr<T> src,\n\n global_ptr<T> dst,\n\n size_t count,\n\n event *signal_event,\n\n event *local_completion,\n\n event *remote_completion = peek_event())\n\n {\n\n size_t nbytes = count * sizeof(T);\n\n return async_copy_and_signal((global_ptr<void>)src,\n\n (global_ptr<void>)dst,\n\n nbytes,\n\n signal_event,\n\n local_completion,\n\n remote_completion);\n\n }\n\n\n\n /**\n\n * async_copy_fence is deprecated. Please use async_wait() instead.\n\n */\n\n void async_copy_fence();\n\n\n\n /**\n\n * async_copy_try is deprecated. Please async_try() instead.\n\n */\n\n int async_copy_try();\n\n\n", "file_path": "include/upcxx/async_copy.h", "rank": 32, "score": 127190.88321816837 }, { "content": "namespace upcxx\n\n{\n\n #define DMAPP_SAFE(FUNCALL) \\\n\n do { \\\n\n dmapp_return_t rv = FUNCALL; \\\n\n if (rv != DMAPP_RC_SUCCESS) { \\\n\n const char *err_str; \\\n\n dmapp_explain_error(rv, &err_str); \\\n\n gasneti_fatalerror(\"DMAPP fatal error (%s) at %s:%d\\n\", err_str, __FILE__, __LINE__); \\\n\n } \\\n\n } while(0)\n\n\n\n /* convert data size in bytes to nelems of dmapp_type_t */\n\n inline\n\n void bytes_to_dmapp_type(void *dst, void *src, size_t nbytes,\n\n uint64_t *nelems, dmapp_type_t *type)\n\n {\n\n size_t d = (size_t)dst;\n\n size_t s = (size_t)src;\n\n if (nbytes % 16 == 0 && d % 16 == 0 && s % 16 == 0) { /* nbytes % 16 */\n\n *type = DMAPP_DQW;\n\n *nelems = nbytes >> 4; /* nbytes / 16 */\n\n } else if (nbytes % 8 == 0 && d % 8 == 0 && s % 8 ==0) { /* nbytes % 8 */\n\n *type = DMAPP_QW;\n\n *nelems = nbytes >> 3; /* nbytes / 8 */\n\n } else if (nbytes % 4 == 0 && d % 4 == 0 && s % 4 ==0) { /* nbytes % 4 */\n\n *type = DMAPP_DW;\n\n *nelems = nbytes >> 2; /* nbytes / 4 */\n\n } else {\n\n *type = DMAPP_BYTE;\n\n *nelems = nbytes;\n\n }\n\n }\n\n\n\n inline\n\n dmapp_seg_desc_t *get_dmapp_seg(uint32_t rank)\n\n {\n\n assert(rank < upcxx::ranks());\n\n return &upcxx_dmapp_segs[rank];\n\n }\n\n\n\n // Init Cray DMAPP for UPC++ w. GASNet\n\n // Should be called after gasnet_attach but before using any DMAPP features\n\n void init_dmapp();\n\n\n", "file_path": "include/upcxx/dmapp_channel/dmapp_helper.h", "rank": 33, "score": 123210.26497892958 }, { "content": "class Output:\n\n def __init__(self):\n\n self.string = ''\n\n\n\n def GetLastLine(self):\n\n index = self.string.rfind('\\n')\n\n if index < 0:\n\n return ''\n\n\n\n return self.string[index + 1:]\n\n\n\n def Append(self, s):\n", "file_path": "scripts/pump.py", "rank": 34, "score": 114438.0761015995 }, { "content": " template<class T> static T add(T val, int = 0) { return val; }\n", "file_path": "examples/stencil/globals.h", "rank": 35, "score": 114380.2961947538 }, { "content": " template<class T> static T add(T val, int = 0) { return val; }\n", "file_path": "examples/cg/globals.h", "rank": 36, "score": 114380.2961947538 }, { "content": " template<class T> static T min(T val) { return val; } \n", "file_path": "examples/ft/globals.h", "rank": 37, "score": 114380.2961947538 }, { "content": " template<class T> static T add(T val, int = 0) { return val; }\n", "file_path": "examples/mg/globals.h", "rank": 38, "score": 114380.2961947538 }, { "content": " template<class T> static T add(T val, int = 0) { return val; }\n", "file_path": "examples/knapsack/globals.h", "rank": 39, "score": 114380.2961947538 }, { "content": "struct Buffer{\n\n void *ptr;\n\n size_t size;\n\n};\n\n\n\n/*\n\n holds information about each remote buffer\n\n each thread has its own array\n\n array has the same length as the number of nodes\n\n*/\n\nstatic struct Buffer **bufferArray;\n\n\n\n/*\n\n initialize data structure for buffer reuse\n\n assumes only one thread in the box will run this code\n\n so it does not acquire any locks\n\n*/\n\nstatic void buffer_init(){\n\n uint32_t i, j;\n\n bufferArray = (struct Buffer **)\n", "file_path": "src/array_bulk.cpp", "rank": 40, "score": 113826.24430933558 }, { "content": "struct node_t {\n\n int id;\n\n int degree;\n\n int elim_step;\n\n int adj_sz; // # of edges of this node, which is the size of adj\n\n upcxx::global_ptr<int> adj;\n\n};\n\n\n\nvoid dump_local_nodes(node_t *local_nodes, int n);\n\n\n\n/**\n\n * Compare the degrees of two nodes\n\n * \\return true if (a->degree < b->agree)\n\n * or ((a->degree == b->degree) && (a->id < b->id))\n\n */\n\nbool node_comp(node_t * & a, node_t * & b)\n\n{\n\n if (a->degree < b->degree) {\n\n return true;\n\n } else {\n", "file_path": "examples/minimum_degree/mdo_upcxx.cpp", "rank": 41, "score": 105953.16376705872 }, { "content": "const char *forkjoin_h_include_error = \"forkjoin.h should only be included once in the main cpp file where user's main() function is defined!\";\n", "file_path": "include/upcxx/forkjoin.h", "rank": 42, "score": 100730.69584365093 }, { "content": "#include \"upcxx/upcxx.h\"\n\n#include \"upcxx/upcxx_internal.h\"\n\n\n\nnamespace upcxx {\n\n int barrier()\n\n {\n\n int rv;\n\n UPCXX_CALL_GASNET(gasnet_coll_barrier_notify(current_gasnet_team(), 0,\n\n GASNET_BARRIERFLAG_UNNAMED));\n\n do {\n\n UPCXX_CALL_GASNET(rv=gasnet_coll_barrier_try(current_gasnet_team(), 0,\n\n GASNET_BARRIERFLAG_UNNAMED));\n\n if (rv == GASNET_ERR_NOT_READY) {\n\n if (advance() < 0) { // process the async task queue\n\n return UPCXX_ERROR;\n\n }\n\n }\n\n } while (rv != GASNET_OK);\n\n\n\n return UPCXX_SUCCESS;\n\n }\n\n} // namespace upcxx\n", "file_path": "src/barrier.cpp", "rank": 43, "score": 98023.7675179916 }, { "content": " int peek();\n", "file_path": "include/upcxx/upcxx_runtime.h", "rank": 44, "score": 96380.15940636332 }, { "content": " size_t nbytes;\n", "file_path": "include/upcxx/upcxx_internal.h", "rank": 45, "score": 96375.56356085329 }, { "content": "#define ONLY_MSPACES 1 // only use mspace from dl malloc\n", "file_path": "include/upcxx/upcxx_internal.h", "rank": 46, "score": 96375.56356085329 }, { "content": " void *ptr;\n", "file_path": "include/upcxx/upcxx_internal.h", "rank": 47, "score": 96375.56356085329 }, { "content": "#define upcxx_finish UPCXX_finish_(UPCXX_UNIQUIFY(fs_))\n", "file_path": "include/upcxx/finish.h", "rank": 48, "score": 96375.56356085329 }, { "content": " inline std::ostream& operator<<(std::ostream& out, const upcxx::range& r)\n\n {\n\n const int buf_sz = 1024;\n\n char buf[buf_sz];\n\n snprintf(buf, buf_sz, \"range: (begin %u, end %u, step %u, count %u)\",\n\n r.begin(), r.end(), r.step(), r.count());\n\n return out << std::string(buf);\n", "file_path": "include/upcxx/range.h", "rank": 49, "score": 95859.16880646067 }, { "content": " inline\n", "file_path": "include/upcxx/team.h", "rank": 50, "score": 95859.11725840985 }, { "content": " shared_lock *myself;\n", "file_path": "include/upcxx/lock.h", "rank": 51, "score": 95853.65806227936 }, { "content": " public:\n\n inline range() :\n\n _begin(0), _end(1), _step(1)\n\n { }\n\n \n\n inline range(int end) :\n\n _begin(0), _end(end), _step(1)\n\n {\n", "file_path": "include/upcxx/range.h", "rank": 52, "score": 95853.65806227936 }, { "content": " event e;\n", "file_path": "include/upcxx/finish.h", "rank": 53, "score": 95853.65806227936 }, { "content": " inline f_scope():done(0)\n\n {\n", "file_path": "include/upcxx/finish.h", "rank": 54, "score": 95853.65806227936 }, { "content": " inline std::ostream& operator<<(std::ostream& out, const group& g)\n", "file_path": "include/upcxx/group.h", "rank": 55, "score": 95853.65806227936 }, { "content": " team::descend_team(t->mychild());\n", "file_path": "include/upcxx/team.h", "rank": 56, "score": 95853.65806227936 }, { "content": " public:\n\n inline shared_lock(rank_t owner=0)\n\n {\n", "file_path": "include/upcxx/lock.h", "rank": 57, "score": 95853.65806227936 }, { "content": " inline event_stack() {\n", "file_path": "include/upcxx/event.h", "rank": 58, "score": 95853.65806227936 }, { "content": " myself = this;\n", "file_path": "include/upcxx/lock.h", "rank": 59, "score": 95853.65806227936 }, { "content": " src[0] = val;\n\n upcxx::reduce(src, dst, 1, root, op, datatype_wrapper<T>::value);\n\n return dst[0];\n\n }\n\n\n\n template<class T> static void reduce_internal(T *src, T *dst,\n\n int count,\n\n upcxx_op_t op) {\n\n reduce_internal(src, dst, count, op, 0);\n\n upcxx::bcast(dst, dst, count * sizeof(T), 0);\n\n }\n\n\n\n template<class T> static void reduce_internal(T *src, T *dst,\n\n int count,\n\n upcxx_op_t op,\n\n int root) {\n\n upcxx::reduce(src, dst, count, root, op, datatype_wrapper<T>::value);\n\n }\n\n\n\n public:\n", "file_path": "include/upcxx/reduce.h", "rank": 60, "score": 94579.61471932441 }, { "content": "#define UPCXXR_NUMBER_TYPE(T) \\\n\n typename datatype_wrapper<T>::number_type\n\n#define UPCXXR_INTEGER_TYPE(T) \\\n\n typename datatype_wrapper<T>::int_type\n\n\n\n#define UPCXXR_REDUCE_ALL_DECL(ret_type, op_name, op_code) \\\n\n template<class T> static ret_type op_name(T val) { \\\n\n return reduce_internal(val, op_code); \\\n\n }\n\n\n\n#define UPCXXR_REDUCE_TO_DECL(ret_type, op_name, op_code) \\\n\n template<class T> static ret_type op_name(T val, int root) { \\\n\n return reduce_internal(val, op_code, root); \\\n\n }\n\n\n\n#define UPCXXR_REDUCE_BULK_ALL_DECL(ret_type, op_name, op_code) \\\n\n template<class T> static void op_name(T *src, T *dst, int count, \\\n\n ret_type * = 0) { \\\n\n reduce_internal(src, dst, count, op_code); \\\n\n }\n", "file_path": "include/upcxx/reduce.h", "rank": 61, "score": 94567.383206494 }, { "content": "\n\n#define UPCXXR_REDUCE_BULK_TO_DECL(ret_type, op_name, op_code) \\\n\n template<class T> static void op_name(T *src, T *dst, int count, \\\n\n int root, ret_type * = 0) { \\\n\n reduce_internal(src, dst, count, op_code, root); \\\n\n }\n\n\n\n#define UPCXXR_ARRAY_NUM_TYPE(Array) \\\n\n UPCXXR_NUMBER_TYPE(UPCXXI_ARRAY_ELEM_TYPE(Array))\n\n\n\n#define UPCXXR_ARRAY_INT_TYPE(Array) \\\n\n UPCXXR_INTEGER_TYPE(UPCXXI_ARRAY_ELEM_TYPE(Array))\n\n\n\n#define UPCXXR_REDUCE_ARRAY_NUM_ALL_DECL(op_name, op_code) \\\n\n template<class Array> \\\n\n static void op_name(Array src, Array dst, \\\n\n UPCXXR_ARRAY_NUM_TYPE(Array) * = 0) { \\\n\n op_name(src.storage_ptr(), dst.storage_ptr(), src.size()); \\\n\n }\n\n\n", "file_path": "include/upcxx/reduce.h", "rank": 62, "score": 94565.83582128862 }, { "content": "#define UPCXXR_REDUCE_ARRAY_INT_ALL_DECL(op_name, op_code) \\\n\n template<class Array> \\\n\n static void op_name(Array src, Array dst, \\\n\n UPCXXR_ARRAY_INT_TYPE(Array) * = 0) { \\\n\n op_name(src.storage_ptr(), dst.storage_ptr(), src.size()); \\\n\n }\n\n\n\n#define UPCXXR_REDUCE_ARRAY_NUM_TO_DECL(op_name, op_code) \\\n\n template<class Array> \\\n\n static void op_name(Array src, Array dst, int root, \\\n\n UPCXXR_ARRAY_NUM_TYPE(Array) * = 0) { \\\n\n op_name(src.storage_ptr(), dst.storage_ptr(), src.size(), \\\n\n root); \\\n\n }\n\n\n\n#define UPCXXR_REDUCE_ARRAY_INT_TO_DECL(op_name, op_code) \\\n\n template<class Array> \\\n\n static void op_name(Array src, Array dst, int root, \\\n\n UPCXXR_ARRAY_INT_TYPE(Array) * = 0) { \\\n\n op_name(src.storage_ptr(), dst.storage_ptr(), src.size(), \\\n", "file_path": "include/upcxx/reduce.h", "rank": 63, "score": 94564.62534749354 }, { "content": "\n\n template<class T> struct datatype_wrapper {};\n\n UPCXXR_WRAPPER_DECL(char, int_type, UPCXX_CHAR);\n\n UPCXXR_WRAPPER_DECL(unsigned char, int_type, UPCXX_UCHAR);\n\n UPCXXR_WRAPPER_DECL(short, int_type, UPCXX_SHORT);\n\n UPCXXR_WRAPPER_DECL(unsigned short, int_type, UPCXX_USHORT);\n\n UPCXXR_WRAPPER_DECL(int, int_type, UPCXX_INT);\n\n UPCXXR_WRAPPER_DECL(unsigned int, int_type, UPCXX_UINT);\n\n UPCXXR_WRAPPER_DECL(long, int_type, UPCXX_LONG);\n\n UPCXXR_WRAPPER_DECL(unsigned long, int_type, UPCXX_ULONG);\n\n UPCXXR_WRAPPER_DECL(long long, int_type, UPCXX_LONG_LONG);\n\n UPCXXR_WRAPPER_DECL(unsigned long long, int_type, UPCXX_ULONG_LONG);\n\n UPCXXR_WRAPPER_DECL(float, float_type, UPCXX_FLOAT);\n\n UPCXXR_WRAPPER_DECL(double, float_type, UPCXX_DOUBLE);\n\n\n", "file_path": "include/upcxx/reduce.h", "rank": 64, "score": 94559.61884517173 }, { "content": "#pragma once\n\n\n\n#include <gasnet.h>\n\n#include <gasnet_tools.h>\n\n\n\nnamespace upcxx {\n", "file_path": "include/upcxx/timer.h", "rank": 65, "score": 94554.65407485007 }, { "content": "/**\n\n * reduce.h - provides higher-level interface to reductions\n\n * \\see collective.h for low-level reduction interface\n\n */\n\n\n\n#pragma once\n\n\n\n#include <upcxx/allocate.h>\n\n#include <upcxx/coll_flags.h>\n\n#include <upcxx/collective.h>\n\n#include <upcxx/interfaces_internal.h>\n\n//#include <team.h>\n\n\n\n#define UPCXXR_WRAPPER_DECL(T, num_class, type_code) \\\n\n template<> struct datatype_wrapper<T> { \\\n\n typedef T number_type; \\\n\n typedef T num_class; \\\n\n static const upcxx_datatype_t value = type_code; \\\n\n }\n\n\n", "file_path": "include/upcxx/reduce.h", "rank": 66, "score": 94554.16287706306 }, { "content": " UPCXXR_REDUCE_NUM_DECLS(add, UPCXX_SUM)\n\n UPCXXR_REDUCE_NUM_DECLS(mult, UPCXX_PROD)\n\n UPCXXR_REDUCE_NUM_DECLS(max, UPCXX_MAX)\n\n UPCXXR_REDUCE_NUM_DECLS(min, UPCXX_MIN)\n\n\n\n UPCXXR_REDUCE_INT_DECLS(lor, UPCXX_LOR)\n\n UPCXXR_REDUCE_INT_DECLS(lxor, UPCXX_LXOR)\n\n UPCXXR_REDUCE_INT_DECLS(land, UPCXX_LAND)\n\n UPCXXR_REDUCE_INT_DECLS(bor, UPCXX_BOR)\n\n UPCXXR_REDUCE_INT_DECLS(bxor, UPCXX_BXOR)\n\n UPCXXR_REDUCE_INT_DECLS(band, UPCXX_BAND)\n\n };\n\n\n\n} /* namespace upcxx */\n\n\n\n#undef UPCXXR_WRAPPER_DECL\n\n#undef UPCXXR_NUMBER_TYPE\n\n#undef UPCXXR_INTEGER_TYPE\n\n#undef UPCXXR_REDUCE_ALL_DECL\n\n#undef UPCXXR_REDUCE_TO_DECL\n", "file_path": "include/upcxx/reduce.h", "rank": 67, "score": 94553.0955878242 }, { "content": " inline double millis() const {\n\n return gasnett_ticks_to_ns(elap_tick) / 1.0E6;\n\n }\n\n\n\n inline double micros() const {\n\n return gasnett_ticks_to_ns(elap_tick) / 1.0E3;\n\n }\n\n\n\n inline double nanos() const {\n\n return gasnett_ticks_to_ns(elap_tick);\n\n }\n\n\n\n static inline double granularity() {\n\n return gasnett_tick_granularityus();\n\n }\n\n\n\n static inline double overhead() {\n\n return gasnett_tick_overheadus();\n\n }\n\n };\n\n}\n", "file_path": "include/upcxx/timer.h", "rank": 68, "score": 94549.79773134725 }, { "content": " root); \\\n\n }\n\n\n\n#define UPCXXR_REDUCE_NUM_DECLS(op_name, op_code) \\\n\n UPCXXR_REDUCE_ALL_DECL(UPCXXR_NUMBER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_TO_DECL(UPCXXR_NUMBER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_BULK_ALL_DECL(UPCXXR_NUMBER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_BULK_TO_DECL(UPCXXR_NUMBER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_ARRAY_NUM_ALL_DECL(op_name, op_code) \\\n\n UPCXXR_REDUCE_ARRAY_NUM_TO_DECL(op_name, op_code)\n\n\n\n#define UPCXXR_REDUCE_INT_DECLS(op_name, op_code) \\\n\n UPCXXR_REDUCE_ALL_DECL(UPCXXR_INTEGER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_TO_DECL(UPCXXR_INTEGER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_BULK_ALL_DECL(UPCXXR_INTEGER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_BULK_TO_DECL(UPCXXR_INTEGER_TYPE(T), op_name, op_code) \\\n\n UPCXXR_REDUCE_ARRAY_INT_ALL_DECL(op_name, op_code) \\\n\n UPCXXR_REDUCE_ARRAY_INT_TO_DECL(op_name, op_code)\n\n\n\nnamespace upcxx {\n", "file_path": "include/upcxx/reduce.h", "rank": 69, "score": 94546.88371251333 }, { "content": "#undef UPCXXR_REDUCE_BULK_ALL_DECL\n\n#undef UPCXXR_REDUCE_BULK_TO_DECL\n\n#undef UPCXXR_ARRAY_NUM_TYPE\n\n#undef UPCXXR_ARRAY_INT_TYPE\n\n#undef UPCXXR_REDUCE_ARRAY_NUM_ALL_DECL\n\n#undef UPCXXR_REDUCE_ARRAY_INT_ALL_DECL\n\n#undef UPCXXR_REDUCE_ARRAY_NUM_TO_DECL\n\n#undef UPCXXR_REDUCE_ARRAY_INT_TO_DECL\n\n#undef UPCXXR_REDUCE_NUM_DECLS\n\n#undef UPCXXR_REDUCE_INT_DECLS\n", "file_path": "include/upcxx/reduce.h", "rank": 70, "score": 94543.87417603498 }, { "content": " event *cb_event;\n", "file_path": "include/upcxx/upcxx_internal.h", "rank": 71, "score": 94334.98406641715 }, { "content": " void **ptr_addr;\n", "file_path": "include/upcxx/upcxx_internal.h", "rank": 72, "score": 94334.98406641715 }, { "content": " extern team team_all;\n", "file_path": "include/upcxx/team.h", "rank": 73, "score": 93407.85215821305 }, { "content": " qnode_t *head;\n", "file_path": "include/upcxx/queue.h", "rank": 74, "score": 93385.22053758062 }, { "content": " struct qnode *next;\n", "file_path": "include/upcxx/queue.h", "rank": 75, "score": 93385.22053758062 }, { "content": " void *data;\n", "file_path": "include/upcxx/queue.h", "rank": 76, "score": 93385.22053758062 }, { "content": " generic_arg16(Function k, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7,\n\n T8 a8, T9 a9, T10 a10, T11 a11, T12 a12, T13 a13, T14 a14, T15 a15,\n\n T16 a16) :\n\n kernel(k), arg1(a1), arg2(a2), arg3(a3), arg4(a4), arg5(a5), arg6(a6),\n\n arg7(a7), arg8(a8), arg9(a9), arg10(a10), arg11(a11), arg12(a12),\n", "file_path": "include/upcxx/async_templates.h", "rank": 77, "score": 93385.22053758062 }, { "content": "int main(int argc, char **argv)\n\n{\n\n int rv = 0;\n\n\n\n // The master spawns tasks and the slaves wait.\n\n if (upcxx::myrank() == 0) {\n\n // start the user main function\n\n rv = _user_main(argc, argv);\n\n upcxx::signal_exit();\n\n } else {\n\n upcxx::wait_for_incoming_tasks();\n\n }\n\n\n\n return rv;\n", "file_path": "include/upcxx/forkjoin.h", "rank": 78, "score": 93385.22053758062 }, { "content": " int _index;\n", "file_path": "include/upcxx/group.h", "rank": 79, "score": 93385.22053758062 }, { "content": " int done;\n", "file_path": "include/upcxx/finish.h", "rank": 80, "score": 93385.22053758062 }, { "content": " inline async_task()\n\n : _caller(0), _callee(0), _ack(NULL), _fp(NULL),\n", "file_path": "include/upcxx/async_impl.h", "rank": 81, "score": 93385.22053758062 }, { "content": " struct qnode *prev;\n", "file_path": "include/upcxx/queue.h", "rank": 82, "score": 93385.22053758062 }, { "content": " int _size;\n", "file_path": "include/upcxx/group.h", "rank": 83, "score": 93385.22053758062 }, { "content": " inline std::ostream& operator<<(std::ostream& out, const async_task& task)\n", "file_path": "include/upcxx/async_impl.h", "rank": 84, "score": 93385.22053758062 }, { "content": "/**\n\n * Test the reduce collective functions\n\n */\n\n\n\n#include <upcxx.h>\n\n\n\nusing namespace std;\n\nusing namespace upcxx;\n\n\n\ntemplate<class T>\n\nvoid test(upcxx_datatype_t dt, size_t count)\n\n{\n\n global_ptr<T> src;\n\n global_ptr<T> dst;\n\n \n\n src = allocate<T>(myrank(), count);\n\n dst = allocate<T>(myrank(), count);\n\n \n\n#ifdef DEBUG\n\n cerr << myrank() << \" scr: \" << src << \"\\n\";\n", "file_path": "examples/basic/test_reduce.cpp", "rank": 88, "score": 52.740453128530646 }, { "content": "global_matrix<double> A, B, C;\n\n\n\ndouble mysecond()\n\n{\n\n struct timeval tv;\n\n gettimeofday(&tv, 0);\n\n return tv.tv_sec + ((double) tv.tv_usec / 1000000);\n\n}\n\n\n\ndouble random_double(void)\n\n{\n\n long long tmp;\n\n\n\n tmp = rand();\n\n tmp = (tmp << 32) | rand();\n\n\n\n return (double)tmp;\n\n\n\n //return 1.0;\n\n}\n", "file_path": "examples/matrixmul/matmul.cpp", "rank": 96, "score": 45.001351883138945 }, { "content": "// Test copy of unit-width and non-unit-width ghost zones.\n\n\n\n#include <iostream>\n\n#include <upcxx.h>\n\n#include <upcxx/array.h>\n\n\n\nusing namespace upcxx;\n\n\n\nvoid test(ndarray<int, 3> A) {\n\n ndarray<ndarray<int, 3, global>, 1> B(RD(ranks()));\n\n B.exchange(A);\n\n upcxx_foreach (p, A.domain()) {\n\n A[p] = 128 * 128 * 128 * p[1] + 128 * 128 * p[2] + 128 * p[3] + myrank();\n\n };\n\n barrier();\n\n if (myrank() == 0) {\n\n int checked = 0;\n\n B[1].copy(A);\n\n std::cout << \"domains: \" << A.domain() << \", \" << B[1].domain() << std::endl;\n\n std::cout << \"intersection: \" << (A.domain() * B[1].domain()) << std::endl;\n", "file_path": "examples/basic/test_array_ghost_copy.cpp", "rank": 97, "score": 44.925975924000575 }, { "content": "/**\n\n * \\example test_new_async.cpp\n\n *\n\n * Test the asynchronous task execution with finish\n\n *\n\n */\n\n\n\n#include <upcxx.h>\n\n#include <upcxx/finish.h>\n\n\n\n#include <iostream>\n\n\n\nusing namespace std;\n\nusing namespace upcxx;\n\n\n\nvoid print_task(int task_id)\n\n{\n\n cout << \"myrank() \" << myrank() << \": task_id \" << task_id << \"\\n\";\n\n}\n\n\n", "file_path": "examples/basic/test_finish.cpp", "rank": 99, "score": 43.30638455408055 } ]
C++
BlackVision/Test/Tools/TestLibCore/Source/Conversions/String2Integer.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
#include "gtest/gtest.h" #include "Serialization/SerializationHelper.h" using namespace bv; template< class Type > class LibCore_String2T_Integer : public testing::Test { protected: LibCore_String2T_Integer() {}; }; template< class Type > class LibCore_String2T_IntegerSigned : public testing::Test { protected: LibCore_String2T_IntegerSigned() {}; }; template< class Type > class LibCore_String2T_IntegerUnsigned : public testing::Test { protected: LibCore_String2T_IntegerUnsigned() {}; }; typedef testing::Types< UInt64, Int64, UInt32, Int32, UInt16, Int16, UInt8, Int8 > IntegerTypesList; typedef testing::Types< Int64, Int32, Int16, Int8 > SignedIntegerTypesList; typedef testing::Types< UInt64, UInt32, UInt16, UInt8 > UnsignedIntegerTypesList; TYPED_TEST_CASE( LibCore_String2T_Integer, IntegerTypesList ); TYPED_TEST_CASE( LibCore_String2T_IntegerSigned, SignedIntegerTypesList ); TYPED_TEST_CASE( LibCore_String2T_IntegerUnsigned, UnsignedIntegerTypesList ); TYPED_TEST( LibCore_String2T_Integer, ValidInput ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "123" ); TypeParam intDef = Convert::String2T< TypeParam >( "123", 5 ); EXPECT_TRUE( intExp.IsValid() ); EXPECT_EQ( intExp.GetVal(), 123 ); EXPECT_EQ( intDef, 123 ); } TYPED_TEST( LibCore_String2T_IntegerSigned, NegativeInput ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "-123" ); TypeParam intDef = Convert::String2T< TypeParam >( "-123", 5 ); EXPECT_TRUE( intExp.IsValid() ); EXPECT_EQ( intExp.GetVal(), -123 ); EXPECT_EQ( intDef, -123 ); } TYPED_TEST( LibCore_String2T_IntegerUnsigned, NegativeInput ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "-123" ); TypeParam intDef = Convert::String2T< TypeParam >( "-123", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConvertFromFloatStr ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "1.0434" ); TypeParam intDef = Convert::String2T< TypeParam >( "1.0434", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConvertOverflowing ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "48446744073709551615" ); TypeParam intDef = Convert::String2T< TypeParam >( "48446744073709551615", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConvertUnderflowing ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "-48446744073709551615" ); TypeParam intDef = Convert::String2T< TypeParam >( "-48446744073709551615", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, TextBeforeNumber ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "bla13" ); TypeParam intDef = Convert::String2T< TypeParam >( "bla13", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, TextAfterNumber ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "13bla" ); TypeParam intDef = Convert::String2T< TypeParam >( "13bla", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, TextInTheMiddleOfNumber ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "13bla234" ); TypeParam intDef = Convert::String2T< TypeParam >( "13bla234", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConversionReversibility ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( Convert::T2String( 123 ) ); EXPECT_TRUE( intExp.IsValid() ); EXPECT_EQ( intExp.GetVal(), 123 ); }
#include "gtest/gtest.h" #include "Serialization/SerializationHelper.h" using namespace bv; template< class Type > class LibCore_String2T_Integer : public testing::Test { protected: LibCore_String2T_Integer() {}; }; template< class Type > class LibCore_String2T_IntegerSigned : public testing::Test { protected: LibCore_String2T_IntegerSigned() {}; }; template< class Type > class LibCore_String2T_IntegerUnsigned : public testing::Test { protected: LibCore_String2T_IntegerUnsigned
mFloatStr ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "1.0434" ); TypeParam intDef = Convert::String2T< TypeParam >( "1.0434", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConvertOverflowing ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "48446744073709551615" ); TypeParam intDef = Convert::String2T< TypeParam >( "48446744073709551615", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConvertUnderflowing ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "-48446744073709551615" ); TypeParam intDef = Convert::String2T< TypeParam >( "-48446744073709551615", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, TextBeforeNumber ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "bla13" ); TypeParam intDef = Convert::String2T< TypeParam >( "bla13", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, TextAfterNumber ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "13bla" ); TypeParam intDef = Convert::String2T< TypeParam >( "13bla", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, TextInTheMiddleOfNumber ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "13bla234" ); TypeParam intDef = Convert::String2T< TypeParam >( "13bla234", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConversionReversibility ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( Convert::T2String( 123 ) ); EXPECT_TRUE( intExp.IsValid() ); EXPECT_EQ( intExp.GetVal(), 123 ); }
() {}; }; typedef testing::Types< UInt64, Int64, UInt32, Int32, UInt16, Int16, UInt8, Int8 > IntegerTypesList; typedef testing::Types< Int64, Int32, Int16, Int8 > SignedIntegerTypesList; typedef testing::Types< UInt64, UInt32, UInt16, UInt8 > UnsignedIntegerTypesList; TYPED_TEST_CASE( LibCore_String2T_Integer, IntegerTypesList ); TYPED_TEST_CASE( LibCore_String2T_IntegerSigned, SignedIntegerTypesList ); TYPED_TEST_CASE( LibCore_String2T_IntegerUnsigned, UnsignedIntegerTypesList ); TYPED_TEST( LibCore_String2T_Integer, ValidInput ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "123" ); TypeParam intDef = Convert::String2T< TypeParam >( "123", 5 ); EXPECT_TRUE( intExp.IsValid() ); EXPECT_EQ( intExp.GetVal(), 123 ); EXPECT_EQ( intDef, 123 ); } TYPED_TEST( LibCore_String2T_IntegerSigned, NegativeInput ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "-123" ); TypeParam intDef = Convert::String2T< TypeParam >( "-123", 5 ); EXPECT_TRUE( intExp.IsValid() ); EXPECT_EQ( intExp.GetVal(), -123 ); EXPECT_EQ( intDef, -123 ); } TYPED_TEST( LibCore_String2T_IntegerUnsigned, NegativeInput ) { Expected< TypeParam > intExp = Convert::String2T< TypeParam >( "-123" ); TypeParam intDef = Convert::String2T< TypeParam >( "-123", 5 ); EXPECT_FALSE( intExp.IsValid() ); EXPECT_EQ( intDef, 5 ); } TYPED_TEST( LibCore_String2T_Integer, ConvertFro
random
[ { "content": " class TestName : public CaseName<gtest_TypeParam_> { \\\n\n private: \\\n\n typedef CaseName<gtest_TypeParam_> TestFixture; \\\n\n typedef gtest_TypeParam_ TypeParam; \\\n\n virtual void TestBody(); \\\n\n }; \\\n\n static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \\\n\n GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\\\n\n __FILE__, __LINE__, #CaseName, #TestName); \\\n\n } \\\n\n template <typename gtest_TypeParam_> \\\n\n void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody()\n\n\n\n# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \\\n\n namespace GTEST_CASE_NAMESPACE_(CaseName) { \\\n\n typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \\\n\n } \\\n\n static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) \\\n\n GTEST_ATTRIBUTE_UNUSED_ = \\\n\n GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\\\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/gtest-typed-test.h", "rank": 0, "score": 304180.06979512994 }, { "content": "class ClassName: public FbxEvent< ClassName <TemplateName,T> >\\\n\n{\\\n\n public: virtual const char* GetEventName() const {return FbxEventName();}\\\n\n private: static const char* FbxEventName() {\\\n\n static FbxString lEventName = (FbxString(#ClassName) +\"<\"+ FbxString(T) +\">\");\\\n\n return lEventName.Buffer();\\\n\n }\\\n\n friend class FbxEvent< ClassName<TemplateName, T> >;\n\n\n\n\n\n//This is the footer macro, to put at the end to close the template class\n\n//created by FBXSDK_EVENT_TEMPLATE_HEADER\n\n#define FBXSDK_EVENT_TEMPLATE_FOOTER()\\\n\n};\n\n\n\n/** FBX event class, derived from FbxEventBase, and it contains a type ID for event. \n\n* It's a template class. You can derive your own types of even. Such as:\n\n* \\code class FbxEventCustom : public FbxEvent<FbxEventCustom> \\endcode\n\n* \\see FbxObjectPropertyChanged FbxEventReferencedDocument FbxEventPostExport\n\n* \\see FbxEventPostImport FbxEventPreExport FbxEventPreImport FbxEventPopulateSystemLibrary\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/core/fbxevent.h", "rank": 1, "score": 299620.48562471574 }, { "content": "class FooTest : public testing::Test {\n\n ...\n\n};\n\n\n\n// Next, declare that you will define a type-parameterized test case\n\n// (the _P suffix is for \"parameterized\" or \"pattern\", whichever you\n\n// prefer):\n\nTYPED_TEST_CASE_P(FooTest);\n\n\n\n// Then, use TYPED_TEST_P() to define as many type-parameterized tests\n\n// for this type-parameterized test case as you want.\n\nTYPED_TEST_P(FooTest, DoesBlah) {\n\n // Inside a test, refer to TypeParam to get the type parameter.\n\n TypeParam n = 0;\n\n ...\n\n}\n\n\n\nTYPED_TEST_P(FooTest, HasPropertyA) { ... }\n\n\n\n// Now the tricky part: you need to register all test patterns before\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/gtest-typed-test.h", "rank": 2, "score": 297668.6695947156 }, { "content": "class FBXSDK_DLL FbxContainerTemplate : public FbxObject\n\n{\n\n FBXSDK_OBJECT_DECLARE(FbxContainerTemplate, FbxObject);\n\n\n\npublic:\n\n /** Parse template file to get extend templates.\n\n * \\param pTemplateFilePath The template file to be parsed.\n\n * \\param pExtendTemplateNames Fill extend templates' names to this array.\n\n * \\remark Call this function to get extend templates' names.\n\n */\n\n void ParseTemplateFile(const char* pTemplateFilePath, FbxArray<FbxString*>& pExtendTemplateNames);\n\n\n\n /** Add extend template path.\n\n * \\param pExtendTemplatePath The template file path to be added.\n\n */\n\n void AddExtendTemplatePath(const char* pExtendTemplatePath);\n\n\n\n /** Get the (pIndex)th extend template path.\n\n * \\param pIndex Index of the queried item.\n\n * \\return The (pIndex)th extend template path.\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/fbxcontainertemplate.h", "rank": 3, "score": 292023.91556018573 }, { "content": " class Iterator : public ParamIteratorInterface<ParamType> {\n\n public:\n\n Iterator(const ParamGeneratorInterface<ParamType>* base,\n\n const ParamGenerator<T1>& g1,\n\n const typename ParamGenerator<T1>::iterator& current1,\n\n const ParamGenerator<T2>& g2,\n\n const typename ParamGenerator<T2>::iterator& current2,\n\n const ParamGenerator<T3>& g3,\n\n const typename ParamGenerator<T3>::iterator& current3,\n\n const ParamGenerator<T4>& g4,\n\n const typename ParamGenerator<T4>::iterator& current4,\n\n const ParamGenerator<T5>& g5,\n\n const typename ParamGenerator<T5>::iterator& current5,\n\n const ParamGenerator<T6>& g6,\n\n const typename ParamGenerator<T6>::iterator& current6,\n\n const ParamGenerator<T7>& g7,\n\n const typename ParamGenerator<T7>::iterator& current7,\n\n const ParamGenerator<T8>& g8,\n\n const typename ParamGenerator<T8>::iterator& current8,\n\n const ParamGenerator<T9>& g9,\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/internal/gtest-param-util-generated.h", "rank": 4, "score": 284547.71478356206 }, { "content": "\tclass LayerElementArrayProxy : public FbxLayerElementArrayTemplate<FbxSurfaceMaterial*>\n\n\t{\n\n\tpublic:\n\n\t\ttypedef FbxLayerElementArrayTemplate<FbxSurfaceMaterial*> ParentClass;\n\n\n\n\t\tLayerElementArrayProxy(EFbxType pType);\n\n\t\tvoid SetContainer( FbxLayerContainer* pContainer, int pInstance = 0);\n\n\t};\n\n\n\n/*****************************************************************************************************************************\n\n** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **\n\n*****************************************************************************************************************************/\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n\n\tvirtual void AllocateArrays();\n\n\tvirtual void SetOwner( FbxLayerContainer* pOwner, int pInstance = 0);\n\n\tvirtual void SetInstance( int pInstance ) { SetOwner( mOwner, pInstance ); }\n\n\n\nprotected:\n\n\tFbxLayerElementMaterial();\n\n\t~FbxLayerElementMaterial();\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 5, "score": 273768.4102959824 }, { "content": "class BVConfig : public IConfig\n\n{\n\nprivate:\n\n \n\n typedef std::map< std::string, std::string > KVMap;\n\n\n\n static const std::string CONFIG_PATH;\n\n\n\nprivate:\n\n\n\n XMLDeserializer m_deserializer;\n\n\n\n KVMap m_properties;\n\n\n\n Int32 m_defaultWindowWidth;\n\n Int32 m_defaultWindowHeight;\n\n\n\n Int32 m_defaultWidth;\n\n Int32 m_defaultHeight;\n\n\n", "file_path": "BlackVision/Applications/LibBVLogic/Source/BVConfig.h", "rank": 6, "score": 272236.31188711344 }, { "content": "class CachedSimpleTypedParameters : public SimpleParameterImpl< InterpolatorType, ValueType, type >, public ICachedParameter\n\n{\n\n typedef SimpleParameterImpl< InterpolatorType, ValueType, type > ParentImpl;\n\n\n\nprivate:\n\n\n\n mutable bool changed;\n\n\n\n mutable ValueType curValue;\n\n mutable ValueType prevValue;\n\n\n\n //template< typename T > \n\n // static inline bool isDifferent( T& a, T& b );\n\npublic:\n\n\n\n CachedSimpleTypedParameters( const std::string & name, const InterpolatorType & interpolator, ITimeEvaluatorPtr evaluator );\n\n\n\n inline ValueType Evaluate () const;\n\n virtual bool Changed () const override;\n\n\n", "file_path": "BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Parameters/CachedSimpleTypedParameters.h", "rank": 7, "score": 270878.3641025762 }, { "content": "class FBXSDK_DLL FbxLayerElementVisibility : public FbxLayerElementTemplate<bool>\n\n{\n\npublic:\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementVisibility);\n\n\n\n/*****************************************************************************************************************************\n\n** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **\n\n*****************************************************************************************************************************/\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n\nprotected:\n\n\tFbxLayerElementVisibility();\n\n\t~FbxLayerElementVisibility();\n\n#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/\n\n};\n\n\n\n/** \\brief Layer element for mapping Textures to a geometry. This class is deprecated.\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 8, "score": 270636.3442559646 }, { "content": "class FBXSDK_DLL FbxLayerElementSmoothing : public FbxLayerElementTemplate<int>\n\n{\n\npublic:\n\n FBXSDK_FRIEND_NEW();\n\n\n\n /** Allocation method.\n\n * \\param pOwner The owner of this layer element.\n\n * \\param pName The name of this layer element.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tstatic FbxLayerElementSmoothing* Create(FbxLayerContainer* pOwner, const char* pName);\n\n\n\n\t/** Sets the Reference Mode.\n\n\t * \\param pMode Specifies the reference mode.\n\n * \\remarks Only support eDirect. \n\n\t */\n\n\tvoid SetReferenceMode( FbxLayerElement::EReferenceMode pMode )\n\n\t{\n\n\t\tif( pMode != FbxLayerElement::eDirect )\n\n\t\t{\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 9, "score": 270636.3442559646 }, { "content": "class FBXSDK_DLL FbxLayerElementCrease : public FbxLayerElementTemplate<double>\n\n{\n\npublic:\n\n FBXSDK_FRIEND_NEW();\n\n\n\n /** Allocation method.\n\n * \\param pOwner The owner of this layer element. \n\n * \\param pName The name of this layer element.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tstatic FbxLayerElementCrease* Create(FbxLayerContainer* pOwner, const char* pName);\n\n\n\n\t/** Sets the Reference Mode.\n\n\t * \\param pMode Specifies the reference mode.\n\n * \\remarks Only support eDirect.\n\n\t */\n\n\tvoid SetReferenceMode( FbxLayerElement::EReferenceMode pMode )\n\n\t{\n\n\t\tif( pMode != FbxLayerElement::eDirect )\n\n\t\t{\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 10, "score": 270636.3442559646 }, { "content": "class FBXSDK_DLL FbxLayerElementHole : public FbxLayerElementTemplate<bool>\n\n{\n\npublic:\n\n FBXSDK_FRIEND_NEW();\n\n\n\n /** Allocation method.\n\n * \\param pOwner The owner of this layer element. \n\n * \\param pName The name of this layer element.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n static FbxLayerElementHole* Create(FbxLayerContainer* pOwner, const char* pName);\n\n\n\n /** Sets the Reference Mode.\n\n * \\param pMode Specifies the reference mode.\n\n * \\remarks Only support eDirect.\n\n */\n\n void SetReferenceMode( FbxLayerElement::EReferenceMode pMode )\n\n {\n\n if( pMode != FbxLayerElement::eDirect )\n\n {\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 11, "score": 270636.3442559646 }, { "content": "class FBXSDK_DLL FbxLayerElementTangent : public FbxLayerElementTemplate<FbxVector4>\n\n{\n\npublic:\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementTangent);\n\n\t\n\nprotected:\n\n\tFbxLayerElementTangent();\n\n\t~FbxLayerElementTangent();\n\n};\n\n\n\n/** Layer element for mapping materials (FbxSurfaceMaterial) to a geometry.\n\n *\n\n * FBX SDK 2011 and later connects materials (FbxSurfaceMaterial) to nodes (FbxNode).\n\n * The direct array of this class is no longer used.\n\n * The integer \"n\" in the index array of this class represents the n-th material (zero-based) connected to the node.\n\n *\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 12, "score": 267788.89219228533 }, { "content": "class FBXSDK_DLL FbxLayerElementNormal : public FbxLayerElementTemplate<FbxVector4>\n\n{\n\npublic:\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementNormal);\n\n\t\n\nprotected:\n\n\tFbxLayerElementNormal();\n\n\t~FbxLayerElementNormal();\n\n};\n\n\n\n/** \\brief Layer element for mapping Binormals to a geometry.\n\n * \\nosubgrouping\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 13, "score": 267788.89219228533 }, { "content": "class FBXSDK_DLL FbxLayerElementBinormal : public FbxLayerElementTemplate<FbxVector4>\n\n{\n\npublic:\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementBinormal);\n\n\t\n\nprotected:\n\n\tFbxLayerElementBinormal();\n\n\t~FbxLayerElementBinormal();\n\n};\n\n\n\n/** \\brief Layer element for mapping Tangents to a geometry.\n\n * \\nosubgrouping\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 14, "score": 267788.89219228533 }, { "content": "class FBXSDK_DLL FbxLayerElementUV : public FbxLayerElementTemplate<FbxVector2>\n\n{\n\npublic:\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementUV);\n\n\t\n\nprotected:\n\n\tFbxLayerElementUV();\n\n\t~FbxLayerElementUV();\n\n};\n\n\n\n/** \\brief Layer element for mapping Vertex Colors to a geometry.\n\n * \\nosubgrouping\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 15, "score": 267788.89219228533 }, { "content": "class FBXSDK_DLL FbxLayerElementUserData : public FbxLayerElementTemplate<void*>\n\n{\n\npublic:\n\n FBXSDK_FRIEND_NEW();\n\n\n\n /** Allocation method.\n\n * \\param pOwner The owner of this layer element. \n\n * \\param pName The layer element name.\n\n * \\param pId The layer element ID.\n\n * \\param pDataTypes Attribute data types of this layer element, one direct array is allocated for each Attribute data type.\n\n * \\param pDataNames Attribute names of this layer element.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n * \\remarks Only \"bool\", \"int\", \"float\" and \"double\" are supported. \n\n */\n\n\tstatic FbxLayerElementUserData* Create(FbxLayerContainer* pOwner, const char* pName, int pId, FbxArray<FbxDataType>& pDataTypes, FbxArray<const char*>& pDataNames);\n\n\n\n /** Allocation method.\n\n * \\param pOwner The owner of this layer element. \n\n * \\param pOther Other layer element from which to copy. \n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 16, "score": 267788.89219228533 }, { "content": "class FBXSDK_DLL FbxLayerElementTexture : public FbxLayerElementTemplate<FbxTexture*>\n\n{\n\npublic:\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementTexture);\n\n\n\n\t/** \\enum EBlendMode Lets you control how textures are combined when you apply multiple layers of texture to a surface.\n\n\t * - \\e eTranslucent The new texture layer is transparent (depending on the Alpha value).\n\n\t * - \\e eAdd Add the color of the new texture to the previous texture.\n\n\t * - \\e eModulate Multiples the color value of the new texture by the color values of all previous layers of texture.\n\n\t * - \\e eModulate2 Multiples the color value of the new texture by two and then by the color values of all previous layers of texture.\n\n\t * - \\e eOver Equivalent to eTranslucent. Blends the new texture over top of the old texture, according to the new texture's alpha channel.\n\n * - \\e eNormal, The colors of the two layers will not interact in any way, and it will display the full value of the colors in layer 1.\n\n * - \\e eDissolve, Dissolve makes the lower layer take on the colors of the top layer, and how much depends on the opacity of the upper layer. \n\n * - \\e eDarken,\t\t Darken compares each pixel value of the upper layer to its counterpart's pixel value of the lower layer and chooses the darker of the two to display.\n\n * - \\e eColorBurn, Color Burn burns in the color of the upper layer with the lower layer. No part of the image will get lighter.\n\n * - \\e eLinearBurn, \t Linear Burn works like multiply but the results are more intense.\n\n * - \\e eDarkerColor, This blend mode simply divides pixel values of one layer with the other.\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 17, "score": 267788.89219228533 }, { "content": "class FBXSDK_DLL FbxLayerElementPolygonGroup : public FbxLayerElementTemplate<int>\n\n{\n\npublic:\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementPolygonGroup);\n\n\t\n\nprotected:\n\n\tFbxLayerElementPolygonGroup();\n\n\t~FbxLayerElementPolygonGroup();\n\n};\n\n\n\n/** \\brief Layer element for mapping UVs to a geometry.\n\n *\n\n * This class represents a UV set belongs to a geometry. Each UV set in a geometry\n\n * has a name to identify itself. The string property FbxTexture.UVSet indicates\n\n * the UV set to use.\n\n *\n\n * \\remarks if the Mapping mode of this LayerElement is \\e eNone, the stored data\n\n * should be treated as irrelevant. In some circumstances, you can still send this data \n\n * to systems that cannot function without UV coordinates, but ensure\n\n * that you have enough coordinates to do so.\n\n * \n\n * \\see FbxTexture\n\n * \\nosubgrouping\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 18, "score": 267788.89219228533 }, { "content": "// ***********************\n\n// Loads assets synchronously from main thread. BV should hang on loading.\n\nclass SyncLoadTest : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( SyncLoadTest )\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n\n\nprivate:\n\n\n\n AssetDescConstPtr m_assetDesc;\n\n\n\n};\n\nREGISTER_FRAMEWORK_GTEST_INFO( SyncLoadTest, BVProjectEditor_Assets_Loading, SyncLoadTest )\n\n\n\n\n\n\n\n// ========================================================================= //\n\n// Implementation\n\n// ========================================================================= //\n\n\n", "file_path": "BlackVision/Test/Tools/BVProjectEditor/Source/AssetsTest/TestSyncLoading.cpp", "rank": 19, "score": 265094.99222327076 }, { "content": "// ***********************\n\n//\n\nclass AsyncLoadingTest : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO( AsyncLoadingTest )\n\n\n\npublic:\n\n\n\n explicit AsyncLoadingTest()\n\n : m_numLoaded( 0 )\n\n {}\n\n\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreModelUpdate () override;\n\n\n\n void AssetLoaded ( IEventPtr );\n\n\n\nprivate:\n\n\n\n AssetDescConstPtr m_assetDesc;\n", "file_path": "BlackVision/Test/Tools/BVProjectEditor/Source/AssetsTest/TestAsyncLoading.cpp", "rank": 20, "score": 265088.0495163235 }, { "content": "class FBXSDK_DLL FbxLayerElementVertexColor : public FbxLayerElementTemplate<FbxColor>\n\n{\n\npublic:\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementVertexColor);\n\n\t\n\nprotected:\n\n\tFbxLayerElementVertexColor();\n\n\t~FbxLayerElementVertexColor();\n\n};\n\n\n\ntemplate <class T> inline FbxLayerElementArrayTemplate<T>& FbxGetDirectArray(FbxLayerElementUserData *pLayerElement, int pIndex, bool* pStatus = NULL);\n\ntemplate <class T> inline FbxLayerElementArrayTemplate<T> const& FbxGetDirectArray(FbxLayerElementUserData const *pLayerElement, int pIndex, bool* pStatus = NULL);\n\ntemplate <class T> inline FbxLayerElementArrayTemplate<T>& FbxGetDirectArray(FbxLayerElementUserData *pLayerElement, const char* pName, bool* pStatus = NULL );\n\ntemplate <class T> inline FbxLayerElementArrayTemplate<T> const& FbxGetDirectArray(FbxLayerElementUserData const *pLayerElement, const char* pName, bool* pStatus = NULL );\n\n\n\n/** \\brief Layer element for mapping custom user data to a geometry. \n\n * This layer element is different from the other types of layer elements in that it has multiple direct arrays. There is one array for each user data attribute.\n\n * Each array is indexed by the index array.\n\n * \\nosubgrouping\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 21, "score": 265012.66012918274 }, { "content": "class FBXSDK_DLL FbxLayerElementMaterial : public FbxLayerElementTemplate<FbxSurfaceMaterial*>\n\n{\n\npublic:\n\n\ttypedef FbxLayerElementTemplate<FbxSurfaceMaterial*> ParentClass;\n\n\n\n /** Allocation method.\n\n * \\return A pointer to the layer element or \\c NULL if creation fails. \n\n */\n\n\tFBXSDK_LAYER_ELEMENT_CREATE_DECLARE(LayerElementMaterial);\n\n\t\n\n /** \\internal\n\n * Internal class to maintain backward compatibility with old FBX code (prior to FBX SDK 2011).\n\n * This class synchronizes the direct array with FbxNode connections.\n\n * Thus, changes on the direct array will reflect on FbxNode.\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/geometry/fbxlayer.h", "rank": 22, "score": 265012.66012918274 }, { "content": "// ***********************\n\n//\n\nclass BVProject : public IUpdatable\n\n{\n\nprivate:\n\n\n\n static const std::string\tMAIN_ROOT_NAME;\n\n static const std::string\tGLOBAL_TIMELINE_NAME;\n\n \n\nprivate:\n\n\n\n BVProjectEditor * m_projectEditor;\n\n Renderer * m_renderer;\n\n audio::AudioRenderer * m_audioRenderer;\n\n\n\n model::TimelineManagerPtr\t\tm_timelineManager;\n\n model::OffsetTimeEvaluatorPtr m_globalTimeline;\n\n UpdatersManagerPtr m_updaters; ///< @todo BVProject should be owner of UpdatersManager. Remove staticness.\n\n\n\n model::SceneModelVec\t m_sceneModelVec;\n\n SceneUPtrVec m_sceneVec;\n\n \n", "file_path": "BlackVision/LibBlackVision/Source/Engine/Editors/BVProject.h", "rank": 23, "score": 262948.41264835466 }, { "content": "// ***********************\n\n//\n\nclass BVSerializeContext : public SerializeContext\n\n{\n\nprivate:\n\n\n\n AssetDescsWithUIDsPtr m_assets;\n\n model::TimelineManager * m_timelineManager;\n\n\n\npublic:\n\n BVSerializeContext( model::TimelineManager * timelineManager )\n\n : m_assets( std::make_shared< AssetDescsWithUIDs >() )\n\n , m_timelineManager( timelineManager )\n\n {\n\n recursive = true;\n\n detailedInfo = true;\n\n pluginsInfo = true;\n\n extendedAssetData = false;\n\n sceneNameInTimeline = true;\n\n inludeUIDs = false;\n\n }\n\n\n", "file_path": "BlackVision/LibBlackVision/Source/Serialization/BV/BVSerializeContext.h", "rank": 24, "score": 262898.02414861263 }, { "content": "// ************************\n\n//\n\nclass BVDeserializeContext : public DeserializeContext\n\n{\n\nprivate:\n\n model::OffsetTimeEvaluatorPtr m_sceneTimeline;\n\n AssetDescsWithUIDsPtr m_assets;\n\n\n\n std::string m_nodePath;\n\n\n\n model::PluginsManager * m_pluginsManager;\n\n model::TimelineManager * m_timelineManager;\n\n\n\npublic:\n\n\n\n BVDeserializeContext ( model::OffsetTimeEvaluatorPtr timeline, AssetDescsWithUIDsPtr assets, model::PluginsManager * pluginsManager, model::TimelineManager * timelineManager );\n\n virtual ~BVDeserializeContext ();\n\n\n\n model::OffsetTimeEvaluatorPtr GetSceneTimeline ();\n\n void SetSceneTimeline ( const model::OffsetTimeEvaluatorPtr & timeline );\n\n model::ITimeEvaluatorPtr GetTimeline ( const std::string & name, const std::string & paramName = \"\" );\n\n// model::ITimeEvaluatorPtr GetRootTimeline ();\n", "file_path": "BlackVision/LibBlackVision/Source/Serialization/BV/BVDeserializeContext.h", "rank": 25, "score": 262898.02414861263 }, { "content": "class IModelNode : public bv::IUpdatable\n\n{\n\npublic:\n\n\n\n virtual const std::string &\t\t\t\t\t\t\tGetName () const = 0;\n\n virtual UniqueID GetUID () const = 0;\n\n\n\n virtual IPluginPtr\t\t\t\t\t\t\t\t\tGetPlugin ( const std::string & name ) const = 0;\n\n virtual IFinalizePluginConstPtr\t\t\t\t\t\tGetFinalizePlugin () const = 0;\n\n\n\n virtual IModelNodePtr\t\t\t\t\t\t\t\tGetNode ( const std::string & path, const std::string & separator = \"/\" ) = 0;\n\n virtual IModelNodePtr\t\t\t\t\t\t\t\tGetNode ( UniqueID id, bool recursive = true ) = 0;\n\n virtual IModelNodePtr\t\t\t\t\t\t\t\tGetChild ( const std::string & name ) = 0;\n\n\n\n virtual const IPluginListFinalized *\t\t\t\tGetPluginList () const = 0;\n\n virtual std::vector< IParameterPtr >\t\t\t\tGetParameters () const = 0;\n\n virtual std::vector< ITimeEvaluatorPtr >\t\t GetTimelines ( bool recursive ) const = 0;\n\n\n\n virtual unsigned int\t\t\t\t\t\t\t\tGetNumChildren () const = 0;\n\n\n", "file_path": "BlackVision/LibBlackVision/Source/Engine/Models/Interfaces/IModelNode.h", "rank": 26, "score": 260921.98186073644 }, { "content": "// ***********************\n\n//\n\nclass TestEditor : public bv::FrameworkTest\n\n{\n\nprotected:\n\n\n\n bv::TestScenePtr m_scene;\n\n\n\npublic:\n\n \n\n explicit TestEditor()\n\n {}\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreModelUpdate () override;\n\n\n\n virtual void InitScene () = 0;\n\n\n\n};\n\n\n\n\n\n\n", "file_path": "BlackVision/Test/Applications/Editor/Source/Scenes/TestEditorBase.h", "rank": 27, "score": 260921.98186073644 }, { "content": "// ***********************\n\n//\n\nclass MockOperation : public bv::IRevertable\n\n{\n\nprivate:\n\n\n\n std::vector< OpEntry > & m_opRegister;\n\n std::string m_operationID;\n\n\n\npublic:\n\n\n\n explicit MockOperation ( std::vector< OpEntry > & opRegister, const std::string & id );\n\n\n\n\n\n // Inherited via IRevertable\n\n virtual bool Undo ( bv::BVProjectEditor * editor ) override;\n\n virtual bool Redo ( bv::BVProjectEditor * editor ) override;\n\n\n\n};\n\n\n\nDEFINE_UPTR_TYPE( MockOperation );\n\n\n\n\n\n// ***********************\n\n//\n\ninline MockOperationUPtr CreateOperation ( std::vector< OpEntry > & opRegister, const std::string & id )\n\n{\n\n auto op = new MockOperation( opRegister, id );\n\n return MockOperationUPtr( op );\n\n}\n", "file_path": "BlackVision/Test/Model/TestUndoRedo/Source/Utils/MockOperation.h", "rank": 28, "score": 260921.98186073644 }, { "content": "class BlackVisionApp : public WindowedApplication\n\n{\n\nprotected:\n\n\n\n BVAppLogic * m_app;\n\n\n\npublic:\n\n\n\n static bool\t\t\tm_sWindowedApplicationInitialized;\n\n\n\npublic:\n\n\n\n static void\t\t\tMainInitializer\t\t ( int argc, char * argv[] );\n\n static void\t\t\tLoggerInitializer\t\t( int argc, char * argv[] );\n\n static bool\t\t\tRegisterInitializer\t\t();\n\n static void RegisterLogicInitializers ();\n\n\n\npublic:\n\n\n\n BlackVisionApp\t\t\t\t();\n", "file_path": "BlackVision/Applications/LibBVLogic/Source/bvApp.h", "rank": 29, "score": 260445.69741385305 }, { "content": "// ***********************\n\n// Test loads asset to 2 plugins at the same time asynchronously and synchronously.\n\n// Sync load should hang and wait for async load.\n\nclass MixedSyncAsyncLoadingTest : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( MixedSyncAsyncLoadingTest )\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreModelUpdate () override;\n\n\n\nprivate:\n\n\n\n AssetDescConstPtr m_assetDesc;\n\n\n\n};\n\nREGISTER_FRAMEWORK_GTEST_INFO( MixedSyncAsyncLoadingTest, BVProjectEditor_Assets_Loading, MixedSyncAsyncLoadingTest )\n\n\n\n\n\n\n\n// ========================================================================= //\n\n// Implementation\n\n// ========================================================================= //\n", "file_path": "BlackVision/Test/Tools/BVProjectEditor/Source/AssetsTest/TestMixedSyncAsyncLoading.cpp", "rank": 30, "score": 256948.9712196716 }, { "content": "// ***********************\n\n//\n\nclass BVTestAppLogic : public BVAppLogic\n\n{\n\n friend class FrameworkTest;\n\n friend class Benchmark;\n\nprivate:\n\n\n\n FrameworkTest * m_test;\n\n\n\npublic:\n\n BVTestAppLogic ( Renderer * renderer, audio::AudioRenderer * audioRenderer, const std::string & testname );\n\n BVTestAppLogic ( Renderer * renderer, audio::AudioRenderer * audioRenderer );\n\n ~BVTestAppLogic ();\n\n\n\n virtual void OnUpdate ( Renderer * renderer, audio::AudioRenderer * audioRenderer ) override;\n\n virtual void LoadScene () override;\n\n\n\n virtual void PostFrameLogic () override;\n\n\n\n void RestartTimer ();\n\n\n", "file_path": "BlackVision/DevTools/TestFramework/Source/Framework/BVTestAppLogic.h", "rank": 31, "score": 256469.0802720604 }, { "content": "// ***********************\n\n// One node follows another. Disable y-axis - logic shouldn't change y component of translation.\n\nclass DisableAxis : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( DisableAxis )\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreRender () override;\n\n\n\n void Initialize ();\n\n\n\nprivate:\n\n\n\n nodelogic::FollowPtr m_follow;\n\n model::BasicNodePtr m_following;\n\n model::BasicNodePtr m_followed;\n\n};\n\nREGISTER_FRAMEWORK_GTEST_INFO( DisableAxis, Logics_Follow, DisableAxis )\n\n\n\n\n\n\n", "file_path": "BlackVision/Test/Logics/TestFollowLogic/Source/TestDisablingAxis.cpp", "rank": 32, "score": 255906.68416225235 }, { "content": "class IModelFullscreenEffect : public bv::IUpdatable\n\n{\n\npublic:\n\n\n\n virtual const std::string &\t\t\t\t\t\tGetName\t\t\t() const = 0;\n\n\n\n virtual IParameterPtr GetParameter ( const std::string & name ) const = 0;\n\n virtual const std::vector< IParameterPtr > & GetParameters\t() const = 0;\n\n\n\n virtual const std::vector< IValueConstPtr > & GetValues\t\t() const = 0;\n\n\n\n virtual ~IModelFullscreenEffect () {};\n\n\n\n};\n\n\n\nDEFINE_PTR_TYPE(IModelFullscreenEffect)\n\nDEFINE_CONST_PTR_TYPE(IModelFullscreenEffect)\n\n\n\n} // model\n\n} // bv\n", "file_path": "BlackVision/LibBlackVision/Source/Engine/Models/Interfaces/IModelFullscreenEffect.h", "rank": 33, "score": 255906.68416225235 }, { "content": "// ***********************\n\n// One node follows another. Check if following node alignment works properly.\n\nclass FollowerAlignment : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( FollowerAlignment )\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreRender () override;\n\n\n\n void Initialize ();\n\n\n\nprivate:\n\n\n\n nodelogic::FollowPtr m_follow;\n\n model::BasicNodePtr m_following;\n\n model::BasicNodePtr m_followed;\n\n};\n\nREGISTER_FRAMEWORK_GTEST_INFO( FollowerAlignment, Logics_Follow, FollowerAlignment )\n\n\n\n\n\n\n", "file_path": "BlackVision/Test/Logics/TestFollowLogic/Source/TestFollowerAlignment.cpp", "rank": 34, "score": 255906.68416225235 }, { "content": "class FreeTypeEngine : public IFontEngine\n\n{\n\nprivate:\n\n\n\n UInt32 m_maxHeight;\n\n UInt32 m_maxWidth;\n\n SizeType m_fontSize;\n\n FT_Library m_library;\n\n FT_Face m_face;\n\n std::string m_fontFilePath;\n\n\n\n Glyph * RenderGlyph ( wchar_t ch, Spans &, SizeType );\n\n\n\n FreeTypeEngine ( const std::string & fontFilePath, size_t fontSize );\n\n\n\npublic:\n\n\n\n virtual TextAtlasPtr CreateAtlas ( UInt32 padding, const std::wstring & wcharsSet, bool makeSizesPowerOf2 = false ) override;\n\n virtual TextAtlasPtr CreateAtlas ( UInt32 padding, UInt32 outline, const std::wstring & wcharsSet, bool makeSizesPowerOf2 = false ) override;\n\n\n", "file_path": "BlackVision/LibBlackVision/Source/Assets/Font/Engines/FreeTypeEngine.h", "rank": 35, "score": 255756.98312181828 }, { "content": "class TestWithParam : public Test, public WithParamInterface<T> {\n\n};\n\n\n\n#endif // GTEST_HAS_PARAM_TEST\n\n\n\n// Macros for indicating success/failure in test code.\n\n\n\n// ADD_FAILURE unconditionally adds a failure to the current test.\n\n// SUCCEED generates a success - it doesn't automatically make the\n\n// current test successful, as a test is only successful when it has\n\n// no failure.\n\n//\n\n// EXPECT_* verifies that a certain condition is satisfied. If not,\n\n// it behaves like ADD_FAILURE. In particular:\n\n//\n\n// EXPECT_TRUE verifies that a Boolean condition is true.\n\n// EXPECT_FALSE verifies that a Boolean condition is false.\n\n//\n\n// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except\n\n// that they will also abort the current function on failure. People\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/gtest.h", "rank": 36, "score": 253123.57988555497 }, { "content": "#define POST_RENDER_FRAMEWORK_TEST_IN_SUITE_IMPL( suite, name ) \\\n\nclass GTEST_TEST_CLASS_NAME_( suite, name ) : public bv::FrameworkTest \\\n\n{ \\\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( GTEST_TEST_CLASS_NAME_( suite, name ) ) \\\n\npublic: \\\n\n \\\n\n virtual void PostRender () override; \\\n\n}; \\\n\n \\\n\nREGISTER_FRAMEWORK_GTEST_INFO( GTEST_TEST_CLASS_NAME_( suite, name ), suite, name ) \\\n\nvoid GTEST_TEST_CLASS_NAME_( suite, name )::PostRender ()\n\n\n\n\n\n#define POST_RENDER_FRAMEWORK_TEST( suite, name ) POST_RENDER_FRAMEWORK_TEST_IN_SUITE_IMPL( suite, name )\n", "file_path": "BlackVision/DevTools/TestFramework/Source/Framework/FrameworkTest.h", "rank": 37, "score": 251786.32275303968 }, { "content": " FT_Size_Request_Type type;\n", "file_path": "BlackVision/Dep/3rdParty/FreeType/include/freetype/freetype.h", "rank": 38, "score": 249753.44839984106 }, { "content": " BDF_PropertyType type;\n", "file_path": "BlackVision/Dep/3rdParty/FreeType/include/freetype/ftbdf.h", "rank": 39, "score": 249753.44839984106 }, { "content": "// The class used to hold all Benchmarks created from static function.\n\n// (ie those created using the BENCHMARK(...) macros.\n\nclass FunctionBenchmark : public Benchmark {\n\n public:\n\n FunctionBenchmark(const char* name, Function* func)\n\n : Benchmark(name), func_(func) {}\n\n\n\n virtual void Run(State& st);\n\n\n\n private:\n\n Function* func_;\n\n};\n\n\n\n#ifdef BENCHMARK_HAS_CXX11\n\ntemplate <class Lambda>\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 40, "score": 249680.8249799794 }, { "content": "class VersionVisitor: public Visitor\n\n{\n\n\tprivate:\n\n\t\t/**\n\n\t\t * Prevent accidental copying\n\n\t\t */\n\n\t\tVersionVisitor(const VersionVisitor& rhs);\n\n\t\tVersionVisitor& operator=(const VersionVisitor& rhs);\n\n\n\n\tprotected:\n\n\n\n\t\t/**\n\n\t\t * The CmdLine of interest.\n\n\t\t */\n\n\t\tCmdLineInterface* _cmd;\n\n\n\n\t\t/**\n\n\t\t * The output object. \n\n\t\t */\n\n\t\tCmdLineOutput** _out;\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/VersionVisitor.h", "rank": 41, "score": 249666.1828345245 }, { "content": "class HelpVisitor: public Visitor\n\n{\n\n\tprivate:\n\n\t\t/**\n\n\t\t * Prevent accidental copying.\n\n\t\t */\n\n\t\tHelpVisitor(const HelpVisitor& rhs);\n\n\t\tHelpVisitor& operator=(const HelpVisitor& rhs);\n\n\n\n\tprotected:\n\n\n\n\t\t/**\n\n\t\t * The CmdLine the output will be generated for. \n\n\t\t */\n\n\t\tCmdLineInterface* _cmd;\n\n\n\n\t\t/**\n\n\t\t * The output object. \n\n\t\t */\n\n\t\tCmdLineOutput** _out;\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/HelpVisitor.h", "rank": 42, "score": 249666.1828345245 }, { "content": "class LambdaBenchmark : public Benchmark {\n\n public:\n\n virtual void Run(State& st) { lambda_(st); }\n\n\n\n private:\n\n template <class OLambda>\n\n LambdaBenchmark(const char* name, OLambda&& lam)\n\n : Benchmark(name), lambda_(std::forward<OLambda>(lam)) {}\n\n\n\n LambdaBenchmark(LambdaBenchmark const&) = delete;\n\n\n\n private:\n\n template <class Lam>\n\n friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&);\n\n\n\n Lambda lambda_;\n\n};\n\n#endif\n\n\n\n} // namespace internal\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 43, "score": 249666.1828345245 }, { "content": "class ValueArg : public Arg \n\n{\n\n protected:\n\n\n\n /**\n\n * The value parsed from the command line.\n\n * Can be of any type, as long as the >> operator for the type\n\n * is defined.\n\n */\n\n T _value;\n\n\n\n\t\t/**\n\n\t\t * Used to support the reset() method so that ValueArg can be\n\n\t\t * reset to their constructed value.\n\n\t\t */\n\n T _default;\n\n\n\n /**\n\n * A human readable description of the type to be parsed.\n\n * This is a hack, plain and simple. Ideally we would use RTTI to\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/ValueArg.h", "rank": 44, "score": 249666.1828345245 }, { "content": "class SwitchArg : public Arg\n\n{\n\n\tprotected:\n\n\n\n\t\t/**\n\n\t\t * The value of the switch.\n\n\t\t */\n\n\t\tbool _value;\n\n\n\n\t\t/**\n\n\t\t * Used to support the reset() method so that ValueArg can be\n\n\t\t * reset to their constructed value.\n\n\t\t */\n\n bool _default;\n\n\n\n\tpublic:\n\n\n\n /**\n\n\t\t * SwitchArg constructor.\n\n\t\t * \\param flag - The one character flag that identifies this\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/SwitchArg.h", "rank": 45, "score": 249666.1828345245 }, { "content": "class MultiArg : public Arg\n\n{\n\npublic:\n\n\ttypedef std::vector<T> container_type;\t\n\n\ttypedef typename container_type::iterator iterator;\n\n\ttypedef typename container_type::const_iterator const_iterator;\n\n\n\nprotected:\n\n\n\n\t/**\n\n\t * The list of values parsed from the CmdLine.\n\n\t */\n\n\tstd::vector<T> _values;\n\n\n\n\t/**\n\n\t * The description of type T to be used in the usage.\n\n\t */\n\n\tstd::string _typeDesc;\n\n\n\n\t/**\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/MultiArg.h", "rank": 46, "score": 249666.1828345245 }, { "content": "// ***********************\n\n// This test sends generated sawtooth audio signal from fake plugin and reads results value from\n\n// video card.\n\nclass AudioSignalPathTest : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO( AudioSignalPathTest )\n\n\n\npublic:\n\n\n\n explicit AudioSignalPathTest()\n\n : m_fakeAudio( nullptr )\n\n , m_fakeVideoCard( nullptr )\n\n , m_numTestFramesDuration( 10 )\n\n , m_numCleanBuffersFrames( 100 )\n\n {}\n\n\n\n explicit AudioSignalPathTest( UInt16 testFramesDuration )\n\n : m_fakeAudio( nullptr )\n\n , m_fakeVideoCard( nullptr )\n\n , m_numTestFramesDuration( testFramesDuration )\n\n , m_numCleanBuffersFrames( 100 )\n\n {}\n\n\n", "file_path": "BlackVision/Test/Engine/TestAudioVideo/Source/AudioCardOut/AudioSignalPath.h", "rank": 47, "score": 248878.91494191275 }, { "content": " FT_RFork_Rule type;\n", "file_path": "BlackVision/Dep/3rdParty/FreeType/include/freetype/internal/ftrfork.h", "rank": 48, "score": 247462.0441760762 }, { "content": " T1_FieldType type; /* type of field */\n", "file_path": "BlackVision/Dep/3rdParty/FreeType/include/freetype/internal/psaux.h", "rank": 49, "score": 247462.0441760762 }, { "content": "#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \\\n\n class BaseClass##_##Method##_Benchmark : public BaseClass { \\\n\n public: \\\n\n BaseClass##_##Method##_Benchmark() : BaseClass() { \\\n\n this->SetName(#BaseClass \"/\" #Method); \\\n\n } \\\n\n \\\n\n protected: \\\n\n virtual void BenchmarkCase(::benchmark::State&); \\\n\n };\n\n\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 50, "score": 247153.27194106075 }, { "content": "// The Mutex class can only be used for mutexes created at runtime. It\n\n// shares its API with MutexBase otherwise.\n\nclass Mutex : public MutexBase {\n\n public:\n\n Mutex() {\n\n GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));\n\n has_owner_ = false;\n\n }\n\n ~Mutex() {\n\n GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));\n\n }\n\n\n\n private:\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);\n\n};\n\n\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/internal/gtest-port.h", "rank": 51, "score": 246962.02705186565 }, { "content": "// Simple reporter that outputs benchmark data to the console. This is the\n\n// default reporter used by RunSpecifiedBenchmarks().\n\nclass ConsoleReporter : public BenchmarkReporter {\n\npublic:\n\n enum OutputOptions {\n\n OO_None = 0,\n\n OO_Color = 1,\n\n OO_Tabular = 2,\n\n OO_ColorTabular = OO_Color|OO_Tabular,\n\n OO_Defaults = OO_ColorTabular\n\n };\n\n explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults)\n\n : output_options_(opts_), name_field_width_(0),\n\n prev_counters_(), printed_header_(false) {}\n\n\n\n virtual bool ReportContext(const Context& context);\n\n virtual void ReportRuns(const std::vector<Run>& reports);\n\n\n\n protected:\n\n virtual void PrintRunData(const Run& report);\n\n virtual void PrintHeader(const Run& report);\n\n\n\n OutputOptions output_options_;\n\n size_t name_field_width_;\n\n UserCounters prev_counters_;\n\n bool printed_header_;\n\n};\n\n\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 52, "score": 246955.35380009547 }, { "content": "class JSONReporter : public BenchmarkReporter {\n\n public:\n\n JSONReporter() : first_report_(true) {}\n\n virtual bool ReportContext(const Context& context);\n\n virtual void ReportRuns(const std::vector<Run>& reports);\n\n virtual void Finalize();\n\n\n\n private:\n\n void PrintRunData(const Run& report);\n\n\n\n bool first_report_;\n\n};\n\n\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 53, "score": 246948.77433678985 }, { "content": "class CSVReporter : public BenchmarkReporter {\n\n public:\n\n CSVReporter() : printed_header_(false) {}\n\n virtual bool ReportContext(const Context& context);\n\n virtual void ReportRuns(const std::vector<Run>& reports);\n\n\n\n private:\n\n void PrintRunData(const Run& report);\n\n\n\n bool printed_header_;\n\n std::set< std::string > user_counter_names_;\n\n};\n\n\n\ninline const char* GetTimeUnitString(TimeUnit unit) {\n\n switch (unit) {\n\n case kMillisecond:\n\n return \"ms\";\n\n case kMicrosecond:\n\n return \"us\";\n\n case kNanosecond:\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 54, "score": 246948.77433678985 }, { "content": "class SpecificationException : public ArgException\n\n{\n\n\tpublic:\n\n\t\t/**\n\n\t\t * Constructor.\n\n\t\t * \\param text - The text of the exception.\n\n\t\t * \\param id - The text identifying the argument source \n\n\t\t * of the exception.\n\n\t\t */\n\n\t\tSpecificationException( const std::string& text = \"undefined exception\",\n\n\t\t\t\t\t const std::string& id = \"undefined\" )\n\n\t\t\t: ArgException( text, \n\n\t\t\t id,\n\n\t\t\t\t\t\t\tstd::string(\"Exception found when an Arg object \")+\n\n\t\t\t\t\t\t\tstd::string(\"is improperly defined by the \") +\n\n\t\t\t\t\t\t\tstd::string(\"developer.\" )) \n\n\t\t{ }\n\n\n\n};\n\n\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/ArgException.h", "rank": 55, "score": 246948.77433678985 }, { "content": " class RunnableImpl : public Runnable {\n\n public:\n\n RunnableImpl(UserThreadFunc* func, T param)\n\n : func_(func),\n\n param_(param) {\n\n }\n\n virtual ~RunnableImpl() {}\n\n virtual void Run() {\n\n func_(param_);\n\n }\n\n\n\n private:\n\n UserThreadFunc* const func_;\n\n const T param_;\n\n\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);\n\n };\n\n\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);\n\n};\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/internal/gtest-port.h", "rank": 56, "score": 246948.77433678985 }, { "content": "class Expected< Result, bv::ExceptionPtr > : public impl::ExpectedBase< Result, bv::ExceptionPtr >\n\n{\n\npublic:\n\n explicit Expected ()\n\n {}\n\n\n\n Expected ( Result::Success )\n\n : ExpectedBase< Result, bv::ExceptionPtr >( Result() )\n\n {}\n\n\n\n Expected ( Result::Failure )\n\n : ExpectedBase< Result, bv::ExceptionPtr >()\n\n {}\n\n\n\n Expected ( const std::string & reason )\n\n : ExpectedBase( bv::ExceptionPtr( new RuntimeException( reason ) ) )\n\n {}\n\n\n\n Expected ( bv::ExceptionPtr & error )\n\n : ExpectedBase< Result, bv::ExceptionPtr >( error )\n", "file_path": "BlackVision/LibCore/Source/Expected.h", "rank": 57, "score": 246065.36474462427 }, { "content": "class Fbx6ClassTemplateMap\n\n{\n\npublic:\n\n\n\n /** Constructor\n\n *\t\n\n */\n\n Fbx6ClassTemplateMap();\n\n\n\n /** Destructor\n\n *\t\n\n */\n\n ~Fbx6ClassTemplateMap();\n\n\n\n // Fbx6ClassTemplateMap will own this template object.\n\n\n\n /** Add the template object to template map\n\n *\t\\param pId Class Id\n\n * \\param pTemplateObject template object\n\n * \\return if the object is successfully added return \\c true, otherwise return \\c false.\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxreaderfbx6.h", "rank": 58, "score": 245792.63924475067 }, { "content": "class FBXSDK_DLL FbxQueryClassId : public FbxQuery\n\n{\n\npublic:\n\n FBXSDK_FRIEND_NEW();\n\n\n\n static FbxQueryClassId* Create(const FbxClassId& pClassId);\n\n virtual FbxInt GetUniqueId() const{ return FBXSDK_QUERY_UNIQUE_ID+3; }\n\n virtual bool IsValid(const FbxProperty& pProperty) const;\n\n virtual bool IsEqual(FbxQuery* pOtherQuery) const;\n\n\n\nprotected:\n\n FbxQueryClassId(const FbxClassId& pClassId);\n\n\n\nprivate:\n\n FbxClassId\tmClassId;\n\n};\n\n\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/core/fbxquery.h", "rank": 59, "score": 245669.83843991556 }, { "content": "// ***********************\n\n// Bug https://www.pivotaltracker.com/story/show/153778657 replication.\n\n//\n\n// When many asynchronous events come to EventsManager, some of them are lost.\n\n// This is caused by lack of synchronization in some parts of EventsManager. It uses multiple queues\n\n// which are changed each frame. After changing, queue is cleared. This switching is not synchronized\n\n// and some of events can be cleared when they came in bad momement.\n\n//\n\n// This test tries to spam EventsManager with so many events as posible to check if all of them passed.\n\n// This is rather random test as often in multithreading, so it can not always be reliable.\n\n//\n\n// This test works in relase mode. In Debug it passes for some reason :(\n\nclass Events_EventsManager_LostEvents : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( Events_EventsManager_LostEvents )\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreModelUpdate () override;\n\n\n\npublic:\n\n\n\n static bv::IEventPtr CreateTestEvent ();\n\n void EventSpammingThread ();\n\n void SpawnThread ();\n\n\n\n void CountEventsHandler ( bv::IEventPtr evt );\n\n void SpammingThreadEnd ( bv::IEventPtr evt );\n\n\n\nprivate:\n\n\n\n UInt64 m_eventsCounter;\n", "file_path": "BlackVision/Test/Applications/TestEventsApi/Source/EventManager/EventManagerTest.cpp", "rank": 60, "score": 244498.22794841556 }, { "content": "// ***********************\n\n//\n\nclass Engine_InputSlots_VideoInputPipeline : public bv::FrameworkTest\n\n{\n\n DECALRE_GTEST_INFO_WITH_CONSTRUCTOR( Engine_InputSlots_VideoInputPipeline )\n\npublic:\n\n\n\n virtual void PreEvents () override;\n\n virtual void PreRender () override;\n\n virtual void PostRender () override;\n\n\n\nprivate:\n\n\n\n void Initialize ();\n\n void CheckOutput ( SizeType frame );\n\n glm::vec4 SamplePoint ( const char * mem, SizeType posX, SizeType posY );\n\n\n\nprivate:\n\n\n\n videocards::FakeVideoCardPtr m_fakeVideoCard;\n\n\n\n};\n", "file_path": "BlackVision/Test/Engine/TestInputSlots/Source/VideoInputPipelineTest.cpp", "rank": 61, "score": 244494.21330152417 }, { "content": "class ValueImpl : public NamedValue\n\n{\n\npublic:\n\n\n\n typedef ValType ValueType;\n\n\n\nprivate:\n\n\n\n ValType m_value;\n\n\n\npublic:\n\n\n\n explicit ValueImpl ( const std::string & name );\n\n\n\npublic:\n\n\n\n virtual ~ValueImpl ();\n\n\n\n virtual ParamType GetType () const override;\n\n virtual const char * GetData () const override;\n", "file_path": "BlackVision/LibBlackVision/Source/Engine/Types/Values/BaseValue.h", "rank": 62, "score": 244488.7555275408 }, { "content": "class Expected : public impl::ExpectedBase< HamType, ErrorType >\n\n{\n\npublic:\n\n explicit Expected () \n\n {}\n\n Expected ( HamType h ) \n\n : ExpectedBase( h ) \n\n {}\n\n Expected ( const std::string & reason )\n\n : ExpectedBase( ErrorType( new RuntimeException( reason ) ) ) \n\n {}\n\n Expected ( const ExpectedBase & that ) // conversion to let ExpectedBase::fromError work\n\n : ExpectedBase( that ) {}\n\n\n\n Expected< HamType, ErrorType > & operator= ( const Expected< HamType, ErrorType > & other );\n\n};\n\n\n\n// ========================================================================= //\n\n// std::string specialization\n\n// ========================================================================= //\n\n\n\ntemplate<>\n", "file_path": "BlackVision/LibCore/Source/Expected.h", "rank": 63, "score": 244463.67763953382 }, { "content": "class CmdLine : public CmdLineInterface\n\n{\n\n\tprotected:\n\n\n\n\t\t/**\n\n\t\t * The list of arguments that will be tested against the\n\n\t\t * command line.\n\n\t\t */\n\n\t\tstd::list<Arg*> _argList;\n\n\n\n\t\t/**\n\n\t\t * The name of the program. Set to argv[0].\n\n\t\t */\n\n\t\tstd::string _progName;\n\n\n\n\t\t/**\n\n\t\t * A message used to describe the program. Used in the usage output.\n\n\t\t */\n\n\t\tstd::string _message;\n\n\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/CmdLine.h", "rank": 64, "score": 244307.9533896783 }, { "content": "class IgnoreRestVisitor: public Visitor\n\n{\n\n\tpublic:\n\n\n\n\t\t/**\n\n\t\t * Constructor.\n\n\t\t */\n\n\t\tIgnoreRestVisitor() : Visitor() {}\n\n\n\n\t\t/**\n\n\t\t * Sets Arg::_ignoreRest.\n\n\t\t */\n\n\t\tvoid visit() { Arg::beginIgnoring(); }\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/IgnoreRestVisitor.h", "rank": 65, "score": 244307.9533896783 }, { "content": "class ArgParseException : public ArgException\n\n{ \n\n\tpublic:\n\n\t\t/**\n\n\t\t * Constructor.\n\n\t\t * \\param text - The text of the exception.\n\n\t\t * \\param id - The text identifying the argument source \n\n\t\t * of the exception.\n\n\t\t */\n\n\t\tArgParseException( const std::string& text = \"undefined exception\", \n\n\t\t\t\t\t const std::string& id = \"undefined\" )\n\n\t\t\t: ArgException( text, \n\n\t\t\t id, \n\n\t\t\t\t\t\t\tstd::string( \"Exception found while parsing \" ) + \n\n\t\t\t\t\t\t\tstd::string( \"the value the Arg has been passed.\" ))\n\n\t\t\t{ }\n\n};\n\n\n\n/**\n\n * Thrown from CmdLine when the arguments on the command line are not\n\n * properly specified, e.g. too many arguments, required argument missing, etc.\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/ArgException.h", "rank": 66, "score": 244307.9533896783 }, { "content": "class FbxStatisticsFbx : public FbxStatistics\n\n{\n\npublic:\n\n virtual bool AddItem(FbxString& pItemName, int pItemCount)\n\n {\n\n mItemName.Add( FbxNew< FbxString >(pItemName) );\n\n mItemCount.Add( pItemCount);\n\n return true;\n\n };\n\n};\n\n\n\n#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/\n\n\n\n#include <fbxsdk/fbxsdk_nsend.h>\n\n\n\n#endif /* _FBXSDK_FILEIO_STATISTICS_FBX_H_ */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbxstatisticsfbx.h", "rank": 67, "score": 244307.9533896783 }, { "content": "class AnimationElement : public ElementBase\n\n{\n\npublic:\n\n typedef ElementBase base_type;\n\n\n\n AnimationElement();\n\n virtual ~AnimationElement();\n\n\n\n /** Get the count of animation channels in the element.\n\n * \\return Return the channel count.\n\n */\n\n int GetChannelCount() const;\n\n\n\n /** Initialize with the content of a COLLADA element.\n\n * This method should be called before ToFBX.\n\n */\n\n void FromCOLLADA(xmlNode * pElement, const SourceElementMapType & pSourceElements);\n\n\n\n /** Initialize with an animation curve.\n\n * This method should be called before ToCOLLADA.\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/collada/fbxcolladaanimationelement.h", "rank": 68, "score": 244307.9533896783 }, { "content": "class StdOutput : public CmdLineOutput\n\n{\n\n\n\n\tpublic:\n\n\n\n\t\t/**\n\n\t\t * Prints the usage to stdout. Can be overridden to \n\n\t\t * produce alternative behavior.\n\n\t\t * \\param c - The CmdLine object the output is generated for. \n\n\t\t */\n\n\t\tvirtual void usage(CmdLineInterface& c);\n\n\n\n\t\t/**\n\n\t\t * Prints the version to stdout. Can be overridden \n\n\t\t * to produce alternative behavior.\n\n\t\t * \\param c - The CmdLine object the output is generated for. \n\n\t\t */\n\n\t\tvirtual void version(CmdLineInterface& c);\n\n\n\n\t\t/**\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/StdOutput.h", "rank": 69, "score": 244307.9533896783 }, { "content": "#define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \\\n\n class BaseClass##_##Method##_Benchmark : public BaseClass<a> { \\\n\n public: \\\n\n BaseClass##_##Method##_Benchmark() : BaseClass<a>() { \\\n\n this->SetName(#BaseClass\"<\" #a \">/\" #Method); \\\n\n } \\\n\n \\\n\n protected: \\\n\n virtual void BenchmarkCase(::benchmark::State&); \\\n\n };\n\n\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 70, "score": 243301.4886514328 }, { "content": "class BVXMLDeserializer : public XMLDeserializer\n\n{\n\npublic:\n\n BVXMLDeserializer( std::istream & in, SizeType numBytes, DeserializeContext * context ); // model::OffsetTimeEvaluatorPtr timeline, AssetDescsWithUIDsPtr assets, model::PluginsManager * pluginsManager, model::TimelineManager * timelineManager );\n\n BVXMLDeserializer( std::string filename, DeserializeContext * context ); //, model::OffsetTimeEvaluatorPtr timeline, AssetDescsWithUIDsPtr assets, model::PluginsManager * pluginsManager, model::TimelineManager * timelineManager );\n\n};\n\n\n\n}", "file_path": "BlackVision/LibBlackVision/Source/Serialization/BV/XML/BVXMLDeserializer.h", "rank": 71, "score": 242513.89410250506 }, { "content": "class MainLoopProcess : public Process\n\n{\n\nprivate:\n\n\n\n\n\n\n\npublic:\n\n\n\n virtual void OnUpdate ( unsigned long millis ) = 0;\n\n\n\n};\n\n\n\n} //bv\n", "file_path": "BlackVision/Applications/LibBVLogic/Source/Application/MainLoopProcess.h", "rank": 72, "score": 242513.89410250506 }, { "content": "class BVXMLSerializer : public XMLSerializer\n\n{\n\npublic:\n\n BVXMLSerializer( BVSerializeContext * context );\n\n\n\n //BVXMLSerializer( AssetDescsWithUIDsPtr assets );\n\n\n\n BVSerializeContext * GetBVSerializeContext();\n\n};\n\n\n\n}\n", "file_path": "BlackVision/LibBlackVision/Source/Serialization/BV/XML/BVXMLSerializer.h", "rank": 73, "score": 242513.89410250506 }, { "content": " enum class EntryType\n\n {\n\n Optional,\n\n Required\n\n };\n\n\n\n template< typename PropertyType >\n\n using ConfigPropertyPtr = PropertyType ( BVConfig::* );\n\n\n\n template< typename PropertyType >\n\n void LoadPropertyValueOrSetDefault ( const char * propertyPath, ConfigPropertyPtr< PropertyType > member, EntryType type );\n\n\n\n template<>\n\n void LoadPropertyValueOrSetDefault< std::string > ( const char * propertyPath, ConfigPropertyPtr< std::string > member, EntryType type );\n\n};\n\n\n\n#define DefaultConfig BVConfig::Instance()\n\n\n\n} //bv\n\n\n\n#include \"BVConfig.inl\"\n", "file_path": "BlackVision/Applications/LibBVLogic/Source/BVConfig.h", "rank": 74, "score": 242370.34525219467 }, { "content": "// The base class for all fixture tests.\n\nclass Fixture : public internal::Benchmark {\n\n public:\n\n Fixture() : internal::Benchmark(\"\") {}\n\n\n\n virtual void Run(State& st) {\n\n this->SetUp(st);\n\n this->BenchmarkCase(st);\n\n this->TearDown(st);\n\n }\n\n\n\n // These will be deprecated ...\n\n virtual void SetUp(const State&) {}\n\n virtual void TearDown(const State&) {}\n\n // ... In favor of these.\n\n virtual void SetUp(State& st) { SetUp(const_cast<const State&>(st)); }\n\n virtual void TearDown(State& st) { TearDown(const_cast<const State&>(st)); }\n\n\n\n protected:\n\n virtual void BenchmarkCase(State&) = 0;\n\n};\n", "file_path": "BlackVision/Dep/3rdParty/GoogleBenchmark/Include/benchmark/benchmark.h", "rank": 75, "score": 241898.0998063249 }, { "content": "// The convenience class for users who need to override just one or two\n\n// methods and are not concerned that a possible change to a signature of\n\n// the methods they override will not be caught during the build. For\n\n// comments about each method please see the definition of TestEventListener\n\n// above.\n\nclass EmptyTestEventListener : public TestEventListener {\n\n public:\n\n virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}\n\n virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,\n\n int /*iteration*/) {}\n\n virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}\n\n virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}\n\n virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}\n\n virtual void OnTestStart(const TestInfo& /*test_info*/) {}\n\n virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}\n\n virtual void OnTestEnd(const TestInfo& /*test_info*/) {}\n\n virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}\n\n virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}\n\n virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}\n\n virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,\n\n int /*iteration*/) {}\n\n virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}\n\n};\n\n\n", "file_path": "BlackVision/Dep/3rdParty/gtest/Include/gtest/gtest.h", "rank": 76, "score": 241746.18782735788 }, { "content": "class FbxReaderFbx6 : public FbxReader\n\n{\n\npublic:\n\n\n\n /** Constructor\n\n *\t\\param pManager the FbxManager Object\n\n * \\param pImporter the FbxImporter to import the SDK objects\n\n * \\param pID id for current reader\n\n * \\param pStatus the FbxStatus object to hold error codes\n\n */\n\n FbxReaderFbx6(FbxManager& pManager, FbxImporter& pImporter, int pID, FbxStatus& pStatus);\n\n\n\n /** Destructor\n\n *\n\n */\n\n virtual ~FbxReaderFbx6();\n\n\n\n /** Open file with certain EFileOpenSpecialFlags\n\n * \\param pFileName name of the File to open\n\n * \\param pFlags the EFileOpenSpecialFlags to open with\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxreaderfbx6.h", "rank": 77, "score": 241740.5271666456 }, { "content": " class InternalFilter : public FbxConnectionPointFilter\n\n\t{\n\n\tpublic:\n\n\t\tInternalFilter(FbxQuery* pQuery);\n\n\t\t~InternalFilter();\n\n\n\n\tpublic:\n\n\t\tFbxConnectionPointFilter*\tRef();\n\n\t\tvoid\t\t\t\t\t\tUnref();\n\n\t\tFbxInt\t\t\t\t\t\tGetUniqueId() const { return mQuery->GetUniqueId(); }\n\n\t\tbool\t\t\t\t\t\tIsValid(FbxConnectionPoint* pConnect) const;\n\n\t\tbool\t\t\t\t\t\tIsEqual(FbxConnectionPointFilter* pConnectFilter) const;\n\n\n\n\t\tFbxQuery*\t\t\t\t\tmQuery;\n\n };\n\n\n\n InternalFilter\tmFilter;\n\n int\t\t\t\tmRefCount;\n\n\n\n FBXSDK_FRIEND_NEW();\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/core/fbxquery.h", "rank": 78, "score": 241740.5271666456 }, { "content": "class FbxWriterFbx7 : public FbxWriter\n\n{\n\npublic:\n\n typedef enum\n\n {\n\n eASCII,\n\n eBINARY,\n\n eENCRYPTED\n\n } EExportMode;\n\n\n\n FbxWriterFbx7(FbxManager& pManager, FbxExporter& pExporter, int pID, FbxStatus& pStatus);\n\n FbxWriterFbx7(FbxManager& pManager, FbxExporter& pExporter, EExportMode pMode, int pID, FbxStatus& pStatus);\n\n virtual ~FbxWriterFbx7();\n\n\n\n virtual bool FileCreate(char* pFileName);\n\n virtual bool FileCreate(FbxStream* pStream, void* pStreamData);\n\n virtual bool FileClose();\n\n virtual bool IsFileOpen();\n\n\n\n virtual void GetWriteOptions();\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxwriterfbx7.h", "rank": 79, "score": 241740.5271666456 }, { "content": "class FbxWriterFbx6 : public FbxWriter\n\n{\n\npublic:\n\n FbxWriterFbx6(FbxManager& pManager, FbxExporter& pExporter, int pID, FbxStatus& pStatus);\n\n virtual ~FbxWriterFbx6();\n\n\n\n virtual bool FileCreate(char* pFileName);\n\n virtual bool\tFileCreate(FbxStream* pStream, void* pStreamData);\n\n virtual bool FileClose();\n\n virtual bool IsFileOpen();\n\n\n\n typedef enum {eASCII, eBINARY, eENCRYPTED} EExportMode;\n\n\n\n void SetExportMode(EExportMode pMode);\n\n\n\n virtual void GetWriteOptions();\n\n virtual bool Write(FbxDocument* pDocument);\n\n virtual bool PreprocessScene(FbxScene& pScene);\n\n virtual bool PostprocessScene(FbxScene& pScene);\n\n virtual void PluginWriteParameters(FbxObject& pParams);\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxwriterfbx6.h", "rank": 80, "score": 241740.5271666456 }, { "content": "class FbxWriterCollada : public FbxWriter \n\n{\n\npublic:\n\n /**\n\n * \\name Constructors and Destructor\n\n */\n\n //@{\n\n\n\n /** Constructor.\n\n * \\param pManager FBX SDK object Manager.\n\n * \\param pID Internal ID.\n\n * \\param pStatus The FbxStatus object to hold error codes.\n\n */\n\n FbxWriterCollada(FbxManager& pManager, int pID, FbxStatus& pStatus);\n\n\n\n //! Destructor.\n\n virtual ~FbxWriterCollada();\n\n\n\n //@}\n\n\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/collada/fbxwritercollada14.h", "rank": 81, "score": 241740.5271666456 }, { "content": " class FunctionCreator : public FunctionCreatorBase\n\n {\n\n public:\n\n\n\n\t\t/** Get Name of the operation function.\n\n\t\t * \\return The Name of the operation function.\n\n\t\t */\n\n virtual const char* GetFunctionName() const\n\n {\n\n return FUNCTION::FunctionName;\n\n }\n\n\n\n\t\t/** Create the operation function.\n\n\t\t*/\n\n virtual Function* CreateFunction() const\n\n {\n\n return FbxNew< FUNCTION >();\n\n }\n\n };\n\n\n\n /** This utility class is used to register and unregister the binding function creators.\n\n * \\nosubgrouping\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/scene/shading/fbxbindingoperator.h", "rank": 82, "score": 241740.5271666456 }, { "content": "class FbxReaderCollada : public FbxReader \n\n{\n\npublic:\n\n /**\n\n * \\name Constructors and Destructor\n\n */\n\n //@{\n\n\n\n /** Constructor.\n\n * \\param pManager FBX SDK object Manager.\n\n * \\param pID Internal ID.\n\n * \\param pStatus The FbxStatus object to hold error codes.\n\n */\n\n FbxReaderCollada(FbxManager& pManager, int pID, FbxStatus& pStatus); \n\n\t\n\n //! Destructor.\n\n virtual ~FbxReaderCollada();\n\n \n\n //@}\n\n\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/collada/fbxreadercollada14.h", "rank": 83, "score": 241740.5271666456 }, { "content": "class CmdLineParseException : public ArgException\n\n{\n\n\tpublic:\n\n\t\t/**\n\n\t\t * Constructor.\n\n\t\t * \\param text - The text of the exception.\n\n\t\t * \\param id - The text identifying the argument source \n\n\t\t * of the exception.\n\n\t\t */\n\n\t\tCmdLineParseException( const std::string& text = \"undefined exception\", \n\n\t\t\t\t\t const std::string& id = \"undefined\" )\n\n\t\t\t: ArgException( text, \n\n\t\t\t id,\n\n\t\t\t\t\t\t\tstd::string( \"Exception found when the values \") +\n\n\t\t\t\t\t\t\tstd::string( \"on the command line do not meet \") +\n\n\t\t\t\t\t\t\tstd::string( \"the requirements of the defined \") +\n\n\t\t\t\t\t\t\tstd::string( \"Args.\" ))\n\n\t\t{ }\n\n};\n\n\n\n/**\n\n * Thrown from Arg and CmdLine when an Arg is improperly specified, e.g. \n\n * same flag as another Arg, same name, etc.\n\n */\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/ArgException.h", "rank": 84, "score": 241740.5271666456 }, { "content": "class FbxReaderFbx7 : public FbxReader\n\n{\n\npublic:\n\n /** \\enum EImportMode File import mode.\n\n *\n\n */\n\n typedef enum\n\n {\n\n eASCII, /**< Plain text mode */\n\n eBINARY, /**< Binary mode */\n\n eENCRYPTED /**< Encrypted mode */\n\n } EImportMode;\n\n\n\n /** Constructor\n\n *\t\\param pManager the FbxManager Object\n\n * \\param pImporter the FbxImporter to import the SDK objects\n\n * \\param pID id for current reader\n\n * \\param pStatus the FbxStatus object to hold error codes\n\n */\n\n FbxReaderFbx7(FbxManager& pManager, FbxImporter& pImporter, int pID, FbxStatus& pStatus);\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxreaderfbx7.h", "rank": 85, "score": 241740.5271666456 }, { "content": "class MultiSwitchArg : public SwitchArg\n\n{\n\n\tprotected:\n\n\n\n\t\t/**\n\n\t\t * The value of the switch.\n\n\t\t */\n\n\t\tint _value;\n\n\n\n\t\t/**\n\n\t\t * Used to support the reset() method so that ValueArg can be\n\n\t\t * reset to their constructed value.\n\n\t\t */\n\n\t\tint _default;\n\n\n\n\tpublic:\n\n\n\n\t\t/**\n\n\t\t * MultiSwitchArg constructor.\n\n\t\t * \\param flag - The one character flag that identifies this\n", "file_path": "BlackVision/Dep/3rdParty/tclap-1.2.1/include/tclap/MultiSwitchArg.h", "rank": 86, "score": 241740.5271666456 }, { "content": "class FbxReaderFbx5 : public FbxReader\n\n{\n\npublic:\n\n\tFbxReaderFbx5(FbxManager& pManager, FbxImporter& pImporter, int pID, FbxStatus& pStatus);\n\n\tvirtual ~FbxReaderFbx5();\n\n\n\n virtual bool FileOpen(char* pFileName, bool pIgnoredArg);\n\n virtual bool FileOpen(char* pFileName, EFileOpenSpecialFlags pFlags){ return FbxReader::FileOpen(pFileName, pFlags); }\n\n\tvirtual bool FileOpen(char* pFileName);\n\n virtual bool FileOpen(FbxFile * pFile);\n\n\tvirtual bool FileOpen(FbxStream * pStream, void* pStreamData);\n\n\tvirtual bool FileClose();\n\n\tvirtual bool IsFileOpen();\n\n\n\n\tvirtual void SetEmbeddingExtractionFolder(const char* pExtractFolder);\n\n\n\n\ttypedef enum \n\n\t{\n\n\t\teASCII,\n\n\t\teBINARY,\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxreaderfbx5.h", "rank": 87, "score": 241740.5271666456 }, { "content": "class FbxWriterFbx5 : public FbxWriter\n\n{\n\npublic:\n\n\tFbxWriterFbx5(FbxManager& pManager, FbxExporter& pExporter, int pID, FbxStatus& pStatus);\n\n\tvirtual ~FbxWriterFbx5();\n\n\n\n\tvirtual bool FileCreate(char* pFileName);\n\n virtual bool FileCreate(FbxStream* pStream, void* pStreamData);\n\n\tvirtual bool FileClose();\n\n\tvirtual bool IsFileOpen();\n\n\n\n\ttypedef enum \n\n\t{\n\n\t\teASCII,\n\n\t\teBINARY,\n\n\t\teENCRYPTED\n\n\t} EExportMode;\n\n\n\n\tvoid SetExportMode(EExportMode pMode);\n\n\n", "file_path": "BlackVision/Dep/3rdParty/FBX/include/fbxsdk/fileio/fbx/fbxwriterfbx5.h", "rank": 88, "score": 241740.5271666456 }, { "content": "#include \"gtest/gtest.h\"\n\n\n\n#include \"Serialization/SerializationHelper.h\"\n\n#include \"Mathematics/glm_inc.h\"\n\n\n\n\n\n// ========================================================================= //\n\n// Test vectors (glm:: vec2, vec3, vec4) conversion. Internal implementation\n\n// uses String2T< float >, so Float tests cover all posible float formats issues.\n\n// ========================================================================= //\n\n\n\n\n\n\n\n\n\nusing namespace bv;\n\n\n\n\n\n// ***********************\n\n//\n\ntemplate< class Type >\n", "file_path": "BlackVision/Test/Tools/TestLibCore/Source/Conversions/String2Vec2.cpp", "rank": 90, "score": 34.506178238328374 }, { "content": "#include \"stdafx.h\"\n\n\n\n#include \"Key.h\"\n\n#include \"Key.inl\"\n\n\n\n#include \"Serialization/SerializationHelper.h\"\n\n\n\n#include \"Mathematics/glm_inc.h\"\n\n\n\n\n\n\n\n#include \"Memory/MemoryLeaks.h\"\n\n\n\n\n\n\n\nnamespace bv\n\n{\n\n#define INSTANTIATE( TIME_TYPE, TYPE ) \\\n\ntemplate class bv::Key< TIME_TYPE, TYPE >;\n\n\n", "file_path": "BlackVision/LibBlackVision/Source/Mathematics/Interpolators/Key.cpp", "rank": 91, "score": 34.398435326976276 }, { "content": "#pragma once\n\n\n\n#include \"CoreDEF.h\"\n\n\n\n#include <boost/circular_buffer.hpp>\n\n\n\n#include <vector>\n\n\n\n\n\n\n\nnamespace bv\n\n{\n\n\n\n\n\n\n\n// ***********************\n\n/// Class holds reusable elements in circular buffer. You can buffers and fill with new data\n\n/// without need to memory realocations.\n\ntemplate< typename ElementType >\n", "file_path": "BlackVision/LibCore/Source/DataTypes/Reusable.h", "rank": 92, "score": 34.07413038207627 }, { "content": "#pragma once\n\n\n\n#include \"DeclareWinTypes.h\"\n\n#include \"FrameStatsService.h\"\n\n\n\n#include <string>\n\n\n\n\n\n\n\nnamespace bv{\n\nusing std::string;\n\nusing std::to_string;\n\n\n\n\n", "file_path": "BlackVision/Applications/LibBVLogic/Source/Statistics/PerformanceMonitor.h", "rank": 93, "score": 33.95992261018324 }, { "content": "#pragma once\n\n\n\n#include \"Engine/Interfaces/IUpdater.h\"\n\n\n\n#include \"Engine/Models/Plugins/Interfaces/IState.h\"\n\n#include \"SimpleTypedStates.h\"\n\n#include \"Engine/Types/Values/TypedValues.h\"\n\n\n\n\n\nnamespace bv { namespace model {\n\n\n\n\n\n\n\ntemplate< typename StateTypePtr, typename ValueTypePtr >\n", "file_path": "BlackVision/LibBlackVision/Source/Engine/Models/Plugins/ParamValModel/SimpleStateUpdater.h", "rank": 94, "score": 33.75140383351184 }, { "content": "#pragma once\n\n\n\n#include \"Serialization/ISerializable.h\"\n\n\n\n\n\n\n\nnamespace bv\n\n{\n\n\n\n\n\n\n\n// ***********************\n\n//\n\ntemplate<class TimeValueT/* = bv::TimeType*/, class ValueT>\n", "file_path": "BlackVision/LibBlackVision/Source/Mathematics/Interpolators/Key.h", "rank": 95, "score": 33.225218868892895 }, { "content": "#pragma once\n\n\n\n#include \"DataArrayRow.h\"\n\n#include \"Mathematics/glm_inc.h\"\n\n\n\n#include <vector>\n\n\n\n\n\n\n\nnamespace bv\n\n{\n\n\n\ntemplate< typename RowType >\n", "file_path": "BlackVision/LibBlackVision/Source/Assets/DataArray/DataArrayTypedRows.h", "rank": 96, "score": 33.17239796117459 }, { "content": "", "file_path": "BlackVision/LibVideoCards/Source/Models/BlueFish/Output/BlueFishVCThread.cpp", "rank": 97, "score": 32.60806711012381 }, { "content": "#pragma once\n\n\n\n#include \"Exception.h\"\n\n#include <assert.h>\n\n\n\nnamespace bv\n\n{\n\n\n\n// ***********************\n\n/// Class used with Expected when we want only get success or failure from function without return value.\n", "file_path": "BlackVision/LibCore/Source/Expected.h", "rank": 98, "score": 32.56865565307961 }, { "content": "#pragma once\n\n\n\n#include \"TextureAsset.h\"\n\n#include \"Assets/Asset.h\"\n\n\n\n#include \"Assets/AssetManager.h\"\t\t\t// Only for LoadTypedAsset template specialization\n\n\n\n\n\nnamespace bv\n\n{\n\n\n\n/**Implements animation asset.\n\n@details\n\nLoads sequence of textures from directory as animation.\n\n\n\n<b>Supported formats:</b> jpg, tga, png, bmp.\n\n\n\n- | UID | Class\n\n----------------------- | ------------------------- | -----------\n\nDescriptor | ANIMATION_ASSET_DESC | @ref bv::AnimationAssetDesc\n", "file_path": "BlackVision/LibBlackVision/Source/Assets/Texture/AnimationAsset.h", "rank": 99, "score": 32.49010720281699 } ]
C++
Xenakios/FloatingInspector.cpp
lorenzopistolesi/sws
6963f7563851c8dd919db426bae825843939077f
#include "stdafx.h" #include "../SnM/SnM_Dlg.h" using namespace std; HWND g_hItemInspector=NULL; bool g_ItemInspectorVisible=false; WDL_DLGRET MyItemInspectorDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { static HMENU g_hItemInspCtxMenu=0; static int g_InspshowMode=1; if (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam)) return r; switch(Message) { case WM_INITDIALOG: g_hItemInspCtxMenu = CreatePopupMenu(); AddToMenu(g_hItemInspCtxMenu, "Show number of selected items/tracks", 666); AddToMenu(g_hItemInspCtxMenu, "Show item properties", 667); break; case WM_RBUTTONUP: { POINT pieru; pieru.x=GET_X_LPARAM(lParam); pieru.y=GET_Y_LPARAM(lParam); ClientToScreen(hwnd,&pieru); int ContextResult = TrackPopupMenu(g_hItemInspCtxMenu,TPM_LEFTALIGN|TPM_RETURNCMD,pieru.x,pieru.y,0,hwnd,NULL); if (ContextResult == 666) g_InspshowMode = 0; else if (ContextResult == 667) g_InspshowMode = 1; break; } case WM_COMMAND: if (LOWORD(wParam)==IDCANCEL) { KillTimer(g_hItemInspector, 1); ShowWindow(g_hItemInspector, SW_HIDE); g_ItemInspectorVisible=false; } break; case WM_TIMER: { ostringstream infoText; const int NumSelItems=CountSelectedMediaItems(NULL); if (g_InspshowMode==0) { if (NumSelItems>0) { if (NumSelItems>1) infoText << NumSelItems << " items selected "; else infoText << "1 item selected "; } else infoText << "No items selected"; int i; MediaTrack *CurTrack; int n=0; for (i=0;i<GetNumTracks();i++) { CurTrack=CSurf_TrackFromID(i+1,false); int isSel=*(int*)GetSetMediaTrackInfo(CurTrack,"I_SELECTED",NULL); if (isSel==1) n++; } if (n>0) { if (n>1) infoText << "\t" << n << " tracks selected"; else infoText << "\t1 track selected"; } else infoText << "\tNo tracks selected"; SetDlgItemText(hwnd,IDC_IISTATIC1,infoText.str().c_str()); } if (g_InspshowMode==1) { vector<MediaItem_Take*> TheTakes; XenGetProjectTakes(TheTakes,true,true); if (TheTakes.size()>0) { infoText << (char*)GetSetMediaItemTakeInfo(TheTakes[0],"P_NAME",NULL) << " Pitch : "; infoText << std::setprecision(3) << *(double*)GetSetMediaItemTakeInfo(TheTakes[0],"D_PITCH",NULL); infoText << "\tPlayrate : " << *(double*)GetSetMediaItemTakeInfo(TheTakes[0],"D_PLAYRATE",NULL); MediaItem* CurItem=(MediaItem*)GetSetMediaItemTakeInfo(TheTakes[0],"P_ITEM",NULL); if (CurItem) { int curTakeInd=666; curTakeInd= *(int*)GetSetMediaItemInfo(CurItem,"I_CURTAKE",NULL); infoText << " Take " << curTakeInd+1; infoText << " / " << GetMediaItemNumTakes(CurItem); } SetDlgItemText(hwnd,IDC_IISTATIC1,infoText.str().c_str()); } else SetDlgItemText(hwnd,IDC_IISTATIC1,"No item selected"); } break; } case WM_DESTROY: g_hItemInspector = NULL; DestroyMenu(g_hItemInspCtxMenu); break; } return 0; } void DoTglFltItemInspector(COMMAND_T*) { if (g_ItemInspectorVisible) { g_ItemInspectorVisible = false; KillTimer(g_hItemInspector, 1); ShowWindow(g_hItemInspector, SW_HIDE); } else { g_ItemInspectorVisible = true; SetTimer(g_hItemInspector, 1, 200, NULL); ShowWindow(g_hItemInspector, SW_SHOW); } }
#include "stdafx.h" #include "../SnM/SnM_Dlg.h" using namespace std; HWND g_hItemInspector=NULL; bool g_ItemInspectorVisible=false; WDL_DLGRET MyItemInspectorDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { static HMENU g_hItemInspCtxMenu=0; static int g_InspshowMode=1; if (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam)) return r; switch(Message) { case WM_INITDIALOG: g_hItemInspCtxMenu = CreatePopupMenu(); AddToMenu(g_hItemInspCtxMenu, "Show number of selected items/tracks", 666); AddToMenu(g_hItemInspCtxMenu, "Show item properties", 667); break; case WM_RBUTTONUP: { POINT pieru; pieru.x=GET_X_LPARAM(lParam); pieru.y=GET_Y_LPARAM(lParam); ClientToScreen(hwnd,&pieru); int ContextResult = TrackPopupMenu(g_hItemInspCtxMenu,TPM_LEFTALIGN|TPM_RETURNCMD,pieru.x,pieru.y,0,hwnd,NULL); if (ContextResult == 666) g_InspshowMode = 0; else if (ContextResult == 667) g_InspshowMode = 1; break; } case WM_COMMAND: if (LOWORD(wParam)==IDCANCEL) { KillTimer(g_hItemInspector, 1); ShowWindow(g_hItemInspector, SW_HIDE); g_ItemInspectorVisible=false; } break; case WM_TIMER: { ostringstream infoText; const int NumSelItems=CountSelectedMediaItems(NULL); if (g_InspshowMode==0) { if (NumSelItems>0) { if (NumSelItems>1) infoText << NumSelItems << " items selected "; else infoText << "1 item selected "; } else infoText << "No items selected"; int i; MediaTrack *CurTrack; int n=0; for (i=0;i<GetNumTracks();i++) { CurTrack=CSurf_TrackFromID(i+1,false); int isSel=*(int*)GetSetMediaTrackInfo(CurTrack,"I_SELECTED",NULL); if (isSel==1) n++; } if (n>0) { if (n>1) infoText << "\t" << n << " tracks selected"; else infoText << "\t1 track selected"; } else infoText << "\tNo tracks selected"; SetDlgItemText(hwnd,IDC_IISTATIC1,infoText.str().c_str()); } if (g_InspshowMode==1) { vector<MediaItem_Take*> TheTakes; XenGetProjectTakes(TheTakes,true,true); if (TheTakes.size()>0) { infoText << (char*)GetSetMediaItemTakeInfo(TheTakes[0],"P_NAME",NULL) << " Pitch : "; infoText << std::setprecision(3) << *(double*)GetSetMediaItemTakeInfo(TheTakes[0],"D_PITCH",NULL); infoText << "\tPlayrate : " << *(double*)GetSetMediaItemTakeInfo(TheTakes[0],"D_PLAYRATE",NULL); MediaItem* CurItem=(MediaItem*)GetSetMediaItemTakeInfo(TheTakes[0],"P_ITEM",NULL); if (CurItem) { int curTakeInd=666; curTakeInd= *(int*)GetSetMediaItemInfo(CurItem,"I_CURTAKE",NULL); infoText << " Take " << curTakeInd+1; infoText << " / " << GetMediaItemNumTakes(CurItem); } SetDlgItemText(hwnd,IDC_IISTATIC1,infoText.str().c_str()); } else SetDlgItemText(hwnd,IDC_IISTATIC1,"No item selected"); } break; } case WM_DESTROY: g_hItemInspector = NULL; DestroyMenu(g_hItemInspCtxMenu); break; } return 0; }
void DoTglFltItemInspector(COMMAND_T*) { if (g_ItemInspectorVisible) { g_ItemInspectorVisible = false; KillTimer(g_hItemInspector, 1); ShowWindow(g_hItemInspector, SW_HIDE); } else { g_ItemInspectorVisible = true; SetTimer(g_hItemInspector, 1, 200, NULL); ShowWindow(g_hItemInspector, SW_SHOW); } }
function_block-full_function
[ { "content": "class CmdSelectAllItemsOnTrackBetweenLoopPoints: public RprCommand\n\n{\n\npublic:\n\n\tCmdSelectAllItemsOnTrackBetweenLoopPoints(bool allInLoop) {m_allInLoop = allInLoop;}\n\nprivate:\n\n\tvirtual void doCommand(int flag);\n\n\tbool m_allInLoop;\n\n};\n\n\n", "file_path": "Fingers/MediaItemCommands.h", "rank": 0, "score": 165664.23609949515 }, { "content": "void DoSelectFirstItemInSelectedTrack(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 1, "score": 136121.2200999522 }, { "content": "void DoSelectTracksWithNoItems(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 2, "score": 129699.26011149267 }, { "content": "void DoSelectFirstTakesInItems(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 3, "score": 125011.57365020062 }, { "content": "void DoSelectLastTakesInItems(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 4, "score": 125011.57365020062 }, { "content": "void DoShuffleSelectTakesInItems(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 5, "score": 125011.57365020062 }, { "content": "void RestoreOrigTracksAndItemsSelection(WDL_TypedBuf<MediaTrack*> origSelTracks, WDL_TypedBuf<MediaItem*> origSelItems);\n", "file_path": "Misc/Adam.h", "rank": 6, "score": 124896.05702154226 }, { "content": "void DoSkipSelectAllItemsOnTracks(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 7, "score": 124896.05702154226 }, { "content": "void SWS_GetSelectedMediaItemsOnTrack(WDL_TypedBuf<MediaItem*>* buf, MediaTrack* tr);\n", "file_path": "sws_util.h", "rank": 8, "score": 120435.9072761058 }, { "content": "void SelectRecArmedTracksOfSelItems(WDL_TypedBuf<MediaItem*> selItems);\n", "file_path": "Misc/Adam.h", "rank": 9, "score": 120435.90727610579 }, { "content": "void DoSelectItemUnderEditCursorOnSelTrack(COMMAND_T*);\n", "file_path": "Xenakios/XenakiosExts.h", "rank": 10, "score": 116283.32585303909 }, { "content": "class ActiveTakeTrack\n\n{\n\npublic:\n\n\tActiveTakeTrack(MediaTrack* tr);\n\n\tActiveTakeTrack(LineParser* lp);\n\n\t~ActiveTakeTrack();\n\n\tvoid Restore(MediaTrack* tr);\n\n char* ItemString(char* str, int maxLen);\n\n\n\n\tWDL_PtrList<ActiveTake> m_items;\n\n\tGUID m_guid;\n\n};\n\n\n\nextern SWSProjConfig<WDL_PtrList_DOD<ActiveTakeTrack> > g_activeTakeTracks;\n\n\n\nvoid SaveActiveTakes(COMMAND_T* = NULL);\n\nvoid RestoreActiveTakes(COMMAND_T* = NULL);\n", "file_path": "Freeze/ActiveTake.h", "rank": 11, "score": 112593.6290917796 }, { "content": "class MediaItem_Take;\n", "file_path": "Fingers/RprTake.h", "rank": 12, "score": 112522.44402635309 }, { "content": "class TrackState\n\n{\n\npublic:\n\n\tTrackState(MediaTrack* tr, bool bSelOnly);\n\n\tTrackState(LineParser* lp);\n\n\t~TrackState();\n\n\tvoid AddSelItems(MediaTrack* tr);\n\n\tvoid UnselAllItems(MediaTrack* tr);\n\n\tvoid Restore(MediaTrack* tr, bool bSelOnly);\n\n char* ItemString(char* str, int maxLen);\n\n\tvoid SelectItems(MediaTrack* tr);\n\n\n\n\tWDL_PtrList<ItemState> m_items;\n\n\tGUID m_guid;\n\n\tbool m_bFIPM;\n\n\tint m_iColor;\n\n};\n\n\n\nextern SWSProjConfig<WDL_PtrList_DOD<TrackState> > g_tracks;\n\n\n\nvoid SaveTrack(COMMAND_T* ct);\n\nvoid RestoreTrack(COMMAND_T* ct);\n\nvoid SelItemsWithState(COMMAND_T* ct);\n\nvoid SaveSelOnTrack(COMMAND_T* ct);\n\nvoid RestoreSelOnTrack(COMMAND_T* ct);\n", "file_path": "Freeze/TrackItemState.h", "rank": 13, "score": 112345.77767784521 }, { "content": "class ItemState\n\n{\n\npublic:\n\n\tItemState(LineParser* lp);\n\n\tItemState(MediaItem* mi);\n\n\tMediaItem* FindItem(MediaTrack* tr);\n\n\tvoid Restore(MediaTrack* tr, bool bSelOnly);\n\n char* ItemString(char* str, int maxLen);\n\n\tvoid Select(MediaTrack* tr);\n\n\n\n\tGUID m_guid;\n\n\tbool m_bMute;\n\n\tbool m_bSel;\n\n\tfloat m_fFIPMy;\n\n\tfloat m_fFIPMh;\n\n\tint m_iColor;\n\n\tdouble m_dVol;\n\n\tdouble m_dFadeIn;\n\n\tdouble m_dFadeOut;\n\n};\n\n\n", "file_path": "Freeze/TrackItemState.h", "rank": 14, "score": 112324.22218029355 }, { "content": "class SelItemsTrack\n\n{\n\npublic:\n\n\tSelItemsTrack(MediaTrack* tr);\n\n\tSelItemsTrack(LineParser* lp);\n\n\t~SelItemsTrack();\n\n\tvoid Add(LineParser* lp, int iSlot);\n\n\tvoid SaveTemp(MediaTrack* tr);\n\n\tvoid Save(MediaTrack* tr, int iSlot);\n\n\tvoid Restore(MediaTrack* tr, int iSlot);\n\n\tvoid PreviousSelection(MediaTrack* tr);\n\n char* ItemString(char* str, int maxLen, bool* bDone);\n\n\n\n\tSelItems* m_selItems[SEL_SLOTS];\n\n\tSelItems* m_lastSel;\n\n\tGUID m_guid;\n\n};\n\n\n\nextern SWSProjConfig<WDL_PtrList_DOD<SelItemsTrack> > g_selItemsTrack;\n\nextern SWSProjConfig<SelItems> g_selItems;\n\n\n\n// \"Exported\" functions\n\nvoid RestoreSelTrackSelItems(COMMAND_T* = NULL);\n\nvoid SaveSelTrackSelItems(COMMAND_T*);\n\nvoid RestoreLastSelItemTrack(COMMAND_T*);\n\nvoid SaveSelItems(COMMAND_T*);\n\nvoid RestoreSelItems(COMMAND_T*);\n", "file_path": "Freeze/ItemSelState.h", "rank": 15, "score": 108541.48859937338 }, { "content": "/******************************************************************************\n\n/ TrackItemState.h\n\n/\n\n/ Copyright (c) 2009 Tim Payne (SWS)\n\n/\n\n/\n\n/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\n/ of this software and associated documentation files (the \"Software\"), to deal\n\n/ in the Software without restriction, including without limitation the rights to\n\n/ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n\n/ of the Software, and to permit persons to whom the Software is furnished to\n\n/ do so, subject to the following conditions:\n\n/ \n\n/ The above copyright notice and this permission notice shall be included in all\n\n/ copies or substantial portions of the Software.\n\n/ \n\n/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\n/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\n/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\n/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n", "file_path": "Freeze/TrackItemState.h", "rank": 16, "score": 106872.34364687404 }, { "content": "/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\n/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\n/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\n/ OTHER DEALINGS IN THE SOFTWARE.\n\n/\n\n******************************************************************************/\n\n\n\n\n\n#pragma once\n\n\n", "file_path": "Freeze/TrackItemState.h", "rank": 17, "score": 106859.84215930363 }, { "content": "enum EnvType { eENVTYPE_TRACK=0, eENVTYPE_TAKE=1, eENVTYPE_MIDICC=2 };\n", "file_path": "Padre/padreEnvelopeProcessor.h", "rank": 18, "score": 104876.11139206703 }, { "content": "\t\tMunRaita = CSurf_TrackFromID(i+1,FALSE);\n\n\t\tnumItems=GetTrackNumMediaItems(MunRaita);\n\n\t\tMain_OnCommand(40635,0);\n\n\t\tfor (j=0;j<numItems;j++)\n\n\t\t{\n\n\t\t\tCurItem = GetTrackMediaItem(MunRaita,j);\n\n\t\t\t//propertyName=\"D_\";\n\n\t\t\tItemSelected=*(bool*)GetSetMediaItemInfo(CurItem,\"B_UISEL\",NULL);\n\n\t\t\tif (ItemSelected==TRUE)\n\n\t\t\t{\n\n\t\t\t\tMain_OnCommand(40601,0); // render items as new take\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t*fxtail=OldTail;\n\n\tUpdateTimeline();\n\n}\n\n\n\nWDL_DLGRET RenderItemsWithTailDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 19, "score": 102196.95176607557 }, { "content": "\n\nint NumSteps=2;\n\nint StepOffset=1;\n\nint SkipItemSource=0; // 0 for all in selected tracks, 1 for items selected in selected tracks\n\n\n\nWDL_DLGRET SelEveryNthDialogProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n\n\t\treturn r;\n\n\n\n\tswitch(Message)\n\n {\n\n case WM_INITDIALOG:\n\n\t\t\t{\n\n\t\t\t//SetDlgItemText(hwnd, IDC_EDIT1, \"2\");\n\n\t\t\t//SetDlgItemText(hwnd, IDC_EDIT2, \"0\");\n\n\t\t\tchar TextBuf[32];\n\n\t\t\tsprintf(TextBuf,\"%d\",NumSteps);\n\n\n\n\t\t\tSetDlgItemText(hwnd, IDC_EDIT1, TextBuf);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 20, "score": 102194.01748672027 }, { "content": "\t\tSWS_GetSelectedMediaItemsOnTrack(&items, track);\n\n\n\n\t\tfor (int j = 1; j < items.GetSize(); j++)\n\n\t\t{\n\n\t\t\tdouble dPrevItemStart = *(double*)GetSetMediaItemInfo(items.Get()[j - 1], \"D_POSITION\", NULL);\n\n\t\t\tdouble dNewPos = dPrevItemStart + theGap;\n\n\t\t\tif (bEnd) // From the previous selected item end, add the prev item length\n\n\t\t\t\tdNewPos += *(double*)GetSetMediaItemInfo(items.Get()[j-1], \"D_LENGTH\", NULL);\n\n\n\n\t\t\tGetSetMediaItemInfo(items.Get()[j], \"D_POSITION\", &dNewPos);\n\n\t\t}\n\n\t}\n\n}\n\n\n\nWDL_DLGRET ReposItemsDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n\n\t\treturn r;\n\n\n\n\tswitch(Message)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 21, "score": 102190.80185832441 }, { "content": "void DoSetItemVols(double theVol)\n\n{\n\n\tfor (int i=0;i<GetNumTracks();i++)\n\n\t{\n\n\t\tMediaTrack* pTrack = CSurf_TrackFromID(i+1, false);\n\n\t\tfor (int j = 0; j < GetTrackNumMediaItems(pTrack); j++)\n\n\t\t{\n\n\t\t\tMediaItem* CurItem = GetTrackMediaItem(pTrack,j);\n\n\t\t\tif (*(bool*)GetSetMediaItemInfo(CurItem, \"B_UISEL\", NULL))\n\n\t\t\t\tGetSetMediaItemInfo(CurItem, \"D_VOL\", &theVol);\n\n\t\t}\n\n\t}\n\n\tUndo_OnStateChangeEx(__LOCALIZE(\"Set item volume\",\"sws_undo\"), 4, -1);\n\n\tUpdateTimeline();\n\n}\n\n\n\n\n\nWDL_DLGRET ItemSetVolDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 22, "score": 102190.12255134132 }, { "content": "/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\n/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\n/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\n/ OTHER DEALINGS IN THE SOFTWARE.\n\n/\n\n******************************************************************************/\n\n\n\n#include \"stdafx.h\"\n\n#include \"../SnM/SnM_Dlg.h\"\n\n#include \"../reaper/localize.h\"\n\n#include \"Parameters.h\"\n\n#include \"../Breeder/BR_Util.h\"\n\n\n\nusing namespace std;\n\n\n\nint XenGetProjectItems(vector<MediaItem*>& TheItems,bool OnlySelectedItems, bool IncEmptyItems)\n\n{\n\n\tTheItems.clear();\n\n\tfor (int i = 0; i < GetNumTracks(); i++)\n\n\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 23, "score": 102188.84869192784 }, { "content": "\t\tMessageBox(g_hwndParent, __LOCALIZE(\"None or more than 1 item selected\",\"sws_mbox\"),__LOCALIZE(\"Xenakios - Error\",\"sws_mbox\") ,MB_OK);\n\n\tdelete TheTakes;\n\n}\n\n\n\ntypedef struct\n\n{\n\n\tdouble Gap;\n\n\tbool bEnd;\n\n} t_ReposItemsParams;\n\n\n\nt_ReposItemsParams g_ReposItemsParams = { 1.0, false };\n\n\n\nvoid RepositionItems(double theGap, bool bEnd) // bEnd = true gap from end else start\n\n{\n\n\tWDL_TypedBuf<MediaItem*> items;\n\n\n\n\tint numTracks = CountTracks(NULL);\n\n\tfor (int i = 0; i < numTracks; i++)\n\n\t{\n\n\t\tMediaTrack* track = CSurf_TrackFromID(i + 1, false);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 24, "score": 102185.53033808034 }, { "content": "\treturn 0;\n\n}\n\n\n\nvoid DoShowItemVolumeDialog(COMMAND_T*)\n\n{\n\n\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_ITEMVOLUME), g_hwndParent, ItemSetVolDlgProc);\n\n}\n\n\n\nWDL_DLGRET ItemPanVolDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n\n\t\treturn r;\n\n\n\n\tswitch(Message)\n\n {\n\n case WM_INITDIALOG:\n\n\n\n\t\t\tSetDlgItemText(hwnd, IDC_VOLEDIT, \"\");\n\n\t\t\tSetDlgItemText(hwnd, IDC_PANEDIT, \"\");\n\n\t\t\tSetFocus(GetDlgItem(hwnd, IDC_VOLEDIT));\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 25, "score": 102185.17499066955 }, { "content": "{\n\n\tShowSelectSkipFromSelectedItems(0);\n\n}\n\n\n\nvoid DoSkipSelectFromSelectedItems(COMMAND_T*)\n\n{\n\n\tShowSelectSkipFromSelectedItems(1);\n\n}\n\n\n\nint *TakeIndexes;\n\n\n\nbool GenerateShuffledTakeRandomTable(int *IntTable,int numItems,int badFirstNumber)\n\n{\n\n\tint *CheckTable=new int[1024];\n\n\tbool GoodFound=FALSE;\n\n\tint IterCount=0;\n\n\tint rndInt;\n\n\tint i;\n\n\tfor (i=0;i<1024;i++)\n\n\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 26, "score": 102183.90990662605 }, { "content": "\t\tMediaTrack* CurTrack = CSurf_TrackFromID(i+1, false);\n\n\t\tfor (int j = 0; j < GetTrackNumMediaItems(CurTrack); j++)\n\n\t\t{\n\n\t\t\tMediaItem* CurItem = GetTrackMediaItem(CurTrack, j);\n\n\t\t\tif (CurItem && (!OnlySelectedItems || *(bool*)GetSetMediaItemInfo(CurItem, \"B_UISEL\", NULL)))\n\n\t\t\t{\n\n\t\t\t\tif (IncEmptyItems || GetMediaItemNumTakes(CurItem) > 0)\n\n\t\t\t\t\tTheItems.push_back(CurItem);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn (int)TheItems.size();\n\n}\n\n\n\nint XenGetProjectTakes(vector<MediaItem_Take*>& TheTakes, bool OnlyActive, bool OnlyFromSelectedItems)\n\n{\n\n\tTheTakes.clear();\n\n\tfor (int i = 0; i < GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* CurTrack = CSurf_TrackFromID(i+1,false);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 27, "score": 102182.44923662874 }, { "content": "\n\n\t\tUndo_EndBlock(__LOCALIZE(\"Repeat paste\",\"sws_undo\"),0);\n\n\t}\n\n}\n\n\n\n\n\n\n\nWDL_DLGRET RepeatPasteDialogProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tstatic double dTimeInterval = 1.0;\n\n\tstatic double dBeatInterval = 1.0;\n\n\tstatic char cBeatStr[50] = \"1\";\n\n\tstatic int iNumRepeats = 1;\n\n\tstatic int iRepeatMode = 2;\n\n\n\n\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n\n\t\treturn r;\n\n\n\n\tswitch(Message)\n\n {\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 28, "score": 102180.4051538431 }, { "content": "\n\nvoid DoReposItemsDlg(COMMAND_T*)\n\n{\n\n\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_REPOSITEMS), g_hwndParent, ReposItemsDlgProc);\n\n}\n\n\n\nvoid DoSpeadSelItemsOverNewTx(COMMAND_T* ct)\n\n{\n\n\tif (CountSelectedMediaItems(NULL) > 1)\n\n\t{\n\n\t\tfor (int i = 0; i < CountTracks(NULL) ; ++i)\n\n\t\t{\n\n\t\t\tMediaTrack* track = GetTrack(NULL, i);\n\n\t\t\tint id = CSurf_TrackToID(track, false);\n\n\t\t\tint depth = *(int*)GetSetMediaTrackInfo(track, \"I_FOLDERDEPTH\", NULL);\n\n\t\t\tvector<MediaItem*> items = GetSelItems(track);\n\n\n\n\t\t\tbool found = false;\n\n\t\t\tfor (int j =0; j < (int)items.size() ; ++j)\n\n\t\t\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 29, "score": 102179.48843607248 }, { "content": "\t\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\t\treturn 0;\n\n\t\t\t\t\t}\n\n\t\t\t\tcase IDCANCEL:\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\t\treturn 0;\n\n\t\t\t\t\t}\n\n\t\t\t}\n\n\t}\n\n\treturn 0;\n\n}\n\n\n\nvoid ShowSelectSkipFromSelectedItems(int SelectMode)\n\n{\n\n\tSkipItemSource=SelectMode;\n\n\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_SELECT_NTH_ITEMDLG), g_hwndParent, SelEveryNthDialogProc);\n\n}\n\n\n\nvoid DoSkipSelectAllItemsOnTracks(COMMAND_T*)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 30, "score": 102179.43897578526 }, { "content": "\t\tfor (int j = 0; j < GetTrackNumMediaItems(CurTrack); j++)\n\n\t\t{\n\n\t\t\tMediaItem* CurItem=GetTrackMediaItem(CurTrack,j);\n\n\t\t\tif (CurItem && (!OnlyFromSelectedItems || *(bool*)GetSetMediaItemInfo(CurItem,\"B_UISEL\",NULL)))\n\n\t\t\t{\n\n\t\t\t\tif (OnlyActive)\n\n\t\t\t\t{\n\n\t\t\t\t\tMediaItem_Take* CurTake = GetMediaItemTake(CurItem, -1);\n\n\t\t\t\t\tif (CurTake)\n\n\t\t\t\t\t\tTheTakes.push_back(CurTake);\n\n\t\t\t\t}\n\n\t\t\t\telse for (int k = 0; k < GetMediaItemNumTakes(CurItem); k++)\n\n\t\t\t\t{\n\n\t\t\t\t\tMediaItem_Take* CurTake = GetMediaItemTake(CurItem, k);\n\n\t\t\t\t\tif (CurTake)\n\n\t\t\t\t\t\tTheTakes.push_back(CurTake);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 31, "score": 102178.51649304898 }, { "content": "\t\tif (oddOreven==1)\n\n\t\t\tGetSetMediaItemInfo(TheItems[i],\"D_POSITION\",&itempos);\n\n\t}\n\n\tUpdateTimeline();\n\n\tUndo_OnStateChangeEx(__LOCALIZE(\"Swing item positions\",\"sws_undo\"),UNDO_STATE_ITEMS,-1);\n\n}\n\n\n\nWDL_DLGRET SwingItemsDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tchar tbuf[200];\n\n\n\n\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n\n\t\treturn r;\n\n\n\n\tif (Message==WM_INITDIALOG)\n\n\t{\n\n\t\tsprintf(tbuf,\"%.2f\",g_swingAmt*100.0);\n\n\t\tSetDlgItemText(hwnd,IDC_EDIT1,tbuf);\n\n\t\treturn 0;\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 32, "score": 102176.90565719 }, { "content": "\n\n\tint numItems;\n\n\n\n\tPreventUIRefresh(1);\n\n\t//Main_OnCommand(40289,0); // Unselect all items\n\n\tbool NewSelectedStatus=false;\n\n\tint flags, i, j;\n\n\tfor (i=0;i<GetNumTracks();i++)\n\n\t{\n\n\t\tGetTrackInfo(i,&flags);\n\n\t\t//if (flags & 0x02)\n\n\t\t{\n\n\t\t\tMunRaita = CSurf_TrackFromID(i+1,FALSE);\n\n\t\t\tint ItemCounter=0;\n\n\t\t\tnumItems=GetTrackNumMediaItems(MunRaita);\n\n\t\t\tfor (j=0;j<numItems;j++)\n\n\t\t\t{\n\n\t\t\t\tCurItem = GetTrackMediaItem(MunRaita,j);\n\n\t\t\t\tbool ItemSelected=*(bool*)GetSetMediaItemInfo(CurItem,\"B_UISEL\",NULL);\n\n\t\t\t\tif (ItemSelected)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 33, "score": 102176.50664046805 }, { "content": "\telse\n\n\t\tMessageBox(g_hwndParent, __LOCALIZE(\"No or only one item selected!\",\"sws_mbox\"), __LOCALIZE(\"Xenakios - Error\",\"sws_mbox\"), MB_OK);\n\n\n\n}\n\n\n\nint OpenInExtEditor(int editorIdx)\n\n{\n\n\tvector<MediaItem_Take*> TheTakes;\n\n\tXenGetProjectTakes(TheTakes,true,true);\n\n\tif (TheTakes.size()==1)\n\n\t{\n\n\t\tMediaItem* CurItem=(MediaItem*)GetSetMediaItemTakeInfo(TheTakes[0],\"P_ITEM\",NULL);\n\n\n\n\t\t//Main_OnCommand(40639,0); // duplicate active take\n\n\t\tMain_OnCommand(40601,0); // render items and add as new take\n\n\t\t//int curTakeIndex=*(int*)GetSetMediaItemInfo(CurItem,\"I_CURTAKE\",NULL);\n\n\t\tMediaItem_Take *CopyTake=GetMediaItemTake(CurItem,-1);\n\n\t\tPCM_source *ThePCM=(PCM_source*)GetSetMediaItemTakeInfo(CopyTake,\"P_SOURCE\",NULL);\n\n\t\tif (ThePCM && ThePCM->GetFileName())\n\n\t\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 34, "score": 102176.2110168148 }, { "content": "\t\t\tSendMessage(GetDlgItem(hwnd, IDC_VOLEDIT), EM_SETSEL, 0, -1);\n\n\t\t\tbreak;\n\n case WM_COMMAND:\n\n switch(LOWORD(wParam))\n\n {\n\n case IDOK:\n\n\t\t\t\t{\n\n\t\t\t\t\tchar TempString[100];\n\n\t\t\t\t\tGetDlgItemText(hwnd,IDC_VOLEDIT,TempString,99);\n\n\t\t\t\t\tbool SetVol=FALSE;\n\n\t\t\t\t\tbool SetPan=FALSE;\n\n\t\t\t\t\tdouble NewVol=strtod(TempString,NULL);\n\n\n\n\t\t\t\t\tif (strcmp(TempString,\"\")!=0)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tif (NewVol>-144.0)\n\n\t\t\t\t\t\t\tNewVol=exp(NewVol*0.115129254);\n\n\t\t\t\t\t\telse\n\n\t\t\t\t\t\t\tNewVol=0;\n\n\t\t\t\t\t\tSetVol=TRUE;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 35, "score": 102175.28770651792 }, { "content": "\tMain_OnCommand(40361,0); // apply track fx in mono to items\n\n\tdouble dVol = 1.0;\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n\n\tfor (int i = 0; i < cnt; i++)\n\n\t\tGetSetMediaItemInfo(GetSelectedMediaItem(0, i), \"D_VOL\", &dVol);\n\n\tUndo_EndBlock(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS);\n\n}\n\n\n\nvoid DoSelItemsToEndOfTrack(COMMAND_T*)\n\n{\n\n\tPreventUIRefresh(1);\n\n\tfor (int i = 0; i < GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i+1, false);\n\n\t\tbool bSel = false;\n\n\t\tfor (int j = 0; j < GetTrackNumMediaItems(tr); j++)\n\n\t\t{\n\n\t\t\tMediaItem* mi = GetTrackMediaItem(tr, j);\n\n\t\t\tif (!bSel && *(bool*)GetSetMediaItemInfo(mi, \"B_UISEL\", NULL))\n\n\t\t\t\tbSel = true;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 36, "score": 102175.19999358163 }, { "content": "\treturn (int)TheTakes.size();\n\n}\n\n\n\nvoid DoMoveItemsLeftByItemLen(COMMAND_T* ct)\n\n{\n\n\tvector<MediaItem*> VecItems;\n\n\tfor (int i = 0; i < GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* CurTrack=CSurf_TrackFromID(i+1,false);\n\n\t\tfor (int j = 0; j < GetTrackNumMediaItems(CurTrack); j++)\n\n\t\t{\n\n\t\t\tMediaItem* CurItem = GetTrackMediaItem(CurTrack,j);\n\n\t\t\tbool isSel = *(bool*)GetSetMediaItemInfo(CurItem, \"B_UISEL\", NULL);\n\n\t\t\tif (isSel) VecItems.push_back(CurItem);\n\n\t\t}\n\n\t}\n\n\tfor (int i = 0; i < (int)VecItems.size(); i++)\n\n\t{\n\n\t\tdouble CurPos = *(double*)GetSetMediaItemInfo(VecItems[i], \"D_POSITION\", NULL);\n\n\t\tdouble dItemLen = *(double*)GetSetMediaItemInfo(VecItems[i], \"D_LENGTH\", NULL);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 37, "score": 102174.82117783262 }, { "content": "\tif (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam))\n\n\t\treturn r;\n\n\n\n\tswitch(Message)\n\n {\n\n case WM_INITDIALOG:\n\n\t\t{\n\n\t\t\tchar TextBuf[32];\n\n\n\n\t\t\tsprintf(TextBuf,\"%.2f\",g_lastTailLen);\n\n\t\t\tSetDlgItemText(hwnd, IDC_EDIT1, TextBuf);\n\n\t\t\tSetFocus(GetDlgItem(hwnd, IDC_EDIT1));\n\n\t\t\tSendMessage(GetDlgItem(hwnd, IDC_EDIT1), EM_SETSEL, 0, -1);\n\n\t\t\tbreak;\n\n\t\t}\n\n case WM_COMMAND:\n\n switch(LOWORD(wParam))\n\n {\n\n case IDOK:\n\n\t\t\t\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 38, "score": 102174.62063693436 }, { "content": "\t\treturn r;\n\n\n\n\tswitch(Message)\n\n {\n\n case WM_INITDIALOG:\n\n\t\t{\n\n\t\t\tSetDlgItemText(hwnd, IDC_VOLEDIT, \"0.0\");\n\n\t\t\tSetFocus(GetDlgItem(hwnd, IDC_VOLEDIT));\n\n\t\t\tSendMessage(GetDlgItem(hwnd, IDC_VOLEDIT), EM_SETSEL, 0, -1);\n\n\t\t\tbreak;\n\n\t\t}\n\n case WM_COMMAND:\n\n switch(LOWORD(wParam))\n\n {\n\n case IDOK:\n\n\t\t\t\t{\n\n\t\t\t\t\tchar tbuf[100];\n\n\t\t\t\t\tGetDlgItemText(hwnd,IDC_VOLEDIT,tbuf,99);\n\n\t\t\t\t\tdouble NewVol=1.0;\n\n\t\t\t\t\tbool WillSetVolume=false;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 39, "score": 102174.61574464022 }, { "content": "\t\t{\n\n\t\t\tIntTable[i]=rndInt;\n\n\t\t\tCheckTable[rndInt]=1;\n\n\t\t}\n\n\t}\n\n\tdelete[] CheckTable;\n\n\treturn FALSE;\n\n}\n\n\n\nvoid DoShuffleSelectTakesInItems(COMMAND_T* ct)\n\n{\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n\n\tfor (int i = 0; i < cnt; ++i)\n\n\t{\n\n\t\tMediaItem* item = GetSelectedMediaItem(NULL, i);\n\n\t\tint takeCount = CountTakes(item);\n\n\t\tif (takeCount > 1)\n\n\t\t{\n\n\t\t\tint id = *(int*)GetSetMediaItemInfo(item,\"I_CURTAKE\",NULL);\n\n\t\t\t--takeCount; // for MTRand\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 40, "score": 102174.14870893562 }, { "content": "\t\t\tsprintf(TextBuf,\"%d\",StepOffset);\n\n\t\t\tSetDlgItemText(hwnd, IDC_EDIT2, TextBuf);\n\n\t\t\tSetFocus(GetDlgItem(hwnd, IDC_EDIT1));\n\n\t\t\tSendMessage(GetDlgItem(hwnd, IDC_EDIT1), EM_SETSEL, 0, -1);\n\n\t\t\treturn 0;\n\n\t\t\t}\n\n case WM_COMMAND:\n\n switch(LOWORD(wParam))\n\n {\n\n case IDOK:\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tchar TempString[32];\n\n\t\t\t\t\t\tGetDlgItemText(hwnd,IDC_EDIT1,TempString,31);\n\n\t\t\t\t\t\tNumSteps=atoi(TempString);\n\n\t\t\t\t\t\tGetDlgItemText(hwnd,IDC_EDIT2,TempString,31);\n\n\t\t\t\t\t\tStepOffset=atoi(TempString);\n\n\t\t\t\t\t\tif (SkipItemSource==0)\n\n\t\t\t\t\t\t\tDoSelectEveryNthItemOnSelectedTracks(NumSteps,StepOffset);\n\n\t\t\t\t\t\tif (SkipItemSource==1)\n\n\t\t\t\t\t\t\tDoSelectSkipSelectOnSelectedItems(NumSteps,StepOffset);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 41, "score": 102172.57833155231 }, { "content": "}\n\n\n\nvoid DoInvertItemSelection(COMMAND_T* _ct)\n\n{\n\n\tPreventUIRefresh(1);\n\n\tfor (int i = 1; i <= GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i, FALSE);\n\n\t\tfor (int j = 0; j < GetTrackNumMediaItems(tr); j++)\n\n\t\t{\n\n\t\t\tMediaItem* CurItem = GetTrackMediaItem(tr, j);\n\n\t\t\tif (*(bool*)GetSetMediaItemInfo(CurItem, \"B_UISEL\", NULL))\n\n\t\t\t\tGetSetMediaItemInfo(CurItem, \"B_UISEL\", &g_bFalse);\n\n\t\t\telse\n\n\t\t\t\tGetSetMediaItemInfo(CurItem, \"B_UISEL\", &g_bTrue);\n\n\t\t}\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateArrange();\n\n\tUndo_OnStateChangeEx2(NULL, SWS_CMD_SHORTNAME(_ct), UNDO_STATE_ALL, -1);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 42, "score": 102171.39628269913 }, { "content": "\treturn 0;\n\n}\n\n\n\n\n\nvoid DoShowVolPanDialog(COMMAND_T*)\n\n{\n\n\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_ITEMPANVOLDIALOG), g_hwndParent, ItemPanVolDlgProc);\n\n}\n\n\n\nvoid DoChooseNewSourceFileForSelTakes(COMMAND_T* ct)\n\n{\n\n\tWDL_PtrList<MediaItem_Take> *TheTakes=new (WDL_PtrList<MediaItem_Take>);\n\n\tPCM_source *ThePCMSource;\n\n\tint i;\n\n\tint NumActiveTakes=GetActiveTakes(TheTakes);\n\n\tif (NumActiveTakes>0)\n\n\t{\n\n\t\tMediaItem_Take* CurTake;\n\n\t\tchar* cFileName = BrowseForFiles(__LOCALIZE(\"Choose new source file\",\"sws_mbox\"), NULL, NULL, false, plugin_getFilterList());\n\n\t\tif (cFileName)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 43, "score": 102171.15241908238 }, { "content": "\t\t\t\t\t}\n\n\n\n\t\t\t\t\tGetDlgItemText (hwnd,IDC_PANEDIT,TempString,99);\n\n\t\t\t\t\tdouble NewPan=strtod(TempString,NULL);\n\n\t\t\t\t\tif (strcmp(TempString,\"\")!=0)\n\n\t\t\t\t\t\tSetPan=TRUE;\n\n\t\t\t\t\tDoSetVolPan(NewVol,NewPan/100.0,SetVol,SetPan);\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tcase IDCANCEL:\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t}\n\n\treturn 0;\n\n}\n\n\n\nvoid PasteMultipletimes(int NumPastes, double TimeIntervalQN, int RepeatMode)\n\n{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 44, "score": 102170.57041606653 }, { "content": "\tUndo_BeginBlock();\n\n\tMain_OnCommand(40652, 0); // set item rate to 1.0\n\n\tMain_OnCommand(40653, 0); // reset item pitch to 0.0\n\n\tUndo_EndBlock(SWS_CMD_SHORTNAME(ct),0);\n\n}\n\n\n\nvoid DoApplyTrackFXStereoAndResetVol(COMMAND_T* ct)\n\n{\n\n\tUndo_BeginBlock();\n\n\tMain_OnCommand(40209,0); // apply track fx in stereo to items\n\n\tdouble dVol = 1.0;\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n\n\tfor (int i = 0; i < cnt; i++)\n\n\t\tGetSetMediaItemInfo(GetSelectedMediaItem(0, i), \"D_VOL\", &dVol);\n\n\tUndo_EndBlock(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS);\n\n}\n\n\n\nvoid DoApplyTrackFXMonoAndResetVol(COMMAND_T* ct)\n\n{\n\n\tUndo_BeginBlock();\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 45, "score": 102170.22724694191 }, { "content": "void DoRepeatPaste(COMMAND_T*)\n\n{\n\n\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_REPEATPASTEDLG), g_hwndParent, RepeatPasteDialogProc);\n\n}\n\n\n\nvoid DoSelectEveryNthItemOnSelectedTracks(int Step,int ItemOffset)\n\n{\n\n\tPreventUIRefresh(1);\n\n\n\n\tMain_OnCommand(40289,0); // Unselect all items\n\n\n\n\tint flags;\n\n\tfor (int i = 0; i < GetNumTracks(); i++)\n\n\t{\n\n\t\tGetTrackInfo(i,&flags);\n\n\t\tif (flags & 0x02)\n\n\t\t{\n\n\t\t\tMediaTrack* MunRaita = CSurf_TrackFromID(i+1,FALSE);\n\n\t\t\tint ItemCounter = 0;\n\n\t\t\tfor (int j = 0; j < GetTrackNumMediaItems(MunRaita); j++)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 46, "score": 102170.19804172197 }, { "content": "\tdouble dRightEdge = GetCursorPosition();\n\n\tbool modified = false;\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n\n\tfor (int i = 0; i < cnt; i++)\n\n\t{\n\n\t\tmodified = true;\n\n\t\tMediaItem* CurItem = GetSelectedMediaItem(0, i);\n\n\t\tdouble LeftEdge = *(double*)GetSetMediaItemInfo(CurItem, \"D_POSITION\", NULL);\n\n\t\tdouble NewLength = dRightEdge - LeftEdge;\n\n\t\tGetSetMediaItemInfo(CurItem, \"D_LENGTH\", &NewLength);\n\n\t}\n\n\tif (modified)\n\n\t{\n\n\t\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS, -1);\n\n\t\tUpdateTimeline();\n\n\t}\n\n}\n\n\n\nvoid DoResetItemRateAndPitch(COMMAND_T* ct)\n\n{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 47, "score": 102170.16683657448 }, { "content": "\t\tcase WM_INITDIALOG:\n\n\t\t{\n\n\t\t\tchar TextBuf[32];\n\n\t\t\tsprintf(TextBuf,\"%.2f\", dTimeInterval);\n\n\t\t\tSetDlgItemText(hwnd, IDC_EDIT1, TextBuf);\n\n\n\n\t\t\tsprintf(TextBuf,\"%d\", iNumRepeats);\n\n\t\t\tSetDlgItemText(hwnd, IDC_NUMREPEDIT, TextBuf);\n\n\t\t\tInitFracBox(GetDlgItem(hwnd, IDC_NOTEVALUECOMBO), cBeatStr);\n\n\n\n\t\t\tSetFocus(GetDlgItem(hwnd, IDC_NUMREPEDIT));\n\n\t\t\tSendMessage(GetDlgItem(hwnd, IDC_NUMREPEDIT), EM_SETSEL, 0, -1);\n\n\n\n\t\t\tswitch (iRepeatMode)\n\n\t\t\t{\n\n\t\t\t\tcase 0: CheckDlgButton(hwnd, IDC_RADIO1, BST_CHECKED); break;\n\n\t\t\t\tcase 1: CheckDlgButton(hwnd, IDC_RADIO2, BST_CHECKED); break;\n\n\t\t\t\tcase 2: CheckDlgButton(hwnd, IDC_RADIO3, BST_CHECKED); break;\n\n\t\t\t}\n\n\t\t\tbreak;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 48, "score": 102169.87190036644 }, { "content": "void DoOpenAssociatedRPP(COMMAND_T*)\n\n{\n\n\tWDL_PtrList<MediaItem_Take> *TheTakes=new (WDL_PtrList<MediaItem_Take>);\n\n\tPCM_source *ThePCMSource;\n\n\tMediaItem_Take* CurTake;\n\n\tint NumActiveTakes=GetActiveTakes(TheTakes);\n\n\tif (NumActiveTakes==1)\n\n\t{\n\n\t\tCurTake=TheTakes->Get(0); // we will only support first selected item for now\n\n\t\tThePCMSource=(PCM_source*)GetSetMediaItemTakeInfo(CurTake,\"P_SOURCE\",NULL);\n\n\n\n\t\tif (ThePCMSource && ThePCMSource->GetFileName())\n\n\t\t{\n\n\t\t\tchar RPPFileNameBuf[1024];\n\n\t\t\tsprintf(RPPFileNameBuf,\"%s\\\\reaper.exe \\\"%s.RPP\\\"\",GetExePath(), ThePCMSource->GetFileName());\n\n\t\t\tif (!DoLaunchExternalTool(RPPFileNameBuf))\n\n\t\t\t\tMessageBox(g_hwndParent, __LOCALIZE(\"Could not launch REAPER!\",\"sws_mbox\"), __LOCALIZE(\"Xenakios - Error\",\"sws_mbox\"), MB_OK);\n\n\t\t}\n\n\t}\n\n\telse\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 49, "score": 102169.67243203406 }, { "content": "\t\t\tGetSetMediaItemInfo(GetTrackMediaItem(tr, j), \"B_UISEL\", &g_bTrue);\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateArrange();\n\n\tUndo_OnStateChangeEx2(NULL, SWS_CMD_SHORTNAME(_ct), UNDO_STATE_ALL, -1);\n\n}\n\n\n\nvoid DoSetAllTakesPlay()\n\n{\n\n\tWDL_TypedBuf<MediaItem*> items;\n\n\tSWS_GetSelectedMediaItems(&items);\n\n\tfor (int i = 0; i < items.GetSize(); i++)\n\n\t\tGetSetMediaItemInfo(items.Get()[i], \"B_ALLTAKESPLAY\", &g_bTrue);\n\n}\n\n\n\n\n\nvoid DoPanTakesOfItemSymmetrically()\n\n{\n\n\tWDL_TypedBuf<MediaItem*> items;\n\n\tSWS_GetSelectedMediaItems(&items);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 50, "score": 102169.64056276287 }, { "content": "\t\t\telse if (bSel)\n\n\t\t\t\tGetSetMediaItemInfo(mi, \"B_UISEL\", &g_bTrue);\n\n\t\t}\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateArrange();\n\n}\n\n\n\nvoid DoSelItemsToStartOfTrack(COMMAND_T* _ct)\n\n{\n\n\tPreventUIRefresh(1);\n\n\tfor (int i = 0; i < GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i+1, false);\n\n\t\tint iLastSelItem = -1;\n\n\t\tfor (int j = 0; j < GetTrackNumMediaItems(tr); j++)\n\n\t\t\tif (*(bool*)GetSetMediaItemInfo(GetTrackMediaItem(tr, j), \"B_UISEL\", NULL))\n\n\t\t\t\tiLastSelItem = j;\n\n\n\n\t\tfor (int j = 0; j < iLastSelItem; j++)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 51, "score": 102168.42137476616 }, { "content": " {\n\n\t\tcase WM_INITDIALOG:\n\n\t\t{\n\n\t\t\tif (!g_ReposItemsParams.bEnd)\n\n\t\t\t\tCheckDlgButton(hwnd, IDC_RADIO1, BST_CHECKED);\n\n\t\t\telse\n\n\t\t\t\tCheckDlgButton(hwnd, IDC_RADIO2, BST_CHECKED);\n\n\t\t\tchar TextBuf[32];\n\n\n\n\t\t\tsprintf(TextBuf, \"%.2f\", g_ReposItemsParams.Gap);\n\n\t\t\tSetDlgItemText(hwnd, IDC_EDIT1, TextBuf);\n\n\t\t\tSetFocus(GetDlgItem(hwnd, IDC_EDIT1));\n\n\t\t\tSendMessage(GetDlgItem(hwnd, IDC_EDIT1), EM_SETSEL, 0, -1);\n\n\t\t\tbreak;\n\n\t\t}\n\n case WM_COMMAND:\n\n switch(LOWORD(wParam))\n\n {\n\n case IDOK:\n\n\t\t\t\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 52, "score": 102168.2007739127 }, { "content": "\t\t\t\t\tchar textbuf[30];\n\n\t\t\t\t\tGetDlgItemText(hwnd, IDC_EDIT1, textbuf, 30);\n\n\t\t\t\t\tdouble theGap = atof(textbuf);\n\n\t\t\t\t\tbool bEnd = IsDlgButtonChecked(hwnd, IDC_RADIO2) == BST_CHECKED;\n\n\t\t\t\t\tRepositionItems(theGap, bEnd);\n\n\t\t\t\t\tUpdateTimeline();\n\n\t\t\t\t\tUndo_OnStateChangeEx(__LOCALIZE(\"Reposition items\", \"sws_undo\"), UNDO_STATE_ITEMS, -1);\n\n\t\t\t\t\tg_ReposItemsParams.Gap = theGap;\n\n\t\t\t\t\tg_ReposItemsParams.bEnd = bEnd;\n\n\n\n\t\t\t\t\tEndDialog(hwnd, 0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tcase IDCANCEL:\n\n\t\t\t\t\tEndDialog(hwnd, 0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t}\n\n\treturn 0;\n\n}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 53, "score": 102167.92059782265 }, { "content": "\tMediaItem* CurItem;\n\n\n\n\tint numItems;;\n\n\n\n\tchar textbuf[100];\n\n\tint sz=0; int *fxtail = (int *)get_config_var(\"itemfxtail\",&sz);\n\n int OldTail=*fxtail;\n\n\tif (sz==sizeof(int) && fxtail)\n\n\t{\n\n\n\n\t\tint msTail=int(1000*TailLen);\n\n\t\t*fxtail=msTail;\n\n\t\tsprintf(textbuf,\"%d\",msTail);\n\n\t}\n\n\n\n\tbool ItemSelected=false;\n\n\tint i;\n\n\tint j;\n\n\tfor (i=0;i<GetNumTracks();i++)\n\n\t{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 54, "score": 102167.5896097665 }, { "content": "\tdouble dFade = 0.0;\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n\n\tfor (int i = 0; i < cnt; i++)\n\n\t{\n\n\t\tMediaItem* item = GetSelectedMediaItem(0, i);\n\n\t\tGetSetMediaItemInfo(item, \"D_FADEINLEN\", &dFade);\n\n\t\tGetSetMediaItemInfo(item, \"D_FADEOUTLEN\", &dFade);\n\n\t\tGetSetMediaItemInfo(item, \"D_FADEINLEN_AUTO\", &dFade);\n\n\t\tGetSetMediaItemInfo(item, \"D_FADEOUTLEN_AUTO\", &dFade);\n\n\t}\n\n\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS, -1);\n\n\tUpdateTimeline();\n\n}\n\n\n\n\n\nvoid DoTrimLeftEdgeToEditCursor(COMMAND_T* ct)\n\n{\n\n\tdouble NewLeftEdge = GetCursorPosition();\n\n\tbool modified = false;\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 55, "score": 102167.02521848204 }, { "content": "\tfor (int i = 0; i < cnt; i++)\n\n\t{\n\n\t\tMediaItem* CurItem = GetSelectedMediaItem(0, i);\n\n\t\tdouble OldLeftEdge = *(double*)GetSetMediaItemInfo(CurItem, \"D_POSITION\", NULL);\n\n\t\tdouble OldLength = *(double*)GetSetMediaItemInfo(CurItem, \"D_LENGTH\", NULL);\n\n\t\t/* nothing to do if edit cursor is past item right edge */\n\n\t\tif(NewLeftEdge > OldLength + OldLeftEdge)\n\n\t\t\tcontinue;\n\n\t\tmodified = true;\n\n\t\tdouble NewLength = OldLength + (OldLeftEdge - NewLeftEdge);\n\n\t\tfor (int k = 0; k < GetMediaItemNumTakes(CurItem); k++)\n\n\t\t{\n\n\t\t\tMediaItem_Take* CurTake = GetMediaItemTake(CurItem, k);\n\n\t\t\tif (CurTake)\n\n\t\t\t{\n\n\t\t\t\tdouble OldMediaOffset = *(double*)GetSetMediaItemTakeInfo(CurTake, \"D_STARTOFFS\", NULL);\n\n\t\t\t\tdouble playRate = *(double*)GetSetMediaItemTakeInfo(CurTake, \"D_PLAYRATE\", NULL);\n\n\t\t\t\t/* media offsets needs to be scaled by playRate */\n\n\t\t\t\tdouble NewMediaOffset = (OldMediaOffset / playRate - (OldLeftEdge - NewLeftEdge)) * playRate;\n\n\t\t\t\tif(NewMediaOffset < 0) {\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 56, "score": 102166.56801742758 }, { "content": "\t\t\t{\n\n\t\t\t\tMediaItem* CurItem = GetTrackMediaItem(MunRaita,j);\n\n\n\n\t\t\t\tif ((ItemCounter % Step) == ItemOffset)\n\n\t\t\t\t\tGetSetMediaItemInfo(CurItem,\"B_UISEL\",&g_bTrue);\n\n\t\t\t\telse\n\n\t\t\t\t\tGetSetMediaItemInfo(CurItem,\"B_UISEL\",&g_bFalse);\n\n\n\n\t\t\t\tItemCounter++;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateArrange();\n\n}\n\n\n\nvoid DoSelectSkipSelectOnSelectedItems(int Step,int ItemOffset)\n\n{\n\n\tMediaTrack* MunRaita;\n\n\tMediaItem* CurItem;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 57, "score": 102164.82585385014 }, { "content": "\t\t\t\t\tchar textbuf[100];\n\n\t\t\t\t\tGetDlgItemText(hwnd,IDC_EDIT1,textbuf,100);\n\n\t\t\t\t\tg_lastTailLen=atof(textbuf);\n\n\t\t\t\t\tDoWorkForRenderItemsWithTail(g_lastTailLen);\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tcase IDCANCEL:\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t}\n\n\treturn 0;\n\n}\n\n\n\nvoid DoRenderItemsWithTail(COMMAND_T*)\n\n{\n\n\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_RENDITEMS), g_hwndParent, RenderItemsWithTailDlgProc);\n\n}\n\n\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 58, "score": 102164.07005016427 }, { "content": "\tdelete TheTakes;\n\n}\n\n\n\n\n\nvoid DoSetVolPan(double Vol, double Pan, bool SetVol, bool SetPan)\n\n{\n\n\tvector<MediaItem_Take*> TheTakes;\n\n\tXenGetProjectTakes(TheTakes,true,true);\n\n\tdouble NewVol=Vol;\n\n\tdouble NewPan=Pan;\n\n\tfor (int i=0;i<(int)TheTakes.size();i++)\n\n\t{\n\n\t\tif (SetVol) GetSetMediaItemTakeInfo(TheTakes[i],\"D_VOL\",&NewVol);\n\n\t\tif (SetPan) GetSetMediaItemTakeInfo(TheTakes[i],\"D_PAN\",&NewPan);\n\n\n\n\t}\n\n\tUndo_OnStateChangeEx(__LOCALIZE(\"Set take vol/pan\",\"sws_undo\"),UNDO_STATE_ITEMS,-1);\n\n\tUpdateTimeline();\n\n}\n\n\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 59, "score": 102163.89919023632 }, { "content": "\t\tdouble NewPos = CurPos - dItemLen;\n\n\t\tGetSetMediaItemInfo(VecItems[i], \"D_POSITION\", &NewPos);\n\n\t}\n\n\tUpdateTimeline();\n\n\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS, -1);\n\n}\n\n\n\nvoid DoToggleTakesNormalize(COMMAND_T* ct)\n\n{\n\n\tWDL_PtrList<MediaItem_Take> *TheTakes=new (WDL_PtrList<MediaItem_Take>);\n\n\tint NumActiveTakes=GetActiveTakes(TheTakes);\n\n\tint NumNormalizedTakes=0;\n\n\tfor (int i=0;i<NumActiveTakes;i++)\n\n\t{\n\n\t\tif (TheTakes->Get(i))\n\n\t\t{\n\n\t\t\tdouble TakeVol=*(double*)GetSetMediaItemTakeInfo(TheTakes->Get(i),\"D_VOL\",NULL);\n\n\t\t\tif (TakeVol!=1.0) NumNormalizedTakes++;\n\n\t\t}\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 60, "score": 102163.64490204613 }, { "content": "\tif (ItemsInTimeSel.size()==0)\n\n\t{\n\n\t\tMain_OnCommand(40006,0);\n\n\t}\n\n}\n\n\n\nvoid DoDeleteMutedItems(COMMAND_T* ct)\n\n{\n\n\tUndo_BeginBlock();\n\n\tvector<MediaItem*> pitems;\n\n\tXenGetProjectItems(pitems,false,true);\n\n\tint i;\n\n\tfor (i=0;i<(int)pitems.size();i++)\n\n\t{\n\n\t\tbool muted=*(bool*)GetSetMediaItemInfo(pitems[i],\"B_MUTE\",0);\n\n\t\tif (muted)\n\n\t\t\tDeleteTrackMediaItem (GetMediaItem_Track(pitems[i]), pitems[i]);\n\n\t}\n\n\tUndo_EndBlock(SWS_CMD_SHORTNAME(ct),UNDO_STATE_ITEMS);\n\n\tUpdateTimeline();\n\n}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 61, "score": 102163.38630770317 }, { "content": "\n\n\t\t\tstatic int prevId = id;\n\n\t\t\tint newId = prevId;\n\n\t\t\tif (takeCount != 1)\n\n\t\t\t{\n\n\t\t\t\twhile (newId == prevId)\n\n\t\t\t\t\tnewId = g_MTRand.randInt(takeCount);\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t\tnewId = g_MTRand.randInt(takeCount);\n\n\n\n\t\t\tprevId = newId;\n\n\n\n\t\t\tGetSetMediaItemInfo(item,\"I_CURTAKE\",&newId);\n\n\t\t}\n\n\t}\n\n\tUpdateArrange();\n\n\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct),UNDO_STATE_ITEMS,-1);\n\n}\n\n\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 62, "score": 102163.30652451659 }, { "content": "\tif (NumNormalizedTakes>0)\n\n\t{\n\n\t\tfor (int i=0;i<NumActiveTakes;i++)\n\n\t\t{\n\n\t\t\tif (TheTakes->Get(i))\n\n\t\t\t{\n\n\t\t\t\tdouble TheGain=1.0;\n\n\t\t\t\tGetSetMediaItemTakeInfo(TheTakes->Get(i),\"D_VOL\",&TheGain);\n\n\t\t\t}\n\n\t\t}\n\n\t\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct),UNDO_STATE_ITEMS,-1);\n\n\t\tUpdateTimeline();\n\n\t}\n\n\telse\n\n\t{\n\n\t\tUndo_BeginBlock2(NULL);\n\n\t\tMain_OnCommand(40108, 0); // normalize items\n\n\t\tUndo_EndBlock2(NULL, SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS | UNDO_STATE_TRACKCFG | UNDO_STATE_MISCCFG);\n\n\t\tUpdateTimeline();\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 63, "score": 102162.9427213069 }, { "content": "\t\tCheckTable[i]=0;\n\n\t\tIntTable[i]=0;\n\n\t}\n\n\n\n\tfor (i=0;i<numItems;i++)\n\n\t{\n\n\t\tGoodFound=FALSE;\n\n\t\twhile (!GoodFound)\n\n\t\t{\n\n\t\t\trndInt=rand() % numItems;\n\n\t\t\tif ((CheckTable[rndInt]==0) && (rndInt!=badFirstNumber) && (i==0))\n\n\t\t\t\tGoodFound=TRUE;\n\n\t\t\tif ((CheckTable[rndInt]==0) && (i>0))\n\n\t\t\t\tGoodFound=TRUE;\n\n\n\n\t\t\tIterCount++;\n\n\t\t\tif (IterCount>1000000)\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\tif (GoodFound)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 64, "score": 102162.27384832685 }, { "content": "void DoMoveItemsToEditCursor(COMMAND_T* ct)\n\n{\n\n\tdouble EditCurPos=GetCursorPosition();\n\n\tconst int cnt=CountSelectedMediaItems(NULL);\n\n\tfor (int i = 0; i < cnt; i++)\n\n\t{\n\n\t\tMediaItem* CurItem = GetSelectedMediaItem(0, i);\n\n\t\tdouble SnapOffset = *(double*)GetSetMediaItemInfo(CurItem, \"D_SNAPOFFSET\", NULL);\n\n\t\tdouble NewPos = EditCurPos - SnapOffset;\n\n\t\tGetSetMediaItemInfo(CurItem, \"D_POSITION\", &NewPos);\n\n\t}\n\n\tif (cnt)\n\n\t{\n\n\t\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS, -1);\n\n\t\tUpdateTimeline();\n\n\t}\n\n}\n\n\n\nvoid DoRemoveItemFades(COMMAND_T* ct)\n\n{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 65, "score": 102162.22293859615 }, { "content": "\tint i;\n\n\tfor (i=0;i<(int)TheItems.size();i++)\n\n\t{\n\n\t\tdouble itemPos=*(double*)GetSetMediaItemInfo(TheItems[i],\"D_POSITION\",NULL);\n\n\t\tOldItemPositions.push_back(itemPos);\n\n\t\tdouble dItemLen=*(double*)GetSetMediaItemInfo(TheItems[i],\"D_LENGTH\",NULL);\n\n\t\tOlddItemLens.push_back(dItemLen);\n\n\t}\n\n\t//Main_OnCommand(40289,0); // unselect all\n\n\tUndo_BeginBlock();\n\n\tMain_OnCommand(40543,0); // implode selected items to item\n\n\tMain_OnCommand(40698,0); // copy item\n\n\tvector<MediaItem*> PastedItems;\n\n\tvector<MediaItem*> TempItem; // oh fuck what shit this is\n\n\tfor (i=1;i<(int)OldItemPositions.size();i++)\n\n\t{\n\n\t\tSetEditCurPos(OldItemPositions[i],false,false);\n\n\t\tMain_OnCommand(40058,0);\n\n\t\tXenGetProjectItems(TempItem,true,false); // basically a way to get the first selected item, messsyyyyy\n\n\t\tdouble newdItemLen=OlddItemLens[i];\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 66, "score": 102162.15726518686 }, { "content": "\t\t\t\t\tif (strcmp(tbuf,\"\")!=0)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tWillSetVolume=true;\n\n\t\t\t\t\t\tNewVol=atof(tbuf);\n\n\t\t\t\t\t\tif (NewVol>-144.0)\n\n\t\t\t\t\t\t\tNewVol=exp(NewVol*0.115129254);\n\n\t\t\t\t\t\telse NewVol=0.0;\n\n\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (WillSetVolume)\n\n\t\t\t\t\t\tDoSetItemVols(NewVol);\n\n\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tcase IDCANCEL:\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 67, "score": 102162.10851403071 }, { "content": "\t\t\t\tif (*(bool*)GetSetMediaItemInfo(items[j], \"B_UISEL\", NULL))\n\n\t\t\t\t{\n\n\t\t\t\t\tfound = true;\n\n\t\t\t\t\tInsertTrackAtIndex(id,true); ++id;\n\n\t\t\t\t\tMoveMediaItemToTrack(items[j], CSurf_TrackFromID(id, false));\n\n\t\t\t\t\t++i; // needed for the first FOR loop since new tracks are getting added\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif (found && depth != 1) // make children out of newly created tracks\n\n\t\t\t{\n\n\t\t\t\tdepth -= 1;\n\n\t\t\t\tGetSetMediaTrackInfo(CSurf_TrackFromID(id, false),\"I_FOLDERDEPTH\",&depth);\n\n\t\t\t\tdepth = 1;\n\n\t\t\t\tGetSetMediaTrackInfo(track,\"I_FOLDERDEPTH\",&depth);\n\n\t\t\t}\n\n\t\t}\n\n\t\tTrackList_AdjustWindows(false);\n\n\t\tUpdateArrange();\n\n\t\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct),UNDO_STATE_ALL,-1);\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 68, "score": 102160.95292774474 }, { "content": "\t\t\t\t\t\tdBeatInterval = parseFrac(cBeatStr);\n\n\t\t\t\t\t\tPasteMultipletimes(iNumRepeats, dBeatInterval, iRepeatMode);\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse if (iRepeatMode == 1)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tGetDlgItemText(hwnd, IDC_EDIT1, str, 100);\n\n\t\t\t\t\t\tdTimeInterval = atof(str);\n\n\t\t\t\t\t\tPasteMultipletimes(iNumRepeats, dTimeInterval, iRepeatMode);\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse if (iRepeatMode == 0)\n\n\t\t\t\t\t\tPasteMultipletimes(iNumRepeats, 1.0, iRepeatMode);\n\n\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tcase IDCANCEL:\n\n\t\t\t\t\tEndDialog(hwnd,0);\n\n\t\t\t\t\tbreak;\n\n\t\t}\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 69, "score": 102160.94501781458 }, { "content": "\tfor (int i = 0; i < items.GetSize(); i++)\n\n\t{\n\n\t\tint iTakes = GetMediaItemNumTakes(items.Get()[i]);\n\n\t\tfor (int j = 0; j < iTakes; j++)\n\n\t\t{\n\n\t\t\tMediaItem_Take* take = GetMediaItemTake(items.Get()[i], j);\n\n\t\t\tif (take)\n\n\t\t\t{\n\n\t\t\t\tdouble dNewPan= -1.0 + ((2.0 / (iTakes - 1)) * j);\n\n\t\t\t\tGetSetMediaItemTakeInfo(take, \"D_PAN\", &dNewPan);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid DoPanTakesSymmetricallyWithUndo(COMMAND_T* ct)\n\n{\n\n\tDoPanTakesOfItemSymmetrically();\n\n\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct),4,-1);\n\n\tUpdateTimeline();\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 70, "score": 102160.88368222846 }, { "content": "\t\t{\n\n\t\t\tMain_OnCommand(40440,0); // Selected Media Offline\n\n\t\t\tfor (i=0;i<NumActiveTakes;i++)\n\n\t\t\t{\n\n\t\t\t\tCurTake=TheTakes->Get(i);\n\n\t\t\t\tThePCMSource=(PCM_source*)GetSetMediaItemTakeInfo(CurTake,\"P_SOURCE\",NULL);\n\n\t\t\t\tif (ThePCMSource)\n\n\t\t\t\t{\n\n\t\t\t\t\tif (strcmp(ThePCMSource->GetType(), \"SECTION\") != 0)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tPCM_source *NewPCMSource = PCM_Source_CreateFromFile(cFileName);\n\n\t\t\t\t\t\tif (NewPCMSource!=0)\n\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tGetSetMediaItemTakeInfo(CurTake,\"P_SOURCE\",NewPCMSource);\n\n\t\t\t\t\t\t\tdelete ThePCMSource;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tPCM_source *TheOtherPCM=ThePCMSource->GetSource();\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 71, "score": 102160.29561874803 }, { "content": "\tDialogBox(g_hInst, MAKEINTRESOURCE(IDD_SWINGITEMPOS), g_hwndParent, SwingItemsDlgProc);\n\n}\n\n\n\nvoid DoTimeSelAdaptDelete(COMMAND_T*)\n\n{\n\n\tvector<MediaItem*> SelItems;\n\n\tvector<MediaItem*> ItemsInTimeSel;\n\n\tXenGetProjectItems(SelItems,true,true);\n\n\tdouble OldTimeSelLeft=0.0;\n\n\tdouble OldTimeSelRight=0.0;\n\n\tGetSet_LoopTimeRange(false,false,&OldTimeSelLeft,&OldTimeSelRight,false);\n\n\tint i;\n\n\tif (OldTimeSelRight-OldTimeSelLeft>0.0)\n\n\t{\n\n\t\tfor (i=0;i<(int)SelItems.size();i++)\n\n\t\t{\n\n\t\t\tdouble itempos=*(double*)GetSetMediaItemInfo(SelItems[i],\"D_POSITION\",0);\n\n\t\t\tdouble dItemLen=*(double*)GetSetMediaItemInfo(SelItems[i],\"D_LENGTH\",0);\n\n\t\t\tbool itemsel=*(bool*)GetSetMediaItemInfo(SelItems[i],\"B_UISEL\",0);\n\n\t\t\tif (itemsel)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 72, "score": 102159.50478480489 }, { "content": "}\n\n\n\n\n\nvoid DoImplodeTakesSetPlaySetSymPans(COMMAND_T* ct)\n\n{\n\n\tUndo_BeginBlock();\n\n\tMain_OnCommand(40438,0); // implode items across tracks into takes\n\n\tDoSetAllTakesPlay();\n\n\tDoPanTakesOfItemSymmetrically();\n\n\tUndo_EndBlock(SWS_CMD_SHORTNAME(ct),0);\n\n\t//UpdateTimeline();\n\n}\n\n\n\ndouble g_lastTailLen;\n\n\n\nvoid DoWorkForRenderItemsWithTail(double TailLen)\n\n{\n\n\t// Unselect all tracks\n\n\n\n\tMediaTrack* MunRaita;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 73, "score": 102159.40606773534 }, { "content": "\tif (Message==WM_COMMAND && LOWORD(wParam)==IDOK)\n\n\t{\n\n\t\tGetDlgItemText(hwnd,IDC_EDIT1,tbuf,199);\n\n\t\tg_swingAmt=atof(tbuf)/100.0;\n\n\t\tif (g_swingAmt<-0.95) g_swingAmt=-0.95; // come on let's be sensible, why anyone would swing more, or even close to this!\n\n\t\tif (g_swingAmt>0.95) g_swingAmt=0.95;\n\n\t\tPerformSwingItemPositions(g_swingBase,g_swingAmt);\n\n\t\tEndDialog(hwnd,0);\n\n\t\treturn 0;\n\n\t}\n\n\tif (Message==WM_COMMAND && LOWORD(wParam)==IDCANCEL)\n\n\t{\n\n\t\tEndDialog(hwnd,0);\n\n\t\treturn 0;\n\n\t}\n\n\treturn 0;\n\n}\n\n\n\nvoid DoSwingItemPositions(COMMAND_T*)\n\n{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 74, "score": 102158.24382123738 }, { "content": "\t\t}\n\n\t\tcase WM_COMMAND:\n\n switch(LOWORD(wParam))\n\n {\n\n\t\t\t\tcase IDOK:\n\n\t\t\t\t{\n\n\t\t\t\t\tchar str[100];\n\n\t\t\t\t\tGetDlgItemText(hwnd, IDC_NUMREPEDIT, str, 100);\n\n\t\t\t\t\tiNumRepeats = atoi(str);\n\n\n\n\t\t\t\t\tif (IsDlgButtonChecked(hwnd, IDC_RADIO1) == BST_CHECKED)\n\n\t\t\t\t\t\tiRepeatMode = 0;\n\n\t\t\t\t\telse if (IsDlgButtonChecked(hwnd, IDC_RADIO2) == BST_CHECKED)\n\n\t\t\t\t\t\tiRepeatMode = 1;\n\n\t\t\t\t\telse if (IsDlgButtonChecked(hwnd, IDC_RADIO3) == BST_CHECKED)\n\n\t\t\t\t\t\tiRepeatMode = 2;\n\n\n\n\t\t\t\t\tif (iRepeatMode == 2)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tGetDlgItemText(hwnd, IDC_NOTEVALUECOMBO, cBeatStr, 100);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 75, "score": 102157.94623035275 }, { "content": "/******************************************************************************\n\n/ ItemTakeCommands.cpp\n\n/\n\n/ Copyright (c) 2009 Tim Payne (SWS), original code by Xenakios\n\n/\n\n/\n\n/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\n/ of this software and associated documentation files (the \"Software\"), to deal\n\n/ in the Software without restriction, including without limitation the rights to\n\n/ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n\n/ of the Software, and to permit persons to whom the Software is furnished to\n\n/ do so, subject to the following conditions:\n\n/\n\n/ The above copyright notice and this permission notice shall be included in all\n\n/ copies or substantial portions of the Software.\n\n/\n\n/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\n/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\n/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\n/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 76, "score": 102157.43914220379 }, { "content": "\t\t\tcase 1: // Time interval\n\n\t\t\t\tfor (int i = 0; i < NumPastes; i++)\n\n\t\t\t\t{\n\n\t\t\t\t\tMain_OnCommand(40058,0); // Paste\n\n\t\t\t\t\tSetEditCurPos(dStartTime + (i+1) * TimeIntervalQN, false, false);\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase 2: // Beat interval\n\n\t\t\t{\n\n\t\t\t\tdouble dStartBeat = TimeMap_timeToQN(dStartTime);\n\n\t\t\t\tfor (int i = 0; i < NumPastes; i++)\n\n\t\t\t\t{\n\n\t\t\t\t\tMain_OnCommand(40058,0); // Paste\n\n\t\t\t\t\tSetEditCurPos(TimeMap_QNToTime(dStartBeat + (i+1) * TimeIntervalQN), false, false);\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (*pCursorMode & 8) // If \"don't move cursor after paste\" move the cursor back\n\n\t\t\tSetEditCurPos(dStartTime, false, false);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 77, "score": 102155.77381227697 }, { "content": "\tif (NumPastes > 0)\n\n\t{\n\n\t\tint* pCursorMode = (int*)GetConfigVar(\"itemclickmovecurs\");\n\n\t\tdouble dStartTime = GetCursorPosition();\n\n\n\n\t\tUndo_BeginBlock();\n\n\n\n\t\tswitch (RepeatMode)\n\n\t\t{\n\n\t\t\tcase 0: // No gaps\n\n\t\t\t{\n\n\t\t\t\t// Cursor mode must set to move the cursor after paste\n\n\t\t\t\t// Clear bit 8 of itemclickmovecurs\n\n\t\t\t\tint savedMode = *pCursorMode;\n\n\t\t\t\t*pCursorMode &= ~8;\n\n\t\t\t\tfor (int i = 0; i < NumPastes; i++)\n\n\t\t\t\t\tMain_OnCommand(40058,0); // Paste\n\n\t\t\t\t*pCursorMode = savedMode; // Restore the cursor mode\n\n\t\t\t\tbreak;\n\n\t\t\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 78, "score": 102154.96682295631 }, { "content": "}\n\n\n\nbool DoLaunchExternalTool(const char *ExeFilename)\n\n{\n\n\tif (!ExeFilename)\n\n\t\treturn false;\n\n\n\n#ifdef _WIN32\n\n\tSTARTUPINFO si = { sizeof(si) };\n\n\tPROCESS_INFORMATION pi;\n\n\tchar* cFile = _strdup(ExeFilename);\n\n\tbool bRet = CreateProcess(0, cFile, 0, 0, FALSE, 0, 0, 0, &si, &pi) ? true : false;\n\n\tfree(cFile);\n\n\treturn bRet;\n\n#else\n\n\tMessageBox(g_hwndParent, __LOCALIZE(\"Not supported on OSX, sorry!\", \"sws_mbox\"), __LOCALIZE(\"SWS - Error\", \"sws_mbox\"), MB_OK);\n\n\treturn false;\n\n#endif\n\n}\n\n\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 79, "score": 102154.26299961067 }, { "content": "\t\t\t\t{\n\n\t\t\t\t\tif ((ItemCounter % Step)==ItemOffset)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tNewSelectedStatus=TRUE;\n\n\t\t\t\t\t\tGetSetMediaItemInfo(CurItem,\"B_UISEL\",&NewSelectedStatus);\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tNewSelectedStatus=FALSE;\n\n\t\t\t\t\t\tGetSetMediaItemInfo(CurItem,\"B_UISEL\",&NewSelectedStatus);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tItemCounter++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateArrange();\n\n}\n\n\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 80, "score": 102154.13670885455 }, { "content": "\t\t\t\t\t\tif (TheOtherPCM!=0)\n\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tPCM_source *NewPCMSource=PCM_Source_CreateFromFile(cFileName);\n\n\t\t\t\t\t\t\tif (NewPCMSource)\n\n\t\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\tThePCMSource->SetSource(NewPCMSource);\n\n\t\t\t\t\t\t\t\tdelete TheOtherPCM;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfree(cFileName);\n\n\t\t\tMain_OnCommand(40047,0); // Build any missing peaks\n\n\t\t\tMain_OnCommand(40439,0); // Selected Media Online\n\n\t\t\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct),UNDO_STATE_ITEMS,-1);\n\n\t\t\tUpdateTimeline();\n\n\t\t}\n\n\t}\n\n\tdelete TheTakes;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 81, "score": 102152.97931848792 }, { "content": "\t// too bad this doesn't work so well\n\n\t// maybe someone could make it work :)\n\n\tvector<MediaItem*> TheItems;\n\n\tXenGetProjectItems(TheItems,true,false);\n\n\tint i;\n\n\t//double temvo=TimeMap_GetDividedBpmAtTime(0.0);\n\n\tfor (i=0;i<(int)TheItems.size();i++)\n\n\t{\n\n\t\tdouble itempos=*(double*)GetSetMediaItemInfo(TheItems[i],\"D_POSITION\",0);\n\n\t\tdouble itemposQN=TimeMap_timeToQN(itempos);\n\n\t\tint itemposSXTHN=(int)((itemposQN*4.0)+0.5);\n\n\t\t//double itemposinsixteenths=itemposQN*4.0;\n\n\t\tint oddOreven=itemposSXTHN % 2;\n\n\t\tdouble yay=fabs(swingAmt);\n\n\t\tdouble newitemposQN=itemposQN;\n\n\t\tif (swingAmt>0)\n\n\t\t\tnewitemposQN=itemposQN+(1.0/4.0*yay); // to right\n\n\t\tif (swingAmt<0)\n\n\t\t\tnewitemposQN=itemposQN-(1.0/4.0*yay); // to left\n\n\t\titempos=TimeMap_QNToTime(newitemposQN);\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 82, "score": 102152.6876531907 }, { "content": "\t\t\t\t\tdouble shiftAmount = -NewMediaOffset / playRate;\n\n\t\t\t\t\tNewLeftEdge += shiftAmount;\n\n\t\t\t\t\tNewLength -= shiftAmount;\n\n\t\t\t\t\tNewMediaOffset = 0.0f;\n\n\t\t\t\t}\n\n\t\t\t\tGetSetMediaItemTakeInfo(CurTake,\"D_STARTOFFS\",&NewMediaOffset);\n\n\t\t\t}\n\n\t\t}\n\n\t\tGetSetMediaItemInfo(CurItem, \"D_POSITION\", &NewLeftEdge);\n\n\t\tGetSetMediaItemInfo(CurItem, \"D_LENGTH\", &NewLength);\n\n\t}\n\n\tif (modified)\n\n\t{\n\n\t\tUndo_OnStateChangeEx(SWS_CMD_SHORTNAME(ct), UNDO_STATE_ITEMS, -1);\n\n\t\tUpdateTimeline();\n\n\t}\n\n}\n\n\n\nvoid DoTrimRightEdgeToEditCursor(COMMAND_T* ct)\n\n{\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 83, "score": 102151.82879731129 }, { "content": "\t\t\t{\n\n\t\t\t\tint intersectmatches=0;\n\n\t\t\t\tif (OldTimeSelLeft>=itempos && OldTimeSelRight<=itempos+dItemLen)\n\n\t\t\t\t\tintersectmatches++;\n\n\t\t\t\tif (itempos>=OldTimeSelLeft && itempos+dItemLen<=OldTimeSelRight)\n\n\t\t\t\t\tintersectmatches++;\n\n\t\t\t\tif (OldTimeSelLeft<=itempos+dItemLen && OldTimeSelRight>=itempos+dItemLen)\n\n\t\t\t\t\tintersectmatches++;\n\n\t\t\t\tif (OldTimeSelRight>=itempos && OldTimeSelLeft<itempos)\n\n\t\t\t\t\tintersectmatches++;\n\n\t\t\t\tif (intersectmatches>0)\n\n\t\t\t\t\tItemsInTimeSel.push_back(SelItems[i]);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t// 40312\n\n\tif (ItemsInTimeSel.size()>0)\n\n\t{\n\n\t\tMain_OnCommand(40312,0);\n\n\t}\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 84, "score": 102150.56675596334 }, { "content": "\t\tGetSetMediaItemInfo(TempItem[0],\"D_LENGTH\",&newdItemLen);\n\n\t\t//PastedItems.push_back(TempItem[0]);\n\n\t}\n\n\t/*\n\n\tfor (i=0;i<PastedItems.size();i++)\n\n\t{\n\n\t\tdouble newdItemLen=OlddItemLens[i+1];\n\n\t\tGetSetMediaItemInfo(PastedItems[i],\"D_LENGTH\",&newdItemLen);\n\n\t}\n\n\t*/\n\n\t//40058 // paste\n\n\tUndo_EndBlock(SWS_CMD_SHORTNAME(ct),0);\n\n}\n\n\n\ndouble g_swingBase=1.0/4.0;\n\ndouble g_swingAmt=0.2;\n\n\n\nvoid PerformSwingItemPositions(double swingBase,double swingAmt)\n\n{\n\n\t// 14th October 2009 (X)\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 85, "score": 102147.11370338373 }, { "content": "\t\t\tchar ExeString[2048];\n\n\t\t\tif (editorIdx==0 && g_external_app_paths.PathToAudioEditor1)\n\n\t\t\t\tsprintf(ExeString,\"\\\"%s\\\" \\\"%s\\\"\",g_external_app_paths.PathToAudioEditor1,ThePCM->GetFileName());\n\n\t\t\telse if (editorIdx==1 && g_external_app_paths.PathToAudioEditor2)\n\n\t\t\t\tsprintf(ExeString,\"\\\"%s\\\" \\\"%s\\\"\",g_external_app_paths.PathToAudioEditor2,ThePCM->GetFileName());\n\n\t\t\tDoLaunchExternalTool(ExeString);\n\n\t\t}\n\n\t}\n\n\treturn -666;\n\n}\n\n\n\nvoid DoOpenInExtEditor1(COMMAND_T*) { OpenInExtEditor(0); }\n\nvoid DoOpenInExtEditor2(COMMAND_T*) { OpenInExtEditor(1); }\n\n\n\nvoid DoMatrixItemImplode(COMMAND_T* ct)\n\n{\n\n\tvector<MediaItem*> TheItems;\n\n\tXenGetProjectItems(TheItems,true,false);\n\n\tvector<double> OldItemPositions;\n\n\tvector<double> OlddItemLens;\n", "file_path": "Xenakios/ItemTakeCommands.cpp", "rank": 86, "score": 102146.40559065592 }, { "content": "class RprItem;\n", "file_path": "Fingers/RprTake.h", "rank": 87, "score": 102139.3756436453 }, { "content": "class RprTake;\n", "file_path": "Fingers/RprItem.h", "rank": 88, "score": 102139.3756436453 }, { "content": "\tfor (int i = 0; i < GetTrackNumMediaItems(tr); i++)\n\n\t{\n\n\t\tMediaItem* mi = GetTrackMediaItem(tr, i);\n\n\t\tif (*(bool*)GetSetMediaItemInfo(mi, \"B_UISEL\", NULL))\n\n\t\t{\n\n\t\t\tint j;\n\n\t\t\tfor (j = 0; j < m_items.GetSize(); j++)\n\n\t\t\t\tif (mi == m_items.Get(j)->FindItem(tr))\n\n\t\t\t\t{\n\n\t\t\t\t\tItemState* is = m_items.Get(j);\n\n\t\t\t\t\tm_items.Set(j, new ItemState(mi));\n\n\t\t\t\t\tdelete is;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\tif (j == m_items.GetSize())\n\n\t\t\t\tm_items.Add(new ItemState(mi));\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 89, "score": 102030.05103545894 }, { "content": "\tif (mi == NULL)\n\n\t\treturn;\n\n\tGetSetMediaItemInfo(mi, \"B_UISEL\", &g_bTrue);\n\n}\n\n\n\n//*****************************************************\n\n// TrackState Class\n\nTrackState::TrackState(MediaTrack* tr, bool bSelOnly)\n\n{\t// Remember item states on this track\n\n\tm_guid = *(GUID*)GetSetMediaTrackInfo(tr, \"GUID\", NULL);\n\n\tm_bFIPM = *(bool*)GetSetMediaTrackInfo(tr, \"B_FREEMODE\", NULL);\n\n\tm_iColor = *(int*)GetSetMediaTrackInfo(tr, \"I_CUSTOMCOLOR\", NULL);\n\n\tfor (int i = 0; i < GetTrackNumMediaItems(tr); i++)\n\n\t{\n\n\t\tMediaItem* mi = GetTrackMediaItem(tr, i);\n\n\t\tif (!bSelOnly || *(bool*)GetSetMediaItemInfo(mi, \"B_UISEL\", NULL))\n\n\t\t\tm_items.Add(new ItemState(mi));\n\n\t}\n\n}\n\n\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 90, "score": 102029.80678163588 }, { "content": "\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i, false);\n\n\t\tif (*(int*)GetSetMediaTrackInfo(tr, \"I_SELECTED\", NULL))\n\n\t\t{\n\n\t\t\t// First see if this track is saved already\n\n\t\t\tint j;\n\n\t\t\tfor (j = 0; j < g_tracks.Get()->GetSize(); j++)\n\n\t\t\t\tif (TrackMatchesGuid(tr, &g_tracks.Get()->Get(j)->m_guid))\n\n\t\t\t\t{\n\n\t\t\t\t\tg_tracks.Get()->Get(j)->AddSelItems(tr);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\tif (j == g_tracks.Get()->GetSize())\n\n\t\t\t\tg_tracks.Get()->Add(new TrackState(tr, true));\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid RestoreSelOnTrack(COMMAND_T* _ct)\n\n{\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 91, "score": 102027.88614478485 }, { "content": "void SelItemsWithState(COMMAND_T* _ct)\n\n{\n\n\tPreventUIRefresh(1);\n\n\tfor (int i = 1; i <= GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i, false);\n\n\t\tif (*(int*)GetSetMediaTrackInfo(tr, \"I_SELECTED\", NULL))\n\n\t\t\t// Find the saved track\n\n\t\t\tfor (int j = 0; j < g_tracks.Get()->GetSize(); j++)\n\n\t\t\t\tif (TrackMatchesGuid(tr, &g_tracks.Get()->Get(j)->m_guid))\n\n\t\t\t\t\tg_tracks.Get()->Get(j)->SelectItems(tr);\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateArrange();\n\n\tUndo_OnStateChangeEx2(NULL, SWS_CMD_SHORTNAME(_ct), UNDO_STATE_ALL, -1);\n\n}\n\n\n\nvoid SaveSelOnTrack(COMMAND_T*)\n\n{\n\n\tfor (int i = 1; i <= GetNumTracks(); i++)\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 92, "score": 102027.43062689608 }, { "content": "ItemState::ItemState(MediaItem* mi)\n\n{\n\n\tm_guid = *(GUID*)GetSetMediaItemInfo(mi, \"GUID\", NULL);\n\n\tm_bMute = *(bool*)GetSetMediaItemInfo(mi, \"B_MUTE\", NULL);\n\n\tm_fFIPMy = *(float*)GetSetMediaItemInfo(mi, \"F_FREEMODE_Y\", NULL);\n\n\tm_fFIPMh = *(float*)GetSetMediaItemInfo(mi, \"F_FREEMODE_H\", NULL);\n\n\tm_bSel = *(bool*)GetSetMediaItemInfo(mi, \"B_UISEL\", NULL);\n\n\tm_iColor = *(int*)GetSetMediaItemInfo(mi, \"I_CUSTOMCOLOR\", NULL);\n\n\tm_dVol = *(double*)GetSetMediaItemInfo(mi, \"D_VOL\", NULL);\n\n\tm_dFadeIn = *(double*)GetSetMediaItemInfo(mi, \"D_FADEINLEN\", NULL);\n\n\tm_dFadeOut = *(double*)GetSetMediaItemInfo(mi, \"D_FADEOUTLEN\", NULL);\n\n}\n\n\n\nMediaItem* ItemState::FindItem(MediaTrack* tr)\n\n{\n\n\t// Find the media item in the track\n\n\tMediaItem* mi = NULL;\n\n\tfor (int i = 0; i < GetTrackNumMediaItems(tr); i++)\n\n\t{\n\n\t\tmi = GetTrackMediaItem(tr, i);\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 93, "score": 102026.80236704837 }, { "content": "\tfor (int i = 1; i <= GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i, false);\n\n\t\tif (*(int*)GetSetMediaTrackInfo(tr, \"I_SELECTED\", NULL))\n\n\t\t{\n\n\t\t\t// First see if this track is saved already\n\n\t\t\tint j;\n\n\t\t\tfor (j = 0; j < g_tracks.Get()->GetSize(); j++)\n\n\t\t\t{\n\n\t\t\t\tif (TrackMatchesGuid(tr, &g_tracks.Get()->Get(j)->m_guid))\n\n\t\t\t\t{\n\n\t\t\t\t\tTrackState* ts = g_tracks.Get()->Get(j);\n\n\t\t\t\t\tg_tracks.Get()->Set(j, new TrackState(tr, false));\n\n\t\t\t\t\tdelete ts;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif (j == g_tracks.Get()->GetSize())\n\n\t\t\t\tg_tracks.Get()->Add(new TrackState(tr, false));\n\n\t\t}\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 94, "score": 102023.9266534516 }, { "content": "\n\nchar* TrackState::ItemString(char* str, int maxLen)\n\n{\n\n\tchar guidStr[64];\n\n\tguidToString(&m_guid, guidStr);\n\n\t_snprintf(str, maxLen, \"<TRACKSTATE %s %d %d\", guidStr, m_bFIPM, m_iColor);\n\n\treturn str;\n\n}\n\n\n\nvoid TrackState::SelectItems(MediaTrack* tr)\n\n{\n\n\tUnselAllItems(tr);\n\n\tfor (int i = 0; i < m_items.GetSize(); i++)\n\n\t\tm_items.Get(i)->Select(tr);\n\n}\n\n\n\n//*****************************************************\n\n// Global Functions\n\nvoid SaveTrack(COMMAND_T*)\n\n{\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 95, "score": 102023.14979259756 }, { "content": "/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\n/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\n/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\n/ OTHER DEALINGS IN THE SOFTWARE.\n\n/\n\n******************************************************************************/\n\n\n\n\n\n#include \"stdafx.h\"\n\n#include \"TrackItemState.h\"\n\n\n\n//*****************************************************\n\n// Globals\n\nSWSProjConfig<WDL_PtrList_DOD<TrackState> > g_tracks;\n\n\n\n//*****************************************************\n\n// ItemState Class\n\nItemState::ItemState(LineParser* lp)\n\n{\n\n\tif (lp->getnumtokens() < 5)\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 96, "score": 102022.37382473922 }, { "content": "\t\tif (GuidsEqual(&m_guid, (GUID*)GetSetMediaItemInfo(mi, \"GUID\", NULL)))\n\n\t\t\treturn mi;\n\n\t}\n\n\treturn NULL;\n\n}\n\n\n\nvoid ItemState::Restore(MediaTrack* tr, bool bSelOnly)\n\n{\n\n\t// First gotta find the media item in the track\n\n\tMediaItem* mi = FindItem(tr);\n\n\tif (mi == NULL)\n\n\t\treturn;\n\n\tif (!bSelOnly || *(bool*)GetSetMediaItemInfo(mi, \"B_UISEL\", NULL))\n\n\t{\n\n\t\tGetSetMediaItemInfo(mi, \"B_MUTE\", &m_bMute);\n\n\t\tGetSetMediaItemInfo(mi, \"F_FREEMODE_Y\", &m_fFIPMy);\n\n\t\tGetSetMediaItemInfo(mi, \"F_FREEMODE_H\", &m_fFIPMh);\n\n\t\tif (!bSelOnly)\n\n\t\t\tGetSetMediaItemInfo(mi, \"B_UISEL\", &m_bSel);\n\n\t\tGetSetMediaItemInfo(mi, \"I_CUSTOMCOLOR\", &m_iColor);\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 97, "score": 102021.39288818784 }, { "content": "void TrackState::UnselAllItems(MediaTrack* tr)\n\n{\n\n\tfor (int i = 0; i < GetTrackNumMediaItems(tr); i++)\n\n\t\tGetSetMediaItemInfo(GetTrackMediaItem(tr, i), \"B_UISEL\", &g_bFalse);\n\n}\n\n\n\nvoid TrackState::Restore(MediaTrack* tr, bool bSelOnly)\n\n{\n\n\t// The level above Restore already knows the MediaTrack* so\n\n\t// pass it in, even though we can get it ourselves from the\n\n\t// GUID\n\n\tif (!bSelOnly)\n\n\t{\n\n\t\tUnselAllItems(tr);\n\n\t\tGetSetMediaTrackInfo(tr, \"B_FREEMODE\", &m_bFIPM);\n\n\t\tGetSetMediaTrackInfo(tr, \"I_CUSTOMCOLOR\", &m_iColor);\n\n\t}\n\n\tfor (int i = 0; i < m_items.GetSize(); i++)\n\n\t\tm_items.Get(i)->Restore(tr, bSelOnly);\n\n}\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 98, "score": 102021.27483002066 }, { "content": "\tPreventUIRefresh(1);\n\n\tfor (int i = 1; i <= GetNumTracks(); i++)\n\n\t{\n\n\t\tMediaTrack* tr = CSurf_TrackFromID(i, false);\n\n\t\tif (*(int*)GetSetMediaTrackInfo(tr, \"I_SELECTED\", NULL))\n\n\t\t\t// Find the saved track\n\n\t\t\tfor (int j = 0; j < g_tracks.Get()->GetSize(); j++)\n\n\t\t\t\tif (TrackMatchesGuid(tr, &g_tracks.Get()->Get(j)->m_guid))\n\n\t\t\t\t\tg_tracks.Get()->Get(j)->Restore(tr, true);\n\n\t}\n\n\tPreventUIRefresh(-1);\n\n\tUpdateTimeline();\n\n\tUndo_OnStateChangeEx2(NULL, SWS_CMD_SHORTNAME(_ct), UNDO_STATE_ALL, -1);\n\n}\n", "file_path": "Freeze/TrackItemState.cpp", "rank": 99, "score": 102021.22561210244 } ]
C++
Library/Source/Nanites/CoreFoundation/NCoreFoundation.cpp
refnum/Nano
dceb0907061f7845d8a3c662f309ca164e932e6f
#include "NCoreFoundation.h" NCFType ToCF(const NAny& theValue) { NNumber theNumber; NCFType cfObject; if (theValue.IsBool()) { cfObject.Set(theValue.GetBool() ? kCFBooleanTrue : kCFBooleanFalse); } else if (theValue.IsArray()) { cfObject.Set(ToCF(theValue.GetArray())); } else if (theValue.IsData()) { cfObject.Set(ToCF(theValue.GetData())); } else if (theValue.Is<NDate>()) { cfObject.Set(ToCF(theValue.Get<NDate>())); } else if (theValue.IsDictionary()) { cfObject.Set(ToCF(theValue.GetDictionary())); } else if (theValue.IsString()) { cfObject.Set(ToCF(theValue.GetString())); } else if (theValue.IsTime()) { cfObject.Set(ToCF(theValue.GetTime())); } else if (theValue.Is<NURL>()) { cfObject.Set(ToCF(theValue.Get<NURL>())); } else if (theNumber.SetValue(theValue)) { cfObject.Set(ToCF(theNumber)); } else { NN_LOG_ERROR("Unable to convert Nano object to CF!"); } return cfObject; } NAny ToNN(CFTypeRef cfObject) { NAny theObject; if (cfObject != nullptr) { CFTypeID cfType = CFGetTypeID(cfObject); if (cfType == CFBooleanGetTypeID()) { theObject = CFBooleanGetValue(CFBooleanRef(cfObject)) ? true : false; } else if (cfType == CFArrayGetTypeID()) { NCFArray cfArray; cfArray.Set(CFArrayRef(cfObject)); theObject = cfArray.GetArray(); } else if (cfType == CFDataGetTypeID()) { NCFData cfData; cfData.Set(CFDataRef(cfObject)); theObject = cfData.GetData(); } else if (cfType == CFDateGetTypeID()) { NCFDate cfDate; cfDate.Set(CFDateRef(cfObject)); theObject = cfDate.GetDate(); } else if (cfType == CFDictionaryGetTypeID()) { NCFDictionary cfDictionary; cfDictionary.Set(CFDictionaryRef(cfObject)); theObject = cfDictionary.GetDictionary(); } else if (cfType == CFNumberGetTypeID()) { NCFNumber cfNumber; cfNumber.Set(CFNumberRef(cfObject)); theObject = cfNumber.GetNumber(); } else if (cfType == CFStringGetTypeID()) { NCFString cfString; cfString.Set(CFStringRef(cfObject)); theObject = cfString.GetString(); } else if (cfType == CFURLGetTypeID()) { NCFURL cfURL; cfURL.Set(CFURLRef(cfObject)); theObject = cfURL.GetURL(); } else { NN_LOG_ERROR("Unable to convert CF object to Nano!"); } } return theObject; }
#include "NCoreFoundation.h" NCFType ToCF(const NAny& theValue) { NNumber theNumber; NCFType cfObject; if (theValue.IsBool()) { cfObject.Set(theValue.GetBool() ? kCFBooleanTrue : kCFBooleanFalse); } else if (theValue.IsArray()) { cfObject.Set(ToCF(theValue.GetArray())); } else if (theValue.IsData()) { cfObject.Set(ToCF(theValue.GetData())); } else if (theValue.Is<NDate>()) { cfObject.Set(ToCF(theValue.Get<NDate>())); } else if (theValue.IsDictionary()) { cfObject.Set(ToCF(theValue.GetDictionary())); } else if (theValue.IsString()) { cfObject.Set(ToCF(theValue.GetString())); } else if (theValue.IsTime()) { cfObject.Set(ToCF(theValue.GetTime())); } else if (theValue.Is<NURL>()) { cfObject.Set(ToCF(theValue.Get<NURL>())); } else
return cfObject; } NAny ToNN(CFTypeRef cfObject) { NAny theObject; if (cfObject != nullptr) { CFTypeID cfType = CFGetTypeID(cfObject); if (cfType == CFBooleanGetTypeID()) { theObject = CFBooleanGetValue(CFBooleanRef(cfObject)) ? true : false; } else if (cfType == CFArrayGetTypeID()) { NCFArray cfArray; cfArray.Set(CFArrayRef(cfObject)); theObject = cfArray.GetArray(); } else if (cfType == CFDataGetTypeID()) { NCFData cfData; cfData.Set(CFDataRef(cfObject)); theObject = cfData.GetData(); } else if (cfType == CFDateGetTypeID()) { NCFDate cfDate; cfDate.Set(CFDateRef(cfObject)); theObject = cfDate.GetDate(); } else if (cfType == CFDictionaryGetTypeID()) { NCFDictionary cfDictionary; cfDictionary.Set(CFDictionaryRef(cfObject)); theObject = cfDictionary.GetDictionary(); } else if (cfType == CFNumberGetTypeID()) { NCFNumber cfNumber; cfNumber.Set(CFNumberRef(cfObject)); theObject = cfNumber.GetNumber(); } else if (cfType == CFStringGetTypeID()) { NCFString cfString; cfString.Set(CFStringRef(cfObject)); theObject = cfString.GetString(); } else if (cfType == CFURLGetTypeID()) { NCFURL cfURL; cfURL.Set(CFURLRef(cfObject)); theObject = cfURL.GetURL(); } else { NN_LOG_ERROR("Unable to convert CF object to Nano!"); } } return theObject; }
if (theNumber.SetValue(theValue)) { cfObject.Set(ToCF(theNumber)); } else { NN_LOG_ERROR("Unable to convert Nano object to CF!"); }
if_condition
[ { "content": " ExprList *pReturnEL; /* List of expressions to return */\n", "file_path": "Library/Source/Nano/Internal/Components/sqlite-3.36.0/sqlite3.36.0.c", "rank": 0, "score": 52241.32236349526 }, { "content": "static const char KW_INCLUDE[]\n", "file_path": "Library/Source/Nano/Internal/Components/expat-2.4.1/xmlrole.c", "rank": 1, "score": 52234.6644733665 }, { "content": "using NCFType = NCFObject<CFTypeRef>;\n", "file_path": "Library/Source/Nanites/CoreFoundation/NCoreFoundation.h", "rank": 2, "score": 46465.82656183484 }, { "content": "class NNumber;\n", "file_path": "Library/Source/Nano/Files/NPropertyList.h", "rank": 3, "score": 35433.96043438372 }, { "content": "class NNumber;\n", "file_path": "Library/Source/Nano/Types/NDictionary.h", "rank": 4, "score": 35433.96043438372 }, { "content": "class NNumber;\n", "file_path": "Library/Source/Nano/Types/NAny.h", "rank": 5, "score": 35433.96043438372 }, { "content": "//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n\nclass NNumber;\n", "file_path": "Library/Source/Nano/Application/NPreferenceFile.h", "rank": 6, "score": 35433.96043438372 }, { "content": "class NNumber;\n", "file_path": "Library/Source/Nano/Application/NPreferences.h", "rank": 7, "score": 35433.96043438372 }, { "content": "class NNumber;\n", "file_path": "Library/Source/Nano/Types/NArray.h", "rank": 8, "score": 35433.96043438372 }, { "content": "//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n\nclass NN_EMPTY_BASE NNumber final : public NMixinComparable<NNumber>\n\n{\n\npublic:\n\n\ttemplate<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>\n\n\t\t\t\t\t\t\t\t\t\tNNumber(T theValue);\n\n\t\t\t\t\t\t\t\t\t\tNNumber(const NNumber& theValue);\n\n\t\t\t\t\t\t\t\t\t\tNNumber(const NString& theValue);\n\n\n\n\t\t\t\t\t\t\t\t\t\tNNumber() = default;\n\n\n\n\n\n\t// Is this an integer number?\n\n\tbool IsInteger() const;\n\n\n\n\n\n\t// Is this a real number?\n\n\tbool IsReal() const;\n\n\n\n\n\n\t// Is this a signed number?\n", "file_path": "Library/Source/Nano/Types/NNumber.h", "rank": 9, "score": 27353.976308682013 }, { "content": "\n\n//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NNumber.inl\"\n\n\n\n\n\n\n\n#endif // NNUMBER_H\n", "file_path": "Library/Source/Nano/Types/NNumber.h", "rank": 10, "score": 14.013563257328062 }, { "content": "\n\n\n\npublic:\n\n\t// NMixinComparable\n\n\tbool CompareEqual(const NAny& theValue) const;\n\n\tNComparison CompareOrder(const NAny& theValue) const;\n\n};\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NAny.inl\"\n\n\n\n\n\n\n\n#endif // NANY_H\n", "file_path": "Library/Source/Nano/Types/NAny.h", "rank": 11, "score": 12.407607617671632 }, { "content": "\t\t\n\n\t\t3. Neither the name of the copyright holder nor the names of its\n\n\t\tcontributors may be used to endorse or promote products derived from\n\n\t\tthis software without specific prior written permission.\n\n\t\t\n\n\t\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\n\t\t\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\n\t\tLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\n\t\tA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\n\t\tHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\n\t\tSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\n\t\tLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\n\t\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\n\t\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\n\t\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n\t\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\t___________________________________________________________________________\n\n*/\n\n#ifndef NNUMBER_H\n\n#define NNUMBER_H\n", "file_path": "Library/Source/Nano/Types/NNumber.h", "rank": 12, "score": 10.388393306107886 }, { "content": "\t\t\n\n\t\t3. Neither the name of the copyright holder nor the names of its\n\n\t\tcontributors may be used to endorse or promote products derived from\n\n\t\tthis software without specific prior written permission.\n\n\t\t\n\n\t\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\n\t\t\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\n\t\tLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\n\t\tA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\n\t\tHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\n\t\tSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\n\t\tLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\n\t\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\n\t\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\n\t\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n\t\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\t___________________________________________________________________________\n\n*/\n\n#ifndef NANY_H\n\n#define NANY_H\n", "file_path": "Library/Source/Nano/Types/NAny.h", "rank": 13, "score": 10.388393306107886 }, { "content": "} // namespace Catch\n\n\n\n// end catch_matchers_string.h\n\n// start catch_matchers_vector.h\n\n\n\n#include <algorithm>\n\n\n\nnamespace Catch {\n\nnamespace Matchers {\n\n\n\n namespace Vector {\n\n template<typename T>\n\n struct ContainsElementMatcher : MatcherBase<std::vector<T>> {\n\n\n\n ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}\n\n\n\n bool match(std::vector<T> const &v) const override {\n\n for (auto const& el : v) {\n\n if (el == m_comparator) {\n\n return true;\n", "file_path": "Library/Source/Nanites/Catch/catch.hpp", "rank": 14, "score": 10.290426222859438 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NCommonPOSIX.h\"\n\n\n\n// Nano\n\n#include \"NDebug.h\"\n\n#include \"NFileUtils.h\"\n\n#include \"NFormat.h\"\n\n#include \"NString.h\"\n\n#include \"NSystem.h\"\n\n#include \"NTimeUtils.h\"\n\n\n\n// System\n\n#include <dirent.h>\n\n#include <errno.h>\n\n#include <fcntl.h>\n\n#include <math.h>\n\n#include <stdlib.h>\n\n#include <sys/fcntl.h>\n\n#include <sys/mman.h>\n\n#include <sys/stat.h>\n", "file_path": "Library/Source/Nano/Internal/Targets/Common/NCommonPOSIX.cpp", "rank": 15, "score": 8.505669035546047 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NCommonLinux.h\"\n\n\n\n// Nano\n\n#include \"NCommonPOSIX.h\"\n\n#include \"NDebug.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NFormat.h\"\n\n#include \"NMachine.h\"\n\n#include \"NNumber.h\"\n\n#include \"NPropertyList.h\"\n\n#include \"NSystem.h\"\n\n#include \"NTimeUtils.h\"\n\n#include \"NanoTargets.h\"\n\n\n\n// System\n\n#include <fcntl.h>\n\n#include <linux/fs.h>\n\n#include <semaphore.h>\n\n#include <sys/stat.h>\n", "file_path": "Library/Source/Nano/Internal/Targets/Common/NCommonLinux.cpp", "rank": 16, "score": 8.466998736554885 }, { "content": "//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NMutex.h\"\n\n#include \"NNumber.h\"\n\n#include \"NPreference.h\"\n\n#include \"NString.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n#include \"NVariant.h\"\n\n\n\n// System\n\n#include <any>\n\n\n\n\n\n\n\n\n", "file_path": "NanoTest/Source/Benchmarks/BSizeOf.cpp", "rank": 17, "score": 8.466299942490105 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NDeque.h\"\n\n#include \"NFunction.h\"\n\n#include \"NMutex.h\"\n\n#include \"NRunLoopTask.h\"\n\n#include \"NSemaphore.h\"\n\n#include \"NString.h\"\n\n#include \"NThread.h\"\n\n#include \"NanoConstants.h\"\n\n\n\n// System\n\n#include <atomic>\n\n#include <memory>\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Threads/NThreadPool.h", "rank": 18, "score": 8.454289463143995 }, { "content": "\n\n\n\n//============================================================================\n\n//\t\tInclude files\n\n//----------------------------------------------------------------------------\n\n#include <sys/select.h>\n\n#include <sys/fcntl.h>\n\n#include <sys/utsname.h>\n\n#include <sys/wait.h>\n\n#include <locale.h>\n\n#include <errno.h>\n\n#include <unistd.h>\n\n\n\n#if NANO_USING_GD\n\n#include \"gd.h\"\n\n#endif\n\n\n\n#include \"NFileUtilities.h\"\n\n#include \"NTargetSystem.h\"\n\n\n", "file_path": "Library/Source/Nano/Internal/Targets/Linux/NLinuxSystem.cpp", "rank": 19, "score": 8.448525125031578 }, { "content": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n#ifndef TSL_HOPSCOTCH_HASH_H\n\n#define TSL_HOPSCOTCH_HASH_H\n\n\n\n\n\n#include <algorithm>\n\n#include <cassert>\n\n#include <cmath>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <exception>\n\n#include <functional>\n\n#include <initializer_list>\n\n#include <iterator>\n\n#include <limits>\n\n#include <memory>\n\n#include <stdexcept>\n\n#include <tuple>\n", "file_path": "Library/Source/Nano/Internal/Components/hopscotch-map-2.3.0/hopscotch_hash.h", "rank": 20, "score": 8.448103968123863 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NPreferences.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NAsync.h\"\n\n#include \"NBroadcaster.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NFormat.h\"\n\n#include \"NNumber.h\"\n\n#include \"NScopedLock.h\"\n\n#include \"NSet.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NString.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n", "file_path": "Library/Source/Nano/Application/NPreferences.cpp", "rank": 21, "score": 8.448103968123863 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NDBHandle.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NDBQuery.h\"\n\n#include \"NDBResult.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NFormat.h\"\n\n#include \"NFunction.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NThread.h\"\n\n#include \"NTimeUtils.h\"\n\n#include \"Nano_sqlite3.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n", "file_path": "Library/Source/Nano/Files/NDBHandle.cpp", "rank": 22, "score": 8.409508392118962 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NLog.h\"\n\n\n\n// Nano\n\n#include \"NScopedLock.h\"\n\n#include \"NThreadID.h\"\n\n#include \"NTimeUtils.h\"\n\n\n\n// System\n\n#include <inttypes.h>\n\n#include <math.h>\n\n#include <stdarg.h>\n\n#include <stdio.h>\n\n#include <string.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n", "file_path": "Library/Source/Nano/Debugging/NLog.cpp", "rank": 23, "score": 8.401488466002245 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDataEncoder.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NFile.h\"\n\n#include \"NFileHandle.h\"\n\n#include \"NFileUtils.h\"\n\n#include \"NFormat.h\"\n\n#include \"NMathUtils.h\"\n\n#include \"NPropertyList.h\"\n\n#include \"NTestFixture.h\"\n\n\n\n// System\n\n#include <stdlib.h>\n\n\n\n\n\n\n\n\n\n\n", "file_path": "NanoTest/Source/Nano/Files/TPropertyList.cpp", "rank": 24, "score": 8.394744616213353 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NCGContext.h\"\n\n\n\n// Nano\n\n#include \"NCFString.h\"\n\n#include \"NCGColor.h\"\n\n#include \"NCGImage.h\"\n\n#include \"NCGShading.h\"\n\n#include \"NCache.h\"\n\n#include \"NCoreFoundation.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NImage.h\"\n\n#include \"NMathUtils.h\"\n\n#include \"NMutex.h\"\n\n#include \"NScopedLock.h\"\n\n\n\n// System\n\n#include <CoreText/CTStringAttributes.h>\n\n\n\n\n", "file_path": "Library/Source/Nanites/CoreGraphics/NCGContext.cpp", "rank": 25, "score": 8.39318988039668 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFunction.h\"\n\n#include \"NMutex.h\"\n\n#include \"NRunLoop.h\"\n\n#include \"NString.h\"\n\n#include \"NanoTypes.h\"\n\n\n\n// System\n\n#include <atomic>\n\n#include <memory>\n\n#include <thread>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Threads/NThread.h", "rank": 26, "score": 8.385725961817846 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinAppendable.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinContainer.h\"\n\n#include \"NMixinHashable.h\"\n\n#include \"NRange.h\"\n\n#include \"NStdUtility.h\"\n\n#include \"NanoMacros.h\"\n\n\n\n\n\n// System\n\n#include <atomic>\n\n#include <vector>\n\n\n\n\n\n\n\n\n", "file_path": "Library/Source/Nano/Data/NData.h", "rank": 27, "score": 8.384609817202033 }, { "content": "#include \"NPoint.h\"\n\n#include \"NSize.h\"\n\n#include \"NRectangle.h\"\n\n#include \"NColor.h\"\n\n#include \"NDate.h\"\n\n#include \"NArray.h\"\n\n#include \"NVariant.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n\n\n\n\n\n\n\n\n\n\n//============================================================================\n\n//\t\tClass declaration\n\n//----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nanites/Windows/NRegistry.h", "rank": 28, "score": 8.370022492712486 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinContainer.h\"\n\n#include \"NStdUtility.h\"\n\n#include \"NanoMacros.h\"\n\n\n\n// System\n\n#include <atomic>\n\n#include <memory>\n\n#include <optional>\n\n#include <type_traits>\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n\ntemplate<typename T>\n", "file_path": "Library/Source/Nano/Types/NDeque.h", "rank": 29, "score": 8.354377727651235 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFlags.h\"\n\n#include \"NMixinAppendable.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinContainer.h\"\n\n#include \"NMixinHashable.h\"\n\n#include \"NRange.h\"\n\n#include \"NStdUtility.h\"\n\n#include \"NStringEncodings.h\"\n\n#include \"NanoMacros.h\"\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Find flags\n", "file_path": "Library/Source/Nano/Text/NString.h", "rank": 30, "score": 8.345275213493414 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFile.h\"\n\n#include \"NFileHandle.h\"\n\n#include \"NMap.h\"\n\n#include \"NProgressable.h\"\n\n#include \"NTime.h\"\n\n\n\n// System\n\n#include <functional>\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Files/NDBHandle.h", "rank": 31, "score": 8.334339515065606 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFunction.h\"\n\n#include \"NMutex.h\"\n\n#include \"NThreadID.h\"\n\n#include \"NTime.h\"\n\n\n\n// System\n\n#include <deque>\n\n#include <memory>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Threads/NRunLoop.h", "rank": 32, "score": 8.328622722401535 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NDebug.h\"\n\n#include \"NLogOutput.h\"\n\n#include \"NMutex.h\"\n\n#include \"NanoConstants.h\"\n\n\n\n// System\n\n#include <stdarg.h>\n\n#include <stdlib.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Debugging/NLog.h", "rank": 33, "score": 8.328622722401535 }, { "content": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n#ifndef TSL_HOPSCOTCH_GROWTH_POLICY_H\n\n#define TSL_HOPSCOTCH_GROWTH_POLICY_H \n\n\n\n\n\n#include <algorithm>\n\n#include <array>\n\n#include <climits>\n\n#include <cmath>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <iterator>\n\n#include <limits>\n\n#include <ratio>\n\n#include <stdexcept>\n\n\n\n\n\n/**\n", "file_path": "Library/Source/Nano/Internal/Components/hopscotch-map-2.3.0/hopscotch_growth_policy.h", "rank": 34, "score": 8.328366169041931 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NFile.h\"\n\n#include \"NFileHandle.h\"\n\n#include \"NFileInfo.h\"\n\n#include \"NFileMap.h\"\n\n#include \"NThread.h\"\n\n#include \"NTime.h\"\n\n\n\n// System\n\n#include <sys/stat.h>\n\n#include <sys/time.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Internal/Targets/Common/NCommonPOSIX.h", "rank": 35, "score": 8.323262997850271 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NFileUtils.h\"\n\n\n\n// Nano\n\n#include \"NCommonWindows.h\"\n\n#include \"NData.h\"\n\n#include \"NFileInfo.h\"\n\n#include \"NString.h\"\n\n\n\n// System\n\n#include <Shlobj.h>\n\n#include <ktmw32.h>\n\n#include <shellapi.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tLibraries\n", "file_path": "Library/Source/Nano/Internal/Targets/Windows/WindowsNFileUtils.cpp", "rank": 36, "score": 8.316892821667123 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NPoint.h\"\n\n#include \"NRectangle.h\"\n\n#include \"NSize.h\"\n\n#include \"NString.h\"\n\n\n\n// System\n\n#include <Windows.h>\n\n#include <objidl.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInline functions\n\n//-----------------------------------------------------------------------------\n\n// Nano to Windows\n", "file_path": "Library/Source/Nanites/Windows/NWindows.h", "rank": 37, "score": 8.30871690873483 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NBundle.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NFileHandle.h\"\n\n#include \"NFilePath.h\"\n\n#include \"NFormat.h\"\n\n#include \"NMutex.h\"\n\n#include \"NPropertyList.h\"\n\n#include \"NScopedLock.h\"\n\n#include \"NString.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Constants\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Files/NBundle.cpp", "rank": 38, "score": 8.292379173131028 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n\n\n// Nano\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NFormat.h\"\n\n#include \"NNumber.h\"\n\n#include \"NRange.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NString.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNArray::HasValue : Is a value present?\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Types/NArray.cpp", "rank": 39, "score": 8.292379173131028 }, { "content": "//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NData.h\"\n\n#include \"NDataCompressor.h\"\n\n#include \"NFunction.h\"\n\n#include \"NMachine.h\"\n\n#include \"NRandom.h\"\n\n#include \"NSharedMutex.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NThread.h\"\n\n\n\n// System\n\n#include <shared_mutex>\n\n\n\n#if !NN_TARGET_WINDOWS\n\n\t#include <pthread.h>\n\n#endif // !NN_TARGET_WINDOWS\n\n\n\n\n\n\n", "file_path": "NanoTest/Source/Benchmarks/BSharedMutex.cpp", "rank": 40, "score": 8.2866761345244 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NAny.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NString.h\"\n\n#include \"NTime.h\"\n\n\n\n// System\n\n#include <typeindex>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNAny::IsArray : Is the value an NArray?\n", "file_path": "Library/Source/Nano/Types/NAny.cpp", "rank": 41, "score": 8.28221765351512 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NPreferences.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NStdContainer.h\"\n\n#include \"NString.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n\n//\t\tGetTestDictionary : Get a test dictionary.\n", "file_path": "NanoTest/Source/Nano/Application/TPreferences.cpp", "rank": 42, "score": 8.2728720536089 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NPreference.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NStdContainer.h\"\n\n#include \"NString.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n\n//\t\tGetTestDictionary : Get a test dictionary.\n", "file_path": "NanoTest/Source/Nano/Application/TPreference.cpp", "rank": 43, "score": 8.2728720536089 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NPreferenceFile.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NStdContainer.h\"\n\n#include \"NString.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n\n//\t\tGetTestDictionary : Get a test dictionary.\n", "file_path": "NanoTest/Source/Nano/Application/TPreferenceFile.cpp", "rank": 44, "score": 8.259113886338149 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NString.h\"\n\n\n\n// Nano\n\n#include \"NData.h\"\n\n#include \"NDataDigest.h\"\n\n#include \"NStringComparator.h\"\n\n#include \"NStringEncoder.h\"\n\n#include \"NStringScanner.h\"\n\n#include \"NStringTransformer.h\"\n\n#include \"NThread.h\"\n\n#include \"NUnicodeView.h\"\n\n\n\n// System\n\n#include <atomic>\n\n#include <cstddef>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Types\n\n//-----------------------------------------------------------------------------\n\n// Encoded string data\n\n//\n\n// The data for a string in a particular encoding.\n", "file_path": "Library/Source/Nano/Text/NString.cpp", "rank": 45, "score": 8.256979816353695 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NMap.h\"\n\n#include \"NMutex.h\"\n\n#include \"NReceiver.h\"\n\n#include \"NString.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Events/NBroadcaster.h", "rank": 46, "score": 8.251881971041053 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NMixinComparable.h\"\n\n#include \"NPoint.h\"\n\n#include \"NSize.h\"\n\n#include \"NanoMacros.h\"\n\n#include \"NanoTypes.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Positions\n", "file_path": "Library/Source/Nano/Graphics/NRectangle.h", "rank": 47, "score": 8.251881971041053 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NVariant.h\"\n\n#include \"NanoMacros.h\"\n\n\n\n// System\n\n#include <type_traits>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Limits\n", "file_path": "Library/Source/Nano/Types/NNumber.h", "rank": 48, "score": 8.251881971041053 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NCFObject.h\"\n\n#include \"NColor.h\"\n\n#include \"NPoint.h\"\n\n#include \"NRectangle.h\"\n\n\n\n// System\n\n#include <CoreGraphics/CGShading.h>\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Shading sample\n", "file_path": "Library/Source/Nanites/CoreGraphics/NCGShading.h", "rank": 49, "score": 8.249566313728103 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFileInfo.h\"\n\n#include \"NFileUtils.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NString.h\"\n\n#include \"NUTI.h\"\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Files/NFile.h", "rank": 50, "score": 8.249566313728103 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NMap.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinContainer.h\"\n\n#include \"NString.h\"\n\n\n\n// System\n\n#include <unordered_map>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Types/NDictionary.h", "rank": 51, "score": 8.249566313728103 }, { "content": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n#ifndef TSL_HOPSCOTCH_MAP_H\n\n#define TSL_HOPSCOTCH_MAP_H\n\n\n\n\n\n#include <algorithm>\n\n#include <cstddef>\n\n#include <functional>\n\n#include <initializer_list>\n\n#include <list>\n\n#include <memory>\n\n#include <type_traits>\n\n#include <utility>\n\n#include \"hopscotch_hash.h\"\n\n\n\n\n\nnamespace tsl {\n\n\n", "file_path": "Library/Source/Nano/Internal/Components/hopscotch-map-2.3.0/hopscotch_map.h", "rank": 52, "score": 8.24648079156187 }, { "content": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n * SOFTWARE.\n\n */\n\n#ifndef TSL_HOPSCOTCH_SET_H\n\n#define TSL_HOPSCOTCH_SET_H\n\n\n\n\n\n#include <algorithm>\n\n#include <cstddef>\n\n#include <functional>\n\n#include <initializer_list>\n\n#include <list>\n\n#include <memory>\n\n#include <type_traits>\n\n#include <utility>\n\n#include \"hopscotch_hash.h\"\n\n\n\n\n\nnamespace tsl {\n\n\n", "file_path": "Library/Source/Nano/Internal/Components/hopscotch-map-2.3.0/hopscotch_set.h", "rank": 53, "score": 8.24648079156187 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NCFObject.h\"\n\n#include \"NColor.h\"\n\n#include \"NCoreGraphics.h\"\n\n#include \"NPoint.h\"\n\n#include \"NRectangle.h\"\n\n\n\n// System\n\n#include <CoreGraphics/CGContext.h>\n\n#include <CoreText/CTFont.h>\n\n#include <CoreText/CTLine.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nanites/CoreGraphics/NCGContext.h", "rank": 54, "score": 8.24648079156187 }, { "content": "#include \"NCocoa.h\"\n\n#include \"NCoreGraphics.h\"\n\n#include \"NCoreFoundation.h\"\n\n#include \"NTimeUtilities.h\"\n\n#include \"NCGImage.h\"\n\n#include \"NCFString.h\"\n\n#include \"NThread.h\"\n\n#include \"NSpinLock.h\"\n\n#include \"NMacTarget.h\"\n\n#include \"NTargetSystem.h\"\n\n\n\n\n\n\n\n\n\n\n\n//============================================================================\n\n//\t\tInternal constants\n\n//----------------------------------------------------------------------------\n\n// Tasks\n\nstatic const NIndex kPipeRead\t\t\t\t\t\t\t\t\t\t\t= 0;\n", "file_path": "Library/Source/Nano/Internal/Targets/macOS/NMacSystem.cpp", "rank": 55, "score": 8.231734379490337 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NStdContainer.h\"\n\n#include \"NString.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n\n//\t\tGetTestDictionary : Get a test dictionary.\n\n//-----------------------------------------------------------------------------\n", "file_path": "NanoTest/Source/Nano/Types/TArray.cpp", "rank": 56, "score": 8.231294033276166 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NPOSIX.h\"\n\n\n\n\n\n// Nano\n\n#include \"NFilePath.h\"\n\n#include \"NanoTargets.h\"\n\n\n\n\n\n// System\n\n#include <stdlib.h>\n\n\n\n#if NN_TARGET_WINDOWS\n\n\t#include <io.h>\n\n\t#include <direct.h>\n\n#else\n\n\t#include <unistd.h>\n\n\t#include <sys/param.h>\n\n#endif\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNPOSIX::gmtime : Convert a time_t to a struct tm in GMT (UTC).\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/System/NPOSIX.cpp", "rank": 57, "score": 8.230743666754607 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFileInfo.h\"\n\n#include \"NFileUtils.h\"\n\n#include \"NMachine.h\"\n\n#include \"NProcess.h\"\n\n#include \"NRunLoop.h\"\n\n#include \"NSystem.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Internal/Targets/Common/NCommonDarwin.h", "rank": 58, "score": 8.230036160790133 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinAppendable.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinHashable.h\"\n\n#include \"NString.h\"\n\n#include \"NanoTargets.h\"\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Files/NFilePath.h", "rank": 59, "score": 8.230036160790133 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinComparable.h\"\n\n#include \"NString.h\"\n\n#include \"NanoMacros.h\"\n\n#include \"NanoTypes.h\"\n\n\n\n// System\n\n#include <array>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/System/NVersion.h", "rank": 60, "score": 8.206429570798605 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NFile.h\"\n\n#include \"NanoConstants.h\"\n\n\n\n\n\n// System\n\n#include <functional>\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Files/NFileScanner.h", "rank": 61, "score": 8.20060051040354 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NSystem.h\"\n\n\n\n// Nano\n\n#include \"NFormat.h\"\n\n#include \"NVersion.h\"\n\n#include \"NWindows.h\"\n\n\n\n// System\n\n#include <VersionHelpers.h>\n\n#include <stdlib.h>\n\n#include <sysinfoapi.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNSystem::GetEnv : Get an environment variable.\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Internal/Targets/Windows/WindowsNSystem.cpp", "rank": 62, "score": 8.191251963532395 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NSystem.h\"\n\n\n\n// Nano\n\n#include \"NCommonLinux.h\"\n\n#include \"NCommonPOSIX.h\"\n\n#include \"NFormat.h\"\n\n#include \"NNumber.h\"\n\n#include \"NVersion.h\"\n\n\n\n// System\n\n#include <sys/system_properties.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Internal/Targets/Android/AndroidNSystem.cpp", "rank": 63, "score": 8.191251963532395 }, { "content": "\n\n#include \"NTimer.h\"\n\n#include \"NCoreFoundation.h\"\n\n#include \"NCocoa.h\"\n\n#include \"NCFObject.h\"\n\n#include \"NByteSwap.h\"\n\n#include \"NMacTarget.h\"\n\n#include \"NMutex.h\"\n\n#include \"NTargetThread.h\"\n\n#include \"NTargetNetwork.h\"\n\n\n\n\n\n\n\n\n\n\n\n//============================================================================\n\n// Internal constants\n\n//----------------------------------------------------------------------------\n\n// Misc\n\nstatic const NTime kNetworkSleepTime\t\t\t\t\t\t\t\t= 0.1f;\n", "file_path": "Library/Source/Nano/Internal/Targets/macOS/NMacNetwork.cpp", "rank": 64, "score": 8.1860675304668 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinContainer.h\"\n\n#include \"NanoConstants.h\"\n\n#include \"NanoMacros.h\"\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Types/NRange.h", "rank": 65, "score": 8.183890623110823 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NanoTypes.h\"\n\n\n\n\n\n// System\n\n#include <set>\n\n#include <string>\n\n#include <unordered_map>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Debugging/NUsageBucket.h", "rank": 66, "score": 8.17360694671256 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NDictionary.h\"\n\n#include \"NString.h\"\n\n#include \"NanoConstants.h\"\n\n\n\n// System\n\n#include <memory>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Node types\n", "file_path": "Library/Source/Nano/System/NXMLNode.h", "rank": 67, "score": 8.17360694671256 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NFlags.h\"\n\n#include \"NProgressable.h\"\n\n#include \"NString.h\"\n\n\n\n// System\n\n#include <functional>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Parser flags\n", "file_path": "Library/Source/Nano/System/NXMLParser.h", "rank": 68, "score": 8.17360694671256 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinComparable.h\"\n\n#include \"NanoMacros.h\"\n\n\n\n// System\n\n#include <any>\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Types/NAny.h", "rank": 69, "score": 8.17360694671256 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NDBHandle.h\"\n\n#include \"NData.h\"\n\n#include \"NMixinContainer.h\"\n\n#include \"NString.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Files/NDBResult.h", "rank": 70, "score": 8.17360694671256 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NMachine.h\"\n\n\n\n// Nano\n\n#include \"NCommonWindows.h\"\n\n#include \"NData.h\"\n\n#include \"NMathUtils.h\"\n\n\n\n// System\n\n#include <Windows.h>\n\n#include <intrin.h>\n\n#include <sysinfoapi.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNMachine::GetCores : Get the number of cores.\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Internal/Targets/Windows/WindowsNMachine.cpp", "rank": 71, "score": 8.171996621104343 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NImage.h\"\n\n\n\n// Nano\n\n#include \"NFormat.h\"\n\n#include \"NWindows.h\"\n\n\n\n// System\n\n#include <tchar.h>\n\n#include <wincodec.h>\n\n#include <wincodecsdk.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tLibrary glue\n\n//-----------------------------------------------------------------------------\n\n// SHCreateMemStream\n", "file_path": "Library/Source/Nano/Internal/Targets/Windows/WindowsNImage.cpp", "rank": 72, "score": 8.161475142698858 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NFileInfo.h\"\n\n#include \"NProcess.h\"\n\n#include \"NSemaphore.h\"\n\n#include \"NString.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Internal/Targets/Common/NCommonLinux.h", "rank": 73, "score": 8.146790507093133 }, { "content": "// Formatting library for C++ - implementation\n\n//\n\n// Copyright (c) 2012 - 2016, Victor Zverovich\n\n// All rights reserved.\n\n//\n\n// For the license information refer to format.h.\n\n\n\n#ifndef FMT_FORMAT_INL_H_\n\n#define FMT_FORMAT_INL_H_\n\n\n\n#include <algorithm>\n\n#include <cctype>\n\n#include <cerrno> // errno\n\n#include <climits>\n\n#include <cmath>\n\n#include <cstdarg>\n\n#include <cstring> // std::memmove\n\n#include <cwchar>\n\n#include <exception>\n\n\n", "file_path": "Library/Source/Nano/Internal/Components/fmt-8.0.0/fmt_format-inl.h", "rank": 74, "score": 8.14133530216505 }, { "content": "} // namespace Catch\n\n\n\n// end catch_execution_plan.hpp\n\n// start catch_estimate_clock.hpp\n\n\n\n // Environment measurement\n\n\n\n\n\n// start catch_stats.hpp\n\n\n\n// Statistical analysis tools\n\n\n\n\n\n#include <algorithm>\n\n#include <functional>\n\n#include <vector>\n\n#include <numeric>\n\n#include <tuple>\n\n#include <cmath>\n\n#include <utility>\n", "file_path": "Library/Source/Nanites/Catch/catch.hpp", "rank": 75, "score": 8.133756248937342 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NDictionary.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NFormat.h\"\n\n#include \"NNumber.h\"\n\n#include \"NRange.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNDictionary::HasKey : Is a key present?\n\n//-----------------------------------------------------------------------------\n\nbool NDictionary::HasKey(const NString& theKey) const\n", "file_path": "Library/Source/Nano/Types/NDictionary.cpp", "rank": 76, "score": 8.129691592323143 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NanoTypes.h\"\n\n\n\n// System\n\n#include <string.h>\n\n#include <algorithm>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Types/NMixinComparable.h", "rank": 77, "score": 8.124862367670447 }, { "content": "\t\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\n\t\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\n\t\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n\t\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\t___________________________________________________________________________\n\n*/\n\n//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NPropertyList.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NByteSwap.h\"\n\n#include \"NData.h\"\n\n#include \"NDataEncoder.h\"\n\n#include \"NDateFormatter.h\"\n\n#include \"NFileHandle.h\"\n\n#include \"NFormat.h\"\n\n#include \"NStdAlgorithm.h\"\n", "file_path": "Library/Source/Nano/Files/NPropertyList.cpp", "rank": 78, "score": 8.121943063395385 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinContainer.h\"\n\n\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Types/NArray.h", "rank": 79, "score": 8.120149453889743 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NBroadcast.h\"\n\n#include \"NMutex.h\"\n\n#include \"NPreferenceFile.h\"\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Application/NPreferences.h", "rank": 80, "score": 8.120149453889743 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NMixinComparable.h\"\n\n#include \"NanoMacros.h\"\n\n#include \"NanoTypes.h\"\n\n\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Graphics/NPoint.h", "rank": 81, "score": 8.120149453889743 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NAny.h\"\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NStdContainer.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n\n//\t\tGetTestDictionary : Get a test dictionary.\n\n//-----------------------------------------------------------------------------\n\nstatic NDictionary GetTestDictionary()\n", "file_path": "NanoTest/Source/Nano/Types/TAny.cpp", "rank": 82, "score": 8.113090325967743 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NNumber.h\"\n\n\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NDebug.h\"\n\n#include \"NString.h\"\n\n#include \"NanoConstants.h\"\n\n#include \"Nano_fast_float.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Macros\n\n//-----------------------------------------------------------------------------\n\n#define NN_LOG_INEXACT_COMPARISON 0\n\n\n\n\n", "file_path": "Library/Source/Nano/Types/NNumber.cpp", "rank": 83, "score": 8.094959442583633 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NCFObject.h\"\n\n#include \"NDate.h\"\n\n#include \"NTime.h\"\n\n\n\n// System\n\n#include <CoreFoundation/CFDate.h>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nanites/CoreFoundation/NCFDate.h", "rank": 84, "score": 8.09368207210222 }, { "content": "#include <netdb.h>\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <unistd.h>\n\n\n\n#include \"NTargetNetwork.h\"\n\n\n\n\n\n\n\n\n\n\n\n//============================================================================\n\n// Internal constants\n\n//----------------------------------------------------------------------------\n\nstatic const int kSocketHandleInvalid\t\t\t\t\t\t\t\t= -1;\n\n\n\n\n\n\n\n\n\n\n", "file_path": "Library/Source/Nano/Internal/Targets/Linux/NLinuxNetwork.cpp", "rank": 85, "score": 8.09368207210222 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFlags.h\"\n\n#include \"NStringEncodings.h\"\n\n#include \"NanoConstants.h\"\n\n\n\n// System\n\n#include <unordered_map>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Encoder flags\n\n//\n", "file_path": "Library/Source/Nano/Text/NStringEncoder.h", "rank": 86, "score": 8.09368207210222 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NProgressable.h\"\n\n#include \"NXMLNode.h\"\n\n#include \"NXMLParser.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/System/NXMLEncoder.h", "rank": 87, "score": 8.091766772076857 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NFilePath.h\"\n\n#include \"NFlags.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Files/NFileInfo.h", "rank": 88, "score": 8.091766772076857 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NPreferenceFile.h\"\n\n\n\n// Nano\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NNumber.h\"\n\n#include \"NScopedLock.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NString.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tNPreferenceFile::NPreferenceFile : Constructor.\n\n//-----------------------------------------------------------------------------\n\nNPreferenceFile::NPreferenceFile()\n", "file_path": "Library/Source/Nano/Application/NPreferenceFile.cpp", "rank": 89, "score": 8.080090369970824 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NArray.h\"\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NNumber.h\"\n\n#include \"NStdAlgorithm.h\"\n\n#include \"NStdContainer.h\"\n\n#include \"NTestFixture.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Functions\n\n//-----------------------------------------------------------------------------\n\n//\t\tGetTestDictionary : Get a test dictionary.\n\n//-----------------------------------------------------------------------------\n\nstatic NDictionary GetTestDictionary()\n", "file_path": "NanoTest/Source/Nano/Types/TDictionary.cpp", "rank": 90, "score": 8.080090369970824 }, { "content": " };\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_assertioninfo.h\n\n// start catch_decomposer.h\n\n\n\n// start catch_tostring.h\n\n\n\n#include <vector>\n\n#include <cstddef>\n\n#include <type_traits>\n\n#include <string>\n\n// start catch_stream.h\n\n\n\n#include <iosfwd>\n\n#include <cstddef>\n\n#include <ostream>\n\n\n\nnamespace Catch {\n\n\n\n std::ostream& cout();\n\n std::ostream& cerr();\n\n std::ostream& clog();\n\n\n", "file_path": "Library/Source/Nanites/Catch/catch.hpp", "rank": 91, "score": 8.077062051693963 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NData.h\"\n\n#include \"NMixinAppendable.h\"\n\n#include \"NMixinComparable.h\"\n\n#include \"NMixinContainer.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declaration\n", "file_path": "Library/Source/Nano/Types/NBitVector.h", "rank": 92, "score": 8.067386669017715 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NDate.h\"\n\n#include \"NString.h\"\n\n#include \"NTime.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tConstants\n\n//-----------------------------------------------------------------------------\n\n// Date widths\n", "file_path": "Library/Source/Nano/Time/NDateFormatter.h", "rank": 93, "score": 8.05893970408604 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NMixinComparable.h\"\n\n#include \"NanoMacros.h\"\n\n#include \"NanoTypes.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Graphics/NSize.h", "rank": 94, "score": 8.05893970408604 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NMixinComparable.h\"\n\n#include \"NanoMacros.h\"\n\n#include \"NanoTypes.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Graphics/NVector.h", "rank": 95, "score": 8.05893970408604 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NAny.h\"\n\n#include \"NString.h\"\n\n\n\n// System\n\n#include <vector>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tTypes\n\n//-----------------------------------------------------------------------------\n\n// Forward declarations\n", "file_path": "Library/Source/Nano/Events/NBroadcast.h", "rank": 96, "score": 8.05893970408604 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n#include \"NMixinComparable.h\"\n\n#include \"NPoint.h\"\n\n#include \"NRectangle.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Graphics/NShape.h", "rank": 97, "score": 8.05893970408604 }, { "content": "//=============================================================================\n\n//\t\tIncludes\n\n//-----------------------------------------------------------------------------\n\n// Nano\n\n#include \"NFunction.h\"\n\n#include \"NString.h\"\n\n\n\n\n\n// System\n\n#include <atomic>\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tClass Declaration\n\n//-----------------------------------------------------------------------------\n", "file_path": "Library/Source/Nano/Threads/NThreadTask.h", "rank": 98, "score": 8.05893970408604 }, { "content": "//-----------------------------------------------------------------------------\n\n#include \"NXMLParser.h\"\n\n\n\n// Nano\n\n#include \"NData.h\"\n\n#include \"NDictionary.h\"\n\n#include \"NFileHandle.h\"\n\n#include \"NanoConstants.h\"\n\n#include \"expat.h\"\n\n\n\n\n\n\n\n\n\n\n\n//=============================================================================\n\n//\t\tInternal Macros\n\n//-----------------------------------------------------------------------------\n\nNN_DIAGNOSTIC_IGNORE_CLANG(\"-Wdisabled-macro-expansion\");\n\n\n\n\n", "file_path": "Library/Source/Nano/System/NXMLParser.cpp", "rank": 99, "score": 8.051214721227344 } ]
C++
tests/server.test.cpp
lineCode/webrtc-datachannels
0f814632361c829c3aff1764cb662bd6290d54d9
#include "algo/StringUtils.hpp" #include "config/ServerConfig.hpp" #include "log/Logger.hpp" #include "storage/path.hpp" #include <algorithm> #include <boost/asio.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ssl/context.hpp> #include <boost/asio/ssl/stream.hpp> #include <boost/asio/strand.hpp> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/websocket.hpp> #include <boost/beast/websocket/ssl.hpp> #include <cstddef> #include <cstdlib> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <net/core.hpp> #include <sstream> #include <streambuf> #include <string> #include <thread> #include <vector> #ifndef __has_include static_assert(false, "__has_include not supported"); #else # if __has_include(<filesystem>) # include <filesystem> namespace fs = std::filesystem; # elif __has_include(<experimental/filesystem>) # include <experimental/filesystem> namespace fs = std::experimental::filesystem; # elif __has_include(<boost/filesystem.hpp>) # include <boost/filesystem.hpp> namespace fs = boost::filesystem; # endif #endif #include "testsCommon.h" inline void load_server_certificate(boost::asio::ssl::context& ctx) { const fs::path workDir = gloer::storage::getThisBinaryDirectoryPath(); const fs::path assetsDir = (workDir / gloer::config::ASSETS_DIR); std::string const cert = gloer::storage::getFileContents( workDir / fs::path{"../gloer/assets/certs/server.crt"}); std::string const key = gloer::storage::getFileContents( workDir / fs::path{"../gloer/assets/certs/server.key"}); std::string const dh = gloer::storage::getFileContents( workDir / fs::path{"../gloer/assets/certs/dh.pem"}); ctx.set_password_callback( [](std::size_t, boost::asio::ssl::context_base::password_purpose) { return "1234"; }); ctx.set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); boost::system::error_code ec; ctx.use_certificate_chain(boost::asio::buffer(cert.data(), cert.size()), ec); if (ec) { LOG(WARNING) << "use_certificate_chain error: " << ec.message(); } LOG(WARNING) << "cert: " << cert; ctx.use_private_key(boost::asio::buffer(key.data(), key.size()), boost::asio::ssl::context::file_format::pem, ec); if (ec) { LOG(WARNING) << "use_private_key error: " << ec.message(); } ctx.use_tmp_dh(boost::asio::buffer(dh.data(), dh.size()), ec); if (ec) { LOG(WARNING) << "use_tmp_dh error: " << ec.message(); } } void fail(beast::error_code ec, char const* what) { } class session : public std::enable_shared_from_this<session> { ::tcp::socket socket_; websocket::stream<boost::asio::ssl::stream<::tcp::socket&>> ws_; ::net::strand<::net::io_context::executor_type> strand_; beast::multi_buffer buffer_; public: session(::tcp::socket socket, boost::asio::ssl::context& ctx) : socket_(std::move(socket)), ws_(socket_, ctx), strand_(ws_.get_executor()) {} void run() { LOG(WARNING) << "session run"; ws_.next_layer().async_handshake( boost::asio::ssl::stream_base::server, ::net::bind_executor( strand_, std::bind(&session::on_handshake, shared_from_this(), std::placeholders::_1))); } void on_handshake(beast::error_code ec) { LOG(WARNING) << "on_handshake"; if (ec) return fail(ec, "handshake"); ws_.async_accept(::net::bind_executor( strand_, std::bind(&session::on_accept, shared_from_this(), std::placeholders::_1))); } void on_accept(beast::error_code ec) { LOG(WARNING) << "on_accept"; if (ec) return fail(ec, "accept"); do_read(); } void do_read() { ws_.async_read(buffer_, ::net::bind_executor( strand_, std::bind(&session::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_read(beast::error_code ec, std::size_t bytes_transferred) { LOG(WARNING) << "on_read"; boost::ignore_unused(bytes_transferred); if (ec == websocket::error::closed) return; if (ec) fail(ec, "read"); ws_.text(ws_.got_text()); ws_.async_write( buffer_.data(), ::net::bind_executor(strand_, std::bind(&session::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_write(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) return fail(ec, "write"); buffer_.consume(buffer_.size()); do_read(); } }; class listener : public std::enable_shared_from_this<listener> { boost::asio::ssl::context& ctx_; ::tcp::acceptor acceptor_; ::tcp::socket socket_; public: listener(::net::io_context& ioc, boost::asio::ssl::context& ctx, ::tcp::endpoint endpoint) : ctx_(ctx), acceptor_(ioc), socket_(ioc) { beast::error_code ec; acceptor_.open(endpoint.protocol(), ec); if (ec) { fail(ec, "open"); return; } acceptor_.set_option(::net::socket_base::reuse_address(true), ec); if (ec) { fail(ec, "set_option"); return; } acceptor_.bind(endpoint, ec); if (ec) { fail(ec, "bind"); return; } acceptor_.listen(::net::socket_base::max_listen_connections, ec); if (ec) { fail(ec, "listen"); return; } } void run() { if (!acceptor_.is_open()) return; do_accept(); } void do_accept() { acceptor_.async_accept( socket_, std::bind(&listener::on_accept, shared_from_this(), std::placeholders::_1)); } void on_accept(beast::error_code ec) { if (ec) { fail(ec, "accept"); } else { std::make_shared<session>(std::move(socket_), ctx_)->run(); } do_accept(); } }; SCENARIO("ssltest", "[ssltest]") { auto const address = ::net::ip::make_address("0.0.0.0"); unsigned short const port = 8085; int const threads = 1; ::net::io_context ioc{threads}; boost::asio::ssl::context ctx{boost::asio::ssl::context::sslv23}; load_server_certificate(ctx); std::make_shared<listener>(ioc, ctx, ::tcp::endpoint{address, port})->run(); } SCENARIO("matchers", "[matchers]") { REQUIRE_THAT("Hello olleH", Predicate<std::string>( [](std::string const& str) -> bool { return str.front() == str.back(); }, "First and last character should be equal")); } SCENARIO("vectors can be sized and resized", "[vector]") { GIVEN("A vector with some items") { std::vector<int> v(5); REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 5); WHEN("the size is increased") { v.resize(10); THEN("the size and capacity change") { REQUIRE(v.size() == 10); REQUIRE(v.capacity() >= 10); } } WHEN("the size is reduced") { v.resize(0); THEN("the size changes but not capacity") { REQUIRE(v.size() == 0); REQUIRE(v.capacity() >= 5); } } WHEN("more capacity is reserved") { v.reserve(10); THEN("the capacity changes but not the size") { REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 10); } } WHEN("less capacity is reserved") { v.reserve(0); THEN("neither size nor capacity are changed") { REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 5); } } } }
#include "algo/StringUtils.hpp" #include "config/ServerConfig.hpp" #include "log/Logger.hpp" #include "storage/path.hpp" #include <algorithm> #include <boost/asio.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ssl/context.hpp> #include <boost/asio/ssl/stream.hpp> #include <boost/asio/strand.hpp> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/websocket.hpp> #include <boost/beast/websocket/ssl.hpp> #include <cstddef> #include <cstdlib> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <net/core.hpp> #include <sstream> #include <streambuf> #include <string> #include <thread> #include <vector> #ifndef __has_include static_assert(false, "__has_include not supported"); #else # if __has_include(<filesystem>) # include <filesystem> namespace fs = std::filesystem; # elif __has_include(<experimental/filesystem>) # include <experimental/filesystem> namespace fs = std::experimental::filesystem; # elif __has_include(<boost/filesystem.hpp>) # include <boost/filesystem.hpp> namespace fs = boost::filesystem; # endif #endif #include "testsCommon.h" inline void load_server_certificate(boost::asio::ssl::context& ctx) { const fs::path workDir = gloer::storage::getThisBinaryDirectoryPath(); const fs::path assetsDir = (workDir / gloer::config::ASSETS_DIR); std::string const cert = gloer::storage::getFileContents( workDir / fs::path{"../gloer/assets/certs/server.crt"}); std::string const key = gloer::storage::getFileContents( workDir / fs::path{"../gloer/assets/certs/server.key"}); std::string const dh = gloer::storage::getFileContents( workDir / fs::path{"../gloer/assets/certs/dh.pem"}); ctx.set_password_callback( [](std::size_t, boost::asio::ssl::context_base::password_purpose) { return "1234"; }); ctx.set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); boost::system::error_code ec; ctx.use_certificate_chain(boost::asio::buffer(cert.data(), cert.size()), ec); if (ec) { LOG(WARNING) << "use_certificate_chain error: " << ec.message(); } LOG(WARNING) << "cert: " << cert; ctx.use_private_key(boost::asio::buffer(key.data(), key.size()), boost::asio::ssl::context::file_format::pem, ec); if (ec) { LOG(WARNING) << "use_private_key error: " << ec.message(); } ctx.use_tmp_dh(boost::asio::buffer(dh.data(), dh.size()), ec); if (ec) { LOG(WARNING) << "use_tmp_dh error: " << ec.message(); } } void fail(beast::error_code ec, char const* what) { } class session : public std::enable_shared_from_this<session> { ::tcp::socket socket_; websocket::stream<boost::asio::ssl::stream<::tcp::socket&>> ws_; ::net::strand<::net::io_context::executor_type> strand_; beast::multi_buffer buffer_; public: session(::tcp::socket socket, boost::asio::ssl::context& ctx) : socket_(std::move(socket)), ws_(socket_, ctx), strand_(ws_.get_executor()) {} void run() { LOG(WARNING) << "session run"; ws_.next_layer().async_handshake( boost::asio::ssl::stream_base::server, ::net::bind_executor( strand_, std::bind(&session::on_handshake, shared_from_this(), std::placeholders::_1))); } void on_handshake(beast::error_code ec) { LOG(WARNING) << "on_handshake"; if (ec) return fail(ec, "handshake"); ws_.async_accept(::net::bind_executor( strand_, std::bind(&session::on_accept, shared_from_this(), std::placeholders::_1))); } void on_accept(beast::error_code ec) { LOG(WARNING) << "on_accept"; if (ec) return fail(ec, "accept"); do_read(); } void do_read() { ws_.async_read(buffer_, ::net::bind_executor( strand_, std::bind(&session::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_read(beast::error_code ec, std::size_t bytes_transferred) { LOG(WARNING) << "on_read"; boost::ignore_unused(bytes_transferred); if (ec == websocket::error::closed) return; if (ec) fail(ec, "read"); ws_.text(ws_.got_text()); ws_.async_write( buffer_.data(), ::net::bind_executor(strand_, std::bind(&session::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_write(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) return fail(ec, "write"); buffer_.consume(buffer_.size()); do_read(); } }; class listener : public std::enable_shared_from_this<listener> { boost::asio::ssl::context& ctx_; ::tcp::acceptor acceptor_; ::tcp::socket socket_; public: listener(::net::io_context& ioc, boost::asio::ssl::context& ctx, ::tcp::endpoint endpoint) : ctx_(ctx), acceptor_(ioc), socket_(ioc) { beast::error_code ec; acceptor_.open(endpoint.protocol(), ec); if (ec) { fail(ec, "open"); return; } acceptor_.set_option(::net::socket_base::reuse_address(true), ec); if (ec) { fail(ec, "set_option"); return; } acceptor_.bind(endpoint, ec); if (ec) { fail(ec, "bind"); return; } acceptor_.listen(::net::socket_base::max_listen_connections, ec); if (ec) { fail(ec, "listen"); return; } } void run() { if (!acceptor_.is_open()) return; do_accept(); } void do_accept() { acceptor_.async_accept( socket_, std::bind(&listener::on_accept, shared_from_this(), std::placeholders::_1)); } void on_accept(beast::error_code ec) { if (ec) { fail(ec, "accept"); } else { std::make_shared<session>(std::move(socket_), ctx_)->run(); } do_accept(); } }; SCENARIO("ssltest", "[ssltest]") { auto const address = ::net::ip::make_address("0.0.0.0"); unsigned short const port = 8085; int const threads = 1; ::net::io_context ioc{threads}; boost::asio::ssl::context ctx{boost::asio::ssl::context::sslv23}; load_server_certificate(ctx); std::make_shared<listener>(ioc, ctx, ::tcp::endpoint{address, port})->run(); } SCENARIO("matchers", "[matchers]") { REQUIRE_THAT("Hello olleH", Predicate<std::string>( [](std::string const& str) -> bool { return str.front() == str.back(); }, "First and last character should be equal")); } SCENARIO("vectors can be sized and resized", "[vector]") { GIVEN("A vector with some items") { std::vector<int> v(5); REQUIRE(v.size(
{ REQUIRE(v.size() == 10); REQUIRE(v.capacity() >= 10); } } WHEN("the size is reduced") { v.resize(0); THEN("the size changes but not capacity") { REQUIRE(v.size() == 0); REQUIRE(v.capacity() >= 5); } } WHEN("more capacity is reserved") { v.reserve(10); THEN("the capacity changes but not the size") { REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 10); } } WHEN("less capacity is reserved") { v.reserve(0); THEN("neither size nor capacity are changed") { REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 5); } } } }
) == 5); REQUIRE(v.capacity() >= 5); WHEN("the size is increased") { v.resize(10); THEN("the size and capacity change")
random
[ { "content": "// Sends a WebSocket message and prints the response\n\nclass session : public std::enable_shared_from_this<session>\n\n{\n\n tcp::resolver resolver_;\n\n websocket::stream<beast::tcp_stream> ws_;\n\n beast::flat_buffer buffer_;\n\n std::string host_;\n\n std::string text_;\n\n\n\npublic:\n\n // Resolver and socket require an io_context\n\n explicit\n\n session(net::io_context& ioc)\n\n : resolver_(net::make_strand(ioc))\n\n , ws_(net::make_strand(ioc))\n\n {\n\n }\n\n\n\n // Start the asynchronous operation\n\n void\n\n run(\n", "file_path": "examples/gameclient/src/main.cpp", "rank": 1, "score": 186618.9540673782 }, { "content": "class Thread;\n\n} // namespace rtc\n\n\n\nnamespace webrtc {\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 2, "score": 180002.92277461875 }, { "content": "class ClientSession : public SessionPair, public std::enable_shared_from_this<ClientSession> {\n\nprivate:\n\n // NOTE: ProducerConsumerQueue must be created with a fixed maximum size\n\n // We use Queue per connection\n\n static const size_t MAX_SENDQUEUE_SIZE = 120;\n\n\n\npublic:\n\n //ClientSession() = delete;\n\n\n\n // Take ownership of the socket\n\n explicit ClientSession(boost::asio::io_context& ioc,\n\n ::boost::asio::ssl::context& ctx,\n\n net::WSClientNetworkManager* nm,\n\n const ws::SessionGUID& id);\n\n\n\n ~ClientSession();\n\n\n\n void connectAsClient(const std::string& host, const std::string& port);\n\n\n\n void onClientResolve(beast::error_code ec, tcp::resolver::results_type results);\n", "file_path": "src/net/ws/client/ClientSession.hpp", "rank": 3, "score": 163628.0078182252 }, { "content": "class Listener : public std::enable_shared_from_this<Listener> {\n\n\n\npublic:\n\n Listener(boost::asio::io_context& ioc,\n\n ::boost::asio::ssl::context& ctx,\n\n const boost::asio::ip::tcp::endpoint& endpoint,\n\n std::shared_ptr<std::string const> doc_root, net::WSServerNetworkManager* nm);\n\n\n\n void configureAcceptor();\n\n\n\n // Report a failure\n\n void on_fail(boost::beast::error_code ec, char const* what);\n\n\n\n // Start accepting incoming connections\n\n void run(/*WS_LISTEN_MODE mode*/);\n\n\n\n void do_accept();\n\n\n\n //std::shared_ptr<WsSession> addClientSession(const std::string& newSessId);\n\n\n", "file_path": "src/net/ws/server/Listener.hpp", "rank": 4, "score": 159548.1564653378 }, { "content": "class SessionPair : public SessionBase<ws::SessionGUID> {\n\npublic:\n\n SessionPair(const ws::SessionGUID& id);\n\n\n\n virtual ~SessionPair() {}\n\n\n\n virtual bool isOpen() const = 0;\n\n\n\n virtual void close() = 0;\n\n\n\n virtual void pairToWRTCSession(std::shared_ptr<wrtc::WRTCSession> WRTCSession) = 0;\n\n\n\n virtual bool hasPairedWRTCSession() = 0;\n\n\n\n virtual std::weak_ptr<wrtc::WRTCSession> getWRTCSession() const = 0;\n\n};\n\n\n\n} // namespace net\n\n} // namespace gloer\n", "file_path": "src/net/SessionPair.hpp", "rank": 6, "score": 159360.9096121969 }, { "content": "class WRTCSession : public SessionBase<wrtc::SessionGUID>, public std::enable_shared_from_this<WRTCSession> {\n\nprivate:\n\n // NOTE: ProducerConsumerQueue must be created with a fixed maximum size\n\n // We use Queue per connection\n\n static const size_t MAX_SENDQUEUE_SIZE = 120;\n\npublic:\n\n WRTCSession() = delete;\n\n\n\n explicit WRTCSession(net::WRTCNetworkManager* wrtc_nm,\n\n std::shared_ptr<gloer::net::SessionPair> wsSession,\n\n /*net::WSServerNetworkManager* ws_nm,*/\n\n const wrtc::SessionGUID& webrtcId, const ws::SessionGUID& wsId)\n\n RTC_RUN_ON(thread_checker_);\n\n\n\n ~WRTCSession() override; // RTC_RUN_ON(thread_checker_);\n\n\n\n void CloseDataChannel(bool resetObserver) RTC_RUN_ON(signalingThread());\n\n\n\n // bool handleIncomingJSON(std::shared_ptr<std::string> message) override;\n\n\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 7, "score": 157871.04363596288 }, { "content": "class SessionManager : public SessionManagerBase<WRTCSession, wrtc::SessionGUID> {\n\npublic:\n\n SessionManager(net::WRTCNetworkManager* nm);\n\n\n\n void unregisterSession(const wrtc::SessionGUID& id) override /*RTC_RUN_ON(signalingThread())*/;\n\n\n\nprivate:\n\n net::WRTCNetworkManager* nm_;\n\n};\n\n\n\n} // namespace wrtc\n\n} // namespace net\n\n} // namespace gloer\n", "file_path": "src/net/wrtc/SessionManager.hpp", "rank": 8, "score": 149467.10028722347 }, { "content": "class Thread;\n\n} // namespace rtc\n\n\n\nnamespace webrtc {\n", "file_path": "src/net/wrtc/Callbacks.hpp", "rank": 9, "score": 144247.60377361433 }, { "content": "class ServerSessionManager : public SessionManagerBase<SessionPair, ws::SessionGUID> {\n\npublic:\n\n ServerSessionManager(net::WSServerNetworkManager* nm);\n\n\n\n void unregisterSession(const ws::SessionGUID& id) override;\n\n\n\nprivate:\n\n net::WSServerNetworkManager* nm_;\n\n};\n\n\n\n} // namespace ws\n\n} // namespace net\n\n} // namespace gloer\n", "file_path": "src/net/ws/server/ServerSessionManager.hpp", "rank": 10, "score": 143436.1598239949 }, { "content": "class ClientSessionManager : public SessionManagerBase<SessionPair, ws::SessionGUID> {\n\npublic:\n\n ClientSessionManager(net::WSClientNetworkManager* nm);\n\n\n\n void unregisterSession(const ws::SessionGUID& id) override;\n\n\n\nprivate:\n\n net::WSClientNetworkManager* nm_;\n\n};\n\n\n\n} // namespace ws\n\n} // namespace net\n\n} // namespace gloer\n", "file_path": "src/net/ws/client/ClientSessionManager.hpp", "rank": 11, "score": 143436.1598239949 }, { "content": "// Create SessionDescription events.\n\nclass CSDO : public webrtc::CreateSessionDescriptionObserver {\n\npublic:\n\n CSDO(bool isServer, net::WRTCNetworkManager* nm, std::shared_ptr<WRTCSession> wrtcSess)\n\n : isServer_(isServer), nm_(nm), wrtcSess_(wrtcSess) {}\n\n\n\n /*void OnSuccess(webrtc::SessionDescriptionInterface* desc) override;\n\n\n\n void OnFailure(const std::string& error) override;*/\n\n\n\n // Successfully created a session description.\n\n /*void OnSuccess(webrtc::SessionDescriptionInterface* desc) {\n\n OnAnswerCreated(desc);\n\n }*/\n\n\n\n // Failure to create a session description.\n\n // void OnFailure(const std::string& /* error */) {}\n\n\n\n void OnSuccess(webrtc::SessionDescriptionInterface* desc) override;\n\n\n\n void OnFailure(const std::string& error) override;\n", "file_path": "src/net/wrtc/Observers.hpp", "rank": 12, "score": 143303.65980911616 }, { "content": "// Set SessionDescription events.\n\nclass SSDO : public webrtc::SetSessionDescriptionObserver {\n\npublic:\n\n // Default constructor.\n\n SSDO(net::WRTCNetworkManager* nm, std::shared_ptr<WRTCSession> wrtcSess) : nm_(nm), wrtcSess_(wrtcSess) {}\n\n\n\n // Successfully set a session description.\n\n void OnSuccess() override;\n\n\n\n // Failure to set a sesion description.\n\n void OnFailure(const std::string& error) override;\n\n\n\n // @see\n\n // github.com/sourcey/libsourcey/blob/master/src/webrtc/include/scy/webrtc/peer.h#L102\n\n // Unimplemented virtual function.\n\n void AddRef() const override { return; }\n\n\n\n // Unimplemented virtual function.\n\n rtc::RefCountReleaseStatus Release() const override {\n\n return rtc::RefCountReleaseStatus::kDroppedLastRef;\n\n }\n", "file_path": "src/net/wrtc/Observers.hpp", "rank": 13, "score": 143303.65980911616 }, { "content": "class Thread;\n\n} // namespace rtc\n\n\n\nnamespace webrtc {\n", "file_path": "src/net/wrtc/WRTCServer.hpp", "rank": 14, "score": 141177.68368162087 }, { "content": "class BasicPortAllocator;\n\n}\n\n\n\nnamespace rtc {\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 15, "score": 138579.95087750282 }, { "content": "class CreateOfferObserver : public webrtc::CreateSessionDescriptionObserver\n\n{\n\nprivate:\n\n PeerConnection* _pc;\n\n\n\npublic:\n\n explicit CreateOfferObserver(PeerConnection* pc) : _pc(pc) {}\n\n virtual ~CreateOfferObserver() override {}\n\n\n\n virtual void OnSuccess(webrtc::SessionDescriptionInterface *sdp) override\n\n {\n\n std::cout << \"CreateOfferObserver::OnSuccess\" << std::endl;\n\n pc1->peerConnection->SetLocalDescription(_pc->setLocalDescriptionObserver, sdp);\n\n pc2->createAnswer(sdp);\n\n }\n\n\n\n virtual void OnFailure(const std::string &msg) override\n\n {\n\n std::cout << \"CreateOfferObserver::OnFailure\" << std::endl;\n\n }\n\n};\n\n\n", "file_path": "scripts/WebrtcTestSimple2Peers.cpp", "rank": 16, "score": 134731.05699981345 }, { "content": "class CreateAnswerObserver : public webrtc::CreateSessionDescriptionObserver\n\n{\n\nprivate:\n\n PeerConnection* _pc;\n\n\n\npublic:\n\n explicit CreateAnswerObserver(PeerConnection* pc) : _pc(pc) {}\n\n virtual ~CreateAnswerObserver() override {}\n\n\n\n virtual void OnSuccess(webrtc::SessionDescriptionInterface *sdp) override\n\n {\n\n std::cout << \"CreateAnswerObserver::OnSuccess\" << std::endl;\n\n _pc->peerConnection->SetLocalDescription(_pc->setLocalDescriptionObserver, sdp);\n\n pc1->peerConnection->SetRemoteDescription(pc1->setRemoteDescriptionObserver, sdp);\n\n }\n\n\n\n virtual void OnFailure(const std::string &msg) override\n\n {\n\n std::cout << \"CreateAnswerObserver::OnFailure\" << std::endl;\n\n }\n", "file_path": "scripts/WebrtcTestSimple2Peers.cpp", "rank": 17, "score": 134731.05699981345 }, { "content": "class SetLocalDescriptionObserver : public webrtc::SetSessionDescriptionObserver\n\n{\n\nprivate:\n\n PeerConnection* _pc;\n\n\n\npublic:\n\n explicit SetLocalDescriptionObserver(PeerConnection* pc) : _pc(pc) {}\n\n virtual ~SetLocalDescriptionObserver() override {}\n\n\n\n virtual void OnSuccess() override\n\n {\n\n std::cout << \"SetLocalDescriptionObserver::OnSuccess\" << std::endl;\n\n }\n\n\n\n virtual void OnFailure(const std::string &msg) override\n\n {\n\n std::cout << \"SetLocalDescriptionObserver::OnFailure\" << std::endl;\n\n }\n\n};\n\n\n", "file_path": "scripts/WebrtcTestSimple2Peers.cpp", "rank": 18, "score": 132194.30350426538 }, { "content": "class WRTCServer : public ConnectionManagerBase<wrtc::SessionGUID> {\n\npublic:\n\n WRTCServer(net::WRTCNetworkManager* nm, const gloer::config::ServerConfig& serverConfig, wrtc::SessionManager& sm);\n\n\n\n ~WRTCServer();\n\n\n\n void prepare(const config::ServerConfig& serverConfig);\n\n\n\n void sendToAll(const std::string& message) override;\n\n\n\n void sendTo(const wrtc::SessionGUID& sessionID, const std::string& message) override;\n\n\n\n void run(const gloer::config::ServerConfig& serverConfig) override\n\n RTC_RUN_ON(thread_checker_);\n\n\n\n void finish() override RTC_RUN_ON(thread_checker_);\n\n\n\n // The thread entry point for the WebRTC thread.\n\n // This creates a worker/signaling/network thread in the background.\n\n void webRtcBackgroundThreadEntry();\n", "file_path": "src/net/wrtc/WRTCServer.hpp", "rank": 19, "score": 130914.47644100167 }, { "content": "class ClientConnectionManager : public ConnectionManagerBase<ws::SessionGUID> {\n\npublic:\n\n ClientConnectionManager(net::WSClientNetworkManager* nm, const gloer::config::ServerConfig& serverConfig, ws::ClientSessionManager& sm);\n\n\n\n // void interpret(size_t id, const std::string& message);\n\n\n\n void sendToAll(const std::string& message) override;\n\n\n\n void sendTo(const ws::SessionGUID& sessionID, const std::string& message) override;\n\n\n\n //void unregisterSession(const ws::SessionGUID& id) override;\n\n\n\n // uint32_t getMaxSessionId() const { return maxSessionId_; }\n\n\n\n // TODO: limit max num of open sessions\n\n // uint32_t maxSessionId_ = 0;\n\n\n\n // TODO: limit max num of open connections per IP\n\n // uint32_t maxConnectionsPerIP_ = 0;\n\n std::shared_ptr<ClientSession> addClientSession(\n", "file_path": "src/net/ws/client/ClientConnectionManager.hpp", "rank": 20, "score": 123706.88719814396 }, { "content": "class ServerConnectionManager : public ConnectionManagerBase<ws::SessionGUID> {\n\npublic:\n\n ServerConnectionManager(net::WSServerNetworkManager* nm, const gloer::config::ServerConfig& serverConfig, ws::ServerSessionManager& sm);\n\n\n\n // void interpret(size_t id, const std::string& message);\n\n\n\n void sendToAll(const std::string& message) override;\n\n\n\n void sendTo(const ws::SessionGUID& sessionID, const std::string& message) override;\n\n\n\n // uint32_t getMaxSessionId() const { return maxSessionId_; }\n\n\n\n // TODO: limit max num of open sessions\n\n // uint32_t maxSessionId_ = 0;\n\n\n\n#if 0\n\n // TODO: limit max num of open connections per IP\n\n // uint32_t maxConnectionsPerIP_ = 0;\n\n std::shared_ptr<ClientSession> addClientSession(\n\n const ws::SessionGUID& newSessId);\n", "file_path": "src/net/ws/server/ServerConnectionManager.hpp", "rank": 21, "score": 123706.88719814396 }, { "content": " friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; }\n", "file_path": "lib/rapidjson/error/error.h", "rank": 22, "score": 122639.58240623365 }, { "content": "class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> {\n\npublic:\n\n typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> Base;\n\n typedef typename Base::Ch Ch;\n\n\n\n //! Constructor\n\n /*! \\param os Output stream.\n\n \\param allocator User supplied allocator. If it is null, it will create a private one.\n\n \\param levelDepth Initial capacity of stack.\n\n */\n\n explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : \n\n Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {}\n\n\n\n\n\n explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : \n\n Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}\n\n\n\n#if RAPIDJSON_HAS_CXX11_RVALUE_REFS\n\n PrettyWriter(PrettyWriter&& rhs) :\n\n Base(std::forward<PrettyWriter>(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {}\n", "file_path": "lib/rapidjson/prettywriter.h", "rank": 23, "score": 118500.81982287666 }, { "content": "class SessionBase {\n\npublic:\n\n typedef std::function<void(const session_type& sessId, const std::string& message)>\n\n on_message_callback;\n\n\n\n typedef std::function<void(const session_type& sessId)> on_close_callback;\n\n\n\n typedef uint32_t metadata_key;\n\n\n\n SessionBase(const session_type& id) : id_(id) {}\n\n\n\n virtual ~SessionBase() {}\n\n\n\n virtual void send(const std::string& ss) = 0;\n\n\n\n virtual session_type getId() const { return id_; }\n\n\n\n virtual bool isExpired() const = 0;\n\n\n\n // virtual void setExpiredCallback(); // TODO\n", "file_path": "src/net/SessionBase.hpp", "rank": 24, "score": 118432.66355775621 }, { "content": "class WRTCSession;\n\n} // namespace wrtc\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\n\n\ntemplate<typename session_type>\n", "file_path": "src/net/SessionBase.hpp", "rank": 25, "score": 118432.66355775621 }, { "content": "class WRTCSession;\n\n} // namespace wrtc\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\n\n", "file_path": "src/net/SessionPair.hpp", "rank": 26, "score": 118432.66355775621 }, { "content": "class SessionGUID {\n\npublic:\n\n SessionGUID() = delete;\n\n\n\n explicit SessionGUID(const std::string& id)\n\n : id_(id) {};\n\n\n\n explicit SessionGUID(const std::string&& id)\n\n : id_(std::move(id)) {};\n\n\n\n ~SessionGUID() {};\n\n\n\n operator std::string() const {\n\n return id_;\n\n };\n\n\n\n operator const std::string&() const {\n\n return id_;\n\n }\n\n\n", "file_path": "src/net/wrtc/SessionGUID.hpp", "rank": 27, "score": 115827.15489889187 }, { "content": "class SessionGUID {\n\npublic:\n\n SessionGUID() = delete;\n\n\n\n explicit SessionGUID(const std::string& id)\n\n : id_(id) {};\n\n\n\n explicit SessionGUID(const std::string&& id)\n\n : id_(std::move(id)) {};\n\n\n\n ~SessionGUID() {};\n\n\n\n operator std::string() const {\n\n return id_;\n\n };\n\n\n\n operator const std::string&() const {\n\n return id_;\n\n }\n\n\n", "file_path": "src/net/ws/SessionGUID.hpp", "rank": 28, "score": 115827.15489889187 }, { "content": "class SessionPair;\n\n\n\nnamespace ws {\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 29, "score": 115827.15489889187 }, { "content": "class ServerSession;\n\n}\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace ws {\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 30, "score": 115827.15489889187 }, { "content": "class SessionGUID;\n\n} // namespace wrtc\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace wrtc {\n\n\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 31, "score": 115827.15489889187 }, { "content": "class WRTCSession;\n\n} // namespace wrtc\n\n\n\nnamespace gloer {\n\nnamespace config {\n", "file_path": "src/net/wrtc/SessionManager.hpp", "rank": 32, "score": 115827.15489889187 }, { "content": "class NetworkManager : public NetworkManagerBase {\n\npublic:\n\n explicit NetworkManager(const gloer::config::ServerConfig& serverConfig)\n\n : sm_(this) {\n\n // NOTE: no 'this' in constructor\n\n sessionRunner_ = std::make_shared<session_runner>(this, serverConfig, sm_);\n\n }\n\n\n\n void prepare(const gloer::config::ServerConfig& serverConfig) override {\n\n RTC_DCHECK(sessionRunner_);\n\n sessionRunner_->prepare(serverConfig);\n\n }\n\n\n\n void run(const gloer::config::ServerConfig& serverConfig) override {\n\n RTC_DCHECK(sessionRunner_);\n\n sessionRunner_->run(serverConfig);\n\n }\n\n\n\n void finish() override {\n\n RTC_DCHECK(sessionRunner_);\n", "file_path": "src/net/NetworkManagerBase.hpp", "rank": 33, "score": 115197.6537943832 }, { "content": "class Timer : public rtc::MessageHandler {\n\npublic:\n\n Timer();\n\n virtual ~Timer();\n\n\n\n void start(int intervalMs, std::function<void()> callback);\n\n void singleShot(int delay, std::function<void()> callback);\n\n bool started() const;\n\n void stop();\n\n\n\nprotected:\n\n virtual void OnMessage(rtc::Message* msg) override;\n\n int _interval;\n\n std::function<void()> _callback;\n\n bool _singleShot{false};\n\n\n\n RTC_DISALLOW_COPY_AND_ASSIGN(Timer);\n\n};\n\n\n\n} // namespace wrtc\n\n} // namespace net\n\n} // namespace gloer\n", "file_path": "src/net/wrtc/Timer.hpp", "rank": 34, "score": 115052.18864340096 }, { "content": "class SessionGUID;\n", "file_path": "src/net/ws/server/ServerSession.hpp", "rank": 35, "score": 113374.88549129017 }, { "content": "class WRTCSession;\n\n} // namespace wrtc\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace ws {\n\n\n\n/**\n\n * A class which represents a single connection\n\n * When this class is destroyed, the connection is closed.\n\n **/\n", "file_path": "src/net/ws/server/ServerSession.hpp", "rank": 36, "score": 113374.88549129017 }, { "content": "class SessionDescriptionInterface;\n\n} // namespace webrtc\n\n\n\nnamespace gloer {\n\nnamespace algo {\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 37, "score": 113374.88549129017 }, { "content": "class ServerSession\n\n : public SessionPair, public std::enable_shared_from_this<ServerSession> {\n\nprivate:\n\n // NOTE: ProducerConsumerQueue must be created with a fixed maximum size\n\n // We use Queue per connection\n\n static const size_t MAX_SENDQUEUE_SIZE = 120;\n\n\n\npublic:\n\n ServerSession() = delete;\n\n\n\n // Take ownership of the socket\n\n explicit ServerSession(boost::asio::ip::tcp::socket&& socket,\n\n ::boost::asio::ssl::context& ctx,\n\n net::WSServerNetworkManager* nm,\n\n const ws::SessionGUID& id);\n\n\n\n ~ServerSession();\n\n\n\n // Start the asynchronous operation\n\n void start_accept();\n", "file_path": "src/net/ws/server/ServerSession.hpp", "rank": 38, "score": 113374.88549129017 }, { "content": "class SessionManagerBase {\n\n // static_assert(!std::is_base_of<SessType, SessionI>::value, \"SessType must inherit from\n\n // SessionI\");\n\n\n\npublic:\n\n typedef std::function<void(const std::shared_ptr<SessType>& sess)> on_new_sess_callback;\n\n\n\n SessionManagerBase() {}\n\n\n\n virtual ~SessionManagerBase() {}\n\n\n\n virtual void SetOnNewSessionHandler(on_new_sess_callback handler) {\n\n onNewSessCallback_ = handler;\n\n }\n\n\n\n virtual void\n\n doToAllSessions(std::function<void(const SessGUID& sessId, std::shared_ptr<SessType>)> func);\n\n\n\n /**\n\n * @brief returns the number of connected clients\n", "file_path": "src/net/SessionManagerBase.hpp", "rank": 39, "score": 113374.88549129017 }, { "content": "class WRTCSession;\n\n} // namespace wrtc\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace ws {\n\n\n\n/**\n\n * A class which represents a single connection\n\n * When this class is destroyed, the connection is closed.\n\n **/\n", "file_path": "src/net/ws/client/ClientSession.hpp", "rank": 40, "score": 113374.88549129017 }, { "content": "// Used to implement RTCDataChannel events.\n\n//\n\n// The code responding to these callbacks should unwind the stack before\n\n// using any other webrtc APIs; re-entrancy is not supported.\n\nclass DCO : public webrtc::DataChannelObserver {\n\npublic:\n\n explicit DCO(net::WRTCNetworkManager* nm, webrtc::DataChannelInterface* channel,\n\n std::shared_ptr<WRTCSession> wrtcSess)\n\n : nm_(nm), channelKeepAlive_(channel), wrtcSess_(wrtcSess) {\n\n // @see\n\n // https://github.com/MonsieurCode/udoo-quad-kitkat/blob/master/external/chromium_org/content/renderer/media/rtc_data_channel_handler.cc\n\n channelKeepAlive_->RegisterObserver(this);\n\n }\n\n\n\n ~DCO() override { channelKeepAlive_->UnregisterObserver(); }\n\n\n\n // Buffered amount change.\n\n void OnBufferedAmountChange(uint64_t /* previous_amount */) override;\n\n\n\n void OnStateChange() override;\n\n\n\n // Message received.\n\n void OnMessage(const webrtc::DataBuffer& buffer) override;\n\n\n", "file_path": "src/net/wrtc/Observers.hpp", "rank": 41, "score": 112747.25455131466 }, { "content": "// PeerConnection events.\n\n// @see\n\n// github.com/sourcey/libsourcey/blob/ce311ff22ca02c8a83df7162a70f6aa4f760a761/doc/api-webrtc.md\n\n// TODO: callbacks\n\n// https://github.com/DoubangoTelecom/webrtc-plugin/blob/b7aaab586cef287dc921cb9a4504be67b0e15d50/ExRTCPeerConnection.h\n\nclass PCO : public webrtc::PeerConnectionObserver {\n\npublic:\n\n PCO(net::WRTCNetworkManager* nm,\n\n std::shared_ptr<gloer::net::SessionPair> wsSession,\n\n const wrtc::SessionGUID& webrtcConnId,\n\n const ws::SessionGUID& wsConnId)\n\n : nm_(nm), wsSession_(wsSession), webrtcConnId_(webrtcConnId), wsConnId_(wsConnId) {}\n\n\n\n // TODO: PeerConnectionId\n\n\n\n // Triggered when a remote peer opens a data channel.\n\n void OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> channel) override;\n\n\n\n // Override ICE candidate.\n\n void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override;\n\n\n\n void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override;\n\n\n\n // Triggered when media is received on a new stream from remote peer.\n\n void OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> /* stream*/) override;\n", "file_path": "src/net/wrtc/Observers.hpp", "rank": 42, "score": 112742.55709095403 }, { "content": "class WSServerManager : public ServerManagerBase {\n\npublic:\n\n WSServerManager(std::weak_ptr<GameClient> game);\n\n\n\n void processIncomingMessages();\n\n\n\n bool handleIncomingJSON(const gloer::net::ws::SessionGUID& sessId, const std::string& message);\n\n\n\n void handleClose(const gloer::net::ws::SessionGUID& sessId);\n\n};\n\n\n\n} // namespace gameclient\n", "file_path": "examples/gameclient/src/WSServerManager.hpp", "rank": 43, "score": 111253.14048402556 }, { "content": "class WSServerManager : public ServerManagerBase {\n\npublic:\n\n WSServerManager(std::weak_ptr<GameServer> game);\n\n\n\n void processIncomingMessages();\n\n\n\n bool handleIncomingJSON(const gloer::net::ws::SessionGUID& sessId, const std::string& message);\n\n\n\n void handleClose(const gloer::net::ws::SessionGUID& sessId);\n\n};\n\n\n\n} // namespace gameserver\n", "file_path": "examples/gameserver/src/WSServerManager.hpp", "rank": 44, "score": 111253.14048402556 }, { "content": "class WRTCServerManager : public ServerManagerBase {\n\npublic:\n\n WRTCServerManager(std::weak_ptr<GameServer> game);\n\n\n\n void processIncomingMessages();\n\n\n\n bool handleIncomingJSON(const gloer::net::wrtc::SessionGUID& sessId, const std::string& message);\n\n\n\n void handleClose(const gloer::net::wrtc::SessionGUID& sessId);\n\n};\n\n\n\n} // namespace gameserver\n", "file_path": "examples/gameserver/src/WRTCServerManager.hpp", "rank": 45, "score": 111253.14048402556 }, { "content": "class WRTCServerManager : public ServerManagerBase {\n\npublic:\n\n WRTCServerManager(std::weak_ptr<GameClient> game);\n\n\n\n void processIncomingMessages();\n\n\n\n bool handleIncomingJSON(const gloer::net::wrtc::SessionGUID& sessId, const std::string& message);\n\n\n\n void handleClose(const gloer::net::wrtc::SessionGUID& sessId);\n\n};\n\n\n\n} // namespace gameclient\n", "file_path": "examples/gameclient/src/WRTCServerManager.hpp", "rank": 46, "score": 111253.14048402556 }, { "content": "class GenericDocument : public GenericValue<Encoding, Allocator> {\n\npublic:\n\n typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.\n\n typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document.\n\n typedef Allocator AllocatorType; //!< Allocator type from template parameter.\n\n\n\n //! Constructor\n\n /*! Creates an empty document of specified type.\n\n \\param type Mandatory type of object to create.\n\n \\param allocator Optional allocator for allocating memory.\n\n \\param stackCapacity Optional initial capacity of stack in bytes.\n\n \\param stackAllocator Optional allocator for allocating memory for stack.\n\n */\n\n explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :\n\n GenericValue<Encoding, Allocator>(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()\n\n {\n\n if (!allocator_)\n\n ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();\n\n }\n\n\n", "file_path": "lib/rapidjson/document.h", "rank": 47, "score": 111235.60808458918 }, { "content": "class SessionGUID;\n\n} // namespace ws\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace config {\n", "file_path": "src/net/ws/server/ServerSessionManager.hpp", "rank": 48, "score": 111062.24292324274 }, { "content": "class ClientSession;\n", "file_path": "src/net/ws/client/ClientSessionManager.hpp", "rank": 49, "score": 111062.24292324274 }, { "content": "class SessionPair;\n\n} // namespace config\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace ws {\n\n\n\n/**\n\n * @brief manages currently valid sessions\n\n */\n", "file_path": "src/net/ws/client/ClientSessionManager.hpp", "rank": 50, "score": 111062.24292324274 }, { "content": "class SessionGUID;\n\n} // namespace ws\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace config {\n", "file_path": "src/net/ws/client/ClientSessionManager.hpp", "rank": 51, "score": 111062.24292324274 }, { "content": "class SessionPair;\n\n} // namespace config\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace ws {\n\n\n\n/**\n\n * @brief manages currently valid sessions\n\n */\n", "file_path": "src/net/ws/server/ServerSessionManager.hpp", "rank": 52, "score": 111062.24292324274 }, { "content": "class FileReadStream;\n\n\n\n// filewritestream.h\n\n\n", "file_path": "lib/rapidjson/fwd.h", "rank": 53, "score": 111018.0945623514 }, { "content": "class FileReadStream {\n\npublic:\n\n typedef char Ch; //!< Character type (byte).\n\n\n\n //! Constructor.\n\n /*!\n\n \\param fp File pointer opened for read.\n\n \\param buffer user-supplied buffer.\n\n \\param bufferSize size of buffer in bytes. Must >=4 bytes.\n\n */\n\n FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { \n\n RAPIDJSON_ASSERT(fp_ != 0);\n\n RAPIDJSON_ASSERT(bufferSize >= 4);\n\n Read();\n\n }\n\n\n\n Ch Peek() const { return *current_; }\n\n Ch Take() { Ch c = *current_; Read(); return c; }\n\n size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); }\n\n\n", "file_path": "lib/rapidjson/filereadstream.h", "rank": 54, "score": 111018.0945623514 }, { "content": "class FileWriteStream {\n\npublic:\n\n typedef char Ch; //!< Character type. Only support char.\n\n\n\n FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { \n\n RAPIDJSON_ASSERT(fp_ != 0);\n\n }\n\n\n\n void Put(char c) { \n\n if (current_ >= bufferEnd_)\n\n Flush();\n\n\n\n *current_++ = c;\n\n }\n\n\n\n void PutN(char c, size_t n) {\n\n size_t avail = static_cast<size_t>(bufferEnd_ - current_);\n\n while (n > avail) {\n\n std::memset(current_, c, avail);\n\n current_ += avail;\n", "file_path": "lib/rapidjson/filewritestream.h", "rank": 55, "score": 111010.9602288708 }, { "content": "class FileWriteStream;\n\n\n\n// memorybuffer.h\n\n\n\ntemplate <typename Allocator>\n", "file_path": "lib/rapidjson/fwd.h", "rank": 56, "score": 111010.9602288708 }, { "content": "class MemoryPoolAllocator;\n\n\n\n// stream.h\n\n\n\ntemplate <typename Encoding>\n", "file_path": "lib/rapidjson/fwd.h", "rank": 57, "score": 111004.003981132 }, { "content": "class MemoryPoolAllocator {\n\npublic:\n\n static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)\n\n\n\n //! Constructor with chunkSize.\n\n /*! \\param chunkSize The size of memory chunk. The default is kDefaultChunkSize.\n\n \\param baseAllocator The allocator for allocating memory chunks.\n\n */\n\n MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : \n\n chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)\n\n {\n\n }\n\n\n\n //! Constructor with user-supplied buffer.\n\n /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.\n\n\n\n The user buffer will not be deallocated when this allocator is destructed.\n\n\n\n \\param buffer User supplied buffer.\n\n \\param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).\n", "file_path": "lib/rapidjson/allocators.h", "rank": 58, "score": 111004.003981132 }, { "content": "class GenericStringBuffer {\n\npublic:\n\n typedef typename Encoding::Ch Ch;\n\n\n\n GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}\n\n\n\n#if RAPIDJSON_HAS_CXX11_RVALUE_REFS\n\n GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {}\n\n GenericStringBuffer& operator=(GenericStringBuffer&& rhs) {\n\n if (&rhs != this)\n\n stack_ = std::move(rhs.stack_);\n\n return *this;\n\n }\n\n#endif\n\n\n\n void Put(Ch c) { *stack_.template Push<Ch>() = c; }\n\n void PutUnsafe(Ch c) { *stack_.template PushUnsafe<Ch>() = c; }\n\n void Flush() {}\n\n\n\n void Clear() { stack_.Clear(); }\n", "file_path": "lib/rapidjson/stringbuffer.h", "rank": 59, "score": 110993.64592341284 }, { "content": "class GenericStringBuffer;\n\n\n\ntypedef GenericStringBuffer<UTF8<char>, CrtAllocator> StringBuffer;\n\n\n\n// filereadstream.h\n\n\n", "file_path": "lib/rapidjson/fwd.h", "rank": 60, "score": 110993.64592341284 }, { "content": "class AutoUTFOutputStream {\n\n RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);\n\npublic:\n\n typedef CharType Ch;\n\n\n\n //! Constructor.\n\n /*!\n\n \\param os output stream to be wrapped.\n\n \\param type UTF encoding type.\n\n \\param putBOM Whether to write BOM at the beginning of the stream.\n\n */\n\n AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) {\n\n RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);\n\n\n\n // Runtime check whether the size of character type is sufficient. It only perform checks with assertion.\n\n if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);\n\n if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);\n\n\n\n static const PutFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Put) };\n\n putFunc_ = f[type_];\n", "file_path": "lib/rapidjson/encodedstream.h", "rank": 61, "score": 107948.03978555115 }, { "content": "class AutoUTFInputStream {\n\n RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);\n\npublic:\n\n typedef CharType Ch;\n\n\n\n //! Constructor.\n\n /*!\n\n \\param is input stream to be wrapped.\n\n \\param type UTF encoding type if it is not detected from the stream.\n\n */\n\n AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) {\n\n RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE); \n\n DetectType();\n\n static const TakeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Take) };\n\n takeFunc_ = f[type_];\n\n current_ = takeFunc_(*is_);\n\n }\n\n\n\n UTFType GetType() const { return type_; }\n\n bool HasBOM() const { return hasBOM_; }\n", "file_path": "lib/rapidjson/encodedstream.h", "rank": 62, "score": 107948.03978555115 }, { "content": "class ServerSession;\n\n}\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace wrtc {\n", "file_path": "src/net/wrtc/Callbacks.hpp", "rank": 63, "score": 106822.41491805977 }, { "content": "class SessionPair;\n\n\n\nnamespace ws {\n", "file_path": "src/net/wrtc/Callbacks.hpp", "rank": 64, "score": 106822.41491805977 }, { "content": "class WRTCSession;\n\n} // namespace wrtc\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace wrtc {\n\n\n\n// class NetworkManager; // TODO\n\n\n", "file_path": "src/net/wrtc/Observers.hpp", "rank": 65, "score": 106822.41491805977 }, { "content": "class DCO;\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 66, "score": 106822.41491805977 }, { "content": "class SSDO;\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 67, "score": 106822.41491805977 }, { "content": "class WRTCSession;\n", "file_path": "src/net/wrtc/Callbacks.hpp", "rank": 68, "score": 106822.41491805977 }, { "content": "class SessionPair;\n\n\n\n//class net::WRTCNetworkManager;\n\n\n\nnamespace wrtc {\n", "file_path": "src/net/wrtc/Observers.hpp", "rank": 69, "score": 106822.41491805977 }, { "content": "class CSDO;\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 70, "score": 106822.41491805977 }, { "content": "class DispatchQueue;\n\n} // namespace algo\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace wrtc {\n", "file_path": "src/net/SessionBase.hpp", "rank": 71, "score": 106822.41491805977 }, { "content": "class WRTCServer;\n", "file_path": "src/net/SessionBase.hpp", "rank": 72, "score": 106822.41491805977 }, { "content": "class PCO;\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 73, "score": 106822.41491805977 }, { "content": "class PeerConnectionObserver : public webrtc::PeerConnectionObserver\n\n{\n\nprivate:\n\n PeerConnection* _pc;\n\n\n\npublic:\n\n explicit PeerConnectionObserver(PeerConnection* pc) : _pc(pc) {}\n\n virtual ~PeerConnectionObserver(){};\n\n\n\n virtual void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override\n\n {\n\n std::cout << \"PeerConnectionObserver::OnSignalingChange\" << std::endl;\n\n }\n\n virtual void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override\n\n {\n\n std::cout << \"PeerConnectionObserver::OnIceConnectionChange \" << static_cast<int>(new_state) << std::endl;\n\n switch (new_state)\n\n {\n\n case webrtc::PeerConnectionInterface::kIceConnectionNew:\n\n break;\n", "file_path": "scripts/WebrtcTestSimple2Peers.cpp", "rank": 74, "score": 106633.67720237812 }, { "content": "class DataChannelObserver : public webrtc::DataChannelObserver\n\n{\n\nprivate:\n\n PeerConnection* _pc;\n\n\n\n public:\n\n explicit DataChannelObserver(PeerConnection* pc) : _pc(pc) {}\n\n virtual ~DataChannelObserver() override {}\n\n\n\n virtual void OnStateChange() override\n\n {\n\n std::cout << \"DataChannelObserver::OnStateChange\" << std::endl;\n\n if (_pc->dataChannel->state() == webrtc::DataChannelInterface::kOpen)\n\n {\n\n checkDatachannels();\n\n }\n\n }\n\n\n\n virtual void OnMessage(const webrtc::DataBuffer& buffer) override\n\n {\n\n std::cout << \"DataChannelObserver::OnMessage\" << std::endl;\n\n }\n\n};\n\n\n", "file_path": "scripts/WebrtcTestSimple2Peers.cpp", "rank": 75, "score": 106633.67720237812 }, { "content": "class WRTCSession;\n\n\n", "file_path": "src/net/wrtc/WRTCServer.hpp", "rank": 76, "score": 104013.72804898313 }, { "content": "class ServerSession;\n\n}\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\nnamespace wrtc {\n", "file_path": "src/net/wrtc/WRTCServer.hpp", "rank": 77, "score": 104013.72804898313 }, { "content": "class SessionDescriptionInterface;\n\n} // namespace webrtc\n\n\n\nnamespace gloer {\n\nnamespace algo {\n", "file_path": "src/net/wrtc/Callbacks.hpp", "rank": 78, "score": 104013.72804898313 }, { "content": "class SessionPair;\n\n\n\nnamespace ws {\n", "file_path": "src/net/wrtc/WRTCServer.hpp", "rank": 79, "score": 104013.72804898313 }, { "content": "class DispatchQueue;\n\n} // namespace algo\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\n\n\n//class net::WRTCNetworkManager;\n\n\n\n//template<typename session_type>\n\n//class SessionBase;\n\n\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 80, "score": 104013.72804898313 }, { "content": "class SessionManager;\n", "file_path": "src/net/NetworkManagerBase.hpp", "rank": 81, "score": 104013.72804898313 }, { "content": "// Callback for when we receive a message from the server via the WebSocket.\n\nfunction onWebSocketMessage(event) {\n\n console.log(\"onWebSocketMessage\")\n\n let messageObject = \"\";\n\n try {\n\n messageObject = JSON.parse(event.data);\n\n } catch(e) {\n\n messageObject = event.data;\n\n }\n\n console.log(\"onWebSocketMessage type =\", messageObject.type, \";event.data= \", event.data)\n\n if (messageObject.type === WS_PING_OPCODE) {\n\n const key = messageObject.payload;\n\n pingLatency[key] = performance.now() - pingTimes[key];\n\n } else if (messageObject.type === WS_ANSWER_OPCODE) {\n\n rtcPeerConnection.setRemoteDescription(new RTCSessionDescription(messageObject.payload));\n\n } else if (messageObject.type === WS_CANDIDATE_OPCODE) {\n\n rtcPeerConnection.addIceCandidate(new RTCIceCandidate(messageObject.payload));\n\n } else {\n\n console.log('Unrecognized WebSocket message type.', messageObject);\n\n }\n\n}\n", "file_path": "examples/gameclient/src/main.cpp", "rank": 82, "score": 103714.89343125507 }, { "content": "class Listener;\n", "file_path": "src/net/ws/server/ServerConnectionManager.hpp", "rank": 83, "score": 102369.95641814674 }, { "content": "class DispatchQueue;\n\n} // namespace algo\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\n\n\n//class NetworkManager;\n\n\n\nnamespace ws {\n", "file_path": "src/net/ws/client/ClientSession.hpp", "rank": 84, "score": 101400.09648229317 }, { "content": "class SessionDescriptionInterface;\n\n} // namespace webrtc\n\n\n\nnamespace gloer {\n\nnamespace algo {\n", "file_path": "src/net/wrtc/WRTCServer.hpp", "rank": 85, "score": 101400.09648229317 }, { "content": "class WSServer;\n\n}\n\n\n\nnamespace wrtc {\n", "file_path": "src/net/ws/server/ServerSession.hpp", "rank": 86, "score": 101400.09648229317 }, { "content": "class IceCandidateInterface;\n\n} // namespace webrtc\n\n\n\nnamespace webrtc {\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 87, "score": 101400.09648229317 }, { "content": "class ServerSessionManager;\n", "file_path": "src/net/NetworkManagerBase.hpp", "rank": 88, "score": 101400.09648229317 }, { "content": "class WRTCServer;\n", "file_path": "src/net/ws/server/ServerSession.hpp", "rank": 89, "score": 101400.09648229317 }, { "content": "class ClientSessionManager;\n", "file_path": "src/net/NetworkManagerBase.hpp", "rank": 90, "score": 101400.09648229317 }, { "content": "class PeerConnectivityChecker;\n\n\n\n/**\n\n * A class which represents a single connection\n\n * When this class is destroyed, the connection is closed.\n\n **/\n", "file_path": "src/net/wrtc/WRTCSession.hpp", "rank": 91, "score": 101400.09648229317 }, { "content": "class WRTCServer;\n", "file_path": "src/net/ws/client/ClientSession.hpp", "rank": 92, "score": 101400.09648229317 }, { "content": "class SessionGUID;\n\n} // namespace wrtc\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gameclient {\n\n\n\nusing namespace ::gloer::algo;\n\n\n", "file_path": "examples/gameclient/src/WRTCServerManager.hpp", "rank": 93, "score": 101400.09648229317 }, { "content": "class SessionGUID;\n\n} // namespace ws\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gameserver {\n\n\n", "file_path": "examples/gameserver/src/WSServerManager.hpp", "rank": 94, "score": 101400.09648229317 }, { "content": "class SessionGUID;\n\n} // namespace ws\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gameclient {\n\n\n", "file_path": "examples/gameclient/src/WSServerManager.hpp", "rank": 95, "score": 101400.09648229317 }, { "content": "class DispatchQueue;\n\n} // namespace algo\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace net {\n\n\n\n//class NetworkManager;\n\n\n\nnamespace ws {\n", "file_path": "src/net/ws/server/ServerSession.hpp", "rank": 96, "score": 101400.09648229317 }, { "content": "class ClientSession;\n\n} // namespace ws\n\n\n\n} // namespace net\n\n} // namespace gloer\n\n\n\nnamespace gloer {\n\nnamespace config {\n", "file_path": "src/net/ws/WsNetworkOperation.hpp", "rank": 97, "score": 101400.09648229317 }, { "content": "class ServerSession;\n", "file_path": "src/net/ws/WsNetworkOperation.hpp", "rank": 98, "score": 101400.09648229317 } ]
C++
Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/016.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
#include <iostream> #include <iomanip> using namespace std; int main() { const int MONTHS = 12; float starting_balance, annual_interest_rate, amount_deposited, amount_withdrawn, interest_rate, monthly_interest_rate, balance, total_deposits, total_withdrawn, total_interest_earned; int months_since_established; cout << "\nEnter annual interest rate: "; while (!(cin >> annual_interest_rate)) { cout << "Error: a number must be entered... "; cin.clear(); cin.ignore(123, '\n'); } cout << "Enter starting balance: "; while (!(cin >> starting_balance)) { cout << "Error: a number must be entered... "; cin.clear(); cin.ignore(123, '\n'); } balance = starting_balance; cout << "Enter # of months passed since account was established: "; while (!(cin >> months_since_established)) { cout << "Error: a number must be entered... "; cin.clear(); cin.ignore(123, '\n'); } monthly_interest_rate = annual_interest_rate / MONTHS; for (int i = 0; i < months_since_established; i++) { cout << "Enter the amount deposited for month " << (i + 1) << ": "; while (!(cin >> amount_deposited) || amount_deposited < 0) { cout << "Error: a positive number must be entered." << endl; cout << "Enter the amount deposited for month " << (i + 1) << ": "; cin.clear(); cin.ignore(123, '\n'); } total_deposits += amount_deposited; balance += amount_deposited; if (balance < 0) break; cout << "Enter the amount withdrawn for month " << (i + 1) << ": "; while (!(cin >> amount_withdrawn) || amount_withdrawn < 0) { cout << "Error: a positive number must be entered." << endl; cout << "Enter the amount withdrawn for month " << (i + 1) << ": "; cin.clear(); cin.ignore(123, '\n'); } total_withdrawn += amount_withdrawn; balance -= amount_withdrawn; if (balance < 0) break; interest_rate = (monthly_interest_rate * balance); balance += interest_rate; if (balance < 0) break; total_interest_earned += (interest_rate); } if (balance < 0) { cout << "I'm sorry, your account has been closed" << endl; cout << "due to having a negative balance." << endl; } else { cout << setprecision(2) << fixed << endl; cout << "Starting balance = $" << starting_balance << endl; cout << "Ending balance = $" << balance << endl; cout << "Total amount in deposits = $" << total_deposits << endl; cout << "Total amount in withdrawals = $" << total_withdrawn << endl; cout << "Total interest earned = $" << total_interest_earned; cout << endl << endl; } return 0; }
#include <iostream> #include <iomanip> using namespace std; int main() { const int MONTHS = 12; float starting_balance, annual_interest_rate, amount_deposited, amount_withdrawn, interest_rate, monthly_interest_rate, balance, total_deposits, total_withdrawn, total_interest_earned; int months_since_established; cout << "\nEnter annual interest rate: "; while (!(cin >> annual_interest_rate)) { cout << "Error: a number must be entered... "; cin.clear(); cin.ignore(123, '\n'); } cout << "Enter starting balance: "; while (!(cin >> starting_balance)) { cout << "Error: a number must be entered... "; cin.clear(); cin.ignore(123, '\n'); } balance = starting_balance; cout << "Enter # of months passed since account was established: "; while (!(cin >> months_since_established)) { cout << "Error: a number must be entered... "; cin.clear(); cin.ignore(123, '\n'); } monthly_interest_rate = annual_interest_rate / MONTHS; for (int i = 0; i < months_since_established; i++) { cout << "Enter the amount deposited for month " << (i + 1) << ": "; while (!(cin >> amount_deposited) || amount_deposited < 0) { cout << "Error: a positive number must be entered." << endl; cout << "Enter the amount deposited for month " << (i + 1) << ": "; cin.clear(); cin.ignore(123, '\n'); } total_deposits += amount_deposited; balance += amount_deposited; if (balance < 0) break; cout << "Enter the amount withdrawn for month " << (i + 1) << ": "; while (!(cin >> amount_withdrawn) || amount_withdrawn < 0) { cout << "Error: a positive number must be entered." << endl; cout << "Enter the amount withdrawn for month " << (i + 1) << ": "; cin.clear(); cin.ignore(123, '\n'); } total_withdrawn += amount_withdrawn; balance -= amount_withdrawn; if (balance < 0) break; interest_rate = (monthly_interest_rate * balance);
balance += interest_rate; if (balance < 0) break; total_interest_earned += (interest_rate); } if (balance < 0) { cout << "I'm sorry, your account has been closed" << endl; cout << "due to having a negative balance." << endl; } else { cout << setprecision(2) << fixed << endl; cout << "Starting balance = $" << starting_balance << endl; cout << "Ending balance = $" << balance << endl; cout << "Total amount in deposits = $" << total_deposits << endl; cout << "Total amount in withdrawals = $" << total_withdrawn << endl; cout << "Total interest earned = $" << total_interest_earned; cout << endl << endl; } return 0; }
function_block-function_prefix_line
[ { "content": "//********************************************************************\n\n// This program displays a list of numbers and\n\n// their squares.\n\n//\n\n// JESUS HILARIO HERNANDEZ\n\n// Last updated: October 5, 2016\n\n//\n\n//********************************************************************\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n /* Using a while loop */\n\n\n\n const int MIN_NUMBER = 1, // Strating number to square\n\n MAX_NUMBER = 10; // Maximum number to square\n\n\n\n int num = MIN_NUMBER; // Counter\n", "file_path": "Loops/list-of-squared-numbers-using-while-and-for-loops.cpp", "rank": 0, "score": 101163.78800454728 }, { "content": "\n\n cout << \"Number Number Squared\\n\";\n\n cout << \"-------------------------\\n\";\n\n while (num <= MAX_NUMBER)\n\n {\n\n cout << num << \"\\t\\t\" << (num * num) << endl;\n\n num++; //Increment the counter.\n\n }\n\n\n\n /* Using a for loop */\n\n\n\n cout << \"\\nNumber Number Squared\\n\";\n\n cout << \"-------------------------\\n\";\n\n for (num = MIN_NUMBER; num <= MAX_NUMBER; num++)\n\n {\n\n\n\n cout << num << \"\\t\\t\" << (num * num) << endl;\n\n }\n\n\n\n\n\n return 0;\n\n}\n", "file_path": "Loops/list-of-squared-numbers-using-while-and-for-loops.cpp", "rank": 1, "score": 101142.78976413608 }, { "content": "class Account\n\n{\n\nprivate:\n\n double balance; // Account balance\n\n double interestRate; // Interest rate for the period\n\n double interest; // Interest earned for the period\n\n int transactions; // Number of transactions\n\npublic:\n\n Account(double iRate = 0.045, double bal = 0)\n\n { balance = bal; \n\n interestRate = iRate; \n\n interest = 0;\n\n transactions = 0; }\n\n\n\n void setInterestRate(double iRate)\n\n { interestRate = iRate; }\n\n \n\n void makeDeposit(double amount)\n\n { balance += amount; transactions++; }\n\n \n", "file_path": "SourceCode/chapter 13/Account.h", "rank": 2, "score": 92508.12440563596 }, { "content": "using namespace std;\n\n\n\n// Functions prototypes\n\nvoid doubleArray(int[], int);\n\nvoid showValues(int[], int);\n\n\n\nint main()\n\n{\n\n const int ARRAY_SIZE = 7;\n\n int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7};\n\n\n\n // Display the initial values.\n\n cout << \"The array's values are:\\n\";\n\n showValues(set, ARRAY_SIZE);\n\n\n\n // Double the values in the array within function only.\n\n cout << \"Changed array contents within doubleArray function:\";\n\n doubleArray(set, ARRAY_SIZE);\n\n\n\n // Display the resulting values.\n", "file_path": "Chapter-7-Arrays/7.8-arrays-as-function-arguments/Examples/using-const-array-parameters.cpp", "rank": 3, "score": 91660.63481321014 }, { "content": " cout << \"After calling doubleArray, the values\\n\"\n\n << \"stay the same as initialized in int main():\\n\";\n\n showValues(set, ARRAY_SIZE);\n\n\n\n // Display the resulting values.\n\n cout << \"Calling doubleArray again:\\n\";\n\n doubleArray(set, ARRAY_SIZE);\n\n\n\n cout << \"The array's values in int main remain the same:\\n\";\n\n showValues(set, ARRAY_SIZE);\n\n\n\n return 0;\n\n}\n\n\n\n//***************************************************\n\n// Definition of function doubleArray *\n\n// This function doubles the value of each element *\n\n// in the array passed into nums. The value passed *\n\n// into size is the number of elements in the array.*\n\n//***************************************************\n", "file_path": "Chapter-7-Arrays/7.8-arrays-as-function-arguments/Examples/using-const-array-parameters.cpp", "rank": 4, "score": 91659.26070013118 }, { "content": "//*********************************************************************\n\n// This program uses a function to double the value of each\n\n// element of an array within a function. However, the contents in\n\n// the array cannot be changed because of the const int keyword\n\n// parameter within the function header. Further, this program WILL NOT!!!\n\n// run. A compiler error will occur because the of use of the const keyword\n\n// ...the const keyword makes the array readable only and cannot be changed.\n\n//\n\n// When compiled, this error will occur.\n\n//\n\n// (\n\n// read-only variable is not assignable\n\n// nums[index] *= 2;\n\n// ~~~~~~~~~~~ ^\n\n// )\n\n//\n\n// By: JESUS HILARIO HERNANDEZ\n\n// Last Updated: May 5th, 2017\n\n//*********************************************************************\n\n#include <iostream>\n", "file_path": "Chapter-7-Arrays/7.8-arrays-as-function-arguments/Examples/using-const-array-parameters.cpp", "rank": 5, "score": 91656.85211818152 }, { "content": "\n\nvoid doubleArray(const int nums[], int size)\n\n{\n\n for (int index = 0; index < size; index++)\n\n {\n\n nums[index] *= 2;\n\n cout << nums[index] << \" \";\n\n }\n\n}\n\n\n\n//***************************************************\n\n// Definition of function showValues. *\n\n// This function accepts an array of integers and *\n\n// the array's size as its arguments. The contents *\n\n// of the array displayed. *\n\n//***************************************************\n\n\n\nvoid showValues(const int nums[], int size)\n\n{\n\n for (int index = 0; index < size; index++)\n\n {\n\n cout << nums[index] << \" \";\n\n }\n\n cout << endl;\n\n}\n", "file_path": "Chapter-7-Arrays/7.8-arrays-as-function-arguments/Examples/using-const-array-parameters.cpp", "rank": 6, "score": 91647.48546743557 }, { "content": "class PassFailExam : public PassFailActivity\n\n{\n\nprivate:\n\n int numQuestions; // Number of questions\n\n double pointsEach; // Points for each question\n\n int numMissed; // Number of questions missed\n\npublic:\n\n // Default constructor\n\n PassFailExam() : PassFailActivity()\n\n { numQuestions = 0;\n\n pointsEach = 0.0;\n\n numMissed = 0; }\n\n \n\n // Constructor\n\n PassFailExam(int questions, int missed, double mps) :\n\n PassFailActivity(mps)\n\n { set(questions, missed); }\n\n\n\n // Mutator function\n\n void set(int, int); // Defined in PassFailExam.cpp\n", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailExam.h", "rank": 7, "score": 66167.90517008747 }, { "content": "class NumberList\n\n{\n\nprivate:\n\n // Declare a structure for the list\n\n struct ListNode\n\n {\n\n double value;\n\n struct ListNode *next;\n\n }; \n\n\n\n ListNode *head; // List head pointer\n\n \n\n // Private member functions\n\n int countNodes(ListNode *) const;\n\n void showReverse(ListNode *) const;\n\n \n\npublic:\n\n // Constructor\n\n NumberList()\n\n { head = nullptr; }\n", "file_path": "SourceCode/Chapter 19/NumberList.h", "rank": 8, "score": 62931.84337097599 }, { "content": "class NumberList\n\n{\n\nprivate:\n\n // Declare a structure for the list\n\n struct ListNode\n\n {\n\n double value; // The value in this node\n\n struct ListNode *next; // To point to the next node\n\n }; \n\n\n\n ListNode *head; // List head pointer\n\n\n\npublic:\n\n // Constructor\n\n NumberList()\n\n { head = nullptr; }\n\n \n\n // Destructor\n\n ~NumberList();\n\n \n\n // Linked list operations\n\n void appendNode(double);\n\n void insertNode(double);\n\n void deleteNode(double);\n\n void displayList() const;\n\n};\n\n#endif", "file_path": "SourceCode/Chapter 17/NumberList.h", "rank": 9, "score": 62931.84337097599 }, { "content": "class IntArray\n\n{\n\nprivate:\n\n int *aptr; // Pointer to the array\n\n int arraySize; // Holds the array size\n\n void subscriptError(); // Handles invalid subscripts\n\npublic:\n\n IntArray(int); // Constructor\n\n IntArray(const IntArray &); // Copy constructor\n\n ~IntArray(); // Destructor\n\n \n\n int size() const // Returns the array size\n\n { return arraySize; }\n\n\n\n int &operator[](const int &); // Overloaded [] operator\n\n};\n\n#endif", "file_path": "SourceCode/chapter 14/IntArray.h", "rank": 10, "score": 62864.55609533806 }, { "content": "class IntQueue\n\n{\n\nprivate:\n\n int *queueArray; // Points to the queue array\n\n int queueSize; // The queue size\n\n int front; // Subscript of the queue front\n\n int rear; // Subscript of the queue rear\n\n int numItems; // Number of items in the queue\n\npublic:\n\n // Constructor\n\n IntQueue(int);\n\n \n\n // Copy constructor\n\n IntQueue(const IntQueue &);\n\n \n\n // Destructor\n\n ~IntQueue();\n\n\n\n // Queue operations\n\n void enqueue(int);\n\n void dequeue(int &);\n\n bool isEmpty() const;\n\n bool isFull() const;\n\n void clear();\n\n};\n\n#endif", "file_path": "SourceCode/Chapter 18/IntQueue.h", "rank": 11, "score": 62864.55609533806 }, { "content": "class IntStack\n\n{\n\nprivate:\n\n int *stackArray; // Pointer to the stack array\n\n int stackSize; // The stack size\n\n int top; // Indicates the top of the stack\n\n\n\npublic:\n\n // Constructor\n\n IntStack(int);\n\n\n\n // Copy constructor\n\n IntStack(const IntStack &);\n\n\n\n // Destructor\n\n ~IntStack();\n\n \n\n // Stack operations\n\n void push(int);\n\n void pop(int &);\n\n bool isFull() const;\n\n bool isEmpty() const;\n\n}; \n\n#endif ", "file_path": "SourceCode/Chapter 18/IntStack.h", "rank": 12, "score": 62864.55609533806 }, { "content": "class PassFailActivity : public GradedActivity\n\n{\n\nprotected:\n\n double minPassingScore; // Minimum passing score.\n\npublic:\n\n // Default constructor\n\n PassFailActivity() : GradedActivity()\n\n { minPassingScore = 0.0; }\n\n \n\n // Constructor\n\n PassFailActivity(double mps) : GradedActivity()\n\n { minPassingScore = mps; }\n\n\n\n // Mutator\n\n void setMinPassingScore(double mps)\n\n { minPassingScore = mps; }\n\n\n\n // Accessors\n\n double getMinPassingScore() const\n\n { return minPassingScore; }\n\n \n\n char getLetterGrade() const;\n\n};\n\n#endif", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailActivity.h", "rank": 13, "score": 62617.73250091079 }, { "content": "class PassFailExam : public PassFailActivity\n\n{\n\nprivate:\n\n int numQuestions; // Number of questions\n\n double pointsEach; // Points for each question\n\n int numMissed; // Number of questions missed\n\npublic:\n\n // Default constructor\n\n PassFailExam() : PassFailActivity()\n\n { numQuestions = 0;\n\n pointsEach = 0.0;\n\n numMissed = 0; }\n\n \n\n // Constructor\n\n PassFailExam(int questions, int missed, double mps) :\n\n PassFailActivity(mps)\n\n { set(questions, missed); }\n\n\n\n // Mutator function\n\n void set(int, int); // Defined in PassFailExam.cpp\n", "file_path": "SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h", "rank": 14, "score": 61953.910533744114 }, { "content": "#ifndef PASSFAILEXAM_H\n\n#define PASSFAILEXAM_H\n\n#include \"PassFailActivity.h\"\n\n\n", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailExam.h", "rank": 15, "score": 60985.6083656535 }, { "content": "#ifndef PASSFAILACTIVITY_H\n\n#define PASSFAILACTIVITY_H\n\n#include \"GradedActivity.h\"\n\n\n", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailActivity.h", "rank": 16, "score": 60980.05042395438 }, { "content": "\n\n // Accessor functions\n\n double getNumQuestions() const\n\n { return numQuestions; }\n\n \n\n double getPointsEach() const\n\n { return pointsEach; }\n\n \n\n int getNumMissed() const\n\n { return numMissed; }\n\n};\n\n#endif ", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailExam.h", "rank": 17, "score": 60979.26948487643 }, { "content": "class DynIntStack\n\n{\n\nprivate:\n\n // Structure for stack nodes\n\n struct StackNode\n\n {\n\n int value; // Value in the node\n\n StackNode *next; // Pointer to the next node\n\n };\n\n\n\n StackNode *top; // Pointer to the stack top\n\n\n\npublic:\n\n // Constructor\n\n DynIntStack()\n\n { top = nullptr; }\n\n\n\n // Destructor\n\n ~DynIntStack();\n\n\n\n // Stack operations\n\n void push(int);\n\n void pop(int &);\n\n bool isEmpty();\n\n}; \n\n#endif", "file_path": "SourceCode/Chapter 18/DynIntStack.h", "rank": 18, "score": 60896.842515931494 }, { "content": "class IntBinaryTree\n\n{\n\nprivate:\n\n struct TreeNode\n\n {\n\n int value; // The value in the node\n\n TreeNode *left; // Pointer to left child node\n\n TreeNode *right; // Pointer to right child node\n\n };\n\n\n\n TreeNode *root; // Pointer to the root node\n\n \n\n // Private member functions\n\n void insert(TreeNode *&, TreeNode *&);\n\n void destroySubTree(TreeNode *);\n\n void deleteNode(int, TreeNode *&);\n\n void makeDeletion(TreeNode *&);\n\n void displayInOrder(TreeNode *) const;\n\n void displayPreOrder(TreeNode *) const;\n\n void displayPostOrder(TreeNode *) const;\n", "file_path": "SourceCode/Chapter 20/IntBinaryTree.h", "rank": 19, "score": 60896.842515931494 }, { "content": "class DynIntQueue\n\n{\n\nprivate:\n\n // Structure for the queue nodes\n\n struct QueueNode\n\n {\n\n int value; // Value in a node\n\n QueueNode *next; // Pointer to the next node\n\n };\n\n\n\n QueueNode *front; // The front of the queue\n\n QueueNode *rear; // The rear of the queue\n\n int numItems; // Number of items in the queue\n\npublic:\n\n // Constructor\n\n DynIntQueue();\n\n\n\n // Destructor\n\n ~DynIntQueue();\n\n\n\n // Queue operations\n\n void enqueue(int);\n\n void dequeue(int &);\n\n bool isEmpty() const;\n\n bool isFull() const;\n\n void clear();\n\n};\n\n#endif", "file_path": "SourceCode/Chapter 18/DynIntQueue.h", "rank": 20, "score": 60896.842515931494 }, { "content": "#include \"PassFailExam.h\"\n\n\n\n//********************************************************\n\n// set function *\n\n// The parameters are the number of questions and the *\n\n// number of questions missed. *\n\n//********************************************************\n\n\n\nvoid PassFailExam::set(int questions, int missed)\n\n{ \n\n double numericScore; // To hold the numeric score\n\n\n\n // Set the number of questions and number missed.\n\n numQuestions = questions;\n\n numMissed = missed;\n\n \n\n // Calculate the points for each question.\n\n pointsEach = 100.0 / numQuestions;\n\n \n\n // Calculate the numeric score for this exam.\n\n numericScore = 100.0 - (missed * pointsEach);\n\n \n\n // Call the inherited setScore function to set\n\n // the numeric score.\n\n setScore(numericScore);\n\n} ", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp", "rank": 21, "score": 60053.477080862016 }, { "content": "#include \"PassFailActivity.h\"\n\n\n\n//******************************************************\n\n// Member function PassFailActivity::getLetterGrade *\n\n// This function returns 'P' if the score is passing, *\n\n// otherwise it returns 'F'. *\n\n//******************************************************\n\n\n\nchar PassFailActivity::getLetterGrade() const\n\n{\n\n char letterGrade;\n\n \n\n if (score >= minPassingScore)\n\n letterGrade = 'P';\n\n else \n\n letterGrade = 'F';\n\n \n\n return letterGrade;\n\n} ", "file_path": "SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp", "rank": 22, "score": 60045.94321462755 }, { "content": "class PassFailActivity : public GradedActivity\n\n{\n\nprotected:\n\n double minPassingScore; // Minimum passing score.\n\npublic:\n\n // Default constructor\n\n PassFailActivity() : GradedActivity()\n\n { minPassingScore = 0.0; }\n\n \n\n // Constructor\n\n PassFailActivity(double mps) : GradedActivity()\n\n { minPassingScore = mps; }\n\n\n\n // Mutator\n\n void setMinPassingScore(double mps)\n\n { minPassingScore = mps; }\n\n\n\n // Accessors\n\n double getMinPassingScore() const\n\n { return minPassingScore; }\n\n \n\n virtual char getLetterGrade() const;\n\n};\n\n#endif", "file_path": "SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h", "rank": 23, "score": 55740.465351529056 }, { "content": "// JESUS HILARIO HERNANDEZ\n\n// Last Modified: October 4th, 2016\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n char letter = 'a';\n\n\n\n do\n\n {\n\n cout << \"Please enter a letter\" << endl;\n\n cin >> letter;\n\n cout << \"The letter you entered is \" << letter << endl;\n\n\n\n //Notify user that pressing x will exit the loop.\n\n cout << \"\\nPRESS x IF YOU WISH TO EXIT.\\n\\n\";\n\n }while (letter != 'x');\n\n\n\n return 0;\n\n}\n", "file_path": "Loops/do-while-enter-a-letter.cpp", "rank": 24, "score": 55008.70833381305 }, { "content": " bool withdraw(double amount); // Defined in Account.cpp\n\n \n\n void calcInterest()\n\n { interest = balance * interestRate; balance += interest; }\n\n \n\n double getInterestRate() const\n\n { return interestRate; }\n\n \n\n double getBalance() const\n\n { return balance; }\n\n \n\n double getInterest() const\n\n { return interest; }\n\n \n\n int getTransactions() const\n\n { return transactions; }\n\n};\n\n#endif", "file_path": "SourceCode/chapter 13/Account.h", "rank": 25, "score": 54996.91312179871 }, { "content": "//****************************************************\n\n// This program uses an algorithm for error checking\n\n// and input validation when using numbers.\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last updated: December 2, 2016\n\n//****************************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n // Variables\n\n int number;\n\n\n\n // Ask user to enter a number\n\n cout << \"Enter an number: \";\n\n\n\n while (!(cin >> number))\n\n {\n", "file_path": "InputValidation/number.cpp", "rank": 26, "score": 54976.66573379076 }, { "content": "// Specification file for the Account class.\n\n#ifndef ACCOUNT_H\n\n#define ACCOUNT_H\n\n\n", "file_path": "SourceCode/chapter 13/Account.h", "rank": 27, "score": 54970.73176871151 }, { "content": " // Explain error\n\n cout << \"I'm sorry you've not entered a number. Try again:\";\n\n // Clear input stream\n\n cin.clear();\n\n // discard previous input from user\n\n cin.ignore(123, '\\n');\n\n }\n\n\n\n cout << \"You've entered \" << number << endl;\n\n return 0;\n\n}\n", "file_path": "InputValidation/number.cpp", "rank": 28, "score": 54947.70158577312 }, { "content": "//This program successfully uses both\n\n//cin >> and cin.get() for keyboard input.\n\n\n\n//JESUS HILARIO HERNANDEZ\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n char ch;\n\n int number;\n\n\n\n cout << \"Enter a number: \" << endl;\n\n cin >> number;\n\n cin.ignore(); //Skip the newline character.\n\n cout << \"Enter a character: \" << endl;\n\n ch = cin.get();\n\n cout << \"Thank You!\\n\" << endl;\n\n\n\n return 0;\n\n}\n", "file_path": "Replicated Programs/cin.ignore.cpp", "rank": 29, "score": 53506.59712565103 }, { "content": "// This program sucessfully uses both\n\n// cin >> and cin.ignore() for keyboard unput\n\n\n\n//JESUS HILARIO HERNANDEZ\n\n\n\n//Last modified: 9/26/2016\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n char ch;\n\n int number;\n\n\n\n cout << \"Enter a number: \";\n\n cin >> number;\n\n cin.ignore(); //Skip the newline '\\n' character [Enter]\n\n cout << \"Enter a character: \";\n\n ch = cin.get();\n\n cout << \"Thank You!\" << endl;\n\n\n\n return 0;\n\n}\n", "file_path": "Replicated Programs/cin-ignore.cpp", "rank": 30, "score": 53506.31281607872 }, { "content": "//This program demonstrates three ways\n\n// to use cin.get() to pause a program.\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n char ch; // cin.get() uses any character to achieve it's purpose\n\n\n\n cout << \"This program has paused. Press Enter to continue.\" << endl;\n\n cin.get(ch); //FIRST WAY, YES VARIABLE USED\n\n cout << \"It has paused a second time. Please press Enter again.\" << endl;\n\n ch = cin.get(); //SECOND WAY, YES VARIABLE USED\n\n cout << \"It as paused a third time. Please press the Enter key again.\" << endl;\n\n cin.get(); // THIRD WAY, NO VARIABLE USED.\n\n cout << \"THANK YOU!\" << \" Have a nice day.\" << endl << endl;\n\n\n\n return 0;\n\n}\n", "file_path": "Replicated Programs/cin.getfunction.cpp", "rank": 31, "score": 53494.65774563743 }, { "content": "// Implementation file for the Account class.\n\n#include \"Account.h\"\n\n\n\nbool Account::withdraw(double amount)\n\n{\n\n if (balance < amount)\n\n return false; // Not enough in the account\n\n else\n\n {\n\n balance -= amount;\n\n transactions++;\n\n return true;\n\n }\n\n}", "file_path": "SourceCode/chapter 13/Account.cpp", "rank": 32, "score": 53481.30207435174 }, { "content": " \n\n // Destructor\n\n ~NumberList();\n\n \n\n // Linked List Operations\n\n void appendNode(double);\n\n void insertNode(double);\n\n void deleteNode(double);\n\n void displayList() const;\n\n int numNodes() const\n\n { return countNodes(head); }\n\n void displayBackwards() const\n\n { showReverse(head); }\n\n};\n\n#endif", "file_path": "SourceCode/Chapter 19/NumberList.h", "rank": 33, "score": 53421.75047626479 }, { "content": "// Specification file for the NumberList class\n\n#ifndef NUMBERLIST_H\n\n#define NUMBERLIST_H\n\n\n", "file_path": "SourceCode/Chapter 17/NumberList.h", "rank": 34, "score": 53418.878803786305 }, { "content": "// Specification file for the NumberList class\n\n#ifndef NUMBERLIST_H\n\n#define NUMBERLIST_H\n\n\n", "file_path": "SourceCode/Chapter 19/NumberList.h", "rank": 35, "score": 53418.878803786305 }, { "content": "//********************************************\n\n// This program check for valid user input.\n\n// In this cas the user must enter an integer.\n\n//\n\n// By: Jesus HIlario Hernandez\n\n// Last Updated: December 5, 2016\n\n//********************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n // Variables\n\n int num;\n\n\n\n // Ask user to enter a number\n\n cout << \"Enter your favorite number: \";\n\n\n\n // Error Checkin algorithim\n\n while (!(cin >> num))\n", "file_path": "InputValidation/intCheck.cpp", "rank": 36, "score": 53412.596688563215 }, { "content": "#include <iostream>\n\n#include <ctype.h> // isdigit()\n\n#include <sstream> // stringstream\n\nusing namespace std;\n\n\n\nint main() \n\n{\n\n string user_string_num = \"\";\n\n\n\n int is_num = 0,\n\n decimal_count = 0,\n\n user_converted_num;\n\n\n\n bool is_num_bool = 0;\n\n\n\n do\n\n {\n\n cout << \"Enter a number: \";\n\n cin >> user_string_num;\n\n\n", "file_path": "InputValidation/validate-int.cpp", "rank": 37, "score": 53405.21867049064 }, { "content": " {\n\n // Explain error\n\n cout << \"ERROR: a number must be entered: \";\n\n // Clear input stream\n\n cin.clear();\n\n // Discard previous input\n\n cin.ignore(132, '\\n');\n\n }\n\n // Display the number the user has entered\n\n cout << \"Your favorite number is: \" << num << endl;\n\n // Salutation\n\n cout << \"Thanks. Bye.\" << endl;\n\n return 0;\n\n}\n", "file_path": "InputValidation/intCheck.cpp", "rank": 38, "score": 53390.309504633056 }, { "content": " << \"Number must NOT be a decimal number.\\n\" \n\n << endl;\n\n\n\n cin.clear();\n\n cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n\n\n\n is_num_bool = 0;\n\n is_num = 0;\n\n decimal_count = 0;\n\n }\n\n\n\n\n\n } while (is_num_bool == 0);\n\n \n\n\n\n return 0;\n\n}", "file_path": "InputValidation/validate-int.cpp", "rank": 39, "score": 53373.59386992631 }, { "content": " if (is_num == user_string_num.size()) \n\n {\n\n stringstream str_stream_object(user_string_num);\n\n str_stream_object >> user_converted_num;\n\n\n\n is_num_bool = 1;\n\n\n\n cout << endl\n\n << user_string_num << \"(user_string_num) \"\n\n << \"is a number!\" << endl\n\n << user_converted_num << \"(user_converted_num) \"\n\n << \"is a number!\" << endl\n\n << endl;\n\n }\n\n else\n\n {\n\n cout << endl\n\n << \"Number must NOT contain spaces.\\n\"\n\n << \"Number must NOT contain letters.\\n\"\n\n << \"Number must NOT contain symbols.\\n\"\n", "file_path": "InputValidation/validate-int.cpp", "rank": 40, "score": 53373.484432502904 }, { "content": "// Specification file for the IntQueue class\n\n#ifndef INTQUEUE_H\n\n#define INTQUEUE_H\n\n\n", "file_path": "SourceCode/Chapter 18/IntQueue.h", "rank": 41, "score": 53361.469019754135 }, { "content": "// Specification file for the IntStack class\n\n#ifndef INTSTACK_H\n\n#define INTSTACK_H\n\n\n", "file_path": "SourceCode/Chapter 18/IntStack.h", "rank": 42, "score": 53361.469019754135 }, { "content": "// Specification file for the IntArray class\n\n#ifndef INTARRAY_H\n\n#define INTARRAY_H\n\n\n", "file_path": "SourceCode/chapter 14/IntArray.h", "rank": 43, "score": 53361.469019754135 }, { "content": " if (user_string_num[0] == '-') // jesus -8\n\n is_num++;\n\n\n\n if (user_string_num[0] == '0' && \n\n isdigit(user_string_num[1])) // 0934939\n\n is_num = 0;\n\n else \n\n {\n\n for (int i = 0; i < user_string_num.size(); i++)\n\n {\n\n if (isdigit(user_string_num[i]))\n\n is_num++;\n\n if (user_string_num[i] == '.')\n\n decimal_count++;\n\n }\n\n }\n\n\n\n if (decimal_count == 1) // 66.7 // 8..9.9.9..9.9\n\n is_num = 0;\n\n \n", "file_path": "InputValidation/validate-int.cpp", "rank": 44, "score": 53360.47959818438 }, { "content": " cin.ignore(123, '\\n');\n\n // Receive input again\n\n cin >> letter;\n\n }\n\n return letter;\n\n}\n\n\n\n//***********************************************************\n\n// Function errorCheckInt1-4 checks for valid input. *\n\n// In this case the user must enter and integer or choose *\n\n// a number between 1 and 4. *\n\n//***********************************************************\n\n\n\nint errorCheckInts1_4(int num)\n\n{\n\n while (!(cin >> num) || (num < 1 || num > 4))\n\n {\n\n // Explain the Error\n\n cout << \"ERROR: you must choose a number from 1 to 4.\";\n\n // Clear input stream\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 45, "score": 53355.590454995385 }, { "content": " cout << \"\\nHave a nice day!\" << endl;\n\n return 0;\n\n}\n\n\n\n//***************************************************\n\n// function errorCheckYN check for valid input. *\n\n// In this case the user must enter a Y or and N. *\n\n//***************************************************\n\n\n\nchar errorCheckYorN(char letter)\n\n{\n\n while (!(letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N'))\n\n {\n\n // Explain error\n\n cout << \"ERROR: you must choose either Y or N.\" << endl\n\n << \"Y for Yes or\\n\"\n\n << \"N for No...\";\n\n // Clear input stream\n\n cin.clear();\n\n // Discard previous input\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 46, "score": 53350.16024015022 }, { "content": " break;\n\n\n\n // 4. Mystery Genre\n\n case 4:\n\n Mystery();\n\n break;\n\n\n\n default:\n\n break;\n\n\n\n }\n\n\n\n cout << \"\\nWould you like to return to the main menu? (Y/N)\" << endl;\n\n // Receive user input into repeat_menu\n\n cin >> repeat_menu;\n\n // Error check for valid input (Y/N)\n\n repeat_menu = errorCheckYorN(repeat_menu);\n\n\n\n } while (repeat_menu == 'Y' || repeat_menu == 'y');\n\n\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 47, "score": 53349.080129527116 }, { "content": "// to make another seletion. And then, the user must type\n\n// a Y or an N to redisplay they menu or to end the program.\n\n//\n\n// OUTPUT: Output, in this program, is sent either to the screen\n\n// or to an output file. The user is displayed an initial menu,\n\n// a genre menu, asked to select a book, if they would like to keep\n\n// a book, if they would like to select another book, and if they\n\n// would like to see the inital menu. The output file receives\n\n// data from the program, if the user decides to keep a book. The\n\n// title, date, and author of the book is written to an output file.\n\n//\n\n//******************************************************************\n\n#include <iostream>\n\n#include <fstream>\n\n#include <string>\n\n#include <iomanip>\n\n//#include <windows.h>\n\n#include <cstdlib> //for rand and srand\n\n#include <ctime> // for the time\n\nusing namespace std;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 48, "score": 53348.21324150328 }, { "content": " << \"moving and storage, inspecting individual new and used pianos, the special\" << endl\n\n << \"market for Steinways, and sales gimmicks to watch out for. An annual supplement, \" << endl\n\n << \"sold separately, lists current prices for more than 2,500 new piano models.\" << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n\n\n\n case (SELECT_BOOK_4 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl\n\n << '\\t' << book[SELECT_BOOK_4] << \", by \" << endl\n\n << \"\\t\\t\" << author[SELECT_BOOK_4] << endl << endl;\n\n\n\n // Display Book 4 Description\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 49, "score": 53346.43821641263 }, { "content": " cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n\n\n\n case (SELECT_BOOK_4 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl;\n\n cout << \"\\t\" << title[SELECT_BOOK_4] << \", by \";\n\n cout << author[SELECT_BOOK_4] << endl << endl;\n\n cout << \" \" << description[SELECT_BOOK_4] << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 50, "score": 53346.336377857246 }, { "content": "char errorCheckYorN(char); // Error Check for Y or N.\n\nint errorCheckInts1_4(int); // Error Check range 1-4 and integers\n\n\n\nint main()\n\n{\n\n // Variables\n\n int menu_choice; // Holds Menu Choice\n\n char repeat_menu; // To Re-display the menu_choice\n\n\n\n do\n\n {\n\n // Clear Screen\n\n clearScreen();\n\n\n\n cout << \"\\nChoose a genre to begin\" << endl;\n\n cout << \"\\n1. Music \" << endl;\n\n cout << \"\\n2. Romance\" << endl;\n\n cout << \"\\n3. Adventure\" << endl;\n\n cout << \"\\n4. Mystery\\n\" << endl;\n\n\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 51, "score": 53346.02305385178 }, { "content": " // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n\n\n\n case (SELECT_BOOK_3 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl;\n\n cout << \"\\t\" << title[SELECT_BOOK_3] << \", by \";\n\n cout << author[SELECT_BOOK_3] << endl << endl;\n\n cout << \" \" << description[SELECT_BOOK_3] << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 52, "score": 53342.48030889057 }, { "content": " cout << \"\\t\" << title[SELECT_BOOK_1] << \", by \";\n\n cout << author[SELECT_BOOK_1] << endl << endl;\n\n cout << \" \" << description[SELECT_BOOK_1] << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n\n\n\n case (SELECT_BOOK_2 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl;\n\n cout << \"\\t\" << title[SELECT_BOOK_2] << \", by \";\n\n cout << author[SELECT_BOOK_2] << endl << endl;\n\n cout << \" \" << description[SELECT_BOOK_2] << endl;\n\n\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 53, "score": 53342.32035044492 }, { "content": " cout << \" Invalid answer. Please try again.\" << endl;\n\n }\n\n break;\n\n\n\n }\n\n cout << endl << \" Would you like to return to the Romance menu? (Y/N)\" << endl;\n\n\n\n // Receive into repeat_romancemenu variable\n\n cin >> repeat_romancemenu;\n\n // Error check for input validation\n\n repeat_romancemenu = errorCheckYorN(repeat_romancemenu);\n\n }\n\n while (repeat_romancemenu == 'Y' || repeat_romancemenu == 'y');\n\n}\n\n\n\n/*\n\n *************************************************************************\n\n * This is the Adventure function. This function call from the files the *\n\n * title, author, and date. It will then allow the user to select a book *\n\n * which will then display a description of the book. The user is then *\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 54, "score": 53341.82700899208 }, { "content": " // Ask is user would like to keep book\n\n //cout << \"\\nWould you like to keep this book?\";\n\n //cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n //cin >> keepBook;\n\n // Error check keepBook\n\n //keepBook = errorCheckYorN(keepBook);\n\n break;\n\n case 2:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selection\n\n cout << endl << \" \" << romanceBookInfo[1] << endl << endl;\n\n // Display Description\n\n cout << \"\\tBack in Oregon, Kelsey tries to pick up the \" << endl\n\n << \" pieces of her life and push aside her feelings \" << endl\n\n << \" for Ren. Kelsey Hayes's eighteenth summer was\" << endl\n\n << \" crazy. The kind of crazy nobody would ever\" << endl\n\n << \" believe.\" << endl << endl;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 55, "score": 53341.084878716596 }, { "content": " cout << endl << \"Would you like to return to the Mystery menu? (Y/N)\" << endl;\n\n\n\n // Receive user input into repeat_mysterymenu\n\n cin >> repeat_mysterymenu;\n\n // Error check repeat_mysterymenu\n\n repeat_mysterymenu = errorCheckYorN(repeat_mysterymenu);\n\n\n\n } while (repeat_mysterymenu == 'Y' || repeat_mysterymenu == 'y'); // End do while loop\n\n}\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 56, "score": 53339.335636085634 }, { "content": " cout << \"How Music Works is David Byrne's buoyant \" << endl\n\n << \"celebration of a subject he has spent a lifetime thinking \" << endl\n\n << \"about. Equal parts historian and anthropologist, raconteur \" << endl\n\n << \"and social scientist, Byrne draws on his own work over the \" << endl\n\n << \"years with Talking Heads, Brian Eno, and his myriad collaborators - \" << endl\n\n << \"along with journeys to Wagnerian opera houses, African villages, \" << endl\n\n << \"and anywhere music exisits - to show that music - making is not \" << endl\n\n << \"just the act of a solitary composer in a studio, but rather a logical, \" << endl\n\n << \"populist, and beautiful result of cultural circumstance. \" << endl\n\n << \"A brainy, irresistible adventure, How Music Works is an impassioned \" << endl\n\n << \"argument about music's liberating, life - affirming power.\" << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 57, "score": 53337.79095108508 }, { "content": " << \"occupies in the brain and how it affects the human condition. \" << endl\n\n << \"In Musicophilia, he shows us a variety of what he calls “musical \" << endl\n\n << \"misalignments.” Among them: a man struck by lightning who suddenly \" << endl\n\n << \"desires to become a pianist at the age of forty-two; an entire group \" << endl\n\n << \"of children with Williams syndrome, who are hypermusical from birth; \" << endl\n\n << \"people with “amusia,” to whom a symphony sounds like the clattering of \" << endl\n\n << \"pots and pans; and a man whose memory spans only seven seconds-for everything \" << endl\n\n << \"but music. Illuminating, inspiring, and utterly unforgettable, Musicophilia \" << endl\n\n << \"is Oliver Sacks' latest masterpiece.\" << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n\n // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n\n\n\n case (SELECT_BOOK_2 + 1):\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 58, "score": 53337.66799443564 }, { "content": " // Receive user input into keepBook\n\n cin >> keepBook;\n\n // Error check keepBook\n\n keepBook = errorCheckYorN(keepBook);\n\n break;\n\n\n\n case (SELECT_BOOK_3 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl\n\n << '\\t' << book[SELECT_BOOK_3] << \", by \" << endl\n\n << \"\\t\\t\" << author[SELECT_BOOK_3] << endl << endl;\n\n\n\n // Display Book 3 description\n\n cout << \"\\tThis bible of the piano marketplace \" << endl\n\n << \"is indispensable to buyers and owners of pianos, \" << endl\n\n << \"amateur and professional players alike. Hundreds of thousands \" << endl\n\n << \"of pianos are bought and sold each year, yet most people buy a\" << endl\n\n << \"piano with only the vaguest idea of what to look for as they make this\" << endl\n\n << \"major purchase. The Piano Book evaluates and compares every brand and \" << endl\n\n << \"style of piano sold in the United States. There is information on piano \" << endl\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 59, "score": 53337.48926677694 }, { "content": " // Clear screen\n\n clearScreen();\n\n\n\n // Ask if would like to make another music selection\n\n cout << \"Would you like to make another \"\n\n << \"Adventure genre selection? (Y/N)\";\n\n // Receive user input into anotherSelection\n\n cin >> anotherSelection;\n\n // Error chek anotherSelection for (Y/N)\n\n anotherSelection = errorCheckYorN(anotherSelection);\n\n\n\n } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While\n\n\n\n //Close output File\n\n keptBooks.close();\n\n}\n\n\n\n//***************************************************************\n\n// The mystery function displays a menu with mystery books to *\n\n// choose from. The user is asked to choose a book. A description\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 60, "score": 53336.60342555939 }, { "content": " // Ask if would like to make another music selection\n\n cout << \"Would you like to make another \"\n\n << \"music genre selection? (Y/N)\";\n\n // Receive user input into anotherSelection\n\n cin >> anotherSelection;\n\n // Error check anotherSelection\n\n anotherSelection = errorCheckYorN(anotherSelection);\n\n\n\n } while(anotherSelection == 'y' || anotherSelection == 'Y');// End Do While\n\n\n\n //Close output File\n\n keptBooks.close();\n\n}\n\n\n\n\n\n//***************************************************************\n\n// The romance function displays a menu with romance books to *\n\n// choose from. The user is asked to choose a book. A description\n\n// of the book is then displayed to the user. The user is asked *\n\n// if they would like to keep the book. If yes, the book info is*\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 61, "score": 53335.37321765693 }, { "content": "\n\n cout << \"\\tAside From battling immortal sea monkeys and \" << endl\n\n << \" trekking the jungles of India, she fell in love \" << endl\n\n << \" with Ren, a 300-year-old prince.\" << endl << endl;\n\n\n\n cout << \"\\tWhen danger suddenly forces Kelsey on another \" << endl\n\n << \" Indian quest, with Ren's bad-boy brother, \" << endl\n\n << \" Kishan, the unlikely duo begins to question their \" << endl\n\n << \" true destiny. Ren's life hangs in the balance--\" << endl\n\n << \" so does the truth within Kelsey's heart.\" << endl;\n\n\n\n }\n\n break;\n\n case 3:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selection\n\n cout << endl << \" \" << romanceBookInfo[2] << endl << endl;\n\n // Display Description\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 62, "score": 53332.01635368771 }, { "content": "// then displayed to an output file. If they would not like to *\n\n// keep the book, the user will be asked if they would like *\n\n// to choose another book from the romance menu. *\n\n//***************************************************************\n\n\n\nvoid Romance()\n\n{\n\n // Variables\n\n const int SIZE = 4; // Holds array size\n\n int position = 0;\n\n char repeat_romancemenu; // Holds Y or N to return to Romance menu or not\n\n int menu_romancechoice; // Holds romance book selection\n\n\n\n // Arrays\n\n string romanceBookInfo[SIZE]; // Holds Romance Book info: author, title, date\n\n\n\n // Input / Output Files\n\n ifstream file;\n\n ofstream outputfile;\n\n\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 63, "score": 53331.944304960634 }, { "content": "// of the book is then displayed to the user. The user is asked *\n\n// if they would like to keep the book. If yes, the book info is*\n\n// then displayed to an output file. If they would not like to *\n\n// keep the book, the user will be asked if they would like *\n\n// to choose another book from the mystery menu. *\n\n//***************************************************************\n\n\n\nvoid Mystery()\n\n{\n\n // Variables\n\n const int SIZE = 4; // Holds array size\n\n int position = 0;\n\n char repeat_mysterymenu; // Holds Y or N to return to Romance menu or not\n\n int menu_mysterychoice; // Holds romance book selection\n\n\n\n // Arrays\n\n string mysteryBookInfo[SIZE]; // Holds Romance Book into: author, title, date\n\n\n\n // Input Files\n\n ifstream file;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 64, "score": 53331.458341374484 }, { "content": " cout << \" \" << mysteryBookInfo[count] << endl;\n\n }\n\n\n\n // Close input file.\n\n file.close();\n\n\n\n cout << endl << \" Choose a book to read the discription: \";\n\n\n\n // Receive user input into menu_mysterychoice\n\n // and error check with errorCheckInts1_4 function\n\n menu_mysterychoice = errorCheckInts1_4(menu_mysterychoice);\n\n\n\n cout << endl;\n\n\n\n switch(menu_mysterychoice)\n\n {\n\n case 1:\n\n {\n\n // Clear the screen\n\n clearScreen();\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 65, "score": 53331.17664451846 }, { "content": " // Receive user input into menu_choice\n\n // Error check for valid input\n\n menu_choice = errorCheckInts1_4(menu_choice);\n\n\n\n switch (menu_choice)\n\n {\n\n\n\n // 1. Music Genre\n\n case 1:\n\n Music();\n\n break;\n\n\n\n // 2. Romance Genre\n\n case 2:\n\n Romance();\n\n break;\n\n\n\n // 3. Adventure Genre\n\n case 3:\n\n Adventure();\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 66, "score": 53331.144804088835 }, { "content": " cout << \" \" << romanceBookInfo[count] << endl;\n\n }\n\n\n\n // Close input file.\n\n file.close();\n\n\n\n cout << endl << \" Choose a book to read the description: \";\n\n\n\n // Receive into menu_romancechoice variable\n\n // Error check for input validation\n\n menu_romancechoice = errorCheckInts1_4(menu_romancechoice);\n\n cout << endl;\n\n\n\n switch(menu_romancechoice)\n\n {\n\n case 1:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selction\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 67, "score": 53330.54407185255 }, { "content": "//******************************************************************\n\n// Project name: BookFlix\n\n// Team name:\n\n// Members:\n\n// ASHLEY GUZMAN,\n\n// REAGEN HAMMITT,\n\n// JESUS HERNANDEZ\n\n\n\n// Course: COSC 1436.001 Programming Fundamentals 1\n\n// Group Project\n\n// Due Date: December 4, 2016\n\n// Instructor: Korinne Caruso\n\n//\n\n// PURPOSE: This program displays a book menu selection for the user\n\n// to choose from. The user then searches through the progam for a\n\n// book or books that they would like to read.\n\n//\n\n// INPUT: The input in this program comes either from the user or from\n\n// an input file. The user selects from a initial menu, a book genre\n\n// menu, and must enter a Y or N for either keep a book or to continue\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 68, "score": 53330.00409247269 }, { "content": "\n\n // Ask your to select a book\n\n cout << \"\\nSelect a book: \";\n\n\n\n // Receive into selectBook variable\n\n // Error check for input validation\n\n selectBook = errorCheckInts1_4(selectBook);\n\n\n\n switch (selectBook)\n\n {\n\n case (SELECT_BOOK_1 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl\n\n << '\\t' << book[SELECT_BOOK_1] << \", by \" << endl\n\n << \"\\t\\t\" << author[SELECT_BOOK_1] << endl << endl;\n\n\n\n // Display Description\n\n cout << \"\\tWith the same trademark compassion \" << endl\n\n << \"and erudition he brought to The Man Who Mistook \" << endl\n\n << \"His Wife for a Hat, Oliver Sacks explores the place music \" << endl\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 69, "score": 53329.8845652568 }, { "content": " cout << endl << \" \" << romanceBookInfo[0] << endl << endl;\n\n // Display Description\n\n cout << \"\\tWould you risk it all to \" << endl\n\n << \" change your destiny?\" << endl << endl;\n\n\n\n cout << \"\\tThe last thing Kelsey Hayes thought she'd be\" << endl\n\n << \" doing this summer was trying to break a 300-year\" << endl\n\n << \" old Indian curse. With a mysterious white tiger \" << endl\n\n << \" named Ren. Halfway around the world. But that's\" << endl\n\n << \" exactly what happened.\" << endl << endl;\n\n\n\n cout << \"\\tFace-to-face with dark forces, spellbinding \"<< endl\n\n << \" magic, and mystical worlds where nothing is \" << endl\n\n << \" what it seems, Kelsey risks everything to piece \" << endl\n\n << \" together an ancient prophecy that could break the \" << endl\n\n << \" curse forever. Packed the epic with magic, \" << endl\n\n << \" action-adventure, and romance, Tiger's Curse \" << endl\n\n << \" series will keep you breathless and yearning for \" << endl\n\n << \" more.\" << endl;\n\n }\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 70, "score": 53329.72494097681 }, { "content": " }\n\n\n\n // Close inputFiles\n\n inputAuthors.close();\n\n inputTitle.close();\n\n inputDates.close();\n\n inputDescription.close();\n\n\n\n // Ask your to select a book\n\n cout << \"\\nSelect a book: \";\n\n\n\n // Receive into selectBook variable\n\n // Error check for input validation\n\n selectBook = errorCheckInts1_4(selectBook);\n\n\n\n switch (selectBook)\n\n {\n\n case (SELECT_BOOK_1 + 1):\n\n clearScreen();\n\n cout << \"\\nYou've selected:\" << endl;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 71, "score": 53329.604106415245 }, { "content": " cin.clear();\n\n // Discard previous input\n\n cin.ignore(123, '\\n');\n\n }\n\n return num;\n\n}\n\n\n\n//***************************************************\n\n// function to clear screen, using variable *\n\n// created in PPD statement *\n\n//***************************************************\n\n\n\nvoid clearScreen()\n\n{\n\n system(clearVar);\n\n}\n\n\n\n//***********************************************************\n\n// The Music function displays a list of music books for *\n\n// the user to choose from. The user will be asked if they *\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 72, "score": 53329.44872154164 }, { "content": "\n\n default:\n\n cout << \"NO WORK.\" << endl;\n\n }\n\n\n\n // If no. Say ok.\n\n if (keepBook == 'N' || keepBook == 'n')\n\n {\n\n cout << \"Ok.\\n\" << endl;\n\n }\n\n // If yes. Say awesome!\n\n else if (keepBook == 'y' || keepBook == 'Y')\n\n {\n\n cout << \"Awesome!\\n\" << endl;\n\n // Write to output file books kept by user\n\n keptBooks << book[selectBook - 1] << \", \"\n\n << author[selectBook -1] << \", \"\n\n << date [selectBook -1] << endl;\n\n }\n\n\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 73, "score": 53329.3300148904 }, { "content": "\n\n default:\n\n cout << \"No book selected.\" << endl;\n\n }\n\n\n\n // If no. Say ok.\n\n if (keepBook == 'N' || keepBook == 'n')\n\n {\n\n cout << \"Ok.\\n\" << endl;\n\n }\n\n // If yes. Say awesome!\n\n else if (keepBook == 'y' || keepBook == 'Y')\n\n {\n\n cout << \"That's Great!\\n\" << endl;\n\n // Write to output file books kept by user\n\n keptBooks << title[selectBook - 1] << \", \"\n\n << author[selectBook - 1] << \", \"\n\n << date [selectBook - 1] << endl;\n\n }\n\n\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 74, "score": 53329.27055155346 }, { "content": " // Display Selection\n\n cout << endl << \" \" << mysteryBookInfo[0] << endl << endl;\n\n // Diplay Description\n\n cout << \"\\tThe classic and terrifying story \" << endl\n\n << \"of one of the most famous supernatural events\" << endl\n\n << \"--the infamous possessed house on Long Island from \" << endl\n\n << \"which the Lutz family fled in 1975.\" << endl;\n\n }\n\n break;\n\n\n\n case 2:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selection\n\n cout << endl << \" \" << mysteryBookInfo[0] << endl << endl;\n\n // Diplay Description\n\n cout << \"\\tHarriet Vanger, a scion of one of Sweden's \" << endl\n\n << \"wealthiest families disappeared over forty years ago. \" << endl\n\n << \"All these years later, her aged uncle continues to seek \" << endl\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 75, "score": 53328.82053239945 }, { "content": " SELECT_BOOK_1 = 0,\n\n SELECT_BOOK_2 = 1,\n\n SELECT_BOOK_3 = 2,\n\n SELECT_BOOK_4 = 3;\n\n\n\n // Variables\n\n string author[SIZE]; //author names\n\n string title[SIZE]; // book titles\n\n string date[SIZE]; // book dates\n\n string description[SIZE]; // book descriptions\n\n\n\n int selectBook; // book selection\n\n char keepBook, // Holds Y or N\n\n anotherSelection; // Holds Y or N to return to adventure menu or not\n\n\n\n\n\n\n\n\n\n // Select Book from a list\n\n do\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 76, "score": 53328.357684154085 }, { "content": " cout << \"\\tIn the spring of 1998, Kouichi \" << endl\n\n << \"Sakakibara transfers to Yomiyama North Middle School.\" << endl\n\n << \"In class, he develops a sense of unease as he notices that \" << endl\n\n << \"the people around him act like they're walking on eggshells,\" << endl\n\n << \"and students and teachers alike seem frightened.\" << endl\n\n << \"As a chain of horrific deaths begin to unfold around him,\" << endl\n\n << \"he comes to discover that he has been placed in the cursed Class 3\" << endl\n\n << \"in which the student body head count is always one more than expected.\" << endl\n\n << \"Class 3 is haunted by a vengeful spirit responsible for gruesome deaths \" << endl\n\n << \"in an effort to satisfy its spite. To stop the vicious cycle gripping \" << endl\n\n << \"his new school, Kouichi decides to get to the bottom of the curse,\" << endl\n\n << \"but is he prepared for the horror that lies ahead...?\" << endl;\n\n }\n\n break;\n\n default:\n\n {\n\n cout << \" Invalid answer. Please try again.\" << endl;\n\n }\n\n break;\n\n }\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 77, "score": 53328.31107839163 }, { "content": "\n\n do\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n\n\n // Open input file.\n\n file.open(\"MysteryBooksAshley.txt\");\n\n\n\n // Display book selection\n\n cout << \"\\n\\n\" << endl;\n\n cout << \" Author Title Date\" << endl << endl;\n\n\n\n // This For Loop gets contents from the external file\n\n // and Displays them to the screen.\n\n for (int count = 0; count < SIZE; count++)\n\n {\n\n // getting from external file\n\n getline(file, mysteryBookInfo[count]);\n\n // displays contents to screen\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 78, "score": 53327.97512437182 }, { "content": " do\n\n {\n\n\n\n // Clear the screen\n\n clearScreen();\n\n\n\n // Open input file.\n\n file.open(\"RomanceBooksAshley.txt\");\n\n\n\n // Display book selection\n\n cout << \"\\n\\n\" << endl;\n\n cout << \" Author Title Date\" << endl << endl;\n\n\n\n // This For loop get contents from the external file\n\n // and Displays the to screen.\n\n for (int count = 0; count < SIZE; count++)\n\n {\n\n // getting from external file\n\n getline(file, romanceBookInfo[count]);\n\n // displays contents to screen\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 79, "score": 53327.97512437182 }, { "content": " clearScreen();\n\n cout << \"\\nYou've selected:\" << endl\n\n << '\\t' << book[SELECT_BOOK_2] << \", by \" << endl\n\n << \"\\t\\t\" << author[SELECT_BOOK_2] << endl << endl;\n\n\n\n // Display description\n\n cout << \"\\tIn this sweeping and dramatic narrative, \" << endl\n\n << \"Alex Ross, music critic for The New Yorker, weaves \" << endl\n\n << \"together the histories of the twentieth century and its music,\" << endl\n\n << \"from Vienna before the First World War to Paris in the twenties; \" << endl\n\n << \"from Hitler's Germany and Stalin's Russia to downtown New York \" << endl\n\n << \"in the sixties and seventies up to the present. Taking readers into the \" << endl\n\n << \"labyrinth of modern style, Ross draws revelatory connections \" << endl\n\n << \"between the century's most influential composers and the wider \" << endl\n\n << \"culture. The Rest Is Noise is an astonishing history of the twentieth \" << endl\n\n << \"century as told through its music.\" << endl;\n\n\n\n // Ask is user would like to keep book\n\n cout << \"\\nWould you like to keep this book?\";\n\n cout << \" (Y/N)\";\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 80, "score": 53327.900335954204 }, { "content": " cout << \"\\tGalen, a Syrena prince, searches land for a \" << endl\n\n << \" girl he's heard can communicate with fish. \" << endl\n\n << \" It's while Emma is on vacation at the beach\" << endl\n\n << \" that she meets Galen. Although their connection \" << endl\n\n << \" is immediate and powerful, Galen's not fully convinced \" << endl\n\n << \" that Emma's the one he's been looking for. That is,\" << endl\n\n << \" until a deadly encounter with a shark proves\" << endl\n\n << \" that Emma and her Gift may be the only thing that \" << endl\n\n << \" can save his kingdom. He needs her help no matter\" << endl\n\n << \" what the risk.\" << endl;\n\n\n\n }\n\n break;\n\n case 4:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selection\n\n cout << endl << \" \" << romanceBookInfo[3] << endl << endl;\n\n // Display Description\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 81, "score": 53327.81242453833 }, { "content": " << \"the truth. He hires Mikael Blomkvist, a crusading \" << endl\n\n << \"journalist recently trapped by a libel conviction, to investigate.\" << endl\n\n << \"He is aided by the pierced and tattooed punk prodigy Lisbeth \" << endl\n\n << \"Salander. Together they tap into a vein of unfathomable \" << endl\n\n << \"iniquity and astonishing corruption.\" << endl;\n\n }\n\n break;\n\n\n\n case 3:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selection\n\n cout << endl << \" \" << mysteryBookInfo[0] << endl << endl;\n\n // Diplay Description\n\n cout << \"\\tAn ingenious code hidden in \" << endl\n\n << \"the works of Leonardo da Vinci. A desperate race \" << endl\n\n << \"through the cathedrals and castles of Europe.\" << endl\n\n << \"An astonishing truth concealed for centuries...unveiled \" << endl\n\n << \"at last.\" << endl << endl;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 82, "score": 53327.66078753256 }, { "content": " SELECT_BOOK_1 = 0,\n\n SELECT_BOOK_2 = 1,\n\n SELECT_BOOK_3 = 2,\n\n SELECT_BOOK_4 = 3;\n\n\n\n // Variables\n\n string author[SIZE], // Holds author names\n\n book[SIZE], // Holds book names\n\n date[SIZE]; // Holds book dates\n\n\n\n int selectBook; // Holds book selection\n\n char keepBook, // Holds Y or N\n\n anotherSelection; // Holds Y or N to return to music menu or not\n\n\n\n // Select Book from a list\n\n do\n\n {\n\n // Open input/ouput files\n\n inputAuthors.open(\"MusicAuthorsJesus.txt\");\n\n inputBooks.open(\"MusicTitleJesus.txt\");\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 83, "score": 53327.59822626456 }, { "content": "\n\n cout << \"\\tWhile in Paris, Harvard symbologist \" << endl\n\n << \"Robert Langdon is awakened by a phone call in \" << endl\n\n << \"the dead of the night. The elderly curator of the \" << endl\n\n << \"Louvre has been murdered inside the museum, his body covered \" << endl\n\n << \"in baffling symbols. As Langdon and gifted French cryptologist\" << endl\n\n << \"Sophie Neveu sort through the bizarre riddles, they are stunned \" << endl\n\n << \"to discover a trail of clues hidden in the works of Leonardo da\" << endl\n\n << \"Vinci clues visible for all to see and yet ingeniously disguised \" << endl\n\n << \"by the painter.\" << endl;\n\n }\n\n break;\n\n\n\n case 4:\n\n {\n\n // Clear the screen\n\n clearScreen();\n\n // Display Selection\n\n cout << endl << \" \" << mysteryBookInfo[0] << endl << endl;\n\n // Diplay Description\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 84, "score": 53327.562890527006 }, { "content": " cout << \"\\tEmma has just learned that her mother is a \" << endl\n\n << \" long-lost Poseidon princess, and now struggles \" << endl\n\n << \" with an identity crisis: As a Half-Breed, \" << endl\n\n << \" she's a freak in the human world and an abomination\" << endl\n\n << \" in the Syrena realm. Syrena law states all \" << endl\n\n << \" Half-Breeds should be put to death.\" << endl << endl;\n\n\n\n cout << \"\\tAs if that's not bad enough, her mother's \" << endl\n\n << \" reappearance in the Syrena world turns the \" << endl\n\n << \" two kingdoms Poseidon and Triton against one \" << endl\n\n << \" another. Which leaves Emma with a decision to make:\" << endl\n\n << \" Should she comply with Galen's request to keep\" << endl\n\n << \" herself safe and just hope for the best? Or \" << endl\n\n << \" should she risk it all and reveal herself and\" << endl\n\n << \" her Gift to save a people she's never known?\" << endl;\n\n\n\n }\n\n break;\n\n default:\n\n {\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 85, "score": 53327.46743405233 }, { "content": " inputDates.open(\"MusicDateJesus.txt\");\n\n keptBooks.open(\"RememberedBooks.txt\", ios::out | ios::app);\n\n\n\n clearScreen();\n\n // Display list of music books\n\n cout << \"Here are the available music books: \\n\" << endl;\n\n // Fill arrays with external file data and display contents\n\n for (int count = 0; count < SIZE; count++)\n\n {\n\n getline(inputAuthors, author[count]);\n\n getline(inputBooks, book[count]);\n\n getline(inputDates, date[count]);\n\n cout << '\\t' << (count + 1) << \". \"\n\n << book[count] << \", \" << endl;\n\n }\n\n\n\n // Close inputFiles\n\n inputAuthors.close();\n\n inputBooks.close();\n\n inputDates.close();\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 86, "score": 53326.82662118324 }, { "content": " {\n\n // Open input/ouput files\n\n inputAuthors.open(\"Adventure_authors.txt\");\n\n inputTitle.open(\"Adventure_titles.txt\");\n\n inputDates.open(\"Adventure_date.txt\");\n\n inputDescription.open(\"Adventure_descriptions.txt\");\n\n keptBooks.open(\"KeptAdventureBooks.txt\", ios::out | ios::app);\n\n\n\n clearScreen();\n\n // Display list of music books\n\n cout << \"Here are the available adventure books: \\n\" << endl;\n\n // Fill arrays with external file data and display contents\n\n for (int count = 0; count < SIZE; count++)\n\n {\n\n getline(inputAuthors, author[count]);\n\n getline(inputTitle, title[count]);\n\n getline(inputDates, date[count]);\n\n getline(inputDescription, description[count], '$');\n\n cout << '\\t' << (count + 1) << \". \"\n\n << title[count] << endl;\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 87, "score": 53326.26071855113 }, { "content": " * asked if they would like to keep the book. If they chose 'yes', the *\n\n * book information will be sent to another file. They the user will be *\n\n * asked if they would like to select another book. If they select 'no', *\n\n * the adventure function will end. *\n\n *************************************************************************\n\n */\n\n\n\nvoid Adventure()\n\n{\n\n // Input Stream Objects\n\n ifstream inputAuthors; // For Authors.txt\n\n ifstream inputTitle; // For Books.txt\n\n ifstream inputDates; // For Date.txt\n\n ifstream inputDescription; // For Discription.txt\n\n\n\n // Output Stream Objects\n\n ofstream keptBooks; // Output Stream Object\n\n\n\n // Constants\n\n const int SIZE = 4,\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 88, "score": 53322.86501694288 }, { "content": "// would like to keep the book they've selected. If yes, *\n\n// The book information will be written to an external file.*\n\n// Then, the user will be asked if they would like to make *\n\n// another music selection. If yes, the program will display*\n\n// the menu again. If no, the program will then exit this *\n\n// function. *\n\n//***********************************************************\n\n\n\nvoid Music()\n\n{\n\n // Input Stream Objects\n\n ifstream inputAuthors, // For MusicAuthors.txt\n\n inputBooks, // For MusicBooks.txt\n\n inputDates; // For MusicDate.txt\n\n\n\n // Output Stream Objects\n\n ofstream keptBooks; // Output Stream Object\n\n\n\n // Constants\n\n const int SIZE = 4,\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 89, "score": 53322.84168219888 }, { "content": "\n\n// Directives for clearing the screen\n\n#ifdef _WIN32\n\nchar buffer[4] = \"cls\";\n\nconst char* clearVar = buffer;\n\n#ifdef _WIN64\n\nchar buffer[4] = \"cls\";\n\nconst char* clearVar = buffer;\n\n#endif\n\n#else\n\nchar buffer[6] = \"clear\";\n\nconst char* clearVar = buffer;\n\n#endif\n\n\n\n//Function Prototypes\n\nvoid Music(); // Music Genre\n\nvoid Romance(); // Romance Genre\n\nvoid Adventure(); // Adventure Genre\n\nvoid Mystery(); // Mystery Genre\n\nvoid clearScreen(); // Mystery Genre\n", "file_path": "Projects/BookFlix/main.cpp", "rank": 90, "score": 53319.657760681504 }, { "content": "//******************************************\n\n// This program check for valid user input.\n\n// In this case the characters Y or N\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: December 5, 2016\n\n//******************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n // Variables\n\n char letter;\n\n\n\n // Ask user to enter Y or N\n\n cout << \"Would you like to continue (Y/N)? \";\n\n // Receive user input\n\n cin >> letter;\n\n // Error check algorithim\n", "file_path": "InputValidation/YorNCheck.cpp", "rank": 91, "score": 52080.994403569355 }, { "content": "//***********************************************************\n\n// What is the output of the program if the user enters\n\n// 12 and 14?\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: October 22nd, 2016\n\n//***********************************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nvoid func1(int &, int &);\n\nvoid func2(int &, int &, int &);\n\nvoid func3(int, int, int);\n\n\n\nint main()\n\n{\n\n int x = 0, y = 0, z = 0;\n\n\n\n cout << x << \" \" << y << \" \" << z << endl;\n\n func1(x, y);\n", "file_path": "Chapter-6-Functions/Other/what-would-happen-if-user-enters-12-and-14.cpp", "rank": 92, "score": 52071.911735451955 }, { "content": "//This program demonstrates how setprecision rounds\n\n// a floating point value\n\n\n\n//JESUS HILARIO HERNANDEZ\n\n\n\n//Last modified: 9/27/2016\n\n\n\n#include <iostream> //for input output\n\n#include <iomanip> // REQUIRED FOR setprecision() manipulator\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n double quotient, number1 = 132.3664, number2 = 26.91;\n\n\n\n quotient = number1 / number2;\n\n cout << quotient << endl;\n\n cout << setprecision(5) << quotient << endl; //float 5 digits NOT! decimal places\n\n cout << setprecision(4) << quotient << endl; //float 4 digits NOT! decimal places\n\n cout << setprecision(3) << quotient << endl; //float 3 digits NOT! decimal places\n", "file_path": "Replicated Programs/setprecision-floating-point.cpp", "rank": 93, "score": 52071.882690410355 }, { "content": " while (!((letter == 'y') || (letter == 'Y') || (letter == 'n') || (letter == 'N')))\n\n {\n\n // Explain error\n\n cout << \"ERROR: a Y or an N must be entered: \";\n\n // Clear input stream\n\n cin.clear();\n\n // Discard previous input\n\n cin.ignore(132, '\\n');\n\n // Receive input again\n\n cin >> letter;\n\n }\n\n\n\n if (letter == 'y' || letter == 'Y')\n\n {\n\n cout << \"You've entered \" << letter << \". Let's continue!\" << endl;\n\n }\n\n else if (letter == 'n' || letter == 'N')\n\n {\n\n cout << \"Since you've entered. \" << letter\n\n << \"Let's not continute. :(\" << endl;\n\n }\n\n\n\n\n\n return 0;\n\n}\n", "file_path": "InputValidation/YorNCheck.cpp", "rank": 94, "score": 52068.675036190994 }, { "content": "//***********************************************************\n\n// This program demonstrates how cin can read multiple values\n\n// of different data types.\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: December 6, 2016\n\n//***********************************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n int whole;\n\n double fractional;\n\n char letter;\n\n\n\n cout << \"Enter an integer, a double, and a character: \";\n\n cin >> whole >> fractional >> letter;\n\n cout << \"Whole: \" << whole << endl;\n\n cout << \"Fractional: \" << fractional << endl;\n\n cout << \"Letter: \" << letter << endl;\n\n return 0;\n\n}\n", "file_path": "Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-3.cpp", "rank": 95, "score": 52068.40927285987 }, { "content": "//*********************************\n\n// A well-adjusted printing program.\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: November 21, 2016\n\n//*********************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n cout << \"The following items were top sellers\" << endl;\n\n cout << \"during the month of july:\" << endl;\n\n cout << \"Computer games\" << endl;\n\n cout << \"Coffee\" << endl;\n\n cout << \"Aspirin\" << endl;\n\n return 0;\n\n}", "file_path": "Chapter-2-Intro-to-C++/2.2-The-cout-object/2-5.cpp", "rank": 96, "score": 52067.99326316454 }, { "content": "//***************************************************\n\n// Yet another well-adjusted printing program\n\n// \n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: November 21, 2016\n\n//***************************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n cout << \"The following items were top sellers\\n\";\n\n cout << \"during the month of July:\\n\";\n\n cout << \"Computer games\\nCoffee\";\n\n cout << \"\\nAspirin\\n\";\n\n return 0;\n\n}", "file_path": "Chapter-2-Intro-to-C++/2.2-The-cout-object/2-6.cpp", "rank": 97, "score": 52067.44522833261 }, { "content": "//**********************************************************\n\n// This program asks the user to enter the length and width\n\n// of a rectangle. It calculates the rectangle's area and\n\n// displays the value on the screen.\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: December 6, 2016\n\n//**********************************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n int length, width, area;\n\n\n\n cout << \"This program calculates the area of a \";\n\n cout << \"rectangle.\\n\";\n\n cout << \"Enter the length and width of the rectangle \";\n\n cin >> length >> width;\n\n area = length * width;\n\n cout << \"The area of the rectangle is \" << area << endl;\n\n return 0;\n\n}\n", "file_path": "Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-2.cpp", "rank": 98, "score": 52067.01229307463 }, { "content": "//************************************************\n\n// This program asks the user to enter the length\n\n// and width of a rectangle. It calculates the\n\n// rectangle's area and displays the value on the\n\n// screen.\n\n//\n\n// By: Jesus Hilario Hernandez\n\n// Last Updated: December 6, 2016\n\n//************************************************\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n int length, width, area;\n\n\n\n cout << \"This program calculates the area of a \";\n\n cout << \"rectangle.\\n\";\n\n cout << \"What is the length of the rectangle? \";\n\n cin >> length;\n\n cout << \"What is the width of the rectangle? \";\n\n cin >> width;\n\n area = length * width;\n\n cout << \"The area of the rectangle is \" << area << \".\\n\";\n\n return 0;\n\n}\n", "file_path": "Chapter-3-Expressions-and-Interactivity/3.1 The cin Object/3-1.cpp", "rank": 99, "score": 52066.73960874564 } ]
C++
lib/stages/pulsarNetworkProcess.cpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
#include <arpa/inet.h> #include <assert.h> #include <chrono> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <functional> #include <iostream> #include <math.h> #include <netinet/in.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/socket.h> #include <unistd.h> using std::string; #include "Config.hpp" #include "buffer.h" #include "chimeMetadata.h" #include "errors.h" #include "fpga_header_functions.h" #include "pulsarNetworkProcess.hpp" #include "tx_utils.hpp" #include "util.h" #include "vdif_functions.h" using kotekan::bufferContainer; using kotekan::Config; using kotekan::Stage; REGISTER_KOTEKAN_STAGE(pulsarNetworkProcess); pulsarNetworkProcess::pulsarNetworkProcess(Config& config_, const string& unique_name, bufferContainer& buffer_container) : Stage(config_, unique_name, buffer_container, std::bind(&pulsarNetworkProcess::main_thread, this)) { in_buf = get_buffer("pulsar_out_buf"); register_consumer(in_buf, unique_name.c_str()); udp_pulsar_packet_size = config.get<int>(unique_name, "udp_pulsar_packet_size"); udp_pulsar_port_number = config.get<int>(unique_name, "udp_pulsar_port_number"); number_of_nodes = config.get<int>(unique_name, "number_of_nodes"); number_of_subnets = config.get<int>(unique_name, "number_of_subnets"); timesamples_per_pulsar_packet = config.get_default<int>(unique_name, "timesamples_per_pulsar_packet", 625); num_packet_per_stream = config.get_default<int>(unique_name, "num_packet_per_stream", 80); my_host_name = (char*)malloc(sizeof(char) * 100); CHECK_MEM(my_host_name); } pulsarNetworkProcess::~pulsarNetworkProcess() { free(my_host_name); for (int i = 0; i < number_of_subnets; i++) free(my_ip_address[i]); free(my_ip_address); free(socket_ids); free(myaddr); free(server_address); free(sock_fd); } void pulsarNetworkProcess::main_thread() { int rack, node, nos, my_node_id; std::vector<std::string> link_ip = config.get<std::vector<std::string>>(unique_name, "pulsar_node_ips"); int number_of_pulsar_links = link_ip.size(); INFO("number_of_pulsar_links: {:d}", number_of_pulsar_links); sock_fd = (int*)malloc(sizeof(int) * number_of_subnets); server_address = (sockaddr_in*)malloc(sizeof(sockaddr_in) * number_of_pulsar_links); myaddr = (sockaddr_in*)malloc(sizeof(sockaddr_in) * number_of_pulsar_links); socket_ids = (int*)malloc(sizeof(int) * number_of_pulsar_links); my_ip_address = (char**)malloc(sizeof(char*) * number_of_subnets); for (int i = 0; i < number_of_subnets; i++) my_ip_address[i] = (char*)malloc(sizeof(char) * 100); INFO("number of subnets {:d}\n", number_of_subnets); parse_chime_host_name(rack, node, nos, my_node_id); for (int i = 0; i < number_of_subnets; i++) { if (std::snprintf(my_ip_address[i], 100, "10.%d.%d.1%d", i + 15, nos + rack, node) > 100) { FATAL_ERROR("buffer spill over "); return; } INFO("{:s} ", my_ip_address[i]); } int frame_id = 0; uint8_t* packet_buffer = NULL; for (int i = 0; i < number_of_subnets; i++) { sock_fd[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock_fd[i] < 0) { FATAL_ERROR("network thread: socket() failed: "); return; } } for (int i = 0; i < number_of_subnets; i++) { std::memset((char*)&myaddr[i], 0, sizeof(myaddr[i])); myaddr[i].sin_family = AF_INET; inet_pton(AF_INET, my_ip_address[i], &myaddr[i].sin_addr); myaddr[i].sin_port = htons(udp_pulsar_port_number); if (bind(sock_fd[i], (struct sockaddr*)&myaddr[i], sizeof(myaddr[i])) < 0) { FATAL_ERROR("port binding failed "); return; } } for (int i = 0; i < number_of_pulsar_links; i++) { memset(&server_address[i], 0, sizeof(server_address[i])); server_address[i].sin_family = AF_INET; inet_pton(AF_INET, link_ip[i].c_str(), &server_address[i].sin_addr); server_address[i].sin_port = htons(udp_pulsar_port_number); socket_ids[i] = get_vlan_from_ip(link_ip[i].c_str()) - 15; } int n = 256 * 1024 * 1024; for (int i = 0; i < number_of_subnets; i++) { if (setsockopt(sock_fd[i], SOL_SOCKET, SO_SNDBUF, (void*)&n, sizeof(n)) < 0) { FATAL_ERROR("network thread: setsockopt() failed "); return; } } struct timespec t0, t1; t0.tv_sec = 0; t0.tv_nsec = 0; unsigned long time_interval = num_packet_per_stream * timesamples_per_pulsar_packet * 2560; int my_sequence_id = (int)(my_node_id / 128) + 2 * ((my_node_id % 128) / 8) + 32 * (my_node_id % 8); packet_buffer = wait_for_full_frame(in_buf, unique_name.c_str(), frame_id); if (packet_buffer == NULL) return; mark_frame_empty(in_buf, unique_name.c_str(), frame_id); frame_id = (frame_id + 1) % in_buf->num_frames; clock_gettime(CLOCK_REALTIME, &t0); unsigned long abs_ns = t0.tv_sec * 1e9 + t0.tv_nsec; unsigned long reminder = (abs_ns % time_interval); unsigned long wait_ns = time_interval - reminder + my_sequence_id * 600; add_nsec(t0, wait_ns); CLOCK_ABS_NANOSLEEP(CLOCK_REALTIME, t0); clock_gettime(CLOCK_MONOTONIC, &t0); VDIFHeader* header = reinterpret_cast<VDIFHeader*>(packet_buffer); int64_t vdif_last_seconds = header->seconds; int64_t vdif_last_frame = header->data_frame; while (!stop_thread) { packet_buffer = wait_for_full_frame(in_buf, unique_name.c_str(), frame_id); if (packet_buffer == NULL) break; header = reinterpret_cast<VDIFHeader*>(packet_buffer); time_interval = 2560 * (390625 * (header->seconds - vdif_last_seconds) + 625 * (header->data_frame - vdif_last_frame)); add_nsec(t0, time_interval); t1.tv_sec = t0.tv_sec; t1.tv_nsec = t0.tv_nsec; vdif_last_seconds = header->seconds; vdif_last_frame = header->data_frame; for (int frame = 0; frame < 80; frame++) { for (int beam = 0; beam < 10; beam++) { int e_beam = my_sequence_id + beam; e_beam = e_beam % 10; CLOCK_ABS_NANOSLEEP(CLOCK_MONOTONIC, t1); if (e_beam < number_of_pulsar_links) { sendto(sock_fd[socket_ids[e_beam]], &packet_buffer[(e_beam)*80 * udp_pulsar_packet_size + frame * udp_pulsar_packet_size], udp_pulsar_packet_size, 0, (struct sockaddr*)&server_address[e_beam], sizeof(server_address[e_beam])); } long wait_per_packet = (long)(153600); add_nsec(t1, wait_per_packet); } } mark_frame_empty(in_buf, unique_name.c_str(), frame_id); frame_id = (frame_id + 1) % in_buf->num_frames; } return; }
#include <arpa/inet.h> #include <assert.h> #include <chrono> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <functional> #include <iostream> #include <math.h> #include <netinet/in.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/socket.h> #include <unistd.h> using std::string; #include "Config.hpp" #include "buffer.h" #include "chimeMetadata.h" #include "errors.h" #include "fpga_header_functions.h" #include "pulsarNetworkProcess.hpp" #include "tx_utils.hpp" #include "util.h" #include "vdif_functions.h" using kotekan::bufferContainer; using kotekan::Config; using kotekan::Stage; REGISTER_KOTEKAN_STAGE(pulsarNetworkProcess); pulsarNetworkProcess::pulsarNetworkProcess(Config& config_, const string& unique_name, bufferContainer& buffer_container) : Stage(config_, unique_name, buffer_container, std::bind(&pulsarNetworkProcess::main_thread, this)) { in_buf = get_buffer("pulsar_out_buf"); register_consumer(in_buf, unique_name.c_str()); udp_pulsar_packet_size = config.get<int>(unique_name, "udp_pulsar_packet_size"); udp_pulsar_port_number = config.get<int>(unique_name, "udp_pulsar_port_number"); number_of_nodes = config.get<int>(unique_name, "number_of_nodes"); number_of_subnets = config.get<int>(unique_name, "number_of_subnets"); timesamples_per_pulsar_packet = config.get_default<int>(unique_name, "timesamples_per_pulsar_packet", 625); num_packet_per_stream = config.get_default<int>(unique_name, "num_packet_per_stream", 80); my_host_name = (char*)malloc(sizeof(char) * 100); CHECK_MEM(my_host_name); } pulsarNetworkProcess::~pulsarNetworkProcess() { free(my_host_name); for (int i = 0; i < number_of_subnets; i++) free(my_ip_address[i]); free(my_ip_address); free(socket_ids); free(myaddr); free(server_address); free(sock_fd); } void pulsarNetworkProcess::main_thread() { int rack, node, nos, my_node_id; std::vector<std::string> link_ip = config.get<std::vector<std::string>>(unique_name, "pulsar_node_ips"); int number_of_pulsar_links = link_ip.size(); INFO("number_of_pulsar_links: {:d}", number_of_pulsar_links); sock_fd = (int*)malloc(sizeof(int) * number_of_subnets); server_address = (sockaddr_in*)malloc(sizeof(sockaddr_in) * number_of_pulsar_links); myaddr = (sockaddr_in*)malloc(sizeof(sockaddr_in) * number_of_pulsar_links); socket_ids = (int*)malloc(sizeof(int) * number_of_pulsar_links); my_ip_address = (char**)malloc(sizeof(char*) * number_of_subnets); for (int i = 0; i < number_of_subnets; i++) my_ip_address[i] = (char*)malloc(sizeof(char) * 100); INFO("number of subnets {:d}\n", number_of_subnets); parse_chime_host_name(rack, node, nos, my_node_id); for (int i = 0; i < number_of_subnets; i++) {
INFO("{:s} ", my_ip_address[i]); } int frame_id = 0; uint8_t* packet_buffer = NULL; for (int i = 0; i < number_of_subnets; i++) { sock_fd[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock_fd[i] < 0) { FATAL_ERROR("network thread: socket() failed: "); return; } } for (int i = 0; i < number_of_subnets; i++) { std::memset((char*)&myaddr[i], 0, sizeof(myaddr[i])); myaddr[i].sin_family = AF_INET; inet_pton(AF_INET, my_ip_address[i], &myaddr[i].sin_addr); myaddr[i].sin_port = htons(udp_pulsar_port_number); if (bind(sock_fd[i], (struct sockaddr*)&myaddr[i], sizeof(myaddr[i])) < 0) { FATAL_ERROR("port binding failed "); return; } } for (int i = 0; i < number_of_pulsar_links; i++) { memset(&server_address[i], 0, sizeof(server_address[i])); server_address[i].sin_family = AF_INET; inet_pton(AF_INET, link_ip[i].c_str(), &server_address[i].sin_addr); server_address[i].sin_port = htons(udp_pulsar_port_number); socket_ids[i] = get_vlan_from_ip(link_ip[i].c_str()) - 15; } int n = 256 * 1024 * 1024; for (int i = 0; i < number_of_subnets; i++) { if (setsockopt(sock_fd[i], SOL_SOCKET, SO_SNDBUF, (void*)&n, sizeof(n)) < 0) { FATAL_ERROR("network thread: setsockopt() failed "); return; } } struct timespec t0, t1; t0.tv_sec = 0; t0.tv_nsec = 0; unsigned long time_interval = num_packet_per_stream * timesamples_per_pulsar_packet * 2560; int my_sequence_id = (int)(my_node_id / 128) + 2 * ((my_node_id % 128) / 8) + 32 * (my_node_id % 8); packet_buffer = wait_for_full_frame(in_buf, unique_name.c_str(), frame_id); if (packet_buffer == NULL) return; mark_frame_empty(in_buf, unique_name.c_str(), frame_id); frame_id = (frame_id + 1) % in_buf->num_frames; clock_gettime(CLOCK_REALTIME, &t0); unsigned long abs_ns = t0.tv_sec * 1e9 + t0.tv_nsec; unsigned long reminder = (abs_ns % time_interval); unsigned long wait_ns = time_interval - reminder + my_sequence_id * 600; add_nsec(t0, wait_ns); CLOCK_ABS_NANOSLEEP(CLOCK_REALTIME, t0); clock_gettime(CLOCK_MONOTONIC, &t0); VDIFHeader* header = reinterpret_cast<VDIFHeader*>(packet_buffer); int64_t vdif_last_seconds = header->seconds; int64_t vdif_last_frame = header->data_frame; while (!stop_thread) { packet_buffer = wait_for_full_frame(in_buf, unique_name.c_str(), frame_id); if (packet_buffer == NULL) break; header = reinterpret_cast<VDIFHeader*>(packet_buffer); time_interval = 2560 * (390625 * (header->seconds - vdif_last_seconds) + 625 * (header->data_frame - vdif_last_frame)); add_nsec(t0, time_interval); t1.tv_sec = t0.tv_sec; t1.tv_nsec = t0.tv_nsec; vdif_last_seconds = header->seconds; vdif_last_frame = header->data_frame; for (int frame = 0; frame < 80; frame++) { for (int beam = 0; beam < 10; beam++) { int e_beam = my_sequence_id + beam; e_beam = e_beam % 10; CLOCK_ABS_NANOSLEEP(CLOCK_MONOTONIC, t1); if (e_beam < number_of_pulsar_links) { sendto(sock_fd[socket_ids[e_beam]], &packet_buffer[(e_beam)*80 * udp_pulsar_packet_size + frame * udp_pulsar_packet_size], udp_pulsar_packet_size, 0, (struct sockaddr*)&server_address[e_beam], sizeof(server_address[e_beam])); } long wait_per_packet = (long)(153600); add_nsec(t1, wait_per_packet); } } mark_frame_empty(in_buf, unique_name.c_str(), frame_id); frame_id = (frame_id + 1) % in_buf->num_frames; } return; }
if (std::snprintf(my_ip_address[i], 100, "10.%d.%d.1%d", i + 15, nos + rack, node) > 100) { FATAL_ERROR("buffer spill over "); return; }
if_condition
[]
C++
chrome/browser/chromeos/cros_settings.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
#include "chrome/browser/chromeos/cros_settings.h" #include "base/lazy_instance.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/browser/chromeos/cros_settings_provider.h" #include "chrome/browser/chromeos/user_cros_settings_provider.h" #include "content/common/notification_details.h" #include "content/common/notification_source.h" #include "content/common/notification_type.h" namespace chromeos { static base::LazyInstance<CrosSettings> g_cros_settings( base::LINKER_INITIALIZED); CrosSettings* CrosSettings::Get() { return g_cros_settings.Pointer(); } bool CrosSettings::IsCrosSettings(const std::string& path) { return StartsWithASCII(path, kCrosSettingsPrefix, true); } void CrosSettings::FireObservers(const char* path) { DCHECK(CalledOnValidThread()); std::string path_str(path); SettingsObserverMap::iterator observer_iterator = settings_observers_.find(path_str); if (observer_iterator == settings_observers_.end()) return; NotificationObserverList::Iterator it(*(observer_iterator->second)); NotificationObserver* observer; while ((observer = it.GetNext()) != NULL) { observer->Observe(NotificationType::SYSTEM_SETTING_CHANGED, Source<CrosSettings>(this), Details<std::string>(&path_str)); } } void CrosSettings::Set(const std::string& path, Value* in_value) { DCHECK(CalledOnValidThread()); CrosSettingsProvider* provider; provider = GetProvider(path); if (provider) { provider->Set(path, in_value); } } void CrosSettings::SetBoolean(const std::string& path, bool in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateBooleanValue(in_value)); } void CrosSettings::SetInteger(const std::string& path, int in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateIntegerValue(in_value)); } void CrosSettings::SetDouble(const std::string& path, double in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateDoubleValue(in_value)); } void CrosSettings::SetString(const std::string& path, const std::string& in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateStringValue(in_value)); } bool CrosSettings::AddSettingsProvider(CrosSettingsProvider* provider) { DCHECK(CalledOnValidThread()); providers_.push_back(provider); return true; } bool CrosSettings::RemoveSettingsProvider(CrosSettingsProvider* provider) { DCHECK(CalledOnValidThread()); std::vector<CrosSettingsProvider*>::iterator it = std::find(providers_.begin(), providers_.end(), provider); if (it != providers_.end()) { providers_.erase(it); return true; } return false; } void CrosSettings::AddSettingsObserver(const char* path, NotificationObserver* obs) { DCHECK(path); DCHECK(obs); DCHECK(CalledOnValidThread()); if (!GetProvider(std::string(path))) { NOTREACHED() << "Trying to add an observer for an unregistered setting: " << path; return; } NotificationObserverList* observer_list = NULL; SettingsObserverMap::iterator observer_iterator = settings_observers_.find(path); if (observer_iterator == settings_observers_.end()) { observer_list = new NotificationObserverList; settings_observers_[path] = observer_list; } else { observer_list = observer_iterator->second; } NotificationObserverList::Iterator it(*observer_list); NotificationObserver* existing_obs; while ((existing_obs = it.GetNext()) != NULL) { DCHECK(existing_obs != obs) << path << " observer already registered"; if (existing_obs == obs) return; } observer_list->AddObserver(obs); } void CrosSettings::RemoveSettingsObserver(const char* path, NotificationObserver* obs) { DCHECK(CalledOnValidThread()); SettingsObserverMap::iterator observer_iterator = settings_observers_.find(path); if (observer_iterator == settings_observers_.end()) { return; } NotificationObserverList* observer_list = observer_iterator->second; observer_list->RemoveObserver(obs); } CrosSettingsProvider* CrosSettings::GetProvider( const std::string& path) const { for (size_t i = 0; i < providers_.size(); ++i) { if (providers_[i]->HandlesSetting(path)) { return providers_[i]; } } return NULL; } bool CrosSettings::Get(const std::string& path, Value** out_value) const { DCHECK(CalledOnValidThread()); CrosSettingsProvider* provider; provider = GetProvider(path); if (provider) { return provider->Get(path, out_value); } return false; } bool CrosSettings::GetBoolean(const std::string& path, bool* bool_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsBoolean(bool_value); } bool CrosSettings::GetInteger(const std::string& path, int* out_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsInteger(out_value); } bool CrosSettings::GetDouble(const std::string& path, double* out_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsDouble(out_value); } bool CrosSettings::GetString(const std::string& path, std::string* out_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsString(out_value); } CrosSettings::CrosSettings() { } CrosSettings::~CrosSettings() { DCHECK(providers_.empty()); } }
#include "chrome/browser/chromeos/cros_settings.h" #include "base/lazy_instance.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/browser/chromeos/cros_settings_provider.h" #include "chrome/browser/chromeos/user_cros_settings_provider.h" #include "content/common/notification_details.h" #include "content/common/notification_source.h" #include "content/common/notification_type.h" namespace chromeos { static base::LazyInstance<CrosSettings> g_cros_settings( base::LINKER_INITIALIZED); CrosSettings* CrosSettings::Get() { return g_cros_settings.Pointer(); } bool CrosSettings::IsCrosSettings(const std::string& path) { return StartsWithASCII(path, kCrosSettingsPrefix, true); } void CrosSettings::FireObservers(const char* path) { DCHECK(CalledOnValidThread()); std::string path_str(path); SettingsObserverMap::iterator observer_iterator = settings_observers_.find(path_str); if (observer_iterator == settings_observers_.end()) return; NotificationObserverList::Iterator it(*(observer_iterator->second)); NotificationObserver* observer; while ((observer = it.GetNext()) != NULL) { observer->Observe(NotificationType::SYSTEM_SETTING_CHANGED, Source<CrosSettings>(this), Details<std::string>(&path_str)); } } void CrosSettings::Set(const std::string& path, Value* in_value) { DCHECK(CalledOnValidThread()); CrosSettingsProvider* provider; provider = GetProvider(path); if (provider) { provider->Set(path, in_value); } } void CrosSettings::SetBoolean(const std::string& path, bool in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateBooleanValue(in_value)); } void CrosSettings::SetInteger(const std::string& path, int in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateIntegerValue(in_value)); } void CrosSettings::SetDouble(const std::string& path, double in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateDoubleValue(in_value)); } void CrosSettings::SetString(const std::string& path, const std::string& in_value) { DCHECK(CalledOnValidThread()); Set(path, Value::CreateStringValue(in_value)); } bool CrosSettings::AddSettingsProvider(CrosSettingsProvider* provider) { DCHECK(CalledOnValidThread()); providers_.push_back(provider); return true; } bool CrosSettings::RemoveSettingsProvider(CrosSettingsProvider* provider) { DCHECK(CalledOnValidThread()); std::vector<CrosSettingsProvider*>::iterator it = std::find(providers_.begin(), providers_.end(), provider); if (it != providers_.end()) { providers_.erase(it); return true; } return false; } void CrosSettings::AddSettingsObserver(const char* path, NotificationObserver* obs) { DCHECK(path); DCHECK(obs); DCHECK(CalledOnValidThread()); if (!GetProvider(std::string(path))) { NOTREACHED() << "Trying to add an observer for an unregistered setting: " << path; return; } NotificationObserverList* observer_list = NULL; SettingsObserverMap::iterator observer_iterator = settings_observers_.find(path); if (observer_iterator == settings_observers_.end()) { observer_list = new NotificationObserverList; settings_observers_[path] = observer_list; } else { observer_list = observer_iterator->second; } NotificationObserverList::Iterator it(*observer_list); NotificationObserver* existing_obs; while ((existing_obs = it.GetNext()) != NULL) { DCHECK(existing_obs != obs) << path << " observer already registered"; if (existing_obs == obs) return; } observer_list->AddObserver(obs); } void CrosSettings::RemoveSettingsObserver(const char* path, NotificationObserver* obs) { DCHECK(CalledOnValidThread()); SettingsObserverMap::iterator observer_iterator = settings_observers_.find(path); if (observer_iterator == settings_observers_.end()) { return; } NotificationObserverList* observer_list = observer_iterator->second; observer_list->RemoveObserver(obs); } CrosSettingsProvider* CrosSettings::GetProvider( const std::string& path) const { for (size_t i = 0; i < providers_.size(); ++i) { if (providers_[i]->HandlesSetting(path)) { return providers_[i]; } } return NULL; } bool
bool CrosSettings::GetBoolean(const std::string& path, bool* bool_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsBoolean(bool_value); } bool CrosSettings::GetInteger(const std::string& path, int* out_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsInteger(out_value); } bool CrosSettings::GetDouble(const std::string& path, double* out_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsDouble(out_value); } bool CrosSettings::GetString(const std::string& path, std::string* out_value) const { DCHECK(CalledOnValidThread()); Value* value; if (!Get(path, &value)) return false; return value->GetAsString(out_value); } CrosSettings::CrosSettings() { } CrosSettings::~CrosSettings() { DCHECK(providers_.empty()); } }
CrosSettings::Get(const std::string& path, Value** out_value) const { DCHECK(CalledOnValidThread()); CrosSettingsProvider* provider; provider = GetProvider(path); if (provider) { return provider->Get(path, out_value); } return false; }
function_block-function_prefixed
[ { "content": "struct tuple_size<GTEST_0_TUPLE_(T)> { static const int value = 0; };\n\n\n\ntemplate <GTEST_1_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 0, "score": 425778.8998875817 }, { "content": "struct tuple_size<GTEST_3_TUPLE_(T)> { static const int value = 3; };\n\n\n\ntemplate <GTEST_4_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 1, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_7_TUPLE_(T)> { static const int value = 7; };\n\n\n\ntemplate <GTEST_8_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 2, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_5_TUPLE_(T)> { static const int value = 5; };\n\n\n\ntemplate <GTEST_6_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 3, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_6_TUPLE_(T)> { static const int value = 6; };\n\n\n\ntemplate <GTEST_7_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 4, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_10_TUPLE_(T)> { static const int value = 10; };\n\n\n\ntemplate <int k, class Tuple>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 5, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_2_TUPLE_(T)> { static const int value = 2; };\n\n\n\ntemplate <GTEST_3_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 6, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_8_TUPLE_(T)> { static const int value = 8; };\n\n\n\ntemplate <GTEST_9_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 7, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_1_TUPLE_(T)> { static const int value = 1; };\n\n\n\ntemplate <GTEST_2_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 8, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_4_TUPLE_(T)> { static const int value = 4; };\n\n\n\ntemplate <GTEST_5_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 9, "score": 392010.1203052006 }, { "content": "struct tuple_size<GTEST_9_TUPLE_(T)> { static const int value = 9; };\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "testing/gtest/include/gtest/internal/gtest-tuple.h", "rank": 10, "score": 392010.1203052006 }, { "content": "struct ConstantLabel { int value; const char * label; };\n\n\n\n#if defined(SAFE_TO_DEFINE_TALK_BASE_LOGGING_MACROS)\n\n#define KLABEL(x) { x, #x }\n\n#define TLABEL(x, y) { x, y }\n\n#define LASTLABEL { 0, 0 }\n\n#endif // defined(SAFE_TO_DEFINE_TALK_BASE_LOGGING_MACROS)\n\n\n\nconst char * FindLabel(int value, const ConstantLabel entries[]);\n\nstd::string ErrorName(int err, const ConstantLabel* err_table);\n\n\n\n//////////////////////////////////////////////////////////////////////\n\n\n", "file_path": "third_party/libjingle/overrides/talk/base/logging.h", "rank": 11, "score": 357782.70099871705 }, { "content": "struct ConstantLabel { int value; const char * label; };\n\n#define KLABEL(x) { x, #x }\n\n#define TLABEL(x, y) { x, y }\n\n#define LASTLABEL { 0, 0 }\n\n\n\nconst char * FindLabel(int value, const ConstantLabel entries[]);\n\nstd::string ErrorName(int err, const ConstantLabel* err_table);\n\n\n\n//////////////////////////////////////////////////////////////////////\n\n\n", "file_path": "third_party/libjingle/source/talk/base/logging.h", "rank": 12, "score": 357782.700998717 }, { "content": "class Value;\n\n\n\nnamespace chromeos {\n\n\n", "file_path": "chrome/browser/chromeos/cros_settings_provider.h", "rank": 13, "score": 281875.50263420196 }, { "content": "class ListValue;\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.h", "rank": 14, "score": 269061.4465921202 }, { "content": "enum UseValue {\n\n USE_VALUE_SUPPLIED,\n\n USE_VALUE_DEFAULT\n\n};\n\n\n\nvoid UpdateCacheBool(const std::string& name,\n\n bool value,\n\n UseValue use_value) {\n\n PrefService* prefs = g_browser_process->local_state();\n\n if (use_value == USE_VALUE_DEFAULT)\n\n prefs->ClearPref(name.c_str());\n\n else\n\n prefs->SetBoolean(name.c_str(), value);\n\n prefs->ScheduleSavePersistentPrefs();\n\n}\n\n\n\nvoid UpdateCacheString(const std::string& name,\n\n const std::string& value,\n\n UseValue use_value) {\n\n PrefService* prefs = g_browser_process->local_state();\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 15, "score": 263081.6037491313 }, { "content": "class Value;\n", "file_path": "chrome/browser/ui/webui/options/chromeos/system_settings_provider.h", "rank": 16, "score": 263081.6037491313 }, { "content": "class ListValue;\n\n\n\nnamespace chromeos {\n\n\n", "file_path": "chrome/browser/ui/webui/options/chromeos/system_settings_provider.h", "rank": 17, "score": 257361.7838321568 }, { "content": "class DefaultValue<void> {\n\n public:\n\n static bool Exists() { return true; }\n\n static void Get() {}\n\n};\n\n\n\n// Points to the user-set default value for type T.\n\ntemplate <typename T>\n\nconst T* DefaultValue<T>::value_ = NULL;\n\n\n\n// Points to the user-set default value for type T&.\n\ntemplate <typename T>\n\nT* DefaultValue<T&>::address_ = NULL;\n\n\n\n// Implement this interface to define an action for function type F.\n\ntemplate <typename F>\n", "file_path": "testing/gmock/include/gmock/gmock-actions.h", "rank": 18, "score": 255925.94257980073 }, { "content": "class FooTest : public ::testing::TestWithParam<const char*> {\n\n // You can implement all the usual class fixture members here.\n\n};\n\n\n\n// Then, use the TEST_P macro to define as many parameterized tests\n\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n\n// or \"pattern\", whichever you prefer to think.\n\n\n\nTEST_P(FooTest, DoesBlah) {\n\n // Inside a test, access the test parameter with the GetParam() method\n\n // of the TestWithParam<T> class:\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n ...\n\n}\n\n\n\nTEST_P(FooTest, HasBlahBlah) {\n\n ...\n\n}\n\n\n\n// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test\n", "file_path": "testing/gtest/include/gtest/gtest-param-test.h", "rank": 19, "score": 255004.67581349896 }, { "content": "class BuiltInDefaultValue<const T> {\n\n public:\n\n static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }\n\n static T Get() { return BuiltInDefaultValue<T>::Get(); }\n\n};\n\n\n\n// This partial specialization defines the default values for pointer\n\n// types.\n\ntemplate <typename T>\n", "file_path": "testing/gmock/include/gmock/gmock-actions.h", "rank": 20, "score": 242285.78066839947 }, { "content": "class CrosSettingsProvider {\n\n public:\n\n virtual ~CrosSettingsProvider() {}\n\n\n\n // Sets |in_value| to given |path| in cros settings.\n\n // Note that this takes ownership of |in_value|.\n\n void Set(const std::string& path, Value* in_value);\n\n\n\n // Gets settings value of given |path| to |out_value|.\n\n // Note that |out_value| is owned by the caller, not this class.\n\n virtual bool Get(const std::string& path, Value** out_value) const = 0;\n\n\n\n // Gets the namespace prefix provided by this provider\n\n virtual bool HandlesSetting(const std::string& path) = 0;\n\n\n\n private:\n\n // Does the real job for Set().\n\n virtual void DoSet(const std::string& path, Value* in_value) = 0;\n\n};\n\n\n\n} // namespace chromeos\n\n\n\n#endif // CHROME_BROWSER_CHROMEOS_CROS_SETTINGS_PROVIDER_H_\n", "file_path": "chrome/browser/chromeos/cros_settings_provider.h", "rank": 21, "score": 235926.12520522292 }, { "content": "class WhitelistOpContext : public SignedSettings::Delegate<bool>,\n\n public OpContext {\n\n public:\n\n enum Type {\n\n CHECK,\n\n ADD,\n\n REMOVE,\n\n };\n\n\n\n WhitelistOpContext(Type type,\n\n const std::string& email,\n\n SignedSettingsHelper::Callback* callback,\n\n OpContext::Delegate* delegate)\n\n : OpContext(callback, delegate),\n\n type_(type),\n\n email_(email) {\n\n }\n\n\n\n // chromeos::SignedSettings::Delegate implementation\n\n virtual void OnSettingsOpCompleted(SignedSettings::ReturnCode code,\n", "file_path": "chrome/browser/chromeos/login/signed_settings_helper.cc", "rank": 22, "score": 234302.9180096231 }, { "content": "// CrosSettingsProvider implementation that works with SignedSettings.\n\n// TODO(nkostylev): Rename this class to indicate that it is\n\n// SignedSettings specific.\n\nclass UserCrosSettingsProvider : public CrosSettingsProvider {\n\n public:\n\n UserCrosSettingsProvider();\n\n virtual ~UserCrosSettingsProvider() {}\n\n\n\n // Registers cached users settings in preferences.\n\n static void RegisterPrefs(PrefService* local_state);\n\n\n\n // Methods to use when trusted (signature verified) values are required.\n\n // Return true if subsequent call to corresponding cached_* getter shall\n\n // return trusted value.\n\n // Return false if trusted values are unavailable at a moment.\n\n // In latter case passed task will be posted when ready.\n\n bool RequestTrustedAllowGuest(Task* callback);\n\n bool RequestTrustedAllowNewUser(Task* callback);\n\n bool RequestTrustedDataRoamingEnabled(Task* callback);\n\n bool RequestTrustedShowUsersOnSignin(Task* callback);\n\n bool RequestTrustedOwner(Task* callback);\n\n\n\n // Reloads values from device settings.\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.h", "rank": 23, "score": 232720.16732633737 }, { "content": "// CrosSettingsProvider that abstracts switching of stats/crash\n\n// reporting to Google.\n\nclass MetricsCrosSettingsProvider : public CrosSettingsProvider {\n\n public:\n\n MetricsCrosSettingsProvider() {}\n\n\n\n // Actual methods to control stats/crash reporting. Currently these\n\n // methods are public and static so they are accessible directly\n\n // from cros code. But this will change soon: crosbug.com/7359\n\n static bool SetMetricsStatus(bool enabled);\n\n static bool GetMetricsStatus();\n\n\n\n private:\n\n // CrosSettingsProvider implementation.\n\n virtual void DoSet(const std::string& path, Value* value);\n\n virtual bool Get(const std::string& path, Value** value) const;\n\n virtual bool HandlesSetting(const std::string& path);\n\n\n\n DISALLOW_COPY_AND_ASSIGN(MetricsCrosSettingsProvider);\n\n};\n\n\n\n}; // namespace chromeos\n\n\n\n#endif // CHROME_BROWSER_CHROMEOS_METRICS_CROS_SETTINGS_PROVIDER_H_\n", "file_path": "chrome/browser/chromeos/metrics_cros_settings_provider.h", "rank": 24, "score": 232718.84133497192 }, { "content": "class ProxyCrosSettingsProvider : public CrosSettingsProvider {\n\n public:\n\n ProxyCrosSettingsProvider();\n\n // CrosSettingsProvider implementation.\n\n virtual bool Get(const std::string& path, Value** out_value) const;\n\n virtual bool HandlesSetting(const std::string& path);\n\n\n\n private:\n\n // CrosSettingsProvider implementation.\n\n virtual void DoSet(const std::string& path, Value* value);\n\n\n\n chromeos::ProxyConfigServiceImpl* GetConfigService() const;\n\n\n\n net::ProxyServer CreateProxyServerFromHost(\n\n const std::string& host,\n\n const ProxyConfigServiceImpl::ProxyConfig::ManualProxy& proxy,\n\n net::ProxyServer::Scheme scheme) const;\n\n\n\n net::ProxyServer CreateProxyServerFromPort(\n\n uint16 port,\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.h", "rank": 25, "score": 232702.8876775852 }, { "content": "class StorePropertyOpContext : public SignedSettings::Delegate<bool>,\n\n public OpContext {\n\n public:\n\n StorePropertyOpContext(const std::string& name,\n\n const std::string& value,\n\n SignedSettingsHelper::Callback* callback,\n\n OpContext::Delegate* delegate)\n\n : OpContext(callback, delegate),\n\n name_(name),\n\n value_(value) {\n\n }\n\n\n\n // chromeos::SignedSettings::Delegate implementation\n\n virtual void OnSettingsOpCompleted(SignedSettings::ReturnCode code,\n\n bool unused) OVERRIDE {\n\n VLOG(2) << \"OnSettingsOpCompleted, code = \" << code;\n\n if (callback_)\n\n callback_->OnStorePropertyCompleted(code, name_, value_);\n\n OnOpCompleted();\n\n }\n", "file_path": "chrome/browser/chromeos/login/signed_settings_helper.cc", "rank": 26, "score": 231088.82049668144 }, { "content": "class StorePolicyOpContext : public SignedSettings::Delegate<bool>,\n\n public OpContext {\n\n public:\n\n StorePolicyOpContext(const em::PolicyFetchResponse& policy,\n\n SignedSettingsHelper::Callback* callback,\n\n OpContext::Delegate* delegate)\n\n : OpContext(callback, delegate),\n\n policy_(policy) {\n\n }\n\n\n\n // chromeos::SignedSettings::Delegate implementation\n\n virtual void OnSettingsOpCompleted(SignedSettings::ReturnCode code,\n\n bool unused) OVERRIDE {\n\n VLOG(2) << \"OnSettingsOpCompleted, code = \" << code;\n\n if (callback_)\n\n callback_->OnStorePolicyCompleted(code);\n\n OnOpCompleted();\n\n }\n\n\n\n protected:\n\n // OpContext implementation\n\n virtual void CreateOp() OVERRIDE {\n\n op_ = SignedSettings::CreateStorePolicyOp(&policy_, this);\n\n }\n\n\n\n private:\n\n em::PolicyFetchResponse policy_;\n\n DISALLOW_COPY_AND_ASSIGN(StorePolicyOpContext);\n\n};\n\n\n", "file_path": "chrome/browser/chromeos/login/signed_settings_helper.cc", "rank": 27, "score": 231088.82049668144 }, { "content": "class SetArgumentPointeeAction<N, Proto, true> {\n\n public:\n\n // Constructs an action that sets the variable pointed to by the\n\n // N-th function argument to 'proto'. Both ProtocolMessage and\n\n // proto2::Message have the CopyFrom() method, so the same\n\n // implementation works for both.\n\n explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {\n\n proto_->CopyFrom(proto);\n\n }\n\n\n\n template <typename Result, typename ArgumentTuple>\n\n void Perform(const ArgumentTuple& args) const {\n\n CompileAssertTypesEqual<void, Result>();\n\n ::std::tr1::get<N>(args)->CopyFrom(*proto_);\n\n }\n\n\n\n private:\n\n const internal::linked_ptr<Proto> proto_;\n\n\n\n GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);\n\n};\n\n\n\n// Implements the InvokeWithoutArgs(f) action. The template argument\n\n// FunctionImpl is the implementation type of f, which can be either a\n\n// function pointer or a functor. InvokeWithoutArgs(f) can be used as an\n\n// Action<F> as long as f's type is compatible with F (i.e. f can be\n\n// assigned to a tr1::function<F>).\n\ntemplate <typename FunctionImpl>\n", "file_path": "testing/gmock/include/gmock/gmock-actions.h", "rank": 28, "score": 230141.31703070333 }, { "content": "class SystemSettingsProvider : public CrosSettingsProvider,\n\n public SystemAccess::Observer {\n\n public:\n\n SystemSettingsProvider();\n\n virtual ~SystemSettingsProvider();\n\n\n\n // CrosSettingsProvider overrides.\n\n virtual bool Get(const std::string& path, Value** out_value) const;\n\n virtual bool HandlesSetting(const std::string& path);\n\n\n\n // Overridden from SystemAccess::Observer:\n\n virtual void TimezoneChanged(const icu::TimeZone& timezone);\n\n\n\n // Creates the map of timezones used by the options page.\n\n ListValue* GetTimezoneList();\n\n\n\n private:\n\n // CrosSettingsProvider overrides.\n\n virtual void DoSet(const std::string& path, Value* in_value);\n\n\n", "file_path": "chrome/browser/ui/webui/options/chromeos/system_settings_provider.h", "rank": 29, "score": 229864.18200998747 }, { "content": "// Allows the automation provider to wait for import queries to finish.\n\nclass AutomationProviderImportSettingsObserver\n\n : public importer::ImporterProgressObserver {\n\n public:\n\n AutomationProviderImportSettingsObserver(\n\n AutomationProvider* provider,\n\n IPC::Message* reply_message);\n\n virtual ~AutomationProviderImportSettingsObserver();\n\n\n\n // importer::ImporterProgressObserver:\n\n virtual void ImportStarted() OVERRIDE;\n\n virtual void ImportItemStarted(importer::ImportItem item) OVERRIDE;\n\n virtual void ImportItemEnded(importer::ImportItem item) OVERRIDE;\n\n virtual void ImportEnded() OVERRIDE;\n\n\n\n private:\n\n base::WeakPtr<AutomationProvider> provider_;\n\n scoped_ptr<IPC::Message> reply_message_;\n\n};\n\n\n", "file_path": "chrome/browser/automation/automation_provider_observers.h", "rank": 30, "score": 228640.83710855103 }, { "content": "class CrosSettingsProvider;\n\n\n", "file_path": "chrome/browser/chromeos/cros_settings.h", "rank": 31, "score": 223151.73601282723 }, { "content": "class Value;\n\n\n\nnamespace chromeos {\n\n\n", "file_path": "chrome/browser/chromeos/cros_settings.h", "rank": 32, "score": 216528.98339424227 }, { "content": "// Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#ifndef CHROME_BROWSER_CHROMEOS_CROS_SETTINGS_PROVIDER_H_\n\n#define CHROME_BROWSER_CHROMEOS_CROS_SETTINGS_PROVIDER_H_\n\n\n\n#include <string>\n\n\n", "file_path": "chrome/browser/chromeos/cros_settings_provider.h", "rank": 33, "score": 216469.43905918044 }, { "content": "// Observer used to listen for new tab creation to complete.\n\nclass NewTabObserver : public NotificationObserver {\n\n public:\n\n NewTabObserver(AutomationProvider* automation, IPC::Message* reply_message);\n\n\n\n virtual void Observe(NotificationType type,\n\n const NotificationSource& source,\n\n const NotificationDetails& details) OVERRIDE;\n\n\n\n private:\n\n virtual ~NewTabObserver();\n\n\n\n NotificationRegistrar registrar_;\n\n base::WeakPtr<AutomationProvider> automation_;\n\n scoped_ptr<IPC::Message> reply_message_;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(NewTabObserver);\n\n};\n\n\n", "file_path": "chrome/browser/automation/automation_provider_observers.h", "rank": 34, "score": 215670.57039500013 }, { "content": "class DictionaryValue;\n", "file_path": "chrome/browser/content_settings/content_settings_pref_provider.h", "rank": 35, "score": 214951.36521737417 }, { "content": "class DictionaryValue;\n", "file_path": "chrome/browser/content_settings/content_settings_policy_provider.h", "rank": 36, "score": 214951.36521737414 }, { "content": " void Reload();\n\n\n\n // Helper functions to access cached settings.\n\n static bool cached_allow_guest();\n\n static bool cached_allow_new_user();\n\n static bool cached_data_roaming_enabled();\n\n static bool cached_show_users_on_signin();\n\n static const ListValue* cached_whitelist();\n\n static std::string cached_owner();\n\n\n\n // Returns true if given email is in user whitelist.\n\n // Note this function is for display purpose only and should use\n\n // CheckWhitelist op for the real whitelist check.\n\n static bool IsEmailInCachedWhitelist(const std::string& email);\n\n\n\n // CrosSettingsProvider implementation.\n\n virtual bool Get(const std::string& path, Value** out_value) const;\n\n virtual bool HandlesSetting(const std::string& path);\n\n\n\n void WhitelistUser(const std::string& email);\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.h", "rank": 37, "score": 211353.51059651966 }, { "content": "// Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#include \"chrome/browser/chromeos/cros_settings_provider.h\"\n\n\n\n#include \"base/command_line.h\"\n\n#include \"base/logging.h\"\n\n#include \"base/string_util.h\"\n\n#include \"chrome/common/chrome_switches.h\"\n\n\n\nnamespace chromeos {\n\n\n\nvoid CrosSettingsProvider::Set(const std::string& path, Value* value) {\n\n // We don't allow changing any of the cros settings without prefix\n\n // \"cros.session.\" in the guest mode.\n\n // It should not reach here from UI in the guest mode, but just in case.\n\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession) &&\n\n !::StartsWithASCII(path, \"cros.session.\", true)) {\n\n LOG(ERROR) << \"Ignoring the guest request to change: \" << path;\n\n return;\n\n }\n\n DoSet(path, value);\n\n}\n\n\n\n}; // namespace chromeos\n", "file_path": "chrome/browser/chromeos/cros_settings_provider.cc", "rank": 38, "score": 211350.35756922892 }, { "content": " void UnwhitelistUser(const std::string& email);\n\n\n\n // Updates cached value of the owner.\n\n static void UpdateCachedOwner(const std::string& email);\n\n\n\n private:\n\n // CrosSettingsProvider implementation.\n\n virtual void DoSet(const std::string& path, Value* value);\n\n\n\n DISALLOW_COPY_AND_ASSIGN(UserCrosSettingsProvider);\n\n};\n\n\n\n} // namespace chromeos\n\n\n\n#endif // CHROME_BROWSER_CHROMEOS_USER_CROS_SETTINGS_PROVIDER_H_\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.h", "rank": 39, "score": 211346.60728936645 }, { "content": "// Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#ifndef CHROME_BROWSER_CHROMEOS_PROXY_CROS_SETTINGS_PROVIDER_H_\n\n#define CHROME_BROWSER_CHROMEOS_PROXY_CROS_SETTINGS_PROVIDER_H_\n\n#pragma once\n\n\n\n#include \"base/memory/singleton.h\"\n\n#include \"base/values.h\"\n\n#include \"chrome/browser/chromeos/cros_settings_provider.h\"\n\n#include \"chrome/browser/chromeos/proxy_config_service_impl.h\"\n\n\n\nnamespace chromeos {\n\n\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.h", "rank": 40, "score": 211331.29066255194 }, { "content": "// Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#ifndef CHROME_BROWSER_CHROMEOS_METRICS_CROS_SETTINGS_PROVIDER_H_\n\n#define CHROME_BROWSER_CHROMEOS_METRICS_CROS_SETTINGS_PROVIDER_H_\n\n#pragma once\n\n\n\n#include <string>\n\n\n\n#include \"base/basictypes.h\"\n\n#include \"chrome/browser/chromeos/cros_settings_provider.h\"\n\n\n\nnamespace chromeos {\n\n\n\n// CrosSettingsProvider that abstracts switching of stats/crash\n\n// reporting to Google.\n", "file_path": "chrome/browser/chromeos/metrics_cros_settings_provider.h", "rank": 41, "score": 211325.49323801443 }, { "content": " const ProxyConfigServiceImpl::ProxyConfig::ManualProxy& proxy,\n\n net::ProxyServer::Scheme scheme) const;\n\n\n\n Value* CreateServerHostValue(\n\n const ProxyConfigServiceImpl::ProxyConfig::ManualProxy& proxy) const;\n\n\n\n Value* CreateServerPortValue(\n\n const ProxyConfigServiceImpl::ProxyConfig::ManualProxy& proxy) const;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(ProxyCrosSettingsProvider);\n\n};\n\n\n\n} // namespace chromeos\n\n\n\n#endif // CHROME_BROWSER_CHROMEOS_PROXY_CROS_SETTINGS_PROVIDER_H_\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.h", "rank": 42, "score": 211321.86964046585 }, { "content": "// Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#ifndef CHROME_BROWSER_CHROMEOS_USER_CROS_SETTINGS_PROVIDER_H_\n\n#define CHROME_BROWSER_CHROMEOS_USER_CROS_SETTINGS_PROVIDER_H_\n\n#pragma once\n\n\n\n#include <string>\n\n\n\n#include \"base/basictypes.h\"\n\n#include \"chrome/browser/chromeos/cros_settings_provider.h\"\n\n#include \"chrome/browser/chromeos/login/signed_settings_helper.h\"\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.h", "rank": 43, "score": 211319.58478053648 }, { "content": "// Watches for NewTabUI page loads for performance timing purposes.\n\nclass NewTabUILoadObserver : public NotificationObserver {\n\n public:\n\n explicit NewTabUILoadObserver(AutomationProvider* automation);\n\n virtual ~NewTabUILoadObserver();\n\n\n\n virtual void Observe(NotificationType type,\n\n const NotificationSource& source,\n\n const NotificationDetails& details);\n\n\n\n private:\n\n NotificationRegistrar registrar_;\n\n base::WeakPtr<AutomationProvider> automation_;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(NewTabUILoadObserver);\n\n};\n\n\n", "file_path": "chrome/browser/automation/automation_provider_observers.h", "rank": 44, "score": 208746.33170521245 }, { "content": "// Waits for a connection success or failure for the specified\n\n// network and returns the status to the automation provider.\n\nclass ServicePathConnectObserver : public NetworkConnectObserver {\n\n public:\n\n ServicePathConnectObserver(AutomationProvider* automation,\n\n IPC::Message* reply_message,\n\n const std::string& service_path);\n\n\n\n virtual const chromeos::WifiNetwork* GetWifiNetwork(\n\n chromeos::NetworkLibrary* network_library);\n\n\n\n private:\n\n std::string service_path_;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(ServicePathConnectObserver);\n\n};\n\n\n", "file_path": "chrome/browser/automation/automation_provider_observers.h", "rank": 45, "score": 208734.58892802676 }, { "content": "struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>\n\n : public true_type {}; // NOLINT\n\n\n\n// Converting bool to any integer type is lossless.\n\ntemplate <typename To>\n", "file_path": "testing/gmock/include/gmock/internal/gmock-internal-utils.h", "rank": 46, "score": 208290.9212894811 }, { "content": "class SetShouldContain : public std::unary_function<const std::string&,\n\n std::set<std::string> > {\n\n public:\n\n explicit SetShouldContain(const ACMatches& matched_urls) {\n\n for (ACMatches::const_iterator iter = matched_urls.begin();\n\n iter != matched_urls.end(); ++iter)\n\n matches_.insert(iter->destination_url.spec());\n\n }\n\n\n\n void operator()(const std::string& expected) {\n\n EXPECT_EQ(1U, matches_.erase(expected));\n\n }\n\n\n\n std::set<std::string> LeftOvers() const { return matches_; }\n\n\n\n private:\n\n std::set<std::string> matches_;\n\n};\n\n\n\nvoid HistoryQuickProviderTest::RunTest(const string16 text,\n", "file_path": "chrome/browser/autocomplete/history_quick_provider_unittest.cc", "rank": 47, "score": 206956.1748911697 }, { "content": "class FilePath;\n", "file_path": "chrome/browser/chromeos/enterprise_extension_observer.h", "rank": 48, "score": 206507.75381591357 }, { "content": " return;\n\n }\n\n\n\n if (wifi->failed()) {\n\n scoped_ptr<DictionaryValue> return_value(new DictionaryValue);\n\n return_value->SetString(\"error_string\", wifi->GetErrorString());\n\n AutomationJSONReply(automation_, reply_message_)\n\n .SendSuccess(return_value.get());\n\n delete this;\n\n } else if (wifi->connected()) {\n\n AutomationJSONReply(automation_, reply_message_).SendSuccess(NULL);\n\n delete this;\n\n }\n\n\n\n // The network is in the NetworkLibrary's list, but there's no failure or\n\n // success condition, so just continue waiting for more network events.\n\n}\n\n\n\nServicePathConnectObserver::ServicePathConnectObserver(\n\n AutomationProvider* automation, IPC::Message* reply_message,\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 49, "score": 206457.68028240599 }, { "content": " : automation_(automation), reply_message_(reply_message) {\n\n NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();\n\n network_library->AddNetworkManagerObserver(this);\n\n}\n\n\n\nNetworkConnectObserver::~NetworkConnectObserver() {\n\n NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();\n\n network_library->RemoveNetworkManagerObserver(this);\n\n}\n\n\n\nvoid NetworkConnectObserver::OnNetworkManagerChanged(NetworkLibrary* obj) {\n\n const chromeos::WifiNetwork* wifi = GetWifiNetwork(obj);\n\n if (!wifi) {\n\n // The network was not found, and we assume it no longer exists.\n\n // This could be because the SSID is invalid, or the network went away.\n\n scoped_ptr<DictionaryValue> return_value(new DictionaryValue);\n\n return_value->SetString(\"error_string\", \"Network not found.\");\n\n AutomationJSONReply(automation_, reply_message_)\n\n .SendSuccess(return_value.get());\n\n delete this;\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 50, "score": 206453.26650678235 }, { "content": "// Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#include \"chrome/browser/automation/automation_provider_observers.h\"\n\n\n\n#include \"base/values.h\"\n\n#include \"chrome/browser/automation/automation_provider.h\"\n\n#include \"chrome/browser/chromeos/cros/cros_library.h\"\n\n#include \"chrome/browser/chromeos/login/authentication_notification_details.h\"\n\n#include \"content/common/notification_service.h\"\n\n\n\nusing chromeos::CrosLibrary;\n\nusing chromeos::NetworkLibrary;\n\n\n\nNetworkManagerInitObserver::NetworkManagerInitObserver(\n\n AutomationProvider* automation)\n\n : automation_(automation->AsWeakPtr()) {}\n\n\n\nNetworkManagerInitObserver::~NetworkManagerInitObserver() {\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 51, "score": 206451.21415364245 }, { "content": " const std::string& service_path)\n\n : NetworkConnectObserver(automation, reply_message),\n\n service_path_(service_path) {}\n\n\n\nconst chromeos::WifiNetwork* ServicePathConnectObserver::GetWifiNetwork(\n\n NetworkLibrary* network_library) {\n\n return network_library->FindWifiNetworkByPath(service_path_);\n\n}\n\n\n\nSSIDConnectObserver::SSIDConnectObserver(\n\n AutomationProvider* automation, IPC::Message* reply_message,\n\n const std::string& ssid)\n\n : NetworkConnectObserver(automation, reply_message), ssid_(ssid) {}\n\n\n\nconst chromeos::WifiNetwork* SSIDConnectObserver::GetWifiNetwork(\n\n NetworkLibrary* network_library) {\n\n const chromeos::WifiNetworkVector& wifi_networks =\n\n network_library->wifi_networks();\n\n for (chromeos::WifiNetworkVector::const_iterator iter = wifi_networks.begin();\n\n iter != wifi_networks.end(); ++iter) {\n\n const chromeos::WifiNetwork* wifi = *iter;\n\n if (wifi->name() == ssid_)\n\n return wifi;\n\n }\n\n return NULL;\n\n}\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 52, "score": 206447.27002980176 }, { "content": " NotificationService::AllSources());\n\n}\n\n\n\nScreenLockUnlockObserver::~ScreenLockUnlockObserver() {}\n\n\n\nvoid ScreenLockUnlockObserver::Observe(NotificationType type,\n\n const NotificationSource& source,\n\n const NotificationDetails& details) {\n\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n AutomationJSONReply reply(automation_, reply_message_);\n\n bool is_screen_locked = *Details<bool>(details).ptr();\n\n if (lock_screen_ == is_screen_locked)\n\n reply.SendSuccess(NULL);\n\n else\n\n reply.SendError(\"Screen lock failure.\");\n\n delete this;\n\n}\n\n\n\nNetworkScanObserver::NetworkScanObserver(AutomationProvider* automation,\n\n IPC::Message* reply_message)\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 53, "score": 206443.92658769168 }, { "content": " CrosLibrary::Get()->GetNetworkLibrary()->RemoveNetworkManagerObserver(this);\n\n}\n\n\n\nbool NetworkManagerInitObserver::Init() {\n\n if (!CrosLibrary::Get()->EnsureLoaded()) {\n\n // If cros library fails to load, don't wait for the network\n\n // library to finish initializing, because it'll wait forever.\n\n automation_->OnNetworkLibraryInit();\n\n return false;\n\n }\n\n\n\n CrosLibrary::Get()->GetNetworkLibrary()->AddNetworkManagerObserver(this);\n\n return true;\n\n}\n\n\n\nvoid NetworkManagerInitObserver::OnNetworkManagerChanged(NetworkLibrary* obj) {\n\n if (!obj->wifi_scanning()) {\n\n automation_->OnNetworkLibraryInit();\n\n delete this;\n\n }\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 54, "score": 206442.14499774436 }, { "content": " : automation_(automation), reply_message_(reply_message) {\n\n NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();\n\n network_library->AddNetworkManagerObserver(this);\n\n}\n\n\n\nNetworkScanObserver::~NetworkScanObserver() {\n\n NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();\n\n network_library->RemoveNetworkManagerObserver(this);\n\n}\n\n\n\nvoid NetworkScanObserver::OnNetworkManagerChanged(NetworkLibrary* obj) {\n\n if (obj->wifi_scanning())\n\n return;\n\n\n\n AutomationJSONReply(automation_, reply_message_).SendSuccess(NULL);\n\n delete this;\n\n}\n\n\n\nNetworkConnectObserver::NetworkConnectObserver(AutomationProvider* automation,\n\n IPC::Message* reply_message)\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 55, "score": 206441.71472685202 }, { "content": " return;\n\n }\n\n\n\n AutomationJSONReply reply(automation_, reply_message_.release());\n\n Details<AuthenticationNotificationDetails> auth_details(details);\n\n if (auth_details->success())\n\n reply.SendSuccess(NULL);\n\n else\n\n reply.SendError(\"Login failure.\");\n\n delete this;\n\n}\n\n\n\nScreenLockUnlockObserver::ScreenLockUnlockObserver(\n\n AutomationProvider* automation,\n\n IPC::Message* reply_message,\n\n bool lock_screen)\n\n : automation_(automation),\n\n reply_message_(reply_message),\n\n lock_screen_(lock_screen) {\n\n registrar_.Add(this, NotificationType::SCREEN_LOCK_STATE_CHANGED,\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 56, "score": 206441.4648298029 }, { "content": "}\n\n\n\nLoginManagerObserver::LoginManagerObserver(\n\n AutomationProvider* automation,\n\n IPC::Message* reply_message)\n\n : automation_(automation->AsWeakPtr()),\n\n reply_message_(reply_message) {\n\n registrar_.Add(this, NotificationType::LOGIN_USER_CHANGED,\n\n NotificationService::AllSources());\n\n}\n\n\n\nLoginManagerObserver::~LoginManagerObserver() {}\n\n\n\nvoid LoginManagerObserver::Observe(NotificationType type,\n\n const NotificationSource& source,\n\n const NotificationDetails& details) {\n\n DCHECK(type == NotificationType::LOGIN_USER_CHANGED);\n\n\n\n if (!automation_) {\n\n delete this;\n", "file_path": "chrome/browser/automation/automation_provider_observers_chromeos.cc", "rank": 57, "score": 206438.05588727418 }, { "content": "\n\nvoid MetricsCrosSettingsProvider::DoSet(const std::string& path,\n\n Value* value) {\n\n DCHECK(path == kStatsReportingPref);\n\n bool enabled = false;\n\n CHECK(value->GetAsBoolean(&enabled));\n\n if (SetMetricsStatus(enabled)) {\n\n CrosSettings::Get()->FireObservers(path.c_str());\n\n }\n\n}\n\n\n\nbool MetricsCrosSettingsProvider::Get(const std::string& path,\n\n Value** value) const {\n\n DCHECK(path == kStatsReportingPref);\n\n *value = Value::CreateBooleanValue(GetMetricsStatus());\n\n return true;\n\n}\n\n\n\n// static\n\nbool MetricsCrosSettingsProvider::SetMetricsStatus(bool enabled) {\n", "file_path": "chrome/browser/chromeos/metrics_cros_settings_provider.cc", "rank": 58, "score": 206438.02007007407 }, { "content": "#include \"chrome/browser/chromeos/cros_settings_names.h\"\n\n#include \"chrome/browser/chromeos/login/ownership_service.h\"\n\n#include \"chrome/browser/chromeos/login/user_manager.h\"\n\n#include \"chrome/browser/prefs/pref_service.h\"\n\n#include \"chrome/browser/prefs/scoped_user_pref_update.h\"\n\n#include \"content/browser/browser_thread.h\"\n\n\n\nnamespace chromeos {\n\n\n\nnamespace {\n\n\n\nconst char kTrueIncantation[] = \"true\";\n\nconst char kFalseIncantation[] = \"false\";\n\nconst char kTrustedSuffix[] = \"/trusted\";\n\n\n\n// For all our boolean settings following is applicable:\n\n// true is default permissive value and false is safe prohibitic value.\n\n// Exception: kSignedDataRoamingEnabled which has default value of false.\n\nconst char* kBooleanSettings[] = {\n\n kAccountsPrefAllowNewUser,\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 59, "score": 206433.1932601827 }, { "content": " // BreakPad). But this is not a big deal: crash reporting will be off\n\n // after reboot for the current process while other Chrome processes\n\n // will start when the setting is already set up. Other ChromeOS\n\n // processes does not use BreakPad.\n\n#endif\n\n return new_enabled == enabled;\n\n }\n\n return false;\n\n}\n\n\n\n// static\n\nbool MetricsCrosSettingsProvider::GetMetricsStatus() {\n\n // Loading consent file state causes us to do blocking IO on UI thread.\n\n // Temporarily allow it until we fix http://crbug.com/62626\n\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n\n return GoogleUpdateSettings::GetCollectStatsConsent();\n\n}\n\n\n\nbool MetricsCrosSettingsProvider::HandlesSetting(const std::string& path) {\n\n return ::StartsWithASCII(path, kStatsReportingPref, true);\n\n}\n\n\n\n}; // namespace chromeos\n", "file_path": "chrome/browser/chromeos/metrics_cros_settings_provider.cc", "rank": 60, "score": 206432.1647875203 }, { "content": " dict->SetBoolean(\"managed\", managed);\n\n *out_value = dict;\n\n return true;\n\n } else {\n\n *out_value = NULL;\n\n return false;\n\n }\n\n}\n\n\n\nbool ProxyCrosSettingsProvider::HandlesSetting(const std::string& path) {\n\n return ::StartsWithASCII(path, \"cros.session.proxy\", true);\n\n}\n\n\n\n//----------------- ProxyCrosSettingsProvider: private methods -----------------\n\n\n\nchromeos::ProxyConfigServiceImpl*\n\n ProxyCrosSettingsProvider::GetConfigService() const {\n\n return g_browser_process->chromeos_proxy_config_service_impl();\n\n}\n\n\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 61, "score": 206431.78540004598 }, { "content": "static const char kProxyHttpsPort[] = \"cros.session.proxy.httpsport\";\n\nstatic const char kProxyType[] = \"cros.session.proxy.type\";\n\nstatic const char kProxySingle[] = \"cros.session.proxy.single\";\n\nstatic const char kProxyFtpUrl[] = \"cros.session.proxy.ftpurl\";\n\nstatic const char kProxyFtpPort[] = \"cros.session.proxy.ftpport\";\n\nstatic const char kProxySocks[] = \"cros.session.proxy.socks\";\n\nstatic const char kProxySocksPort[] = \"cros.session.proxy.socksport\";\n\nstatic const char kProxyIgnoreList[] = \"cros.session.proxy.ignorelist\";\n\n\n\n//------------------ ProxyCrosSettingsProvider: public methods -----------------\n\n\n\nProxyCrosSettingsProvider::ProxyCrosSettingsProvider() { }\n\n\n\nvoid ProxyCrosSettingsProvider::DoSet(const std::string& path,\n\n Value* in_value) {\n\n if (!in_value) {\n\n return;\n\n }\n\n\n\n chromeos::ProxyConfigServiceImpl* config_service = GetConfigService();\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 62, "score": 206428.37054830315 }, { "content": "}\n\n\n\nvoid UserCrosSettingsProvider::DoSet(const std::string& path,\n\n Value* in_value) {\n\n UserCrosSettingsTrust::GetInstance()->Set(path, in_value);\n\n}\n\n\n\nbool UserCrosSettingsProvider::Get(const std::string& path,\n\n Value** out_value) const {\n\n if (IsControlledBooleanSetting(path)) {\n\n PrefService* prefs = g_browser_process->local_state();\n\n *out_value = CreateSettingsBooleanValue(\n\n prefs->GetBoolean(path.c_str()),\n\n prefs->IsManagedPreference(path.c_str()),\n\n !UserManager::Get()->current_user_is_owner());\n\n return true;\n\n } else if (path == kAccountsPrefUsers) {\n\n ListValue* user_list = new ListValue;\n\n GetUserWhitelist(user_list);\n\n *out_value = user_list;\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 63, "score": 206426.9581136584 }, { "content": " if (IsControlledBooleanSetting(pref_path)) {\n\n if (pref_path == kSignedDataRoamingEnabled)\n\n local_state->RegisterBooleanPref(pref_path.c_str(), false);\n\n else\n\n local_state->RegisterBooleanPref(pref_path.c_str(), true);\n\n } else if (IsControlledStringSetting(pref_path)) {\n\n local_state->RegisterStringPref(pref_path.c_str(), \"\");\n\n } else {\n\n DCHECK(IsControlledListSetting(pref_path));\n\n local_state->RegisterListPref(pref_path.c_str());\n\n }\n\n}\n\n\n\n// Create a settings boolean value with \"managed\" and \"disabled\" property.\n\n// \"managed\" property is true if the setting is managed by administrator.\n\n// \"disabled\" property is true if the UI for the setting should be disabled.\n\nValue* CreateSettingsBooleanValue(bool value, bool managed, bool disabled) {\n\n DictionaryValue* dict = new DictionaryValue;\n\n dict->Set(\"value\", Value::CreateBooleanValue(value));\n\n dict->Set(\"managed\", Value::CreateBooleanValue(managed));\n\n dict->Set(\"disabled\", Value::CreateBooleanValue(disabled));\n\n return dict;\n\n}\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 64, "score": 206426.35410687476 }, { "content": "DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UserCrosSettingsTrust);\n\n\n\nnamespace chromeos {\n\n\n\nUserCrosSettingsProvider::UserCrosSettingsProvider() {\n\n // Trigger prefetching of settings.\n\n UserCrosSettingsTrust::GetInstance();\n\n}\n\n\n\n// static\n\nvoid UserCrosSettingsProvider::RegisterPrefs(PrefService* local_state) {\n\n for (size_t i = 0; i < arraysize(kBooleanSettings); ++i)\n\n RegisterSetting(local_state, kBooleanSettings[i]);\n\n for (size_t i = 0; i < arraysize(kStringSettings); ++i)\n\n RegisterSetting(local_state, kStringSettings[i]);\n\n for (size_t i = 0; i < arraysize(kListSettings); ++i)\n\n RegisterSetting(local_state, kListSettings[i]);\n\n}\n\n\n\nbool UserCrosSettingsProvider::RequestTrustedAllowGuest(Task* callback) {\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 65, "score": 206426.2056789867 }, { "content": " StartFetchingSetting(kStringSettings[i]);\n\n }\n\n\n\n void Set(const std::string& path, Value* in_value) {\n\n PrefService* prefs = g_browser_process->local_state();\n\n DCHECK(!prefs->IsManagedPreference(path.c_str()));\n\n\n\n if (!UserManager::Get()->current_user_is_owner()) {\n\n LOG(WARNING) << \"Changing settings from non-owner, setting=\" << path;\n\n\n\n // Revert UI change.\n\n CrosSettings::Get()->FireObservers(path.c_str());\n\n return;\n\n }\n\n\n\n if (IsControlledBooleanSetting(path)) {\n\n bool bool_value = false;\n\n if (in_value->GetAsBoolean(&bool_value)) {\n\n OnBooleanPropertyChange(path, bool_value);\n\n std::string value = bool_value ? kTrueIncantation : kFalseIncantation;\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 66, "score": 206423.6384096261 }, { "content": " SignedSettingsHelper::Get()->StartStorePropertyOp(path, value, this);\n\n UpdateCacheBool(path, bool_value, USE_VALUE_SUPPLIED);\n\n\n\n VLOG(1) << \"Set cros setting \" << path << \"=\" << value;\n\n }\n\n } else if (path == kDeviceOwner) {\n\n VLOG(1) << \"Setting owner is not supported. Please use \"\n\n \"'UpdateCachedOwner' instead.\";\n\n } else if (path == kAccountsPrefUsers) {\n\n VLOG(1) << \"Setting user whitelist is not implemented. Please use \"\n\n \"whitelist/unwhitelist instead.\";\n\n } else {\n\n LOG(WARNING) << \"Try to set unhandled cros setting \" << path;\n\n }\n\n }\n\n\n\n private:\n\n // upper bound for number of retries to fetch a signed setting.\n\n static const int kNumRetriesLimit = 9;\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 67, "score": 206421.84241873166 }, { "content": " return true;\n\n }\n\n\n\n return false;\n\n}\n\n\n\nbool UserCrosSettingsProvider::HandlesSetting(const std::string& path) {\n\n return ::StartsWithASCII(path, \"cros.accounts.\", true) ||\n\n ::StartsWithASCII(path, \"cros.signed.\", true);\n\n}\n\n\n\nvoid UserCrosSettingsProvider::WhitelistUser(const std::string& email) {\n\n SignedSettingsHelper::Get()->StartWhitelistOp(\n\n email, true, UserCrosSettingsTrust::GetInstance());\n\n PrefService* prefs = g_browser_process->local_state();\n\n ListPrefUpdate cached_whitelist_update(prefs, kAccountsPrefUsers);\n\n cached_whitelist_update->Append(Value::CreateStringValue(email));\n\n prefs->ScheduleSavePersistentPrefs();\n\n}\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 68, "score": 206420.65843367853 }, { "content": "// static\n\nconst ListValue* UserCrosSettingsProvider::cached_whitelist() {\n\n PrefService* prefs = g_browser_process->local_state();\n\n const ListValue* cached_users = prefs->GetList(kAccountsPrefUsers);\n\n if (!prefs->IsManagedPreference(kAccountsPrefUsers)) {\n\n if (cached_users == NULL) {\n\n // Update whitelist cache.\n\n GetUserWhitelist(NULL);\n\n cached_users = prefs->GetList(kAccountsPrefUsers);\n\n }\n\n }\n\n if (cached_users == NULL) {\n\n NOTREACHED();\n\n cached_users = new ListValue;\n\n }\n\n return cached_users;\n\n}\n\n\n\n// static\n\nstd::string UserCrosSettingsProvider::cached_owner() {\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 69, "score": 206420.063553758 }, { "content": " } else if (path == kProxyIgnoreList) {\n\n net::ProxyBypassRules bypass_rules;\n\n if (in_value->GetType() == Value::TYPE_LIST) {\n\n const ListValue* list_value = static_cast<const ListValue*>(in_value);\n\n for (size_t x = 0; x < list_value->GetSize(); x++) {\n\n std::string val;\n\n if (list_value->GetString(x, &val)) {\n\n bypass_rules.AddRuleFromString(val);\n\n }\n\n }\n\n config_service->UISetProxyConfigBypassRules(bypass_rules);\n\n }\n\n }\n\n}\n\n\n\nbool ProxyCrosSettingsProvider::Get(const std::string& path,\n\n Value** out_value) const {\n\n bool found = false;\n\n bool managed = false;\n\n Value* data;\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 70, "score": 206419.4905566401 }, { "content": "// Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#include \"chrome/browser/chromeos/proxy_cros_settings_provider.h\"\n\n\n\n#include \"base/command_line.h\"\n\n#include \"base/string_util.h\"\n\n#include \"chrome/browser/browser_process.h\"\n\n#include \"chrome/browser/ui/browser_list.h\"\n\n#include \"chrome/common/chrome_switches.h\"\n\n\n\nnamespace chromeos {\n\n\n\nstatic const char kProxyPacUrl[] = \"cros.session.proxy.pacurl\";\n\nstatic const char kProxySingleHttp[] = \"cros.session.proxy.singlehttp\";\n\nstatic const char kProxySingleHttpPort[] = \"cros.session.proxy.singlehttpport\";\n\nstatic const char kProxyHttpUrl[] = \"cros.session.proxy.httpurl\";\n\nstatic const char kProxyHttpPort[] = \"cros.session.proxy.httpport\";\n\nstatic const char kProxyHttpsUrl[] = \"cros.session.proxy.httpsurl\";\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 71, "score": 206418.3144968312 }, { "content": "void UserCrosSettingsProvider::UnwhitelistUser(const std::string& email) {\n\n SignedSettingsHelper::Get()->StartWhitelistOp(\n\n email, false, UserCrosSettingsTrust::GetInstance());\n\n\n\n PrefService* prefs = g_browser_process->local_state();\n\n ListPrefUpdate cached_whitelist_update(prefs, kAccountsPrefUsers);\n\n StringValue email_value(email);\n\n if (cached_whitelist_update->Remove(email_value) != -1)\n\n prefs->ScheduleSavePersistentPrefs();\n\n}\n\n\n\n// static\n\nvoid UserCrosSettingsProvider::UpdateCachedOwner(const std::string& email) {\n\n UpdateCacheString(kDeviceOwner, email, USE_VALUE_SUPPLIED);\n\n}\n\n\n\n} // namespace chromeos\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 72, "score": 206417.5681546144 }, { "content": "\n\n NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary();\n\n cros->SetCellularDataRoamingAllowed(new_value);\n\n }\n\n }\n\n\n\n // Called right after signed value was checked.\n\n void OnBooleanPropertyRetrieve(const std::string& path,\n\n bool value,\n\n UseValue use_value) {\n\n if (path == kSignedDataRoamingEnabled) {\n\n if (!CrosLibrary::Get()->EnsureLoaded())\n\n return;\n\n\n\n NetworkLibrary* cros = CrosLibrary::Get()->GetNetworkLibrary();\n\n const NetworkDevice* cellular = cros->FindCellularDevice();\n\n if (cellular) {\n\n bool device_value = cellular->data_roaming_allowed();\n\n bool new_value = (use_value == USE_VALUE_SUPPLIED) ? value : false;\n\n if (device_value != new_value)\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 73, "score": 206413.46175356483 }, { "content": "// Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#include \"chrome/browser/chromeos/metrics_cros_settings_provider.h\"\n\n\n\n#include \"base/string_util.h\"\n\n#include \"base/threading/thread_restrictions.h\"\n\n#include \"base/values.h\"\n\n#include \"chrome/browser/chromeos/cros_settings.h\"\n\n#include \"chrome/browser/chromeos/cros_settings_names.h\"\n\n#include \"chrome/browser/chromeos/login/user_manager.h\"\n\n#include \"chrome/browser/ui/options/options_util.h\"\n\n#include \"chrome/installer/util/google_update_settings.h\"\n\n\n\n#if defined(USE_LINUX_BREAKPAD)\n\n#include \"chrome/app/breakpad_linux.h\"\n\n#endif\n\n\n\nnamespace chromeos {\n", "file_path": "chrome/browser/chromeos/metrics_cros_settings_provider.cc", "rank": 74, "score": 206413.4444167702 }, { "content": "bool UserCrosSettingsProvider::RequestTrustedOwner(Task* callback) {\n\n return UserCrosSettingsTrust::GetInstance()->RequestTrustedEntity(\n\n kDeviceOwner, callback);\n\n}\n\n\n\nvoid UserCrosSettingsProvider::Reload() {\n\n UserCrosSettingsTrust::GetInstance()->Reload();\n\n}\n\n\n\n// static\n\nbool UserCrosSettingsProvider::cached_allow_guest() {\n\n // Trigger prefetching if singleton object still does not exist.\n\n UserCrosSettingsTrust::GetInstance();\n\n return g_browser_process->local_state()->GetBoolean(kAccountsPrefAllowGuest);\n\n}\n\n\n\n// static\n\nbool UserCrosSettingsProvider::cached_allow_new_user() {\n\n // Trigger prefetching if singleton object still does not exist.\n\n UserCrosSettingsTrust::GetInstance();\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 75, "score": 206413.1125729546 }, { "content": " kAccountsPrefAllowGuest,\n\n kAccountsPrefShowUserNamesOnSignIn,\n\n kSignedDataRoamingEnabled,\n\n};\n\n\n\nconst char* kStringSettings[] = {\n\n kDeviceOwner\n\n};\n\n\n\nconst char* kListSettings[] = {\n\n kAccountsPrefUsers\n\n};\n\n\n\nbool IsControlledBooleanSetting(const std::string& pref_path) {\n\n // TODO(nkostylev): Using std::find for 4 value array generates this warning\n\n // in chroot stl_algo.h:231: error: array subscript is above array bounds.\n\n // GCC 4.4.3\n\n return (pref_path == kAccountsPrefAllowNewUser) ||\n\n (pref_path == kAccountsPrefAllowGuest) ||\n\n (pref_path == kAccountsPrefShowUserNamesOnSignIn) ||\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 76, "score": 206410.85136204978 }, { "content": " // Trigger prefetching if singleton object still does not exist.\n\n UserCrosSettingsTrust::GetInstance();\n\n if (!g_browser_process || !g_browser_process->local_state())\n\n return std::string();\n\n return g_browser_process->local_state()->GetString(kDeviceOwner);\n\n}\n\n\n\n// static\n\nbool UserCrosSettingsProvider::IsEmailInCachedWhitelist(\n\n const std::string& email) {\n\n const ListValue* whitelist = cached_whitelist();\n\n if (whitelist) {\n\n StringValue email_value(email);\n\n for (ListValue::const_iterator i(whitelist->begin());\n\n i != whitelist->end(); ++i) {\n\n if ((*i)->Equals(&email_value))\n\n return true;\n\n }\n\n }\n\n return false;\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 77, "score": 206409.88728357322 }, { "content": " if (proxy.server.is_valid())\n\n host = proxy.server.host_port_pair().host();\n\n if (host.length() == 0 && port == 0)\n\n return net::ProxyServer();\n\n net::HostPortPair host_port_pair(host, port);\n\n return net::ProxyServer(scheme, host_port_pair);\n\n}\n\n\n\nValue* ProxyCrosSettingsProvider::CreateServerHostValue(\n\n const ProxyConfigServiceImpl::ProxyConfig::ManualProxy& proxy) const {\n\n return proxy.server.is_valid() ?\n\n Value::CreateStringValue(proxy.server.host_port_pair().host()) :\n\n NULL;\n\n}\n\n\n\nValue* ProxyCrosSettingsProvider::CreateServerPortValue(\n\n const ProxyConfigServiceImpl::ProxyConfig::ManualProxy& proxy) const {\n\n return proxy.server.is_valid() ?\n\n Value::CreateIntegerValue(proxy.server.host_port_pair().port()) :\n\n NULL;\n\n}\n\n\n\n} // namespace chromeos\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 78, "score": 206409.73401469114 }, { "content": " (pref_path == kSignedDataRoamingEnabled);\n\n}\n\n\n\nbool IsControlledStringSetting(const std::string& pref_path) {\n\n return std::find(kStringSettings,\n\n kStringSettings + arraysize(kStringSettings),\n\n pref_path) !=\n\n kStringSettings + arraysize(kStringSettings);\n\n}\n\n\n\nbool IsControlledListSetting(const std::string& pref_path) {\n\n return std::find(kListSettings,\n\n kListSettings + arraysize(kListSettings),\n\n pref_path) !=\n\n kListSettings + arraysize(kListSettings);\n\n}\n\n\n\nvoid RegisterSetting(PrefService* local_state, const std::string& pref_path) {\n\n local_state->RegisterBooleanPref((pref_path + kTrustedSuffix).c_str(),\n\n false);\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 79, "score": 206409.22745622578 }, { "content": "// Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can be\n\n// found in the LICENSE file.\n\n\n\n#include \"chrome/browser/chromeos/user_cros_settings_provider.h\"\n\n\n\n#include <map>\n\n#include <set>\n\n\n\n#include \"base/hash_tables.h\"\n\n#include \"base/logging.h\"\n\n#include \"base/memory/singleton.h\"\n\n#include \"base/string_util.h\"\n\n#include \"base/task.h\"\n\n#include \"base/values.h\"\n\n#include \"chrome/browser/browser_process.h\"\n\n#include \"chrome/browser/chromeos/cros/cros_library.h\"\n\n#include \"chrome/browser/chromeos/cros/login_library.h\"\n\n#include \"chrome/browser/chromeos/cros/network_library.h\"\n\n#include \"chrome/browser/chromeos/cros_settings.h\"\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 80, "score": 206407.6635163114 }, { "content": " UserCrosSettingsTrust()\n\n : ownership_service_(OwnershipService::GetSharedInstance()),\n\n retries_left_(kNumRetriesLimit) {\n\n // Start prefetching Boolean and String preferences.\n\n Reload();\n\n }\n\n\n\n ~UserCrosSettingsTrust() {\n\n if (BrowserThread::CurrentlyOn(BrowserThread::UI) &&\n\n CrosLibrary::Get()->EnsureLoaded()) {\n\n // Cancels all pending callbacks from us.\n\n SignedSettingsHelper::Get()->CancelCallback(this);\n\n }\n\n }\n\n\n\n // Called right before boolean property is changed.\n\n void OnBooleanPropertyChange(const std::string& path, bool new_value) {\n\n if (path == kSignedDataRoamingEnabled) {\n\n if (!CrosLibrary::Get()->EnsureLoaded())\n\n return;\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 81, "score": 206407.48602351302 }, { "content": " virtual void OnWhitelistCompleted(SignedSettings::ReturnCode code,\n\n const std::string& email) {\n\n VLOG(1) << \"Add \" << email << \" to whitelist, code=\" << code;\n\n\n\n // Reload the whitelist on settings op failure.\n\n if (code != SignedSettings::SUCCESS)\n\n CrosSettings::Get()->FireObservers(kAccountsPrefUsers);\n\n }\n\n\n\n // Implementation of SignedSettingsHelper::Callback.\n\n virtual void OnUnwhitelistCompleted(SignedSettings::ReturnCode code,\n\n const std::string& email) {\n\n VLOG(1) << \"Remove \" << email << \" from whitelist, code=\" << code;\n\n\n\n // Reload the whitelist on settings op failure.\n\n if (code != SignedSettings::SUCCESS)\n\n CrosSettings::Get()->FireObservers(kAccountsPrefUsers);\n\n }\n\n\n\n // Pending callbacks that need to be invoked after settings verification.\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 82, "score": 206406.32116739269 }, { "content": " return g_browser_process->local_state()->GetBoolean(\n\n kAccountsPrefAllowNewUser);\n\n}\n\n\n\n// static\n\nbool UserCrosSettingsProvider::cached_data_roaming_enabled() {\n\n // Trigger prefetching if singleton object still does not exist.\n\n UserCrosSettingsTrust::GetInstance();\n\n return g_browser_process->local_state()->GetBoolean(\n\n kSignedDataRoamingEnabled);\n\n}\n\n\n\n// static\n\nbool UserCrosSettingsProvider::cached_show_users_on_signin() {\n\n // Trigger prefetching if singleton object still does not exist.\n\n UserCrosSettingsTrust::GetInstance();\n\n return g_browser_process->local_state()->GetBoolean(\n\n kAccountsPrefShowUserNamesOnSignIn);\n\n}\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 83, "score": 206405.51680632884 }, { "content": " } else if (path == kProxyHttpPort) {\n\n found = (data = CreateServerPortValue(config.http_proxy));\n\n } else if (path == kProxyHttpsPort) {\n\n found = (data = CreateServerPortValue(config.https_proxy));\n\n } else if (path == kProxyFtpPort) {\n\n found = (data = CreateServerPortValue(config.ftp_proxy));\n\n } else if (path == kProxySocksPort) {\n\n found = (data = CreateServerPortValue(config.socks_proxy));\n\n } else if (path == kProxyIgnoreList) {\n\n ListValue* list = new ListValue();\n\n net::ProxyBypassRules::RuleList bypass_rules = config.bypass_rules.rules();\n\n for (size_t x = 0; x < bypass_rules.size(); x++) {\n\n list->Append(Value::CreateStringValue(bypass_rules[x]->ToString()));\n\n }\n\n *out_value = list;\n\n return true;\n\n }\n\n if (found) {\n\n DictionaryValue* dict = new DictionaryValue;\n\n dict->Set(\"value\", data);\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 84, "score": 206404.78117203087 }, { "content": " config.ftp_proxy.server);\n\n set_config = true;\n\n }\n\n if (config.socks_proxy.server.is_valid()) {\n\n config_service->UISetProxyConfigToProxyPerScheme(\"socks\",\n\n config.socks_proxy.server);\n\n set_config = true;\n\n }\n\n if (!set_config) {\n\n config_service->UISetProxyConfigToProxyPerScheme(\"http\",\n\n net::ProxyServer());\n\n }\n\n }\n\n } else {\n\n config_service->UISetProxyConfigToDirect();\n\n }\n\n }\n\n } else if (path == kProxySingle) {\n\n bool val;\n\n if (in_value->GetAsBoolean(&val)) {\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 85, "score": 206404.30685331178 }, { "content": " const UserManager::User& self = UserManager::Get()->logged_in_user();\n\n bool is_owner = UserManager::Get()->current_user_is_owner();\n\n\n\n for (size_t i = 0; i < whitelist.size(); ++i) {\n\n const std::string& email = whitelist[i];\n\n\n\n if (user_list) {\n\n DictionaryValue* user = new DictionaryValue;\n\n user->SetString(\"email\", email);\n\n user->SetString(\"name\", \"\");\n\n user->SetBoolean(\"owner\", is_owner && email == self.email());\n\n user_list->Append(user);\n\n }\n\n\n\n cached_whitelist_update->Append(Value::CreateStringValue(email));\n\n }\n\n\n\n prefs->ScheduleSavePersistentPrefs();\n\n return true;\n\n}\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 86, "score": 206403.8621000333 }, { "content": " base::hash_map< std::string, std::vector< Task* > > callbacks_;\n\n\n\n OwnershipService* ownership_service_;\n\n\n\n // In order to guard against occasional failure to fetch a property\n\n // we allow for some number of retries.\n\n int retries_left_;\n\n\n\n friend class SignedSettingsHelper;\n\n friend struct DefaultSingletonTraits<UserCrosSettingsTrust>;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(UserCrosSettingsTrust);\n\n};\n\n\n\n} // namespace\n\n\n\n} // namespace chromeos\n\n\n\n// We want to use NewRunnableMethod with this class but need to disable\n\n// reference counting since it is singleton.\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 87, "score": 206403.6777327656 }, { "content": " MessageLoop::current()->PostTask(FROM_HERE, callbacks_vector[i]);\n\n callbacks_vector.clear();\n\n }\n\n if (code == SignedSettings::SUCCESS)\n\n CrosSettings::Get()->FireObservers(name.c_str());\n\n }\n\n\n\n // Implementation of SignedSettingsHelper::Callback.\n\n virtual void OnStorePropertyCompleted(SignedSettings::ReturnCode code,\n\n const std::string& name,\n\n const std::string& value) {\n\n VLOG(1) << \"Store cros setting \" << name << \"=\" << value << \", code=\"\n\n << code;\n\n\n\n // Reload the setting if store op fails.\n\n if (code != SignedSettings::SUCCESS)\n\n SignedSettingsHelper::Get()->StartRetrieveProperty(name, this);\n\n }\n\n\n\n // Implementation of SignedSettingsHelper::Callback.\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 88, "score": 206403.45780446313 }, { "content": " const std::string& name,\n\n const std::string& value) {\n\n if (!IsControlledBooleanSetting(name) && !IsControlledStringSetting(name)) {\n\n NOTREACHED();\n\n return;\n\n }\n\n\n\n bool is_owned = ownership_service_->GetStatus(true) ==\n\n OwnershipService::OWNERSHIP_TAKEN;\n\n PrefService* prefs = g_browser_process->local_state();\n\n switch (code) {\n\n case SignedSettings::SUCCESS:\n\n case SignedSettings::NOT_FOUND:\n\n case SignedSettings::KEY_UNAVAILABLE: {\n\n bool fallback_to_default = !is_owned\n\n || (code == SignedSettings::NOT_FOUND);\n\n DCHECK(fallback_to_default || code == SignedSettings::SUCCESS);\n\n if (fallback_to_default)\n\n VLOG(1) << \"Going default for cros setting \" << name;\n\n else\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 89, "score": 206403.38278552613 }, { "content": " cros->SetCellularDataRoamingAllowed(new_value);\n\n }\n\n }\n\n }\n\n\n\n void StartFetchingSetting(const std::string& name) {\n\n DCHECK(g_browser_process);\n\n PrefService* prefs = g_browser_process->local_state();\n\n if (!prefs)\n\n return;\n\n // Do not trust before fetching complete.\n\n prefs->ClearPref((name + kTrustedSuffix).c_str());\n\n prefs->ScheduleSavePersistentPrefs();\n\n if (CrosLibrary::Get()->EnsureLoaded()) {\n\n SignedSettingsHelper::Get()->StartRetrieveProperty(name, this);\n\n }\n\n }\n\n\n\n // Implementation of SignedSettingsHelper::Callback.\n\n virtual void OnRetrievePropertyCompleted(SignedSettings::ReturnCode code,\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 90, "score": 206403.0187517078 }, { "content": " config.mode ==\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig::MODE_PAC_SCRIPT) {\n\n data = Value::CreateIntegerValue(3);\n\n } else if (config.mode ==\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig::MODE_SINGLE_PROXY ||\n\n config.mode ==\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig::MODE_PROXY_PER_SCHEME) {\n\n data = Value::CreateIntegerValue(2);\n\n } else {\n\n data = Value::CreateIntegerValue(1);\n\n }\n\n found = true;\n\n } else if (path == kProxySingle) {\n\n data = Value::CreateBooleanValue(config.mode ==\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig::MODE_SINGLE_PROXY);\n\n found = true;\n\n } else if (path == kProxyFtpUrl) {\n\n found = (data = CreateServerHostValue(config.ftp_proxy));\n\n } else if (path == kProxySocks) {\n\n found = (data = CreateServerHostValue(config.socks_proxy));\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 91, "score": 206402.16088813022 }, { "content": " return UserCrosSettingsTrust::GetInstance()->RequestTrustedEntity(\n\n kAccountsPrefAllowGuest, callback);\n\n}\n\n\n\nbool UserCrosSettingsProvider::RequestTrustedAllowNewUser(Task* callback) {\n\n return UserCrosSettingsTrust::GetInstance()->RequestTrustedEntity(\n\n kAccountsPrefAllowNewUser, callback);\n\n}\n\n\n\nbool UserCrosSettingsProvider::RequestTrustedShowUsersOnSignin(Task* callback) {\n\n return UserCrosSettingsTrust::GetInstance()->RequestTrustedEntity(\n\n kAccountsPrefShowUserNamesOnSignIn, callback);\n\n}\n\n\n\nbool UserCrosSettingsProvider::RequestTrustedDataRoamingEnabled(\n\n Task* callback) {\n\n return UserCrosSettingsTrust::GetInstance()->RequestTrustedEntity(\n\n kSignedDataRoamingEnabled, callback);\n\n}\n\n\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 92, "score": 206401.34012688766 }, { "content": " VLOG(1) << \"Retrieved cros setting \" << name << \"=\" << value;\n\n if (IsControlledBooleanSetting(name)) {\n\n OnBooleanPropertyRetrieve(name, (value == kTrueIncantation),\n\n fallback_to_default ? USE_VALUE_DEFAULT : USE_VALUE_SUPPLIED);\n\n UpdateCacheBool(name, (value == kTrueIncantation),\n\n fallback_to_default ? USE_VALUE_DEFAULT : USE_VALUE_SUPPLIED);\n\n } else if (IsControlledStringSetting(name)) {\n\n UpdateCacheString(name, value,\n\n fallback_to_default ? USE_VALUE_DEFAULT : USE_VALUE_SUPPLIED);\n\n }\n\n break;\n\n }\n\n case SignedSettings::OPERATION_FAILED:\n\n default: {\n\n DCHECK(code == SignedSettings::OPERATION_FAILED);\n\n DCHECK(is_owned);\n\n LOG(ERROR) << \"On owned device: failed to retrieve cros \"\n\n \"setting, name=\" << name;\n\n if (retries_left_ > 0) {\n\n retries_left_ -= 1;\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 93, "score": 206400.62550663218 }, { "content": " return true;\n\n }\n\n return false;\n\n }\n\n\n\n bool RequestTrustedEntity(const std::string& name, Task* callback) {\n\n if (RequestTrustedEntity(name)) {\n\n delete callback;\n\n return true;\n\n } else {\n\n if (callback)\n\n callbacks_[name].push_back(callback);\n\n return false;\n\n }\n\n }\n\n\n\n void Reload() {\n\n for (size_t i = 0; i < arraysize(kBooleanSettings); ++i)\n\n StartFetchingSetting(kBooleanSettings[i]);\n\n for (size_t i = 0; i < arraysize(kStringSettings); ++i)\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 94, "score": 206399.72836564897 }, { "content": " int val;\n\n if (in_value->GetAsInteger(&val)) {\n\n config_service->UISetProxyConfigToSingleProxy(CreateProxyServerFromPort(\n\n val, config.single_proxy, net::ProxyServer::SCHEME_HTTP));\n\n }\n\n } else if (path == kProxyHttpUrl) {\n\n std::string val;\n\n if (in_value->GetAsString(&val)) {\n\n config_service->UISetProxyConfigToProxyPerScheme(\"http\",\n\n CreateProxyServerFromHost(\n\n val, config.http_proxy, net::ProxyServer::SCHEME_HTTP));\n\n }\n\n } else if (path == kProxyHttpPort) {\n\n int val;\n\n if (in_value->GetAsInteger(&val)) {\n\n config_service->UISetProxyConfigToProxyPerScheme(\"http\",\n\n CreateProxyServerFromPort(\n\n val, config.http_proxy, net::ProxyServer::SCHEME_HTTP));\n\n }\n\n } else if (path == kProxyHttpsUrl) {\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 95, "score": 206399.64824384623 }, { "content": " chromeos::ProxyConfigServiceImpl* config_service = GetConfigService();\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig config;\n\n config_service->UIGetProxyConfig(&config);\n\n\n\n if (path == kProxyPacUrl) {\n\n if (config.automatic_proxy.pac_url.is_valid()) {\n\n data = Value::CreateStringValue(config.automatic_proxy.pac_url.spec());\n\n found = true;\n\n }\n\n } else if (path == kProxySingleHttp) {\n\n found = (data = CreateServerHostValue(config.single_proxy));\n\n } else if (path == kProxySingleHttpPort) {\n\n found = (data = CreateServerPortValue(config.single_proxy));\n\n } else if (path == kProxyHttpUrl) {\n\n found = (data = CreateServerHostValue(config.http_proxy));\n\n } else if (path == kProxyHttpsUrl) {\n\n found = (data = CreateServerHostValue(config.https_proxy));\n\n } else if (path == kProxyType) {\n\n if (config.mode ==\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig::MODE_AUTO_DETECT ||\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 96, "score": 206399.500723547 }, { "content": " std::string val;\n\n if (in_value->GetAsString(&val)) {\n\n config_service->UISetProxyConfigToProxyPerScheme(\"https\",\n\n CreateProxyServerFromHost(\n\n val, config.https_proxy, net::ProxyServer::SCHEME_HTTP));\n\n }\n\n } else if (path == kProxyHttpsPort) {\n\n int val;\n\n if (in_value->GetAsInteger(&val)) {\n\n config_service->UISetProxyConfigToProxyPerScheme(\"https\",\n\n CreateProxyServerFromPort(\n\n val, config.https_proxy, net::ProxyServer::SCHEME_HTTP));\n\n }\n\n } else if (path == kProxyType) {\n\n int val;\n\n if (in_value->GetAsInteger(&val)) {\n\n if (val == 3) {\n\n if (config.automatic_proxy.pac_url.is_valid())\n\n config_service->UISetProxyConfigToPACScript(\n\n config.automatic_proxy.pac_url);\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 97, "score": 206399.10927270757 }, { "content": " StartFetchingSetting(name);\n\n return;\n\n }\n\n LOG(ERROR) << \"No retries left\";\n\n if (IsControlledBooleanSetting(name)) {\n\n // For boolean settings we can just set safe (false) values\n\n // and continue as trusted.\n\n OnBooleanPropertyRetrieve(name, false, USE_VALUE_SUPPLIED);\n\n UpdateCacheBool(name, false, USE_VALUE_SUPPLIED);\n\n } else {\n\n prefs->ClearPref((name + kTrustedSuffix).c_str());\n\n return;\n\n }\n\n break;\n\n }\n\n }\n\n prefs->SetBoolean((name + kTrustedSuffix).c_str(), true);\n\n {\n\n std::vector<Task*>& callbacks_vector = callbacks_[name];\n\n for (size_t i = 0; i < callbacks_vector.size(); ++i)\n", "file_path": "chrome/browser/chromeos/user_cros_settings_provider.cc", "rank": 98, "score": 206398.4304179171 }, { "content": " // Don't persist settings to device for guest session.\n\n config_service->UISetPersistToDevice(\n\n !CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession));\n\n // Retrieve proxy config.\n\n chromeos::ProxyConfigServiceImpl::ProxyConfig config;\n\n config_service->UIGetProxyConfig(&config);\n\n\n\n if (path == kProxyPacUrl) {\n\n std::string val;\n\n if (in_value->GetAsString(&val)) {\n\n GURL url(val);\n\n config_service->UISetProxyConfigToPACScript(url);\n\n }\n\n } else if (path == kProxySingleHttp) {\n\n std::string val;\n\n if (in_value->GetAsString(&val)) {\n\n config_service->UISetProxyConfigToSingleProxy(CreateProxyServerFromHost(\n\n val, config.single_proxy, net::ProxyServer::SCHEME_HTTP));\n\n }\n\n } else if (path == kProxySingleHttpPort) {\n", "file_path": "chrome/browser/chromeos/proxy_cros_settings_provider.cc", "rank": 99, "score": 206397.50676610143 } ]
C++
aha/main.cpp
dlarudgus20/newly-aha
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
#include <iostream> #include <string> #include <type_traits> #include <variant> #include <locale> #include <boost/program_options.hpp> #include <boost/iterator/transform_iterator.hpp> namespace bpo = boost::program_options; #include "../libahafront/aha/front/source.hpp" #include "../libahafront/aha/front/lexer.hpp" #include "../libahafront/aha/front/parser.hpp" using namespace aha::front; inline std::string utf32narrow(std::u32string_view str) { auto fn = [](char32_t ch) { return static_cast<char>(ch); }; auto tbeg = boost::iterators::make_transform_iterator(str.begin(), fn); auto tend = boost::iterators::make_transform_iterator(str.end(), fn); return std::string(tbeg, tend); }; int main(int argc, char* argv[]) { repl_source src; lexer ll; parser yy; auto get_input = [&src] (bool fresh) { std::string str; std::cout << (fresh ? ">> " : "-- "); if (!getline(std::cin, str)) { src.feedEof(); } else { if (fresh && str == ":{") { while (true) { std::cout << "-- "; if (!getline(std::cin, str)) { src.feedEof(); break; } else if (str == ":}") { break; } else { src.feedString(str + "\n"); } } } else { src.feedString(str + "\n"); } } }; bool interpolated = false; auto print_error = [](source_positional_error& ex) { auto pos = ex.getPosition(); std::cerr << ex.getSource().getName() << ":" << (pos.line + 1) << ":" << (pos.col + 1) << ": " << ex.what() << std::endl; }; while (true) { try { bool fresh = true; std::optional<token> tok; while (true) { tok = ll.lex(src); if (tok) break; auto rs = ll.getLastResult(); if (rs == lex_result::exhausted) { get_input(fresh); fresh = false; } else { ll.clearAll(); src.clearAll(); std::cin.clear(); fresh = true; } } if (std::holds_alternative<token_indent>(tok->data)) { auto t = std::get<token_indent>(tok->data); std::cout << "indent { " << t.level << " }\n"; } else if (std::holds_alternative<token_newline>(tok->data)) { auto t = std::get<token_newline>(tok->data); std::cout << "newline {}\n"; } else if (std::holds_alternative<token_punct>(tok->data)) { auto t = std::get<token_punct>(tok->data); auto str = utf32narrow(t.str); std::cout << "punct { '" << str << "' }\n"; } else if (std::holds_alternative<token_keyword>(tok->data)) { auto t = std::get<token_keyword>(tok->data); auto str = utf32narrow(t.str); std::cout << "keyword { '" << str << "' }\n"; } else if (std::holds_alternative<token_contextual_keyword>(tok->data)) { auto t = std::get<token_contextual_keyword>(tok->data); auto str = utf32narrow(t.str); std::cout << "contextual keyword { '" << str << "' }\n"; } else if (std::holds_alternative<token_identifier>(tok->data)) { auto t = std::get<token_identifier>(tok->data); auto str = utf32narrow(t.str); std::cout << "identifier { '" << str << "' }\n"; } else if (std::holds_alternative<token_number>(tok->data)) { auto t = std::get<token_number>(tok->data); if (!t.is_float) { std::cout << "integer [radix:" << t.radix << "] { " << t.integer << t.postfix << " }\n"; } else { std::cout << "float [radix:" << t.radix << "] { " << t.integer; if (!t.fraction.empty()) std::cout << "." << t.fraction; if (!t.exponent.empty()) std::cout << (t.radix == 10 ? "e" : "p") << t.exponent; std::cout << t.postfix << " }\n"; } } else if (std::holds_alternative<token_normal_string>(tok->data)) { auto t = std::get<token_normal_string>(tok->data); auto str = utf32narrow(t.str); auto deli = static_cast<char>(t.delimiter); std::cout << "normal string { " << deli << str << deli << " }\n"; } else if (std::holds_alternative<token_raw_string>(tok->data)) { auto t = std::get<token_raw_string>(tok->data); auto str = utf32narrow(t.str); auto deli = static_cast<char>(t.delimiter); std::cout << "raw string { " << deli << str << deli << " }\n"; } else if (std::holds_alternative<token_interpol_string_start>(tok->data)) { auto t = std::get<token_interpol_string_start>(tok->data); auto str = utf32narrow(t.str); std::cout << "interpolated string (start) { `" << str << "{ }\n"; interpolated = true; } else if (std::holds_alternative<token_interpol_string_mid>(tok->data)) { auto t = std::get<token_interpol_string_mid>(tok->data); auto str = utf32narrow(t.str); std::cout << "interpolated string (mid) { }" << str << "${ }\n"; } else if (std::holds_alternative<token_interpol_string_end>(tok->data)) { auto t = std::get<token_interpol_string_end>(tok->data); auto str = utf32narrow(t.str); std::cout << "interpolated string (end) { " << (interpolated ? '}' : '`') << str << "` }\n"; interpolated = false; } else { throw std::logic_error("add handler ..."); } } catch (lexer_error& ex) { print_error(ex); ll.clearBuffer(); } catch (invalid_byteseq& ex) { print_error(ex); src.clearBuffer(); } } return 0; }
#include <iostream> #include <string> #include <type_traits> #include <variant> #include <locale> #include <boost/program_options.hpp> #include <boost/iterator/transform_iterator.hpp> namespace bpo = boost::program_options; #include "../libahafront/aha/front/source.hpp" #include "../libahafront/aha/front/lexer.hpp" #include "../libahafront/aha/front/parser.hpp" using namespace aha::front;
; int main(int argc, char* argv[]) { repl_source src; lexer ll; parser yy; auto get_input = [&src] (bool fresh) { std::string str; std::cout << (fresh ? ">> " : "-- "); if (!getline(std::cin, str)) { src.feedEof(); } else { if (fresh && str == ":{") { while (true) { std::cout << "-- "; if (!getline(std::cin, str)) { src.feedEof(); break; } else if (str == ":}") { break; } else { src.feedString(str + "\n"); } } } else { src.feedString(str + "\n"); } } }; bool interpolated = false; auto print_error = [](source_positional_error& ex) { auto pos = ex.getPosition(); std::cerr << ex.getSource().getName() << ":" << (pos.line + 1) << ":" << (pos.col + 1) << ": " << ex.what() << std::endl; }; while (true) { try { bool fresh = true; std::optional<token> tok; while (true) { tok = ll.lex(src); if (tok) break; auto rs = ll.getLastResult(); if (rs == lex_result::exhausted) { get_input(fresh); fresh = false; } else { ll.clearAll(); src.clearAll(); std::cin.clear(); fresh = true; } } if (std::holds_alternative<token_indent>(tok->data)) { auto t = std::get<token_indent>(tok->data); std::cout << "indent { " << t.level << " }\n"; } else if (std::holds_alternative<token_newline>(tok->data)) { auto t = std::get<token_newline>(tok->data); std::cout << "newline {}\n"; } else if (std::holds_alternative<token_punct>(tok->data)) { auto t = std::get<token_punct>(tok->data); auto str = utf32narrow(t.str); std::cout << "punct { '" << str << "' }\n"; } else if (std::holds_alternative<token_keyword>(tok->data)) { auto t = std::get<token_keyword>(tok->data); auto str = utf32narrow(t.str); std::cout << "keyword { '" << str << "' }\n"; } else if (std::holds_alternative<token_contextual_keyword>(tok->data)) { auto t = std::get<token_contextual_keyword>(tok->data); auto str = utf32narrow(t.str); std::cout << "contextual keyword { '" << str << "' }\n"; } else if (std::holds_alternative<token_identifier>(tok->data)) { auto t = std::get<token_identifier>(tok->data); auto str = utf32narrow(t.str); std::cout << "identifier { '" << str << "' }\n"; } else if (std::holds_alternative<token_number>(tok->data)) { auto t = std::get<token_number>(tok->data); if (!t.is_float) { std::cout << "integer [radix:" << t.radix << "] { " << t.integer << t.postfix << " }\n"; } else { std::cout << "float [radix:" << t.radix << "] { " << t.integer; if (!t.fraction.empty()) std::cout << "." << t.fraction; if (!t.exponent.empty()) std::cout << (t.radix == 10 ? "e" : "p") << t.exponent; std::cout << t.postfix << " }\n"; } } else if (std::holds_alternative<token_normal_string>(tok->data)) { auto t = std::get<token_normal_string>(tok->data); auto str = utf32narrow(t.str); auto deli = static_cast<char>(t.delimiter); std::cout << "normal string { " << deli << str << deli << " }\n"; } else if (std::holds_alternative<token_raw_string>(tok->data)) { auto t = std::get<token_raw_string>(tok->data); auto str = utf32narrow(t.str); auto deli = static_cast<char>(t.delimiter); std::cout << "raw string { " << deli << str << deli << " }\n"; } else if (std::holds_alternative<token_interpol_string_start>(tok->data)) { auto t = std::get<token_interpol_string_start>(tok->data); auto str = utf32narrow(t.str); std::cout << "interpolated string (start) { `" << str << "{ }\n"; interpolated = true; } else if (std::holds_alternative<token_interpol_string_mid>(tok->data)) { auto t = std::get<token_interpol_string_mid>(tok->data); auto str = utf32narrow(t.str); std::cout << "interpolated string (mid) { }" << str << "${ }\n"; } else if (std::holds_alternative<token_interpol_string_end>(tok->data)) { auto t = std::get<token_interpol_string_end>(tok->data); auto str = utf32narrow(t.str); std::cout << "interpolated string (end) { " << (interpolated ? '}' : '`') << str << "` }\n"; interpolated = false; } else { throw std::logic_error("add handler ..."); } } catch (lexer_error& ex) { print_error(ex); ll.clearBuffer(); } catch (invalid_byteseq& ex) { print_error(ex); src.clearBuffer(); } } return 0; }
inline std::string utf32narrow(std::u32string_view str) { auto fn = [](char32_t ch) { return static_cast<char>(ch); }; auto tbeg = boost::iterators::make_transform_iterator(str.begin(), fn); auto tend = boost::iterators::make_transform_iterator(str.end(), fn); return std::string(tbeg, tend); }
function_block-full_function
[ { "content": "// SOFTWARE.\n\n\n\n#pragma once\n\n\n\n#include <string>\n\n#include <string_view>\n\n#include <vector>\n\n#include <deque>\n\n#include <optional>\n\n#include <stdexcept>\n\n\n\nnamespace aha::front\n\n{\n", "file_path": "libahafront/aha/front/source.hpp", "rank": 1, "score": 9.50118388292686 }, { "content": "// SOFTWARE.\n\n\n\n#pragma once\n\n\n\n#include <string>\n\n#include <string_view>\n\n#include <vector>\n\n#include <deque>\n\n#include <optional>\n\n#include <variant>\n\n#include <utility>\n\n\n\n#include \"source.hpp\"\n\n\n\nnamespace aha::front\n\n{\n", "file_path": "libahafront/aha/front/lexer.hpp", "rank": 2, "score": 9.284893347623354 }, { "content": "// SOFTWARE.\n\n\n\n#include \"pch.h\"\n\n#include \"aha/front/lexer.hpp\"\n\n\n\n#include \"aha/front/source.hpp\"\n\n\n\n#include <boost/iterator/transform_iterator.hpp>\n\n\n\n#include \"is_newline.h\"\n\n#include \"ext.h\"\n\n\n\nnamespace\n\n{\n\n using namespace aha::front;\n\n\n\n template <typename TokenData>\n\n token make_token(TokenData&& data, source& src, source_position beg, source_position end)\n\n {\n\n token tok { &src, beg, end, std::forward<TokenData>(data) };\n", "file_path": "libahafront/lexer.cpp", "rank": 3, "score": 7.838809353482121 }, { "content": "// SOFTWARE.\n\n\n\n#include \"pch.h\"\n\n#include \"aha/front/source.hpp\"\n\n\n\n#include \"is_newline.h\"\n\n\n\nnamespace aha::front\n\n{\n\n source::~source() = default;\n\n\n\n repl_source::repl_source(std::string name /* = \"<repl>\" */)\n\n : m_name(std::move(name))\n\n {\n\n init();\n\n }\n\n\n\n repl_source::~repl_source() = default;\n\n\n\n void repl_source::init()\n", "file_path": "libahafront/source.cpp", "rank": 4, "score": 7.156891541532527 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n// SOFTWARE.\n\n\n\n#pragma once\n\n\n\n#include \"lexer.hpp\"\n\n\n\nnamespace aha::front\n\n{\n", "file_path": "libahafront/aha/front/parser.hpp", "rank": 5, "score": 5.936948005792258 }, { "content": "// SOFTWARE.\n\n\n\n#include \"pch.h\"\n\n#include \"aha/front/parser.hpp\"\n\n\n\nnamespace aha::front\n\n{\n\n parser::parser() = default;\n\n parser::~parser() = default;\n\n\n\n void parser::parse(const token& tok)\n\n {\n\n }\n\n}\n", "file_path": "libahafront/parser.cpp", "rank": 6, "score": 5.594023369816082 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\n// SOFTWARE.\n\n\n\n#include \"pch.h\"\n", "file_path": "libahafront/pch.cpp", "rank": 8, "score": 4.748336165678472 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "libahafront/source.cpp", "rank": 10, "score": 4.511161589865315 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "libahafront/aha/front/lexer.hpp", "rank": 11, "score": 4.511161589865315 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "libahafront/parser.cpp", "rank": 12, "score": 4.511161589865315 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "libahafront/lexer.cpp", "rank": 13, "score": 4.511161589865315 }, { "content": "// The MIT License (MIT)\n\n//\n\n// Copyright (c) 2016 Im Kyeong-Hyeon ([email protected])\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in all\n\n// copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "libahafront/aha/front/source.hpp", "rank": 14, "score": 4.511161589865315 }, { "content": " return tok;\n\n }\n\n}\n\n\n\nnamespace aha::front\n\n{\n\n lexer::lexer()\n\n {\n\n init();\n\n }\n\n\n\n lexer::~lexer() = default;\n\n\n\n void lexer::init()\n\n {\n\n m_flags.interpol_string_after = false;\n\n m_flags.enable_interpol_block_end = false;\n\n\n\n m_last_result = lex_result::exhausted;\n\n }\n", "file_path": "libahafront/lexer.cpp", "rank": 15, "score": 4.459945259180861 }, { "content": " source_position beg;\n\n source_position end;\n\n\n\n std::variant<\n\n token_indent,\n\n token_newline,\n\n token_punct,\n\n token_keyword,\n\n token_contextual_keyword,\n\n token_identifier,\n\n token_normal_string,\n\n token_raw_string,\n\n token_interpol_string_start,\n\n token_interpol_string_mid,\n\n token_interpol_string_end,\n\n token_number\n\n > data;\n\n };\n\n\n", "file_path": "libahafront/aha/front/lexer.hpp", "rank": 17, "score": 3.2914548989592296 }, { "content": " struct token_contextual_keyword\n\n {\n\n std::u32string str;\n\n };\n\n struct token_identifier\n\n {\n\n std::u32string str;\n\n };\n\n struct token_normal_string\n\n {\n\n char32_t delimiter;\n\n std::u32string str;\n\n };\n\n struct token_raw_string\n\n {\n\n char32_t delimiter;\n\n std::u32string str;\n\n };\n\n struct token_interpol_string_start\n\n {\n", "file_path": "libahafront/aha/front/lexer.hpp", "rank": 20, "score": 3.0788442114124512 }, { "content": " {\n\n m_flags.normal_string = true;\n\n }\n\n else if (ch == U'`')\n\n {\n\n m_flags.interpol_string = true;\n\n }\n\n else if (m_flags.enable_interpol_block_end && ch == U'}')\n\n {\n\n m_flags.interpol_string = true;\n\n }\n\n else\n\n {\n\n throwErrorWithRevert(lexer_error(src, pos, \"unexpected character\"));\n\n }\n\n }\n\n }\n\n else\n\n {\n\n if (m_flags.comment_line)\n", "file_path": "libahafront/lexer.cpp", "rank": 21, "score": 3.062447330511809 }, { "content": " std::u32string str;\n\n };\n\n struct token_interpol_string_mid\n\n {\n\n std::u32string str;\n\n };\n\n struct token_interpol_string_end\n\n {\n\n std::u32string str;\n\n };\n\n struct token_number\n\n {\n\n unsigned radix;\n\n std::string integer, fraction, exponent, postfix;\n\n bool is_float;\n\n };\n\n\n\n struct token\n\n {\n\n source* ptr_src;\n", "file_path": "libahafront/aha/front/lexer.hpp", "rank": 22, "score": 3.0462241728819897 }, { "content": " {\n\n bool identifier : 1;\n\n bool unknown_number : 1;\n\n bool binary : 1;\n\n bool octal : 1;\n\n bool heximal : 1;\n\n bool decimal : 1;\n\n bool punct : 1;\n\n bool normal_string : 1;\n\n bool raw_string : 1;\n\n bool interpol_string : 1;\n\n bool comment_line : 1;\n\n bool comment_block : 1;\n\n bool comment_block_contains_newline : 1;\n\n bool comment_block_might_closing : 1;\n\n bool commented_out : 1;\n\n\n\n bool interpol_string_after : 1;\n\n bool enable_interpol_block_end : 1;\n\n } m_flags;\n", "file_path": "libahafront/aha/front/lexer.hpp", "rank": 23, "score": 3.0188809022125556 }, { "content": " skip = true;\n\n }\n\n else\n\n {\n\n if (ch == U'\\n')\n\n {\n\n m_flags.comment_block_contains_newline = true;\n\n }\n\n\n\n m_flags.comment_block_might_closing = false;\n\n }\n\n }\n\n\n\n if (!commented_out)\n\n {\n\n if (m_flags.raw_string && m_str_token.size() == 1)\n\n {\n\n if (ch != U'\\'' && ch != U'\\\"')\n\n m_flags.raw_string = false;\n\n }\n", "file_path": "libahafront/lexer.cpp", "rank": 25, "score": 2.7467614456991196 }, { "content": " m_flags.punct = false;\n\n m_flags.normal_string = false;\n\n m_flags.raw_string = false;\n\n m_flags.interpol_string = false;\n\n m_flags.comment_line = false;\n\n m_flags.comment_block = false;\n\n m_flags.comment_block_contains_newline = false;\n\n m_flags.comment_block_might_closing = false;\n\n\n\n if (isIdentifierFirstChar(ch))\n\n {\n\n m_flags.identifier = true;\n\n }\n\n else if (ch == U'0')\n\n {\n\n m_flags.unknown_number = true;\n\n }\n\n else if (U'1' <= ch && ch <= U'9')\n\n {\n\n m_flags.decimal = true;\n", "file_path": "libahafront/lexer.cpp", "rank": 26, "score": 2.728261961675351 }, { "content": "\n\n }\n\n else if (m_flags.normal_string)\n\n {\n\n if (ch != U' ' && (isSeperator(ch) || is_newline(ch)))\n\n {\n\n throwErrorWithRevert(lexer_error(src, pos,\n\n \"non-raw string literal cannot contain seperator or newline character except space\"));\n\n }\n\n else if (ch == m_str_token[0] && m_str_token.back() != U'\\\\')\n\n {\n\n assert(!ret);\n\n ret = make_token(\n\n token_normal_string { m_str_token[0], m_str_token.substr(1) },\n\n src, m_tok_beg, pos);\n\n\n\n m_str_token.clear();\n\n m_tok_beg = pos;\n\n done = true;\n\n skip = true;\n", "file_path": "libahafront/lexer.cpp", "rank": 27, "score": 2.6899741687945435 }, { "content": " }\n\n }\n\n else if (m_flags.interpol_string)\n\n {\n\n // TODO: bugs\n\n if (ch != U' ' && (isSeperator(ch) || is_newline(ch)))\n\n {\n\n throwErrorWithRevert(lexer_error(src, pos,\n\n \"non-raw string literal cannot contain seperator or newline character except space\"));\n\n }\n\n else if ((m_str_token.size() == 1 && m_str_token[0] == U'`') || (m_str_token.size() == 2 && m_str_token[0] == U'@'))\n\n {\n\n // nothing\n\n }\n\n else if (ch == U'`' && m_str_token.back() != U'\\\\')\n\n {\n\n assert(!ret);\n\n ret = make_token(\n\n token_interpol_string_end { m_str_token.substr(1) },\n\n src, m_tok_beg, pos);\n", "file_path": "libahafront/lexer.cpp", "rank": 28, "score": 2.652746147263424 }, { "content": " m_flags.interpol_string_after = true;\n\n m_flags.enable_interpol_block_end = true;\n\n }\n\n else\n\n {\n\n assert(m_str_token.front() == U'}');\n\n\n\n assert(!ret);\n\n ret = make_token(\n\n token_interpol_string_mid { std::move(str) },\n\n src, m_tok_beg, pos);\n\n }\n\n\n\n m_str_token.clear();\n\n m_tok_beg = pos;\n\n done = true;\n\n skip = true;\n\n }\n\n }\n\n else if (m_flags.identifier)\n", "file_path": "libahafront/lexer.cpp", "rank": 29, "score": 2.5460908744079047 }, { "content": "\n\n m_flags.interpol_string_after = false;\n\n m_flags.enable_interpol_block_end = false;\n\n\n\n m_str_token.clear();\n\n m_tok_beg = pos;\n\n done = true;\n\n skip = true;\n\n }\n\n else if (m_str_token.back() == U'$' && ch == U'{')\n\n {\n\n auto str = m_str_token.substr(1, m_str_token.size() - 2);\n\n\n\n if (m_str_token.front() == U'`')\n\n {\n\n assert(!ret);\n\n ret = make_token(\n\n token_interpol_string_start { std::move(str) },\n\n src, m_tok_beg, pos);\n\n\n", "file_path": "libahafront/lexer.cpp", "rank": 30, "score": 2.3727448880097186 }, { "content": "\n\n if (m_flags.raw_string)\n\n {\n\n if (m_str_token.size() >= 3 && m_str_token.back() == m_str_token[1] && ch != m_str_token[1])\n\n {\n\n auto delimiter = m_str_token[1];\n\n\n\n // if not escaped\n\n if ((m_str_token.size() - m_str_token.find_last_not_of(delimiter)) % 2 == 0)\n\n {\n\n assert(!ret);\n\n ret = make_token(\n\n token_raw_string { m_str_token[1], m_str_token.substr(2, m_str_token.size() - 3) },\n\n src, m_tok_beg, pos);\n\n\n\n m_str_token.clear();\n\n m_tok_beg = pos;\n\n done = true;\n\n }\n\n }\n", "file_path": "libahafront/lexer.cpp", "rank": 31, "score": 2.3581494033109083 }, { "content": " init();\n\n }\n\n\n\n void repl_source::feedString(std::string_view line)\n\n {\n\n if (m_error)\n\n throw std::logic_error(\"source has an error\");\n\n if (m_input_end && m_input.empty())\n\n throw std::logic_error(\"repl_source was already fed EOF\");\n\n\n\n m_input.insert(m_input.end(), line.begin(), line.end());\n\n }\n\n\n\n void repl_source::feedEof()\n\n {\n\n if (m_error)\n\n throw std::logic_error(\"source has an error\");\n\n if (m_input_end)\n\n throw std::logic_error(\"repl_source was already fed EOF\");\n\n\n", "file_path": "libahafront/source.cpp", "rank": 32, "score": 2.3437323834644737 }, { "content": " lex_result lexer::getLastResult() const\n\n {\n\n return m_last_result;\n\n }\n\n\n\n void lexer::enableInterpolatedBlockEnd(bool enable)\n\n {\n\n if (!m_flags.interpol_string_after)\n\n throw std::logic_error(\"dis/enabling interpolated block end can be done only during interpolated string\");\n\n\n\n m_flags.enable_interpol_block_end = enable;\n\n }\n\n\n\n void lexer::setContextualKeyword(std::vector<std::u32string> keywords)\n\n {\n\n m_contextual_keywords = std::move(keywords);\n\n }\n\n\n\n bool lexer::isSeperator(char32_t ch)\n\n {\n", "file_path": "libahafront/lexer.cpp", "rank": 33, "score": 2.3294905751183146 }, { "content": "\n\n private:\n\n void init();\n\n\n\n std::string m_name;\n\n\n\n std::deque<char32_t> m_chars;\n\n std::vector<unsigned> m_lines;\n\n bool m_prev_is_CR;\n\n\n\n std::deque<char> m_input;\n\n bool m_input_end;\n\n bool m_error;\n\n\n\n bool popByte(unsigned char& ch);\n\n };\n\n}\n", "file_path": "libahafront/aha/front/source.hpp", "rank": 34, "score": 2.075253643806401 }, { "content": " m_input_end = true;\n\n }\n\n\n\n std::string_view repl_source::getName()\n\n {\n\n return m_name;\n\n }\n\n\n\n std::optional<std::pair<char32_t, source_position>> repl_source::readChar()\n\n {\n\n if (m_error)\n\n throw std::logic_error(\"source has an error\");\n\n\n\n char32_t ret;\n\n\n\n unsigned char b[4];\n\n int count = 0;\n\n if (!popByte(b[0]))\n\n return { };\n\n\n", "file_path": "libahafront/source.cpp", "rank": 37, "score": 1.9686817090839335 }, { "content": " }\n\n else if (punct_chars.find(ch) != std::u32string_view::npos)\n\n {\n\n if (ch == U'/')\n\n {\n\n m_flags.comment_line = true;\n\n m_flags.comment_block = true;\n\n }\n\n else if (ch == U'@')\n\n {\n\n m_flags.raw_string = true;\n\n }\n\n\n\n m_flags.punct = true;\n\n }\n\n else if (ch == U'#')\n\n {\n\n m_flags.comment_line = true;\n\n }\n\n else if (ch == U'\\'' || ch == U'\\\"')\n", "file_path": "libahafront/lexer.cpp", "rank": 38, "score": 1.9486674557410866 }, { "content": " else if (m_flags.decimal)\n\n radix = 10;\n\n else // if (m_flags.heximal)\n\n radix = 16;\n\n\n\n auto substr8 = [](std::u32string_view str, std::size_t pos, std::size_t count) {\n\n auto sub = str.substr(pos, count);\n\n\n\n auto fn = [](char32_t ch) { return static_cast<char>(ch); };\n\n auto tbeg = boost::iterators::make_transform_iterator(sub.begin(), fn);\n\n auto tend = boost::iterators::make_transform_iterator(sub.end(), fn);\n\n\n\n return std::string(tbeg, tend);\n\n };\n\n\n\n token_number tn;\n\n tn.radix = radix;\n\n tn.integer = substr8(m_str_token, beg1, end1 - beg1);\n\n tn.fraction = substr8(m_str_token, beg2, end2 - beg2);\n\n tn.exponent = substr8(m_str_token, beg3, end3 - beg3);\n", "file_path": "libahafront/lexer.cpp", "rank": 39, "score": 1.3853221718284527 }, { "content": " static const std::u32string_view punct_chars = U\"~!@$%^&*()-=+[];:,./<>?|\";\n\n\n\n static const auto toks_punct = ext::make_array<std::u32string_view>(\n\n U\"~\", U\"!\", U\"@\", U\"$\", U\"%\", U\"^\", U\"&\", U\"*\", U\"(\", U\")\", U\"-\", U\"=\", U\"+\",\n\n U\"[\", U\"]\", U\";\", U\":\", U\",\", U\".\", U\"/\", U\"<\", U\">\", U\"?\",\n\n U\"++\", U\"--\", U\">>\", U\"<<\", U\"==\", U\"!=\", U\"<=\", U\">=\", U\"&&\", U\"||\",\n\n U\"+=\", U\"-=\", U\"*=\", U\"/=\", U\"%=\", U\"&=\", U\"|=\", U\"^=\", U\"<<=\", U\">>=\", U\":=:\",\n\n U\"::\", U\"->\", U\"=>\", U\"|>\", U\"&>\", U\"<&\", U\"?.\");\n\n\n\n static const auto toks_keyword = ext::make_array<std::u32string_view>(\n\n U\"module\", U\"import\", U\"class\", U\"interface\", U\"enum\", U\"static\", U\"final\",\n\n U\"public\", U\"private\", U\"protected\", U\"internal\",\n\n U\"func\", U\"in\", U\"let\", U\"var\", U\"this\", U\"event\", U\"curry\", U\"uncurry\",\n\n U\"byte\", U\"sbyte\", U\"short\", U\"ushort\", U\"int\", U\"uint\", U\"long\", U\"ulong\",\n\n U\"bool\", U\"object\", U\"string\");\n\n\n\n static const auto toks_comment_line = ext::make_array<std::u32string_view>(\n\n U\"#\", U\"//\");\n\n\n\n static const std::u32string_view tok_comment_block_begin = U\"/*\";\n", "file_path": "libahafront/lexer.cpp", "rank": 40, "score": 0.9333608132694202 } ]
C++
cornellbox/Eyeo2012/Shockwaves/src/ShockwavesApp.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
#include "cinder/app/AppBasic.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/Text.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/Vbo.h" #include "cinder/gl/GlslProg.h" #include "cinder/ImageIo.h" #include "cinder/Utilities.h" #include "cinder/Camera.h" #include "cinder/Rand.h" #include "Resources.h" #include "CubeMap.h" #include "Controller.h" #include "Room.h" #include "SpringCam.h" using namespace ci; using namespace ci::app; using namespace std; #define APP_WIDTH 1280 #define APP_HEIGHT 720 #define ROOM_FBO_RES 2 #define GRID_DIM 45 class ShockwavesApp : public AppBasic { public: virtual void prepareSettings( Settings *settings ); virtual void setup(); void initVbo(); virtual void mouseDown( MouseEvent event ); virtual void mouseUp( MouseEvent event ); virtual void mouseMove( MouseEvent event ); virtual void mouseDrag( MouseEvent event ); virtual void mouseWheel( MouseEvent event ); virtual void keyDown( KeyEvent event ); virtual void update(); void drawIntoRoomFbo(); virtual void draw(); void drawInfoPanel(); SpringCam mSpringCam; gl::GlslProg mRoomShader; gl::GlslProg mShockwaveShader; gl::GlslProg mNodeShader; gl::Texture mSmokeTex; gl::Texture mGlowTex; gl::Texture mIconTex; CubeMap mCubeMap; Room mRoom; gl::Fbo mRoomFbo; Controller mController; gl::VboMesh mVboMesh; Vec2f mMousePos, mMouseDownPos, mMouseOffset; bool mMousePressed; }; void ShockwavesApp::prepareSettings( Settings *settings ) { settings->setWindowSize( APP_WIDTH, APP_HEIGHT ); settings->setBorderless(); } void ShockwavesApp::setup() { mSpringCam = SpringCam( -450.0f, getWindowAspectRatio() ); try { mRoomShader = gl::GlslProg( loadResource( "room.vert" ), loadResource( "room.frag" ) ); mShockwaveShader = gl::GlslProg( loadResource( "shockwave.vert" ), loadResource( "shockwave.frag" ) ); mNodeShader = gl::GlslProg( loadResource( "node.vert" ), loadResource( "node.frag" ) ); } catch( gl::GlslProgCompileExc e ) { std::cout << e.what() << std::endl; quit(); } gl::Texture::Format mipFmt; mipFmt.enableMipmapping( true ); mipFmt.setMinFilter( GL_LINEAR_MIPMAP_LINEAR ); mipFmt.setMagFilter( GL_LINEAR ); mIconTex = gl::Texture( loadImage( loadResource( "iconShockwaves.png" ) ), mipFmt ); mSmokeTex = gl::Texture( loadImage( loadResource( "smoke.png" ) ), mipFmt ); mGlowTex = gl::Texture( loadImage( loadResource( "glow.png" ) ), mipFmt ); mCubeMap = CubeMap( GLsizei(512), GLsizei(512), Surface8u( loadImage( loadResource( RES_CUBE1_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE2_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE3_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE4_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE5_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE6_ID ) ) ) ); gl::Fbo::Format roomFormat; roomFormat.setColorInternalFormat( GL_RGB ); mRoomFbo = gl::Fbo( APP_WIDTH/ROOM_FBO_RES, APP_HEIGHT/ROOM_FBO_RES, roomFormat ); bool isPowerOn = true; bool isGravityOn = true; mRoom = Room( Vec3f( 350.0f, 200.0f, 350.0f ), isPowerOn, isGravityOn ); mRoom.init(); mMousePos = Vec2f::zero(); mMouseDownPos = Vec2f::zero(); mMouseOffset = Vec2f::zero(); mMousePressed = false; mController.init( &mRoom, GRID_DIM ); } void ShockwavesApp::initVbo() { gl::VboMesh::Layout layout; layout.setStaticPositions(); layout.setStaticNormals(); int numVertices = GRID_DIM * GRID_DIM; mVboMesh = gl::VboMesh( numVertices * 8 * 3, 0, layout, GL_TRIANGLES ); float s = 10.0f; Vec3f p0( 0.0f, s, 0.0f ); Vec3f p1( -s, 0.0f, 0.0f ); Vec3f p2( 0.0f, 0.0f, s ); Vec3f p3( s, 0.0f, 0.0f ); Vec3f p4( 0.0f, 0.0f, -s ); Vec3f p5( 0.0f, -s, 0.0f ); Vec3f n; Vec3f n0 = Vec3f( 0.0f, 0.0f, 1.0f ); Vec3f n1 = Vec3f(-1.0f,-1.0f, 0.0f ); Vec3f n2 = Vec3f(-1.0f, 1.0f, 0.0f ); Vec3f n3 = Vec3f( 1.0f, 1.0f, 0.0f ); Vec3f n4 = Vec3f( 1.0f,-1.0f, 0.0f ); Vec3f n5 = Vec3f( 0.0f, 0.0f,-1.0f ); vector<Vec3f> positions; vector<Vec3f> normals; for( int x = 0; x < GRID_DIM; ++x ) { for( int y = 0; y < GRID_DIM; ++y ) { positions.push_back( p0 ); positions.push_back( p1 ); positions.push_back( p2 ); n = ( p0 + p1 + p2 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p0 ); positions.push_back( p2 ); positions.push_back( p3 ); n = ( p0 + p2 + p3 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p0 ); positions.push_back( p3 ); positions.push_back( p4 ); n = ( p0 + p3 + p4 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p0 ); positions.push_back( p4 ); positions.push_back( p1 ); n = ( p0 + p4 + p1 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p1 ); positions.push_back( p4 ); n = ( p5 + p1 + p4 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p2 ); positions.push_back( p1 ); n = ( p5 + p2 + p1 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p3 ); positions.push_back( p2 ); n = ( p5 + p3 + p2 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p4 ); positions.push_back( p3 ); n = ( p5 + p4 + p3 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); } } mVboMesh.bufferPositions( positions ); mVboMesh.bufferNormals( normals ); mVboMesh.unbindBuffers(); } void ShockwavesApp::mouseDown( MouseEvent event ) { mMouseDownPos = event.getPos(); mMousePressed = true; mMouseOffset = Vec2f::zero(); } void ShockwavesApp::mouseUp( MouseEvent event ) { mMousePressed = false; mMouseOffset = Vec2f::zero(); } void ShockwavesApp::mouseMove( MouseEvent event ) { mMousePos = event.getPos(); } void ShockwavesApp::mouseDrag( MouseEvent event ) { mouseMove( event ); mMouseOffset = ( mMousePos - mMouseDownPos ) * 0.4f; } void ShockwavesApp::mouseWheel( MouseEvent event ) { float dWheel = event.getWheelIncrement(); mRoom.adjustTimeMulti( dWheel ); } void ShockwavesApp::keyDown( KeyEvent event ) { switch( event.getChar() ){ case '1': mController.preset( 1 ); break; case '2': mController.preset( 2 ); break; case ' ': mRoom.togglePower(); break; case 's': mController.explode(); break; default: break; } switch( event.getCode() ){ case KeyEvent::KEY_UP: mSpringCam.setEye( mRoom.getCornerCeilingPos() ); break; case KeyEvent::KEY_DOWN: mSpringCam.setEye( mRoom.getCornerFloorPos() ); break; case KeyEvent::KEY_RIGHT: mSpringCam.resetEye(); break; default: break; } } void ShockwavesApp::update() { if( mMousePressed ) mSpringCam.dragCam( ( mMouseOffset ) * 0.02f, ( mMouseOffset ).length() * 0.02f ); mSpringCam.update( 0.5f ); mRoom.update(); mController.update( mRoom.getTimeDelta(), mRoom.getTick() ); drawIntoRoomFbo(); } void ShockwavesApp::drawIntoRoomFbo() { mRoomFbo.bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ), true ); gl::setMatricesWindow( mRoomFbo.getSize(), false ); gl::setViewport( mRoomFbo.getBounds() ); gl::disableAlphaBlending(); gl::enable( GL_TEXTURE_2D ); glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); Matrix44f m; m.setToIdentity(); m.scale( mRoom.getDims() ); mCubeMap.bind(); mRoomShader.bind(); mRoomShader.uniform( "cubeMap", 0 ); mRoomShader.uniform( "mvpMatrix", mSpringCam.mMvpMatrix ); mRoomShader.uniform( "mMatrix", m ); mRoomShader.uniform( "eyePos", mSpringCam.mEye ); mRoomShader.uniform( "roomDims", mRoom.getDims() ); mRoomShader.uniform( "power", mRoom.getPower() ); mRoomShader.uniform( "lightPower", mRoom.getLightPower() ); mRoomShader.uniform( "timePer", mRoom.getTimePer() * 1.5f + 0.5f ); mRoom.draw(); mRoomShader.unbind(); mRoomFbo.unbindFramebuffer(); glDisable( GL_CULL_FACE ); } void ShockwavesApp::draw() { gl::clear( ColorA( 0.1f, 0.1f, 0.1f, 0.0f ), true ); gl::setMatricesWindow( getWindowSize(), false ); gl::setViewport( getWindowBounds() ); gl::disableDepthRead(); gl::disableDepthWrite(); gl::enableAlphaBlending(); gl::enable( GL_TEXTURE_2D ); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); mRoomFbo.bindTexture(); gl::drawSolidRect( getWindowBounds() ); gl::setMatrices( mSpringCam.getCam() ); drawInfoPanel(); gl::disable( GL_TEXTURE_2D ); gl::enableDepthRead(); gl::enableDepthWrite(); mNodeShader.bind(); mNodeShader.uniform( "mvpMatrix", mSpringCam.mMvpMatrix ); mNodeShader.uniform( "eyePos", mSpringCam.getEye() ); mNodeShader.uniform( "power", mRoom.getPower() ); mNodeShader.uniform( "roomDims", mRoom.getDims() ); mController.drawNodes( &mNodeShader ); mNodeShader.unbind(); gl::color( ColorA( 0.0f, 0.0f, 0.0f, 0.4f ) ); mController.drawConnections(); gl::disableDepthWrite(); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); gl::enable( GL_CULL_FACE ); glCullFace( GL_FRONT ); mShockwaveShader.bind(); mShockwaveShader.uniform( "mvpMatrix", mSpringCam.mMvpMatrix ); mShockwaveShader.uniform( "eyePos", mSpringCam.getEye() ); mShockwaveShader.uniform( "power", mRoom.getPower() ); mShockwaveShader.uniform( "roomDims", mRoom.getDims() ); mController.drawShockwaves( &mShockwaveShader ); mShockwaveShader.unbind(); gl::disable( GL_CULL_FACE ); gl::enable( GL_TEXTURE_2D ); Vec3f right, up; mSpringCam.mCam.getBillboardVectors( &right, &up ); mSmokeTex.bind(); mController.drawSmokes( right, up ); gl::enableAdditiveBlending(); mGlowTex.bind(); mController.drawGlows( right, up ); if( getElapsedFrames()%60 == 59 ) std::cout << "FPS: " << getAverageFps() << std::endl; } void ShockwavesApp::drawInfoPanel() { gl::pushMatrices(); gl::translate( mRoom.getDims() ); gl::scale( Vec3f( -1.0f, -1.0f, 1.0f ) ); gl::color( Color( 1.0f, 1.0f, 1.0f ) * ( 1.0 - mRoom.getPower() ) ); gl::enableAlphaBlending(); float iconWidth = 50.0f; float X0 = 15.0f; float X1 = X0 + iconWidth; float Y0 = 50.0f; float Y1 = Y0 + iconWidth; float c = mRoom.getPower() * 0.5f + 0.5f; gl::color( ColorA( c, c, c, 0.5f ) ); gl::draw( mIconTex, Rectf( X0, Y0, X1, Y1 ) ); c = mRoom.getPower(); gl::color( ColorA( c, c, c, 0.5f ) ); gl::disable( GL_TEXTURE_2D ); float timePer = mRoom.getTimePer(); gl::drawSolidRect( Rectf( Vec2f( X0, Y1 + 2.0f ), Vec2f( X0 + timePer * ( iconWidth ), Y1 + 2.0f + 4.0f ) ) ); float fpsPer = getAverageFps()/60.0f; gl::drawSolidRect( Rectf( Vec2f( X0, Y1 + 4.0f + 4.0f ), Vec2f( X0 + fpsPer * ( iconWidth ), Y1 + 4.0f + 6.0f ) ) ); gl::popMatrices(); } CINDER_APP_BASIC( ShockwavesApp, RendererGl )
#include "cinder/app/AppBasic.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/Text.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/Vbo.h" #include "cinder/gl/GlslProg.h" #include "cinder/ImageIo.h" #include "cinder/Utilities.h" #include "cinder/Camera.h" #include "cinder/Rand.h" #include "Resources.h" #include "CubeMap.h" #include "Controller.h" #include "Room.h" #include "SpringCam.h" using namespace ci; using namespace ci::app; using namespace std; #define APP_WIDTH 1280 #define APP_HEIGHT 720 #define ROOM_FBO_RES 2 #define GRID_DIM 45 class ShockwavesApp : public AppBasic { public: virtual void prepareSettings( Settings *settings ); virtual void setup(); void initVbo(); virtual void mouseDown( MouseEvent event ); virtual void mouseUp( MouseEvent event ); virtual void mouseMove( MouseEvent event ); virtual void mouseDrag( MouseEvent event ); virtual void mouseWheel( MouseEvent event ); virtual void keyDown( KeyEvent event ); virtual void update(); void drawIntoRoomFbo(); virtual void draw(); void drawInfoPanel(); SpringCam mSpringCam; gl::GlslProg mRoomShader; gl::GlslProg mShockwaveShader; gl::GlslProg mNodeShader; gl::Texture mSmokeTex; gl::Texture mGlowTex; gl::Texture mIconTex; CubeMap mCubeMap; Room mRoom; gl::Fbo mRoomFbo; Controller mController; gl::VboMesh mVboMesh; Vec2f mMousePos, mMouseDownPos, mMouseOffset; bool mMousePressed; }; void ShockwavesApp::prepareSettings( Settings *settings ) { settings->setWindowSize( APP_WIDTH, APP_HEIGHT ); settings->setBorderless(); } void ShockwavesApp::setup() { mSpringCam = SpringCam( -450.0f, getWindowAspectRatio() ); try { mRoomShader = gl::GlslProg( loadResource( "room.vert" ), loadResource( "room.frag" ) ); mShockwaveShader = gl::GlslProg( loadResource( "shockwave.vert" ), loadResource( "shockwave.frag" ) ); mNodeShader = gl::GlslProg( loadResource( "node.vert" ), loadResource( "node.frag" ) ); } catch( gl::GlslProgCompileExc e ) { std::cout << e.what() << std::endl; quit(); } gl::Texture::Format mipFmt; mipFmt.enableMipmapping( true ); mipFmt.setMinFilter( GL_LINEAR_MIPMAP_LINEAR ); mipFmt.setMagFilter( GL_LINEAR ); mIconTex = gl::Texture( loadImage( loadResource( "iconShockwaves.png" ) ), mipFmt ); mSmokeTex = gl::Texture( loadImage( loadResource( "smoke.png" ) ), mipFmt ); mGlowTex = gl::Texture( loadImage( loadResource( "glow.png" ) ), mipFmt ); mCubeMap = CubeMap( GLsizei(512), GLsizei(512), Surface8u( loadImage( loadResource( RES_CUBE1_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE2_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE3_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE4_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE5_ID ) ) ), Surface8u( loadImage( loadResource( RES_CUBE6_ID ) ) ) ); gl::Fbo::Format roomFormat; roomFormat.setColorInternalFormat( GL_RGB ); mRoomFbo = gl::Fbo( APP_WIDTH/ROOM_FBO_RES, APP_HEIGHT/ROOM_FBO_RES, roomFormat ); bool isPowerOn = true; bool isGravityOn = true; mRoom = Room( Vec3f( 350.0f, 200.0f, 350.0f ), isPowerOn, isGravityOn ); mRoom.init(); mMousePos = Vec2f::zero(); mMouseDownPos = Vec2f::zero(); mMouseOffset = Vec2f::zero(); mMousePressed = false; mController.init( &mRoom, GRID_DIM ); } void ShockwavesApp::initVbo() { gl::VboMesh::Layout layout; layout.setStaticPositions(); layout.setStaticNormals(); int numVertices = GRID_DIM * GRID
oid ShockwavesApp::keyDown( KeyEvent event ) { switch( event.getChar() ){ case '1': mController.preset( 1 ); break; case '2': mController.preset( 2 ); break; case ' ': mRoom.togglePower(); break; case 's': mController.explode(); break; default: break; } switch( event.getCode() ){ case KeyEvent::KEY_UP: mSpringCam.setEye( mRoom.getCornerCeilingPos() ); break; case KeyEvent::KEY_DOWN: mSpringCam.setEye( mRoom.getCornerFloorPos() ); break; case KeyEvent::KEY_RIGHT: mSpringCam.resetEye(); break; default: break; } } void ShockwavesApp::update() { if( mMousePressed ) mSpringCam.dragCam( ( mMouseOffset ) * 0.02f, ( mMouseOffset ).length() * 0.02f ); mSpringCam.update( 0.5f ); mRoom.update(); mController.update( mRoom.getTimeDelta(), mRoom.getTick() ); drawIntoRoomFbo(); } void ShockwavesApp::drawIntoRoomFbo() { mRoomFbo.bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ), true ); gl::setMatricesWindow( mRoomFbo.getSize(), false ); gl::setViewport( mRoomFbo.getBounds() ); gl::disableAlphaBlending(); gl::enable( GL_TEXTURE_2D ); glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); Matrix44f m; m.setToIdentity(); m.scale( mRoom.getDims() ); mCubeMap.bind(); mRoomShader.bind(); mRoomShader.uniform( "cubeMap", 0 ); mRoomShader.uniform( "mvpMatrix", mSpringCam.mMvpMatrix ); mRoomShader.uniform( "mMatrix", m ); mRoomShader.uniform( "eyePos", mSpringCam.mEye ); mRoomShader.uniform( "roomDims", mRoom.getDims() ); mRoomShader.uniform( "power", mRoom.getPower() ); mRoomShader.uniform( "lightPower", mRoom.getLightPower() ); mRoomShader.uniform( "timePer", mRoom.getTimePer() * 1.5f + 0.5f ); mRoom.draw(); mRoomShader.unbind(); mRoomFbo.unbindFramebuffer(); glDisable( GL_CULL_FACE ); } void ShockwavesApp::draw() { gl::clear( ColorA( 0.1f, 0.1f, 0.1f, 0.0f ), true ); gl::setMatricesWindow( getWindowSize(), false ); gl::setViewport( getWindowBounds() ); gl::disableDepthRead(); gl::disableDepthWrite(); gl::enableAlphaBlending(); gl::enable( GL_TEXTURE_2D ); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); mRoomFbo.bindTexture(); gl::drawSolidRect( getWindowBounds() ); gl::setMatrices( mSpringCam.getCam() ); drawInfoPanel(); gl::disable( GL_TEXTURE_2D ); gl::enableDepthRead(); gl::enableDepthWrite(); mNodeShader.bind(); mNodeShader.uniform( "mvpMatrix", mSpringCam.mMvpMatrix ); mNodeShader.uniform( "eyePos", mSpringCam.getEye() ); mNodeShader.uniform( "power", mRoom.getPower() ); mNodeShader.uniform( "roomDims", mRoom.getDims() ); mController.drawNodes( &mNodeShader ); mNodeShader.unbind(); gl::color( ColorA( 0.0f, 0.0f, 0.0f, 0.4f ) ); mController.drawConnections(); gl::disableDepthWrite(); gl::color( ColorA( 1.0f, 1.0f, 1.0f, 1.0f ) ); gl::enable( GL_CULL_FACE ); glCullFace( GL_FRONT ); mShockwaveShader.bind(); mShockwaveShader.uniform( "mvpMatrix", mSpringCam.mMvpMatrix ); mShockwaveShader.uniform( "eyePos", mSpringCam.getEye() ); mShockwaveShader.uniform( "power", mRoom.getPower() ); mShockwaveShader.uniform( "roomDims", mRoom.getDims() ); mController.drawShockwaves( &mShockwaveShader ); mShockwaveShader.unbind(); gl::disable( GL_CULL_FACE ); gl::enable( GL_TEXTURE_2D ); Vec3f right, up; mSpringCam.mCam.getBillboardVectors( &right, &up ); mSmokeTex.bind(); mController.drawSmokes( right, up ); gl::enableAdditiveBlending(); mGlowTex.bind(); mController.drawGlows( right, up ); if( getElapsedFrames()%60 == 59 ) std::cout << "FPS: " << getAverageFps() << std::endl; } void ShockwavesApp::drawInfoPanel() { gl::pushMatrices(); gl::translate( mRoom.getDims() ); gl::scale( Vec3f( -1.0f, -1.0f, 1.0f ) ); gl::color( Color( 1.0f, 1.0f, 1.0f ) * ( 1.0 - mRoom.getPower() ) ); gl::enableAlphaBlending(); float iconWidth = 50.0f; float X0 = 15.0f; float X1 = X0 + iconWidth; float Y0 = 50.0f; float Y1 = Y0 + iconWidth; float c = mRoom.getPower() * 0.5f + 0.5f; gl::color( ColorA( c, c, c, 0.5f ) ); gl::draw( mIconTex, Rectf( X0, Y0, X1, Y1 ) ); c = mRoom.getPower(); gl::color( ColorA( c, c, c, 0.5f ) ); gl::disable( GL_TEXTURE_2D ); float timePer = mRoom.getTimePer(); gl::drawSolidRect( Rectf( Vec2f( X0, Y1 + 2.0f ), Vec2f( X0 + timePer * ( iconWidth ), Y1 + 2.0f + 4.0f ) ) ); float fpsPer = getAverageFps()/60.0f; gl::drawSolidRect( Rectf( Vec2f( X0, Y1 + 4.0f + 4.0f ), Vec2f( X0 + fpsPer * ( iconWidth ), Y1 + 4.0f + 6.0f ) ) ); gl::popMatrices(); } CINDER_APP_BASIC( ShockwavesApp, RendererGl )
_DIM; mVboMesh = gl::VboMesh( numVertices * 8 * 3, 0, layout, GL_TRIANGLES ); float s = 10.0f; Vec3f p0( 0.0f, s, 0.0f ); Vec3f p1( -s, 0.0f, 0.0f ); Vec3f p2( 0.0f, 0.0f, s ); Vec3f p3( s, 0.0f, 0.0f ); Vec3f p4( 0.0f, 0.0f, -s ); Vec3f p5( 0.0f, -s, 0.0f ); Vec3f n; Vec3f n0 = Vec3f( 0.0f, 0.0f, 1.0f ); Vec3f n1 = Vec3f(-1.0f,-1.0f, 0.0f ); Vec3f n2 = Vec3f(-1.0f, 1.0f, 0.0f ); Vec3f n3 = Vec3f( 1.0f, 1.0f, 0.0f ); Vec3f n4 = Vec3f( 1.0f,-1.0f, 0.0f ); Vec3f n5 = Vec3f( 0.0f, 0.0f,-1.0f ); vector<Vec3f> positions; vector<Vec3f> normals; for( int x = 0; x < GRID_DIM; ++x ) { for( int y = 0; y < GRID_DIM; ++y ) { positions.push_back( p0 ); positions.push_back( p1 ); positions.push_back( p2 ); n = ( p0 + p1 + p2 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p0 ); positions.push_back( p2 ); positions.push_back( p3 ); n = ( p0 + p2 + p3 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p0 ); positions.push_back( p3 ); positions.push_back( p4 ); n = ( p0 + p3 + p4 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p0 ); positions.push_back( p4 ); positions.push_back( p1 ); n = ( p0 + p4 + p1 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p1 ); positions.push_back( p4 ); n = ( p5 + p1 + p4 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p2 ); positions.push_back( p1 ); n = ( p5 + p2 + p1 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p3 ); positions.push_back( p2 ); n = ( p5 + p3 + p2 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); positions.push_back( p5 ); positions.push_back( p4 ); positions.push_back( p3 ); n = ( p5 + p4 + p3 ).normalized(); normals.push_back( n ); normals.push_back( n ); normals.push_back( n ); } } mVboMesh.bufferPositions( positions ); mVboMesh.bufferNormals( normals ); mVboMesh.unbindBuffers(); } void ShockwavesApp::mouseDown( MouseEvent event ) { mMouseDownPos = event.getPos(); mMousePressed = true; mMouseOffset = Vec2f::zero(); } void ShockwavesApp::mouseUp( MouseEvent event ) { mMousePressed = false; mMouseOffset = Vec2f::zero(); } void ShockwavesApp::mouseMove( MouseEvent event ) { mMousePos = event.getPos(); } void ShockwavesApp::mouseDrag( MouseEvent event ) { mouseMove( event ); mMouseOffset = ( mMousePos - mMouseDownPos ) * 0.4f; } void ShockwavesApp::mouseWheel( MouseEvent event ) { float dWheel = event.getWheelIncrement(); mRoom.adjustTimeMulti( dWheel ); } v
random
[]
C++
Core/GraphicsView.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
#include "GraphicsView.h" #include <QtMath> #include <QMimeData> #include <QDebug> #include "View.h" #include "MouseHandler.h" #include "GlobalFunc.h" #include "mainwindow.h" #include "../Image/BaseImage.h" #include "../Widget/MagnifierWidget.h" GraphicsView::GraphicsView(View* view, QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent) , _view(view) , _zoomFactor(MAX_ZOOM / 2) , _showAnnotation(true) , _showCrossLine(false) , _showThreeViewAxes(false) , _showLineScale(true) , _magnifier(new MagnifierWidget(this)) { setDragMode(QGraphicsView::NoDrag); _magnifier->installEventFilter(this); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMouseTracking(true); } QPointF GraphicsView::mapImagePointToScene(qreal x, qreal y) const { QGraphicsPixmapItem* pixmapItem = _view->getPixmapItem(); return pixmapItem->mapToScene(x, y); } void GraphicsView::setZoomValue(int value) { _zoomFactor = value; applyZoomValue(); } void GraphicsView::setZoomValueOffset(int offset) { _zoomFactor += offset; setZoomValue(_zoomFactor); } void GraphicsView::showAnnotation(bool show) { _showAnnotation = show; update(); } void GraphicsView::showCrossLine(bool show) { _showCrossLine = show; update(); } void GraphicsView::showThreeViewAxes(bool show) { _showThreeViewAxes = show; update(); } void GraphicsView::showLineScale(bool show) { _showLineScale = show; update(); } void GraphicsView::showMagnifier() { _magnifier->show(); } void GraphicsView::zoomNormal() { _zoomFactor = MAX_ZOOM / 2; setZoomValue(_zoomFactor); } void GraphicsView::zoom2x() { _zoomFactor = MAX_ZOOM / 2 + ZOOM_STEP; setZoomValue(_zoomFactor); } void GraphicsView::zoom4x() { _zoomFactor = MAX_ZOOM / 2 + ZOOM_STEP * 2; setZoomValue(_zoomFactor); } void GraphicsView::zoom8x() { _zoomFactor = MAX_ZOOM / 2 + ZOOM_STEP * 3; setZoomValue(_zoomFactor); } void GraphicsView::zoomIn() { _zoomFactor += ZOOM_STEP / 10; _zoomFactor = qMin(_zoomFactor, MAX_ZOOM); setZoomValue(_zoomFactor); } void GraphicsView::zoomOut() { _zoomFactor -= ZOOM_STEP / 10; _zoomFactor = qMax(0, _zoomFactor); setZoomValue(_zoomFactor); } void GraphicsView::applyZoomValue() { _zoomFactor = qMax(0, _zoomFactor); _zoomFactor = qMin(_zoomFactor, MAX_ZOOM); qreal ratio = qPow(qreal(2), (_zoomFactor - MAX_ZOOM / 2) / qreal(ZOOM_STEP)); QTransform transform; transform.scale(ratio, ratio); setTransform(transform); } void GraphicsView::mousePressEvent(QMouseEvent* event) { getGlobalWindow()->setActiveView(_view); MouseHandler::handlePress(event); QGraphicsView::mousePressEvent(event); } void GraphicsView::mouseMoveEvent(QMouseEvent* event) { QPoint mousePoint = mapFromGlobal(event->globalPos()) - QPoint(1, 1); QGraphicsPixmapItem* pixmapItem = _view->getPixmapItem(); if (pixmapItem) { QPointF pointScene = mapToScene(mousePoint); QPointF pointPixmap = pixmapItem->mapFromScene(pointScene); QImage image = pixmapItem->pixmap().toImage(); if (pointPixmap.x() >= 0 && pointPixmap.x() < image.width() && pointPixmap.y() >= 0 && pointPixmap.y() < image.height()) { float value = _view->getImageValue(pointPixmap.x(), pointPixmap.y()); int decimal = 4; if (abs(value) > 10.0f) { decimal = 1; } else if (abs(value) > 1.0f) { decimal = 2; } else if (abs(value) > 0.1f) { decimal = 3; } _strCoord = QString(tr("X: %1, Y: %2, Val: %3")).arg(QString::number(pointPixmap.x(), 'f', 0)).arg(QString::number(pointPixmap.y(), 'f', 0)).arg(QString::number(value, 'f', decimal)); QRgb rgbValue = image.pixel(QPoint(pointPixmap.x(), pointPixmap.y())); _strValue = QString("R:%1, G:%2, B:%3").arg(qRed(rgbValue), 3).arg(qGreen(rgbValue), 3).arg(qBlue(rgbValue), 3); } else { _strCoord.clear(); _strValue.clear(); } update(); } MouseHandler::handleMove(event); QGraphicsView::mouseMoveEvent(event); } void GraphicsView::mouseReleaseEvent(QMouseEvent* event) { MouseHandler::handleRelease(event); QGraphicsView::mouseReleaseEvent(event); } void GraphicsView::mouseDoubleClickEvent(QMouseEvent* event) { getGlobalWindow()->singleView(); QGraphicsView::mouseDoubleClickEvent(event); } void GraphicsView::wheelEvent(QWheelEvent* event) { if (event->modifiers() & Qt::ControlModifier) { if (event->angleDelta().y() > 0) getGlobalWindow()->zoomIn(); else getGlobalWindow()->zoomOut(); event->accept(); } else { BaseImage* image = getGlobalImage(); if (image) { if (event->angleDelta().y() > 0) _view->sliceMinusOne(); else _view->slicePlusOne(); } } } void GraphicsView::dragEnterEvent(QDragEnterEvent* event) { event->ignore(); } void GraphicsView::drawForeground(QPainter*, const QRectF&) { BaseImage* image = getGlobalImage(); if (image == nullptr) return; if (_showAnnotation) { drawAnnotation(); } if (_showCrossLine) { drawCrossLine(); } if (_showThreeViewAxes) { drawThreeViewAxes(); } if (_showLineScale) { drawLineScale(); } } bool GraphicsView::eventFilter(QObject* obj, QEvent* event) { if (obj == _magnifier && event->type() == QEvent::MouseMove) { QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); mouseMoveEvent(mouseEvent); return false; } else { return QGraphicsView::eventFilter(obj, event); } } void GraphicsView::focusInEvent(QFocusEvent*) { _view->update(); } void GraphicsView::focusOutEvent(QFocusEvent*) { _view->update(); } void GraphicsView::drawAnnotation() { int fontHeight = 16; if (rect().height() < 400) { fontHeight = 8; } else if (rect().height() < 600) { fontHeight = 10; } else if (rect().height() < 800) { fontHeight = 12; } QFont font("Arial", fontHeight); QPainter painter(viewport()); painter.setFont(font); painter.setPen(QPen(qRgb(255, 255, 150))); int pixelsHigh = painter.fontMetrics().height() * 1.1; int y = rect().bottom() - 10; const int textAreaWidth = 350; qreal scale = qPow(qreal(2), (_zoomFactor - MAX_ZOOM / 2) / qreal(ZOOM_STEP)); QString str = QString(tr("Zoom: %1%")).arg(QString::number(scale * 100.0, 'f', 2)); painter.drawText(QRect(0, 0, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); str = QString(tr("Size: %1%2%3")).arg(_view->imageWidth()).arg(QString(QChar(0x00D7))).arg(_view->imageHeight()); painter.drawText(QRect(0, pixelsHigh, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); str = QString(tr("Slice: %1/%2")).arg(_view->imageCurrentSlice() + 1).arg(_view->imageSlice()); painter.drawText(QRect(0, pixelsHigh * 2, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); float windowLevel = _view->windowLevel(); float windowWidth = _view->windowWidth(); int decimal = 4; if (abs(windowLevel) > 10.0f) { decimal = 1; } else if (abs(windowLevel) > 1.0f) { decimal = 2; } else if (abs(windowLevel) > 0.1f) { decimal = 3; } str = QString(tr("WL: %1 WW: %2")).arg(QString::number(windowLevel, 'f', decimal)).arg(QString::number(windowWidth, 'f', decimal)); painter.drawText(QRect(0, y - pixelsHigh, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); painter.drawText(QRect(rect().width() - textAreaWidth, 0, textAreaWidth - 5, pixelsHigh), Qt::AlignRight, _view->imageDescription()); painter.setPen(QPen(qRgb(255, 100, 100))); painter.drawText(QRect(0, y - pixelsHigh * 2, 600, pixelsHigh), Qt::AlignLeft, _strValue); painter.drawText(QRect(0, y - pixelsHigh * 3, 600, pixelsHigh), Qt::AlignLeft, _strCoord); } void GraphicsView::drawCrossLine() { QRectF rect = _view->getPixmapItem()->sceneBoundingRect(); QPoint topLeft = mapFromScene(rect.topLeft()); QPoint center = mapFromScene(rect.center()); QPoint bottomRight = mapFromScene(rect.bottomRight()); QPainter painter(viewport()); painter.setPen(QPen(QBrush(qRgb(255, 50, 50)), 1, Qt::DotLine)); painter.drawLine(topLeft.x(), center.y(), bottomRight.x(), center.y()); painter.drawLine(center.x(), topLeft.y(), center.x(), bottomRight.y()); } void GraphicsView::drawThreeViewAxes() { QRectF pixmapRect = _view->getPixmapItem()->sceneBoundingRect(); QPainter painter(viewport()); QRect viewRect = rect(); BaseImage* image = getGlobalImage(); int xOffset, yOffset; QColor horzColor, vertColor; if (_view->viewType() == AXIAL_VIEW) { xOffset = image->currentSlice(SAGITTAL_VIEW); yOffset = image->currentSlice(CORONAL_VIEW); horzColor = qRgb(255, 60, 135); vertColor = qRgb(50, 185, 255); } else if (_view->viewType() == CORONAL_VIEW) { xOffset = image->currentSlice(SAGITTAL_VIEW); yOffset = image->currentSlice(AXIAL_VIEW); horzColor = qRgb(255, 225, 15); vertColor = qRgb(50, 185, 255); } else if (_view->viewType() == SAGITTAL_VIEW) { xOffset = image->currentSlice(CORONAL_VIEW); yOffset = image->currentSlice(AXIAL_VIEW); horzColor = qRgb(255, 225, 15); vertColor = qRgb(255, 60, 135); } QPoint center = mapFromScene(pixmapRect.left() + xOffset, pixmapRect.top() + yOffset); painter.setPen(QPen(horzColor)); painter.drawLine(viewRect.left(), center.y(), viewRect.right(), center.y()); painter.setPen(QPen(vertColor)); painter.drawLine(center.x(), viewRect.top(), center.x(), viewRect.bottom()); } void GraphicsView::drawLineScale() { BaseImage* image = getGlobalImage(); if (!image->hasPixelSpacing()) return; float horzPixelSpacing = image->horzPixelSpacing(); float vertPixelSpacing = image->vertPixelSpacing(); float horzDistance = calcScale(horzPixelSpacing); float vertDistance = calcScale(vertPixelSpacing); qreal scale = qPow(qreal(2), (_zoomFactor - MAX_ZOOM / 2) / qreal(ZOOM_STEP)); float horzInterval = horzDistance * scale / horzPixelSpacing; float vertInterval = vertDistance * scale / vertPixelSpacing; int margin = 5; int x = rect().right() - margin; int y = rect().bottom() - margin; QPainter painter(viewport()); painter.setPen(QPen(qRgb(255, 255, 100))); painter.drawLine(rect().center().x() - 5 * horzInterval, y, rect().center().x() + 5 * horzInterval, y); painter.drawLine(x, rect().center().y() - 5 * vertInterval, x, rect().center().y() + 5 * vertInterval); painter.setPen(QPen(qRgb(255, 255, 0))); for (int i = 0; i <= 10; i++) { painter.drawLine(rect().center().x() + (i - 5) * horzInterval, y, rect().center().x() + (i - 5) * horzInterval, y - 5); if (i % 5 == 0) { painter.drawLine(rect().center().x() + (i - 5) * horzInterval, y, rect().center().x() + (i - 5) * horzInterval, y - 10); } painter.drawLine(x, rect().center().y() + (i - 5) * vertInterval, x - 5, rect().center().y() + (i - 5) * vertInterval); if (i % 5 == 0) { painter.drawLine(x, rect().center().y() + (i - 5) * vertInterval, x - 10, rect().center().y() + (i - 5) * vertInterval); } } QString str = QString::number(horzDistance, 'f', 2) + " mm"; painter.drawText(QRect(rect().center().x(), y - 23, 9 * horzInterval, 20), Qt::AlignCenter, str); painter.rotate(-90); str = QString::number(vertDistance, 'f', 2) + " mm"; painter.drawText(QRect(-rect().center().y(), rect().width() - 23 - margin, 9 * horzInterval, 20), Qt::AlignCenter, str); } float GraphicsView::calcScale(float pixelSpacing) { float distance = 20.0f; int flag = 0; while (distance / pixelSpacing > 60) { if (flag == 0) { distance /= 2; } else if (flag == 1) { distance /= 2; } else if (flag == 2) { distance /= 2.5; } flag = (flag + 1) % 3; } return distance; }
#include "GraphicsView.h" #include <QtMath> #include <QMimeData> #include <QDebug> #include "View.h" #include "MouseHandler.h" #include "GlobalFunc.h" #include "mainwindow.h" #include "../Image/BaseImage.h" #include "../Widget/MagnifierWidget.h" GraphicsView::GraphicsView(View* view, QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent) , _view(view) , _zoomFactor(MAX_ZOOM / 2) , _showAnnotation(true) , _showCrossLine(false) , _showThreeViewAxes(false) , _showLineScale(true) , _magnifier(new MagnifierWidget(this)) { setDragMode(QGraphicsView::NoDrag); _magnifier->installEventFilter(this); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMouseTracking(true); } QPointF GraphicsView::mapImagePointToScene(qreal x, qreal y) const { QGraphicsPixmapItem* pixmapItem = _view->getPixmapItem(); return pixmapItem->mapToScene(x, y); } void GraphicsView::setZoomValue(int value) { _zoomFactor = value; applyZoomValue(); } void GraphicsView::setZoomValueOffset(int offset) { _zoomFactor += offset; setZoomValue(_zoomFactor); } void GraphicsView::showAnnotation(bool show) { _showAnnotation = show; update(); } void GraphicsView::showCrossLine(bool show) { _showCrossLine = show; update(); } void GraphicsView::showThreeViewAxes(bool show) { _showThreeViewAxes = show; update(); } void GraphicsView::showLineScale(bool show) { _showLineScale = show; update(); } void GraphicsView::showMagnifier() { _magnifier->show(); } void GraphicsView::zoomNormal() { _zoomFactor = MAX_ZOOM / 2; setZoomValue(_zoomFactor); } void GraphicsView::zoom2x() { _zoomFactor = MAX_ZOOM / 2 + ZOOM_STEP; setZoomValue(_zoomFactor); } void GraphicsView::zoom4x() { _zoomFactor = MAX_ZOOM / 2 + ZOOM_STEP * 2; setZoomValue(_zoomFactor); } void GraphicsView::zoom8x() { _zoomFactor = MAX_ZOOM / 2 + ZOOM_STEP * 3; setZoomValue(_zoomFactor); } void GraphicsView::zoomIn() { _zoomFactor += ZOOM_STEP / 10; _zoomFactor = qMin(_zoomFactor, MAX_ZOOM); setZoomValue(_zoomFactor); } void GraphicsView::zoomOut() { _zoomFactor -= ZOOM_STEP / 10; _zoomFactor = qMax(0, _zoomFactor); setZoomValue(_zoomFactor); } void GraphicsView::applyZoomValue() { _zoomFactor = qMax(0, _zoomFactor); _zoomFactor = qMin(_zoomFactor, MAX_ZOOM); qreal ratio = qPow(qreal(2), (_zoomFactor - MAX_ZOOM / 2) / qreal(ZOOM_STEP)); QTransform transform; transform.scale(ratio, ratio); setTransform(transform); } void GraphicsView::mousePressEvent(QMouseEvent* event) { getGlobalWindow()->setActiveView(_view); MouseHandler::handlePress(event); QGraphicsView::mousePressEvent(event); } void GraphicsView::mouseMoveEvent(QMouseEvent* event) { QPoint mousePoint = mapFromGlobal(event->globalPos()) - QPoint(1, 1); QGraphicsPixmapItem* pixmapItem = _view->getPixmapItem(); if (pixmapItem) { QPointF pointScene = mapToScene(mousePoint); QPointF pointPixmap = pixmapItem->mapFromScene(pointScene); QImage image = pixmapItem->pixmap().toImage(); if (pointPixmap.x() >= 0 && pointPixmap.x() < image.width() && pointPixmap.y() >= 0 && pointPixmap.y() < image.height()) { float value = _view->getImageValue(pointPixmap.x(), pointPixmap.y()); int decimal = 4; if (abs(value) > 10.0f) { decimal = 1; } else if (abs(value) > 1.0f) { decimal = 2; } else if (abs(value) > 0.1f) { decimal = 3; } _strCoord = QString(tr("X: %1, Y: %2, Val: %3")).arg(QString::number(pointPixmap.x(), 'f', 0)).arg(QString::number(pointPixmap.y(), 'f', 0)).arg(QString::number(value, 'f', decimal)); QRgb rgbValue = image.pixel(QPoint(pointPixmap.x(), pointPixmap.y())); _strValue = QString("R:%1, G:%2, B:%3").arg(qRed(rgbValue), 3).arg(qGreen(rgbValue), 3).arg(qBlue(rgbValue), 3); } else { _strCoord.clear(); _strValue.clear(); } update(); } MouseHandler::handleMove(event); QGraphicsView::mouseMoveEvent(event); } void GraphicsView::mouseReleaseEvent(QMouseEvent* event) { MouseHandler::handleRelease(event); QGraphicsView::mouseReleaseEvent(event); } void GraphicsView::mouseDoubleClickEvent(QMouseEvent* event) { getGlobalWindow()->singleView(); QGraphicsView::mouseDoubleClickEvent(event); } void GraphicsView::wheelEvent(QWheelEvent* event) { if (event->modifiers() & Qt::ControlModifier) { if (event->angleDelta().y() > 0) getGlobalWindow()->zoomIn(); else getGlobalWindow()->zoomOut(); event->accept(); } else { BaseImage* image = getGlobalImage(); if (image) { if (event->angleDelta().y() > 0) _view->sliceMinusOne(); else _view->slicePlusOne(); } } } void GraphicsView::dragEnterEvent(QDragEnterEvent* event) { event->ignore(); } void GraphicsView::drawForeground(QPainter*, const QRectF&) { BaseImage* image = getGlobalImage(); if (image == nullptr) return; if (_showAnnotation) { drawAnnotation(); } if (_showCrossLine) { drawCrossLine(); } if (_showThreeViewAxes) { drawThreeViewAxes(); } if (_showLineScale) { drawLineScale(); } } bool GraphicsView::eventFilter(QObject* obj, QEvent* event) { if (obj == _magnifier && event->type() == QEvent::MouseMove) { QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); mouseMoveEvent(mouseEvent); return false; } else { return QGraphicsView::eventFilter(obj, event); } } void GraphicsView::focusInEvent(QFocusEvent*) { _view->update(); } void GraphicsView::focusOutEvent(QFocusEvent*) { _view->update(); } void GraphicsView::drawAnnotation() { int fontHeight = 16; if (rect().height() < 400) { fontHeight = 8; } else if (rect().height() < 600) { fontHeight = 10; } else if (rect().height() < 800) { fontHeight = 12; } QFont font("Arial", fontHeight); QPainter painter(viewport()); painter.setFont(font); painter.setPen(QPen(qRgb(255, 255, 150))); int pixelsHigh = painter.fontMetrics().height() * 1.1; int y = rect().bottom() - 10; const int textAreaWidth = 350; qreal scale = qPow(qreal(2), (_zoomFactor - MAX_ZOOM / 2) / qreal(ZOOM_STEP)); QString str = QString(tr("Zoom: %1%")).arg(QString::number(scale * 100.0, 'f', 2)); painter.drawText(QRect(0, 0, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); str = QString(tr("Size: %1%2%3")).arg(_view->imageWidth()).arg(QString(QChar(0x00D7))).arg(_view->imageHeight()); painter.drawText(QRect(0, pixelsHigh, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); str = QString(tr("Slice: %1/%2")).arg(_view->imageCurrentSlice() + 1).arg(_view->imageSlice()); painter.drawText(QRect(0, pixelsHigh * 2, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); float windowLevel = _view->windowLevel(); float windowWidth = _view->windowWidth(); int decimal = 4; if (abs(windowLevel) > 10.0f) { decimal = 1; } else if (abs(windowLevel) > 1.0f) { decimal = 2; } else if (abs(windowLevel) > 0.1f) { decimal = 3; } str = QString(tr("WL: %1 WW: %2")).arg(QString::number(windowLevel, 'f', decimal)).arg(QString::number(windowWidth, 'f', decimal)); painter.drawText(QRect(0, y - pixelsHigh, textAreaWidth, pixelsHigh), Qt::AlignLeft, str); painter.drawText(QRect(rect().width() - textAreaWidth, 0, textAreaWidth - 5, pixelsHigh), Qt::AlignRight, _view->imageDescription()); painter.setPen(QPen(qRgb(255, 100, 100))); painter.drawText(QRect(0, y - pixelsHigh * 2, 600, pixelsHigh), Qt::AlignLeft, _strValue); painter.drawText(QRect(0, y - pixelsHigh * 3, 600, pixelsHigh), Qt::AlignLeft, _strCoord); } void GraphicsView::drawCrossLine() { QRectF rect = _view->getPixmapItem()->sceneBoundingRect(); QPoint topLeft = mapFromScene(rect.topLeft()); QPoint center = mapFromScene(rect.center()); QPoint bottomRight = mapFromScene(rect.bottomRight()); QPainter painter(viewport()); painter.setPen(QPen(QBrush(qRgb(255, 50, 50)), 1, Qt::DotLine)); painter.drawLine(topLeft.x(), center.y(), bottomRight.x(), center.y()); painter.drawLine(center.x(), topLeft.y(), center.x(), bottomRight.y()); } void GraphicsView::drawThreeViewAxes() { QRectF pixmapRect = _view->getPixmapItem()->sceneBoundingRect(); QPainter painter(viewport()); QRect viewRect = rect(); BaseImage* image = getGlobalImage(); int xOffset, yOffset; QColor horzColor, vertColor; if (_view->viewType() == AXIAL_VIEW) { xOffset = image->currentSlice(SAGITTAL_VIEW); yOffset = image->currentSlice(CORONAL_VIEW); horzColor = qRgb(255, 60, 135); vertColor = qRgb(50, 185, 255); } else if (_view->viewType() == CORONAL_VIEW) { xOffset = image->currentSlice(SAGITTAL_VIEW); yOffset = image->currentSlice(AXIAL_VIEW); horzColor = qRgb(255, 225, 15); vertColor = qRgb(50, 185, 255); } else if (_view->viewType() == SAGITTAL_VIEW) { xOffset = image->currentSlice(CORONAL_VIEW); yOffset = image->currentSlice(AXIAL_VIEW); horzColor = qRgb(255, 225, 15); vertColor = qRgb(255, 60, 135); } QPoint center = mapFromScene(pixmapRect.left() + xOffset, pixmapRect.top() + yOffset); painter.setPen(QPen(horzColor)); painter.drawLine(viewRect.left(), center.y(), viewRect.right(), center.y()); painter.setPen(QPen(vertColor)); painter.drawLine(center.x(), viewRect.top(), center.x(), viewRect.bottom()); } void GraphicsView::drawLineScale() { BaseImage* image = getGlobalImage(); if (!image->hasPixelSpacing()) return; float horzPixelSpacing = image->horzPixelSpacing(); float vertPixelSpacing = image->vertPixelSpacing(); float horzDistance = calcScale(horzPixelSpacing); float vertDistance = calcScale(vertPixelSpacing); qreal scale = qPow(qreal(2), (_zoomFactor - MAX_ZOOM / 2) / qreal(ZOOM_STEP)); float horzInterval = horzDistance * scale / horzPixelSpacing; float vertInterval = vertDistance * scale / vertPixelSpacing; int margin = 5; int x = rect().right() - margin; int y = rect().bottom() - margin; QPainter painter(viewport()); painter.setPen(QPen(qRgb(255, 255, 100))); painter.drawLine(rect().center().x() - 5 * horzInterval, y, rect().center().x() + 5 * horzInterval, y); painter.drawLine(x, rect().center().y() - 5 * vertInterval, x, rect().center().y() + 5 * vertInterval); painter.setPen(QPen(qRgb(255, 255, 0))); for (int i = 0; i <= 10; i++) { painter.drawLine(rect().center().x() + (i - 5) * horzInterval, y, rect().center().x() + (i - 5) * horzInterval, y - 5); if (i % 5 == 0) { painter.drawLine(rect().center().x() + (i - 5) * horzInterval, y, rect().center().x() + (i - 5) * horzInterval, y - 10); } painter.drawLine(x, rect().center().y() + (i - 5) * vertInterval, x - 5, rect().center().y() + (i - 5) * vertInterval); if (i % 5 == 0) { painter.drawLine(x, rect().center().y() + (i - 5) * vertInterval, x - 10, rect().center().y() + (i - 5) * vertInterval); } }
float GraphicsView::calcScale(float pixelSpacing) { float distance = 20.0f; int flag = 0; while (distance / pixelSpacing > 60) { if (flag == 0) { distance /= 2; } else if (flag == 1) { distance /= 2; } else if (flag == 2) { distance /= 2.5; } flag = (flag + 1) % 3; } return distance; }
QString str = QString::number(horzDistance, 'f', 2) + " mm"; painter.drawText(QRect(rect().center().x(), y - 23, 9 * horzInterval, 20), Qt::AlignCenter, str); painter.rotate(-90); str = QString::number(vertDistance, 'f', 2) + " mm"; painter.drawText(QRect(-rect().center().y(), rect().width() - 23 - margin, 9 * horzInterval, 20), Qt::AlignCenter, str); }
function_block-function_prefix_line
[ { "content": "class View;\n", "file_path": "Core/GraphicsScene.h", "rank": 0, "score": 120366.99674812447 }, { "content": "class ImageQualityChartView : public ChartView\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n ImageQualityChartView(QWidget* parent = nullptr);\n\n\n\n void setData(const QVector<qreal>& points);\n\n\n\n void updateData(const QVector<qreal>& points);\n\n\n\n void setRatio(float leftRatio, float rightRatio);\n\n void setLeftRatio(float ratio);\n\n void setRightRatio(float ratio);\n\n\n\npublic slots:\n\n void hoverLine(const QPointF& point, bool state);\n\n void hoverRightLine(const QPointF& point, bool state);\n\n\n\nsignals:\n", "file_path": "Widget/ImageQualityChartView.h", "rank": 1, "score": 92730.80400378595 }, { "content": "class View;\n", "file_path": "Core/GraphicsView.h", "rank": 2, "score": 88065.7203629876 }, { "content": "class CustomEvent : public QEvent\n\n{\n\npublic:\n\n CustomEvent() : QEvent(CustomEvent::type()) {}\n\n\n\n virtual ~CustomEvent() {}\n\n\n\n static QEvent::Type type()\n\n {\n\n if (customEventType == QEvent::None)\n\n {\n\n int generatedType = QEvent::registerEventType();\n\n customEventType = static_cast<QEvent::Type>(generatedType);\n\n }\n\n return customEventType;\n\n }\n\n\n\nprivate:\n\n static QEvent::Type customEventType;\n\n};\n", "file_path": "Widget/CustomEvent.h", "rank": 3, "score": 84541.01198748067 }, { "content": "class ImageQualityChartView;\n\n\n", "file_path": "Dialog/ImageQualityDialog.h", "rank": 4, "score": 83189.75196917936 }, { "content": " void leftRatioChanged(float ratio);\n\n void rightRatioChanged(float ratio);\n\n void sendResult(qreal AHeight, qreal BHeight, qreal CHeight, qreal quality);\n\n\n\nprotected:\n\n void mousePressEvent(QMouseEvent* event) override;\n\n void mouseMoveEvent(QMouseEvent* event) override;\n\n void mouseReleaseEvent(QMouseEvent* event) override;\n\n void mouseDoubleClickEvent(QMouseEvent* event) override;\n\n void resizeEvent(QResizeEvent* event) override;\n\n\n\nprivate:\n\n void addDataPoint(int length);\n\n\n\n void appendConnectionLine();\n\n\n\n void appendABCLine();\n\n\n\nprivate:\n\n float _leftRatio, _rightRatio;\n", "file_path": "Widget/ImageQualityChartView.h", "rank": 5, "score": 80722.89132990714 }, { "content": "#pragma once\n\n\n\n#include \"ChartView.h\"\n\n\n", "file_path": "Widget/ImageQualityChartView.h", "rank": 6, "score": 80703.31963074097 }, { "content": " bool _dragLeft, _dragRight;\n\n int _APosition, _BPosition, _CPosition;\n\n QLineSeries* _leftSeries;\n\n QLineSeries* _rightSeries;\n\n QLineSeries* _leftToRightSeries;\n\n QLineSeries* _ASeries;\n\n QLineSeries* _BSeries;\n\n QLineSeries* _CSeries;\n\n QGraphicsSimpleTextItem* _ALabel;\n\n QGraphicsSimpleTextItem* _BLabel;\n\n QGraphicsSimpleTextItem* _CLabel;\n\n};", "file_path": "Widget/ImageQualityChartView.h", "rank": 7, "score": 80699.68035007374 }, { "content": "class ImageQualityDialog;\n\n\n\n#ifndef VIEW_TYPE\n\n#define AXIAL_VIEW 0\n\n#define CORONAL_VIEW 1\n\n#define SAGITTAL_VIEW 2\n\n#define VOLUME_VIEW 3\n\n#endif\n\n\n\n#include \"GraphicsScene.h\"\n\n\n", "file_path": "Core/View.h", "rank": 8, "score": 80693.35728027423 }, { "content": "class View : public QFrame\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n explicit View(QWidget* parent = nullptr);\n\n\n\n GraphicsView* view() const;\n\n\n\n GraphicsScene* scene();\n\n\n\n int sceneMode();\n\n\n\n void setViewType(int type) { _viewType = type; }\n\n\n\n int viewType() { return _viewType; }\n\n\n\n void showImage(const QImage* image);\n\n \n\n void resetMatrix();\n", "file_path": "Core/View.h", "rank": 9, "score": 80431.19447218128 }, { "content": "class View;\n", "file_path": "Core/mainwindow.h", "rank": 10, "score": 79462.62987364862 }, { "content": "class View;\n", "file_path": "Core/Document.h", "rank": 11, "score": 79462.62987364862 }, { "content": "class QMouseEvent;\n", "file_path": "Core/GraphicsScene.h", "rank": 12, "score": 78973.21475029834 }, { "content": "class View;\n\n\n\nMainWindow* getGlobalWindow();\n\n\n\nDocument* getGlobalDocument();\n\n\n\nView* getGlobalActiveView();\n\n\n\nView* getGlobalAxialView();\n\nView* getGlobalCoronalView();\n\nView* getGlobalSagittalView();\n\n\n\nBaseImage* getGlobalImage();\n\n\n\nvoid repaintView();\n\nvoid repaintView(QImage* image, int viewType = 0);\n\nvoid repaintView(std::shared_ptr<QImage> dstImage, int viewType = 0);\n\nvoid repaintView(std::vector<std::shared_ptr<QImage>> imageVec);\n\n\n\nQPointF stringToPointF(const QString& str);\n", "file_path": "Core/GlobalFunc.h", "rank": 13, "score": 77539.71756977862 }, { "content": "#include \"ImageQualityChartView.h\"\n\n\n\n#include <cmath>\n\n#include <float.h>\n\n#include <QtGui/QMouseEvent>\n\n#include <QValueAxis>\n\n#include <QGraphicsSceneMouseEvent>\n\n#include <QDebug>\n\n\n\nImageQualityChartView::ImageQualityChartView(QWidget* parent)\n\n : ChartView(parent)\n\n , _leftRatio(1 / 3.0f)\n\n , _rightRatio(2 / 3.0f)\n\n , _dragLeft(false)\n\n , _dragRight(false)\n\n , _APosition(0)\n\n , _BPosition(0)\n\n , _CPosition(0)\n\n , _leftSeries(new QLineSeries(this))\n\n , _rightSeries(new QLineSeries(this))\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 14, "score": 77511.88349035394 }, { "content": "{\n\n _leftRatio = leftRatio;\n\n _rightRatio = rightRatio;\n\n}\n\n\n\nvoid ImageQualityChartView::setLeftRatio(float ratio)\n\n{\n\n _leftRatio = ratio;\n\n}\n\n\n\nvoid ImageQualityChartView::setRightRatio(float ratio)\n\n{\n\n _rightRatio = ratio;\n\n}\n\n\n\nvoid ImageQualityChartView::mousePressEvent(QMouseEvent* event)\n\n{\n\n QPointF leftLine = _leftSeries->at(0);\n\n QPointF rightLine = _rightSeries->at(0);\n\n QPointF mousePos = chart()->mapToValue(event->pos());\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 15, "score": 77511.71597601128 }, { "content": "\n\nvoid ImageQualityChartView::addDataPoint(int length)\n\n{\n\n _leftSeries->clear();\n\n _rightSeries->clear();\n\n\n\n QList<QAbstractAxis*> axesList = chart()->axes(Qt::Vertical);\n\n QValueAxis* valueAxis = qobject_cast<QValueAxis*>(axesList[0]);\n\n\n\n float leftPos = _leftRatio * (length - 1);\n\n *_leftSeries << QPointF(leftPos, valueAxis->min()) << QPointF(leftPos, valueAxis->max());\n\n\n\n float rightPos = _rightRatio * (length - 1);\n\n *_rightSeries << QPointF(rightPos, valueAxis->min()) << QPointF(rightPos, valueAxis->max());\n\n}\n\n\n\nvoid ImageQualityChartView::appendConnectionLine()\n\n{\n\n _leftToRightSeries->clear();\n\n\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 16, "score": 77505.55533582222 }, { "content": " appendConnectionLine();\n\n\n\n _rightRatio = mousePos.x() / (_dataSeries->count() - 1);\n\n emit rightRatioChanged(_rightRatio);\n\n }\n\n }\n\n\n\n QChartView::mouseMoveEvent(event);\n\n}\n\n\n\nvoid ImageQualityChartView::mouseReleaseEvent(QMouseEvent* event)\n\n{\n\n _dragLeft = false;\n\n _dragRight = false;\n\n\n\n QChartView::mouseReleaseEvent(event);\n\n}\n\n\n\nvoid ImageQualityChartView::hoverLine(const QPointF&, bool state)\n\n{\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 17, "score": 77505.35739059486 }, { "content": " _BLabel->hide();\n\n _CLabel->hide();\n\n}\n\n\n\nvoid ImageQualityChartView::updateData(const QVector<qreal>& points)\n\n{\n\n ChartView::updateData(points);\n\n\n\n addDataPoint(points.size());\n\n appendConnectionLine();\n\n\n\n _ASeries->clear();\n\n _BSeries->clear();\n\n _CSeries->clear();\n\n _ALabel->hide();\n\n _BLabel->hide();\n\n _CLabel->hide();\n\n}\n\n\n\nvoid ImageQualityChartView::setRatio(float leftRatio, float rightRatio)\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 18, "score": 77504.86269401171 }, { "content": "}\n\n\n\nvoid ImageQualityChartView::mouseDoubleClickEvent(QMouseEvent* event)\n\n{\n\n qreal leftPos = _leftSeries->at(0).x();\n\n qreal rightPos = _rightSeries->at(0).x();\n\n int left = (int)round(qMin(leftPos, rightPos));\n\n int right = (int)round(qMax(leftPos, rightPos));\n\n int objectionNum = abs(right - left) + 1;\n\n\n\n // Find minimum value\n\n qreal minValue1 = _dataSeries->at(left).y();\n\n int nAPos = 0;\n\n for (int i = 0; i < objectionNum; i++)\n\n {\n\n if (minValue1 > _dataSeries->at(i + left).y())\n\n {\n\n minValue1 = _dataSeries->at(i + left).y();\n\n nAPos = i;\n\n }\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 19, "score": 77501.1685723398 }, { "content": " if (abs(mousePos.x() - leftLine.x()) < 3)\n\n {\n\n _dragLeft = true;\n\n }\n\n else if (abs(mousePos.x() - rightLine.x()) < 3)\n\n {\n\n _dragRight = true;\n\n }\n\n\n\n QChartView::mousePressEvent(event);\n\n}\n\n\n\nvoid ImageQualityChartView::mouseMoveEvent(QMouseEvent* event)\n\n{\n\n QPointF mousePos = chart()->mapToValue(event->pos());\n\n if (mousePos.x() >=0 && mousePos.x() < _dataSeries->count() - 1)\n\n {\n\n QList<QAbstractAxis*> axesList = chart()->axes(Qt::Vertical);\n\n QValueAxis* valueAxis = qobject_cast<QValueAxis*>(axesList[0]);\n\n if (_dragLeft)\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 20, "score": 77497.46703206436 }, { "content": " qreal leftPos = _leftSeries->at(0).x();\n\n qreal rightPos = _rightSeries->at(0).x();\n\n\n\n int x0 = (int)floor(leftPos);\n\n int x1 = (int)ceil(leftPos);\n\n qreal lambda_x = leftPos - x0;\n\n qreal leftY = _dataSeries->at(x0).y() * (1 - lambda_x) + _dataSeries->at(x1).y() * lambda_x;\n\n\n\n x0 = (int)floor(rightPos);\n\n x1 = (int)ceil(rightPos);\n\n lambda_x = rightPos - x0;\n\n qreal rightY = _dataSeries->at(x0).y() * (1 - lambda_x) + _dataSeries->at(x1).y() * lambda_x;\n\n *_leftToRightSeries << QPointF(leftPos, leftY) << QPointF(rightPos, rightY);\n\n}\n\n\n\nvoid ImageQualityChartView::appendABCLine()\n\n{\n\n _ASeries->clear();\n\n _BSeries->clear();\n\n _CSeries->clear();\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 21, "score": 77496.21042464061 }, { "content": " }\n\n _CPosition = nCPos + left;\n\n\n\n appendABCLine();\n\n\n\n ChartView::mouseDoubleClickEvent(event);\n\n}\n\n\n\nvoid ImageQualityChartView::resizeEvent(QResizeEvent* event)\n\n{\n\n QPointF ABottom(_APosition, _dataSeries->at(_APosition).y());\n\n QPointF BBottom(_BPosition, _dataSeries->at(_BPosition).y());\n\n QPointF CBottom(_CPosition, _dataSeries->at(_CPosition).y());\n\n\n\n _ALabel->setPos(chart()->mapToPosition(ABottom));\n\n _BLabel->setPos(chart()->mapToPosition(BBottom));\n\n _CLabel->setPos(chart()->mapToPosition(CBottom));\n\n\n\n ChartView::resizeEvent(event);\n\n}\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 22, "score": 77494.41248208926 }, { "content": " , _leftToRightSeries(new QLineSeries(this))\n\n , _ASeries(new QLineSeries(this))\n\n , _BSeries(new QLineSeries(this))\n\n , _CSeries(new QLineSeries(this))\n\n , _ALabel(nullptr)\n\n , _BLabel(nullptr)\n\n , _CLabel(nullptr)\n\n{\n\n setRubberBand(QChartView::NoRubberBand);\n\n\n\n connect(_leftSeries, &QLineSeries::hovered, this, &ImageQualityChartView::hoverLine);\n\n connect(_rightSeries, &QLineSeries::hovered, this, &ImageQualityChartView::hoverLine);\n\n}\n\n\n\nvoid ImageQualityChartView::setData(const QVector<qreal>& points)\n\n{\n\n ChartView::setData(points);\n\n\n\n chart()->setAnimationOptions(QChart::GridAxisAnimations);\n\n\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 23, "score": 77493.65397612748 }, { "content": " if (state)\n\n {\n\n setCursor(Qt::SizeHorCursor);\n\n }\n\n else\n\n {\n\n setCursor(Qt::ArrowCursor);\n\n }\n\n}\n\n\n\nvoid ImageQualityChartView::hoverRightLine(const QPointF&, bool state)\n\n{\n\n if (state)\n\n {\n\n setCursor(Qt::SizeHorCursor);\n\n }\n\n else\n\n {\n\n setCursor(Qt::ArrowCursor);\n\n }\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 24, "score": 77492.88934090512 }, { "content": " }\n\n _APosition = nAPos + left;\n\n\n\n bool* pSearchedFlag = new bool[objectionNum];\n\n memset(pSearchedFlag, 0, sizeof(bool) * objectionNum);\n\n // Set the minimum point mark to true\n\n pSearchedFlag[nAPos] = true;\n\n\n\n // Start searching near the minimum\n\n qreal tempValue = minValue1;\n\n for (int i = nAPos - 1; i >= 0; i--)\n\n {\n\n // If the value to be searched is greater than tempValue\n\n // mark that the value has been searched\n\n if (_dataSeries->at(i + left).y() >= tempValue)\n\n {\n\n pSearchedFlag[i] = true;\n\n tempValue = _dataSeries->at(i + left).y();\n\n }\n\n else\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 25, "score": 77491.56877657722 }, { "content": " {\n\n _leftSeries->clear();\n\n _ASeries->clear();\n\n _BSeries->clear();\n\n _CSeries->clear();\n\n\n\n *_leftSeries << QPointF(mousePos.x(), valueAxis->min()) << QPointF(mousePos.x(), valueAxis->max());\n\n appendConnectionLine();\n\n\n\n _leftRatio = mousePos.x() / (_dataSeries->count() - 1);\n\n emit leftRatioChanged(_leftRatio);\n\n }\n\n else if (_dragRight)\n\n {\n\n _rightSeries->clear();\n\n _ASeries->clear();\n\n _BSeries->clear();\n\n _CSeries->clear();\n\n\n\n *_rightSeries << QPointF(mousePos.x(), valueAxis->min()) << QPointF(mousePos.x(), valueAxis->max());\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 26, "score": 77489.41365214591 }, { "content": " {\n\n break;\n\n }\n\n }\n\n tempValue = minValue1;\n\n for (int i = nAPos + 1; i < objectionNum; i++)\n\n {\n\n if (_dataSeries->at(i + left).y() >= tempValue)\n\n {\n\n pSearchedFlag[i] = true;\n\n tempValue = _dataSeries->at(i + left).y();\n\n }\n\n else\n\n {\n\n break;\n\n }\n\n }\n\n\n\n bool continueSearch = false;\n\n for (int i = 0; i < objectionNum; i++)\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 27, "score": 77488.63358532617 }, { "content": "\n\n if (_CPosition == 0)\n\n return;\n\n\n\n QPointF leftPoint = _leftToRightSeries->at(0);\n\n QPointF rightPoint = _leftToRightSeries->at(1);\n\n\n\n qreal ratio = (_APosition - leftPoint.x()) / (rightPoint.x() - leftPoint.x());\n\n QPointF ATop = QPointF(_APosition, leftPoint.y() * (1 - ratio) + rightPoint.y() * ratio);\n\n QPointF ABottom(_APosition, _dataSeries->at(_APosition).y());\n\n *_ASeries << ABottom << ATop;\n\n\n\n ratio = (_BPosition - leftPoint.x()) / (rightPoint.x() - leftPoint.x());\n\n QPointF BTop = QPointF(_BPosition, leftPoint.y() * (1 - ratio) + rightPoint.y() * ratio);\n\n QPointF BBottom(_BPosition, _dataSeries->at(_BPosition).y());\n\n *_BSeries << BBottom << BTop;\n\n\n\n ratio = (_CPosition - leftPoint.x()) / (rightPoint.x() - leftPoint.x());\n\n QPointF CTop = QPointF(_CPosition, leftPoint.y() * (1 - ratio) + rightPoint.y() * ratio);\n\n QPointF CBottom(_CPosition, _dataSeries->at(_CPosition).y());\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 28, "score": 77488.1288369094 }, { "content": " if (minValue2 > _dataSeries->at(i + left).y() && pSearchedFlag[i] == false)\n\n {\n\n minValue2 = _dataSeries->at(i + left).y();\n\n nBPos = i;\n\n }\n\n }\n\n _BPosition = nBPos + left;\n\n\n\n delete[] pSearchedFlag;\n\n\n\n // Find the maximum value among points A and B\n\n float fLocalMaxValue = -FLT_MAX;\n\n int nCPos = 0;\n\n for (int i = qMin(nAPos, nBPos); i <= qMax(nAPos, nBPos); i++)\n\n {\n\n if (fLocalMaxValue < _dataSeries->at(i + left).y())\n\n {\n\n fLocalMaxValue = _dataSeries->at(i + left).y();\n\n nCPos = i;\n\n }\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 29, "score": 77487.01245194781 }, { "content": " {\n\n if (pSearchedFlag[i] == false)\n\n {\n\n continueSearch = true;\n\n break;\n\n }\n\n }\n\n if (!continueSearch)\n\n {\n\n // This means there is only one peak\n\n _APosition = _BPosition = _CPosition = 0;\n\n delete[] pSearchedFlag;\n\n return;\n\n }\n\n\n\n // Find the minimum value among the remaining points\n\n float minValue2 = FLT_MAX;\n\n int nBPos = 0;\n\n for (int i = 0; i < objectionNum; i++)\n\n {\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 30, "score": 77486.55998716058 }, { "content": " *_CSeries << CBottom << CTop;\n\n\n\n qreal AHeight = chart()->mapToPosition(ABottom).y() - chart()->mapToPosition(ATop).y();\n\n qreal BHeight = chart()->mapToPosition(BBottom).y() - chart()->mapToPosition(BTop).y();\n\n qreal CHeight = chart()->mapToPosition(CBottom).y() - chart()->mapToPosition(CTop).y();\n\n qreal quality = (AHeight + BHeight - 2 * CHeight) / (AHeight + BHeight) * 100.0;\n\n\n\n emit sendResult(AHeight, BHeight, CHeight, quality);\n\n\n\n _ALabel->setPos(chart()->mapToPosition(ABottom));\n\n _BLabel->setPos(chart()->mapToPosition(BBottom));\n\n _CLabel->setPos(chart()->mapToPosition(CBottom));\n\n _ALabel->show();\n\n _BLabel->show();\n\n _CLabel->show();\n\n}\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 31, "score": 77483.938007985 }, { "content": " addDataPoint(points.size());\n\n appendConnectionLine();\n\n\n\n chart()->addSeries(_leftSeries);\n\n chart()->addSeries(_rightSeries);\n\n chart()->addSeries(_leftToRightSeries);\n\n\n\n QPen pen = _leftToRightSeries->pen();\n\n pen.setStyle(Qt::DashLine);\n\n _leftToRightSeries->setPen(pen);\n\n\n\n chart()->addSeries(_ASeries);\n\n chart()->addSeries(_BSeries);\n\n chart()->addSeries(_CSeries);\n\n\n\n // Recreate axes\n\n QList<QAbstractAxis*> axesList = chart()->axes(Qt::Vertical);\n\n QValueAxis* valueAxis = qobject_cast<QValueAxis*>(axesList[0]);\n\n qreal minValue = valueAxis->min();\n\n qreal maxValue = valueAxis->max();\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 32, "score": 77483.7612248273 }, { "content": " chart()->createDefaultAxes();\n\n\n\n axesList = chart()->axes(Qt::Horizontal);\n\n for (int i = 0; i < axesList.size(); i++)\n\n {\n\n axesList[i]->setRange(0, points.size() - 1);\n\n }\n\n axesList = chart()->axes(Qt::Vertical);\n\n for (int i = 0; i < axesList.size(); i++)\n\n {\n\n axesList[i]->setRange(minValue, maxValue);\n\n }\n\n\n\n _ALabel = new QGraphicsSimpleTextItem(chart());\n\n _ALabel->setText(\"A\");\n\n _BLabel = new QGraphicsSimpleTextItem(chart());\n\n _BLabel->setText(\"B\");\n\n _CLabel = new QGraphicsSimpleTextItem(chart());\n\n _CLabel->setText(\"C\");\n\n _ALabel->hide();\n", "file_path": "Widget/ImageQualityChartView.cpp", "rank": 33, "score": 77482.27231241729 }, { "content": "class QGraphicsSceneMouseEvent;\n", "file_path": "Diagram/DiagramTextItem.h", "rank": 34, "score": 70532.34209927272 }, { "content": "class ScanImage : public MonoImage\n\n{\n\npublic:\n\n ScanImage(const QString& pathName);\n\n ScanImage(const ScanImage& src);\n\n virtual ~ScanImage();\n\n\n\n ScanImage& operator=(const ScanImage& src);\n\n\n\npublic:\n\n void setSlice(int slice) override;\n\n\n\n bool hasPixelSpacing() override { return true; }\n\n\n\n float horzPixelSpacing() override { return _dataHeader.HorzPixelSpacing; }\n\n float vertPixelSpacing() override { return _dataHeader.VertPixelSpacing; }\n\n float sliceSpacing() override { return _dataHeader.SliceSpacing; }\n\n\n\n void initWindowWidthAndLevel() override;\n\n\n", "file_path": "Image/ScanImage.h", "rank": 35, "score": 56031.764849318926 }, { "content": "class RawImage : public MonoImage\n\n{\n\npublic:\n\n RawImage(const QString& pathName, int type, int width, int height, int slice, int headerSize, int endian);\n\n RawImage(const RawImage& src);\n\n virtual ~RawImage();\n\n\n\n RawImage& operator=(const RawImage& src);\n\n\n\npublic:\n\n void setSlice(int slice) override;\n\n\n\n void initWindowWidthAndLevel() override;\n\n\n\n BaseImage* copyImage() const override;\n\n\n\n bool copyToImage(BaseImage* image) const override;\n\n\n\nprivate:\n\n // Read data\n\n bool readData(int endian);\n\n\n\nprivate:\n\n int _dataType;\n\n int _headerSize;\n\n};\n", "file_path": "Image/RawImage.h", "rank": 36, "score": 56031.764849318926 }, { "content": "class DICOMImage : public MonoImage\n\n{\n\npublic:\n\n DICOMImage(const QString& pathName);\n\n DICOMImage(QVector<std::shared_ptr<DICOMImage>>& imageVector);\n\n DICOMImage(const DICOMImage& src);\n\n virtual ~DICOMImage() {}\n\n\n\n DICOMImage& operator=(const DICOMImage& src);\n\n\n\npublic:\n\n void setSlice(int slice) override;\n\n void setSlice(int type, int slice) override;\n\n\n\n bool hasPixelSpacing() override { return true; }\n\n\n\n float horzPixelSpacing() override { return _horzPixelSpacing; }\n\n float vertPixelSpacing() override { return _vertPixelSpacing; }\n\n float sliceSpacing() override { return _sliceSpacing; }\n\n\n", "file_path": "Image/DicomImage.h", "rank": 37, "score": 56031.764849318926 }, { "content": "class MonoImage : public BaseImage\n\n{\n\npublic:\n\n MonoImage();\n\n MonoImage(const QString& pathName);\n\n MonoImage(const MonoImage& src);\n\n virtual ~MonoImage();\n\n\n\n MonoImage& operator=(const MonoImage& src);\n\n\n\n bool copyByteToAllImage();\n\n\n\n bool copyByteToImage();\n\n\n\n bool copyByteToImage(QImage* dstImage);\n\n\n\npublic:\n\n int slice() const override { return _slice; }\n\n\n\n void setSlice(int slice) override;\n", "file_path": "Image/MonoImage.h", "rank": 38, "score": 56031.764849318926 }, { "content": "class GeneralImage : public BaseImage\n\n{\n\npublic:\n\n GeneralImage();\n\n GeneralImage(const QString& pathName);\n\n GeneralImage(const GeneralImage& src);\n\n virtual ~GeneralImage();\n\n\n\n GeneralImage& operator=(const GeneralImage& src);\n\n\n\npublic:\n\n // Get backup QImage pointer\n\n QImage* getBackupImage() const { return _backupImage.get(); }\n\n\n\n // Calculate new color\n\n uchar calcNewColor(uchar color, float bottom, float mid, float top, int minColor, int maxColor);\n\n\n\npublic:\n\n // Histogram statistic\n\n void histogramStatistic() override;\n", "file_path": "Image/GeneralImage.h", "rank": 39, "score": 56031.764849318926 }, { "content": "class ImageData;\n", "file_path": "Image/MonoImage.h", "rank": 40, "score": 55715.883142633335 }, { "content": "class BaseImage\n\n{\n\npublic:\n\n BaseImage();\n\n BaseImage(const QString& pathName);\n\n BaseImage(const BaseImage& src);\n\n virtual ~BaseImage();\n\n\n\n BaseImage& operator=(const BaseImage& src);\n\n\n\npublic:\n\n // Get min and max value of image\n\n virtual float getMinValue() const = 0;\n\n virtual float getMaxValue() const = 0;\n\n\n\n // Histogram statistic\n\n virtual void histogramStatistic() = 0;\n\n\n\n virtual float getValue(const QPoint& position) const = 0;\n\n virtual float getValue(int x, int y) const = 0;\n", "file_path": "Image/BaseImage.h", "rank": 41, "score": 55715.883142633335 }, { "content": "class ImageData\n\n{\n\npublic:\n\n ImageData(int width, int height, int slice = 1)\n\n : _width(width)\n\n , _height(height)\n\n , _slice(slice)\n\n , _pixelPerSlice(width * height)\n\n , _totalPixel(_pixelPerSlice * slice)\n\n {\n\n\n\n }\n\n\n\n ImageData(const ImageData& src)\n\n : _width(src._width)\n\n , _height(src._height)\n\n , _slice(src._slice)\n\n , _pixelPerSlice(src._pixelPerSlice)\n\n , _totalPixel(src._totalPixel)\n\n , _minValue(src._minValue)\n", "file_path": "Image/ImageData.h", "rank": 42, "score": 55715.883142633335 }, { "content": "class MonoImageProxy;\n\n\n\n#ifndef VIEW_TYPE\n\n#define AXIAL_VIEW 0\n\n#define CORONAL_VIEW 1\n\n#define SAGITTAL_VIEW 2\n\n#define VOLUME_VIEW 3\n\n#endif\n\n\n", "file_path": "Image/MonoImage.h", "rank": 43, "score": 54661.96137684997 }, { "content": "class ImageDataTemplate : public ImageData\n\n{\n\npublic:\n\n ImageDataTemplate(int width, int height, int slice = 1);\n\n ImageDataTemplate(const ImageDataTemplate& src);\n\n virtual ~ImageDataTemplate();\n\n\n\n ImageDataTemplate& operator=(const ImageDataTemplate& src);\n\n\n\npublic:\n\n // Get original data pointer\n\n void* getOriginalData() override\n\n {\n\n return static_cast<void*>(_originalData.get());\n\n }\n\n\n\n // Get processing data pointer\n\n void* getProcessingData() override\n\n {\n\n return static_cast<void*>(_axialData);\n", "file_path": "Image/ImageDataTemplate.h", "rank": 44, "score": 54448.13842183885 }, { "content": "class MonoImageProxy\n\n{\n\npublic:\n\n MonoImageProxy(MonoImage* image, int width, int height, int type = AXIAL_VIEW);\n\n MonoImageProxy(const MonoImageProxy& src);\n\n ~MonoImageProxy();\n\n\n\n MonoImageProxy& operator=(const MonoImageProxy& src);\n\n\n\npublic:\n\n uchar* getBYTEImage() const { return _byteImage; }\n\n\n\n std::shared_ptr<QImage> getImageEntity() const { return _pImage; }\n\n\n\n void copyByteToImage();\n\n void copyByteToImage(QImage* dstImage);\n\n\n\nprotected:\n\n MonoImage* _image;\n\n\n\n int _width, _height;\n\n\n\n int _type;\n\n\n\n uchar* _byteImage;\n\n\n\n std::shared_ptr<QImage> _pImage;\n\n};\n", "file_path": "Image/MonoImageProxy.h", "rank": 45, "score": 53647.171367470684 }, { "content": " virtual float getValue(int index) const = 0;\n\n virtual float getValue(float x, float y) const;\n\n\n\n virtual float getValueWithType(int type, int index) const { Q_UNUSED(type); return getValue(index); }\n\n\n\n virtual bool hasPixelSpacing() { return false; }\n\n\n\n virtual float horzPixelSpacing() { return 0; }\n\n virtual float vertPixelSpacing() { return 0; }\n\n virtual float sliceSpacing() { return 0; }\n\n\n\n // Create a deep copy of image\n\n virtual BaseImage* copyImage() const = 0;\n\n\n\n virtual bool copyToImage(BaseImage* image) const = 0;\n\n\n\n virtual void restore() = 0;\n\n\n\n virtual void setViewType(int type) { Q_UNUSED(type); }\n\n\n", "file_path": "Image/BaseImage.h", "rank": 46, "score": 53595.1690223044 }, { "content": " void restore() override;\n\n\n\n void setViewType(int type) override;\n\n\n\n int viewType() override { return _currentViewType; }\n\n\n\n QImage* getImageEntity() const override;\n\n\n\npublic:\n\n void setValue(int index, float value);\n\n\n\n // get uchar data\n\n uchar* getBYTEImage(int& width, int& height);\n\n\n\n bool convertAllToByte();\n\n\n\n bool convertToByte();\n\n\n\n std::shared_ptr<QImage> getCoronalImage() const;\n\n std::shared_ptr<QImage> getSagittalImage() const;\n", "file_path": "Image/MonoImage.h", "rank": 47, "score": 53594.98944231087 }, { "content": "\n\n float getValue(const QPoint& position) const override;\n\n float getValue(int x, int y) const override;\n\n float getValue(int index) const override;\n\n\n\n float getMinValue() const override { return 0.0f; }\n\n\n\n float getMaxValue() const override { return 255.0f; }\n\n\n\n BaseImage* copyImage() const override;\n\n\n\n bool copyToImage(BaseImage* image) const override;\n\n\n\n void restore() override;\n\n\n\nprivate:\n\n // Backup origin QImage\n\n void backupImage();\n\n\n\nprivate:\n\n // Backup origin QImage\n\n std::shared_ptr<QImage> _backupImage;\n\n};\n", "file_path": "Image/GeneralImage.h", "rank": 48, "score": 53591.58647481652 }, { "content": " virtual ImageData* copyImageData() const = 0;\n\n\n\n virtual void restoreData() = 0;\n\n\n\n virtual void changeSlice(int type, int slice) = 0;\n\n\n\n virtual int getElementSize() = 0;\n\n\n\n virtual void interpolateData(int index, void* prevData, void* nextData, float ratio) = 0;\n\n\n\npublic:\n\n float getMinimumValue() const { return _minValue; }\n\n\n\n void setMinimumValue(float minValue) { _minValue = minValue; }\n\n\n\n float getMaximumValue() const { return _maxValue; }\n\n\n\n void setMaximumValue(float maxValue) { _maxValue = maxValue; }\n\n\n\nprotected:\n\n int _width, _height, _slice;\n\n\n\n unsigned long _pixelPerSlice;\n\n\n\n unsigned long _totalPixel;\n\n\n\n float _minValue, _maxValue;\n\n};\n", "file_path": "Image/ImageData.h", "rank": 49, "score": 53591.106287799055 }, { "content": "\n\n // Find top and bottom value in data\n\n virtual bool findTopAndBottom() = 0;\n\n\n\n // Allocate data to byte\n\n virtual bool convertToByte(float* data, int size, uchar* byteImage) = 0;\n\n\n\n virtual bool convertToByte(int type, uchar* byteImage) = 0;\n\n\n\n // Save array to QFile\n\n virtual void saveArray(QFile& file) = 0;\n\n\n\n // Rescale array\n\n virtual void rescaleArray(float rescaleSlope, float rescaleIntercept) = 0;\n\n virtual void rescaleArray(int type, float rescaleSlope, float rescaleIntercept) = 0;\n\n\n\n // Rescale top and bottom\n\n virtual void rescaleTopAndBottom(float rescaleSlope, float rescaleIntercept) = 0;\n\n\n\n // Create a deep copy of image data\n", "file_path": "Image/ImageData.h", "rank": 50, "score": 53589.274522727465 }, { "content": " _maxValue = src._maxValue;\n\n\n\n return *this;\n\n }\n\n\n\npublic:\n\n // Get original data pointer\n\n virtual void* getOriginalData() = 0;\n\n\n\n // Get processing data pointer\n\n virtual void* getProcessingData() = 0;\n\n\n\n // Get pixel value of processing data\n\n virtual float getProcessingValue(int type, int index) = 0;\n\n\n\n // Set pixel value of processing data\n\n virtual void setProcessingValue(int type, int index, float value) = 0;\n\n\n\n // Allocate memory\n\n virtual bool allocateMemory() = 0;\n", "file_path": "Image/ImageData.h", "rank": 51, "score": 53586.23613751318 }, { "content": " void setSlice(int type, int slice) override;\n\n\n\n int currentSlice() const override;\n\n int currentSlice(int type) const override;\n\n\n\n float getMinValue() const override;\n\n\n\n float getMaxValue() const override;\n\n\n\n // Histogram statistic\n\n void histogramStatistic() override;\n\n\n\n float getValue(const QPoint& position) const override;\n\n float getValue(int x, int y) const override;\n\n float getValue(int index) const override;\n\n\n\n float getValueWithType(int type, int index) const override;\n\n\n\n virtual void initWindowWidthAndLevel() = 0;\n\n\n", "file_path": "Image/MonoImage.h", "rank": 52, "score": 53584.50047966574 }, { "content": " virtual int viewType() { return 0; }\n\n\n\n virtual QImage* getImageEntity() const { return _pImage.get(); }\n\n\n\n virtual QString getDescription() { return QString(); }\n\n\n\npublic:\n\n int width() const { return _width; }\n\n\n\n int height() const { return _height; }\n\n\n\n virtual int slice() const { return 1; }\n\n\n\n virtual void setSlice(int slice) { Q_UNUSED(slice); }\n\n virtual void setSlice(int type, int slice) { Q_UNUSED(type); Q_UNUSED(slice); }\n\n\n\n virtual int currentSlice() const { return 0; }\n\n virtual int currentSlice(int type) const { Q_UNUSED(type); return 0; }\n\n\n\n float windowWidth() { return _windowWidth; }\n", "file_path": "Image/BaseImage.h", "rank": 53, "score": 53583.53447676558 }, { "content": "\n\nprotected:\n\n bool saveAsRaw(const QString& fileName) override;\n\n\n\nprotected:\n\n bool allocateMemory();\n\n\n\nprotected:\n\n ImageData* _imageData;\n\n\n\n MonoImageProxy* _axialProxy;\n\n MonoImageProxy* _coronalProxy;\n\n MonoImageProxy* _sagittalProxy;\n\n\n\n int _currentViewType;\n\n\n\n int _slice;\n\n\n\n int _currentAxialSlice;\n\n int _currentCoronalSlice;\n\n int _currentSagittalSlice;\n\n};\n", "file_path": "Image/MonoImage.h", "rank": 54, "score": 53581.80472762637 }, { "content": " void initWindowWidthAndLevel() override;\n\n\n\n BaseImage* copyImage() const override;\n\n\n\n bool copyToImage(BaseImage* image) const override;\n\n\n\n void restore() override;\n\n\n\n QString getDescription() { return _seriesDescription; }\n\n\n\nprivate:\n\n // Read data\n\n bool readData();\n\n\n\n void readMoreInfo(DcmDataset* dataset);\n\n\n\n void rescaleArray();\n\n void rescaleArray(int type);\n\n\n\n void rescaleTopAndBottom();\n", "file_path": "Image/DicomImage.h", "rank": 55, "score": 53581.66782001961 }, { "content": " bool copyFromArray(uchar* byteImage, int width, int height);\n\n\n\nprotected:\n\n virtual bool saveAsDcm(const QString& fileName);\n\n\n\n virtual bool saveAsRaw(const QString& fileName);\n\n\n\nprotected:\n\n std::shared_ptr<QImage> _pImage;\n\n\n\n int _width, _height;\n\n\n\n float _windowWidth;\n\n float _windowLevel;\n\n\n\n QString _pathName;\n\n\n\n bool _openSucceed;\n\n\n\n // Storage the pixel number of each channel(0-255)\n\n uint _grayPixelNumber[256];\n\n uint _redPixelNumber[256];\n\n uint _greenPixelNumber[256];\n\n uint _bluePixelNumber[256];\n\n};\n", "file_path": "Image/BaseImage.h", "rank": 56, "score": 53581.535150671756 }, { "content": "\n\nprotected:\n\n QWidget* _widget;\n\n bool _waitForQuit;\n\n\n\n QString _pathName;\n\n\n\n float _minValue;\n\n float _maxValue;\n\n};\n\n\n\ntemplate <class Type>\n", "file_path": "Image/ImageReader.h", "rank": 57, "score": 53577.86172333596 }, { "content": "\n\ntemplate <class Type>\n\nImageReader<Type>::ImageReader(const QString& pathName, int headSize, int pixelCount, int slice, Type* buffer)\n\n : AbstractReader(pathName, nullptr)\n\n , _headSize(headSize)\n\n , _pixelPerSlice(pixelCount)\n\n , _slice(slice)\n\n , _endian(0)\n\n , _buffer(buffer)\n\n{\n\n\n\n}\n\n\n\ntemplate <class Type>\n\nImageReader<Type>::ImageReader(const QString& pathName, int headSize, int pixelCount, int slice, int endian, Type* buffer)\n\n : AbstractReader(pathName, nullptr)\n\n , _headSize(headSize)\n\n , _pixelPerSlice(pixelCount)\n\n , _slice(slice)\n\n , _endian(endian)\n", "file_path": "Image/ImageReader.h", "rank": 58, "score": 53577.11219236876 }, { "content": " BaseImage* copyImage() const override;\n\n\n\n bool copyToImage(BaseImage* image) const override;\n\n\n\npublic:\n\n // Get reference of DataHeader\n\n DataHeader& getDataHeader() { return _dataHeader; }\n\n\n\nprotected:\n\n bool saveAsDcm(const QString& fileName) override;\n\n\n\nprivate:\n\n // Read data header\n\n bool readDataHeader();\n\n\n\n // Read data\n\n bool readData();\n\n\n\n bool isNewHeader(QFile& file);\n\n\n\n void convertHeader(const OldDataHeader& dh);\n\n\n\nprivate:\n\n DataHeader _dataHeader;\n\n};\n", "file_path": "Image/ScanImage.h", "rank": 59, "score": 53576.72663316962 }, { "content": "\n\n float windowLevel() { return _windowLevel; }\n\n\n\n bool isOpenSucceed() { return _openSucceed; }\n\n\n\n QString getPathName() const { return _pathName; }\n\n\n\n // Get each channel's pixel array\n\n uint* getGrayPixelArray() { return _grayPixelNumber; }\n\n uint* getRedPixelArray() { return _redPixelNumber; }\n\n uint* getGreenPixelArray() { return _greenPixelNumber; }\n\n uint* getBluePixelArray() { return _bluePixelNumber; }\n\n\n\n QRgb getPixel(const QPoint& position) const;\n\n QRgb getPixel(int x, int y) const;\n\n\n\n bool save(const QString& fileName);\n\n\n\n void copyToArray(uchar* array);\n\n\n", "file_path": "Image/BaseImage.h", "rank": 60, "score": 53576.5495129013 }, { "content": "#pragma once\n\n\n\n#include <float.h>\n\n#include <QThread>\n\n#include <QFile>\n\n#include <QMessageBox>\n\n\n", "file_path": "Image/ImageReader.h", "rank": 61, "score": 53573.54452745513 }, { "content": " }\n\n\n\n Type* temp = _buffer + n * _pixelPerSlice;\n\n for (int i = 1; i < _pixelPerSlice; i++)\n\n {\n\n if (_minValue > temp[i])\n\n {\n\n _minValue = temp[i];\n\n }\n\n if (_maxValue < temp[i])\n\n {\n\n _maxValue = temp[i];\n\n }\n\n }\n\n\n\n int progress = (n + 1) * 100 / _slice;\n\n QMetaObject::invokeMethod(_widget, \"setProgress\", Qt::QueuedConnection, Q_ARG(int, progress));\n\n }\n\n\n\n file.close();\n", "file_path": "Image/ImageReader.h", "rank": 62, "score": 53573.40117367076 }, { "content": " , _maxValue(src._maxValue)\n\n {\n\n\n\n }\n\n\n\n virtual ~ImageData() {}\n\n\n\n ImageData& operator=(const ImageData& src)\n\n {\n\n if (this == &src)\n\n return *this;\n\n\n\n _width = src._width;\n\n _height = src._height;\n\n _slice = src._slice;\n\n\n\n _pixelPerSlice = src._pixelPerSlice;\n\n _totalPixel = src._totalPixel;\n\n\n\n _minValue = src._minValue;\n", "file_path": "Image/ImageData.h", "rank": 63, "score": 53573.354326734174 }, { "content": "#pragma once\n\n\n\n#include <memory>\n\n#include <QString>\n\n#include <QImage>\n\n\n", "file_path": "Image/BaseImage.h", "rank": 64, "score": 53573.33928229998 }, { "content": "#pragma once\n\n\n\n#include \"MonoImage.h\"\n\n#include \"Dataheader.h\"\n\n#include \"OldDataheader.h\"\n\n\n", "file_path": "Image/ScanImage.h", "rank": 65, "score": 53573.33928229998 }, { "content": "#pragma once\n\n\n\n#include <memory>\n\n\n\n#include \"BaseImage.h\"\n\n\n", "file_path": "Image/GeneralImage.h", "rank": 66, "score": 53573.21668122862 }, { "content": "\n\nprivate:\n\n float _horzPixelSpacing;\n\n float _vertPixelSpacing;\n\n float _sliceSpacing;\n\n\n\n float _imagerPixelSpacing; // Detector pixel size\n\n float _sliceThickness;\n\n\n\n float _SOD;\n\n float _SDD;\n\n\n\n float _imagePositionPatientZ;\n\n\n\n ushort _bitsAllocated;\n\n ushort _bitsStored;\n\n\n\n float _rescaleSlope;\n\n float _rescaleIntercept;\n\n\n\n QString _seriesDescription;\n\n QString _patientsName;\n\n\n\n QString _studyInstanceUID;\n\n QString _seriesInstanceUID;\n\n QString _SOPInstanceUID;\n\n};\n", "file_path": "Image/DicomImage.h", "rank": 67, "score": 53572.96203583561 }, { "content": "#pragma once\n\n\n\n#include \"MonoImage.h\"\n\n\n", "file_path": "Image/DicomImage.h", "rank": 68, "score": 53572.61601915804 }, { "content": "#pragma once\n\n\n\n#include \"MonoImage.h\"\n\n\n", "file_path": "Image/RawImage.h", "rank": 69, "score": 53572.61601915804 }, { "content": "#pragma once\n\n\n\n#include \"BaseImage.h\"\n\n\n", "file_path": "Image/MonoImage.h", "rank": 70, "score": 53572.61601915804 }, { "content": " , _buffer(buffer)\n\n{\n\n\n\n}\n\n\n\ntemplate <class Type>\n\nvoid ImageReader<Type>::run()\n\n{\n\n QFile file(_pathName);\n\n if (!file.open(QFile::ReadOnly))\n\n {\n\n QMetaObject::invokeMethod(_widget, \"reject\", Qt::QueuedConnection);\n\n return;\n\n }\n\n\n\n QMetaObject::invokeMethod(_widget, \"setTitle\", Qt::QueuedConnection, Q_ARG(const QString&, tr(\"Loading file...\")));\n\n\n\n file.seek(_headSize);\n\n for (int n = 0; n < _slice; n++)\n\n {\n", "file_path": "Image/ImageReader.h", "rank": 71, "score": 53572.483589273485 }, { "content": " qint64 readSize = file.read((char*)(_buffer + n * _pixelPerSlice), sizeof(Type) * _pixelPerSlice);\n\n if (readSize != qint64(sizeof(Type)) * qint64(_pixelPerSlice))\n\n {\n\n file.close();\n\n QMessageBox::critical(nullptr, QObject::tr(\"Open image file error\"),\n\n QObject::tr(\"The data size does not match the file information description!\"), QMessageBox::Ok);\n\n QMetaObject::invokeMethod(_widget, \"reject\", Qt::QueuedConnection);\n\n return;\n\n }\n\n\n\n if (_waitForQuit)\n\n return;\n\n\n\n if (_endian == 1 && sizeof(Type) > 1)\n\n {\n\n // Convert endian byte order\n\n for (int i = 0; i < _pixelPerSlice; i++)\n\n {\n\n convertEndian(_buffer + n * _pixelPerSlice + i);\n\n }\n", "file_path": "Image/ImageReader.h", "rank": 72, "score": 53571.19574853487 }, { "content": "\n\n QMetaObject::invokeMethod(_widget, \"accept\", Qt::QueuedConnection);\n\n}\n\n\n\ntemplate <class Type>\n\nvoid ImageReader<Type>::convertEndian(Type* data)\n\n{\n\n for (size_t i = 0; i < sizeof(Type) / 2; i++)\n\n {\n\n char temp = ((char*)data)[sizeof(Type) - i - 1];\n\n ((char*)data)[sizeof(Type) - i - 1] = ((char*)data)[i];\n\n ((char*)data)[i] = temp;\n\n }\n\n}\n", "file_path": "Image/ImageReader.h", "rank": 73, "score": 53569.933285511135 }, { "content": "#pragma once\n\n\n\n#include <QtGlobal>\n\n\n\nQT_BEGIN_NAMESPACE\n", "file_path": "Image/ImageData.h", "rank": 74, "score": 53567.75384321772 }, { "content": "class GraphicsScene : public QGraphicsScene\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n explicit GraphicsScene(QMenu* itemMenu, View* parent = nullptr);\n\n QFont font() const { return _font; }\n\n QColor textColor() const { return _textColor; }\n\n QColor itemColor() const { return _fillColor; }\n\n QColor lineColor() const { return _lineColor; }\n\n\n\n // utilities\n\n void deleteItems(const QList<QGraphicsItem*>& items);\n\n\n\n void setMode(int mode);\n\n\n\n int mode() { return _mode; }\n\n\n\n void setItemType(DiagramItem::DiagramType type);\n\n\n", "file_path": "Core/GraphicsScene.h", "rank": 75, "score": 53053.29287566328 }, { "content": "class GraphicsView;\n", "file_path": "Core/View.h", "rank": 76, "score": 52961.11187623575 }, { "content": "class ImageReader : public AbstractReader\n\n{\n\npublic:\n\n ImageReader(const QString& pathName, int headSize, int pixelCount, int slice, Type* buffer);\n\n ImageReader(const QString& pathName, int headSize, int pixelCount, int slice, int endian, Type* buffer);\n\n\n\nprotected:\n\n void run() override;\n\n\n\nprivate:\n\n // Convert endian byte order\n\n void convertEndian(Type* data);\n\n\n\nprivate:\n\n int _headSize;\n\n int _pixelPerSlice;\n\n int _slice;\n\n int _endian;\n\n Type* _buffer;\n\n};\n", "file_path": "Image/ImageReader.h", "rank": 77, "score": 52669.37341447028 }, { "content": "class ChartView : public QChartView\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n ChartView(QWidget* parent = nullptr);\n\n\n\n bool hasValidData();\n\n\n\n void setData(const QVector<qreal>& points);\n\n\n\n void updateData(const QVector<qreal>& points);\n\n\n\nprotected:\n\n void mouseMoveEvent(QMouseEvent* event) override;\n\n\n\nprotected:\n\n QLineSeries* _dataSeries;\n\n QLineSeries* _hSeries;\n\n QLineSeries* _vSeries;\n\n Callout* _callout;\n\n};\n", "file_path": "Widget/ChartView.h", "rank": 78, "score": 52567.483005804446 }, { "content": "class GraphicsView : public QGraphicsView\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n GraphicsView(View* view, QGraphicsScene* scene, QWidget* parent = nullptr);\n\n\n\n QPointF mapImagePointToScene(qreal x, qreal y) const;\n\n\n\n void setZoomValue(int value);\n\n\n\n void setZoomValueOffset(int offset);\n\n\n\n void showAnnotation(bool show);\n\n\n\n void showCrossLine(bool show);\n\n\n\n void showThreeViewAxes(bool show);\n\n\n\n void showLineScale(bool show);\n", "file_path": "Core/GraphicsView.h", "rank": 79, "score": 52567.483005804446 }, { "content": " }\n\n\n\n // Get pixel value of processing data\n\n float getProcessingValue(int type, int index) override;\n\n\n\n // Set pixel value of processing data\n\n void setProcessingValue(int type, int index, float value) override;\n\n\n\n // Find top and bottom value in data\n\n // bool findTopAndBottom(Type* pData, int num);\n\n bool findTopAndBottom() override;\n\n\n\n // Allocate memory\n\n bool allocateMemory() override;\n\n\n\n // Convert float data to uchar data\n\n bool convertToByte(float* data, int size, uchar* byteImage) override;\n\n\n\n bool convertToByte(int type, uchar* byteImage) override;\n\n\n", "file_path": "Image/ImageDataTemplate.h", "rank": 80, "score": 52141.982729644566 }, { "content": " return _imageData->getProcessingValue(_currentViewType, index);\n\n}\n\n\n\nfloat MonoImage::getValueWithType(int type, int index) const\n\n{\n\n return _imageData->getProcessingValue(type, index);\n\n}\n\n\n\nfloat MonoImage::getMinValue() const\n\n{\n\n return _imageData->getMinimumValue();\n\n}\n\n\n\nfloat MonoImage::getMaxValue() const\n\n{\n\n return _imageData->getMaximumValue();\n\n}\n\n\n\nvoid MonoImage::restore()\n\n{\n", "file_path": "Image/MonoImage.cpp", "rank": 81, "score": 52141.622566262144 }, { "content": " return _coronalProxy->getImageEntity().get();\n\n }\n\n else/* if (_currentType == SAGITTAL_VIEW)*/\n\n {\n\n return _sagittalProxy->getImageEntity().get();\n\n }\n\n}\n\n\n\nvoid MonoImage::setValue(int index, float value)\n\n{\n\n _imageData->setProcessingValue(_currentViewType, index, value);\n\n}\n\n\n\nuchar* MonoImage::getBYTEImage(int& width, int& height)\n\n{\n\n if (_currentViewType == AXIAL_VIEW)\n\n {\n\n width = _width;\n\n height = _height;\n\n return _axialProxy->getBYTEImage();\n", "file_path": "Image/MonoImage.cpp", "rank": 82, "score": 52141.02980508503 }, { "content": " return true;\n\n}\n\n\n\n// Convert data to byte\n\ntemplate <class Type>\n\nbool ImageDataTemplate<Type>::convertToByte(float* data, int size, uchar* byteImage)\n\n{\n\n if (data == nullptr)\n\n return false;\n\n\n\n float variable;\n\n if (_minValue != _maxValue)\n\n {\n\n variable = 255.0f / (_maxValue - _minValue);\n\n }\n\n else\n\n {\n\n variable = 0.0f;\n\n }\n\n\n", "file_path": "Image/ImageDataTemplate.h", "rank": 83, "score": 52140.461319892114 }, { "content": "}\n\n\n\ntemplate <class Type>\n\nvoid ImageDataTemplate<Type>::interpolateData(int index, void* prevData, void* nextData, float ratio)\n\n{\n\n assert(prevData);\n\n assert(nextData);\n\n qint64 offset = index * _width * _height;\n\n\n\n for (int i = 0; i < _pixelPerSlice; i++)\n\n {\n\n _originalData.get()[i + offset] = Type(round(((Type*)prevData)[i] * (1.0f - ratio) + ((Type*)nextData)[i] * ratio));\n\n }\n\n}", "file_path": "Image/ImageDataTemplate.h", "rank": 84, "score": 52139.9776328908 }, { "content": " index = position.y() * _width + position.x();\n\n }\n\n else/* if (_currentType == SAGITTAL_VIEW)*/\n\n {\n\n if (position.x() >= _height || position.y() >= _slice)\n\n return 0;\n\n\n\n index = position.y() * _height + position.x();\n\n }\n\n\n\n return _imageData->getProcessingValue(_currentViewType, index);\n\n}\n\n\n\nfloat MonoImage::getValue(int x, int y) const\n\n{\n\n return getValue(QPoint(x, y));\n\n}\n\n\n\nfloat MonoImage::getValue(int index) const\n\n{\n", "file_path": "Image/MonoImage.cpp", "rank": 85, "score": 52138.74144851478 }, { "content": " // Save array to QFile\n\n void saveArray(QFile& file) override;\n\n\n\n // Rescale array\n\n void rescaleArray(float rescaleSlope, float rescaleIntercept) override;\n\n void rescaleArray(int type, float rescaleSlope, float rescaleIntercept) override;\n\n\n\n // Rescale top and bottom\n\n void rescaleTopAndBottom(float rescaleSlope, float rescaleIntercept) override;\n\n\n\n // Create a deep copy of image data\n\n ImageData* copyImageData() const override;\n\n\n\n void restoreData() override;\n\n\n\n void changeSlice(int type, int slice) override;\n\n\n\n int getElementSize() override { return sizeof(Type); }\n\n\n\n void interpolateData(int index, void* prevData, void* nextData, float ratio) override;\n", "file_path": "Image/ImageDataTemplate.h", "rank": 86, "score": 52136.936537834976 }, { "content": " float v11 = getValue(x1, y1);\n\n\n\n // Bilinear interpolation\n\n // f(x,y)=f(0,0)(1-x)(1-y)+f(0,1)(1-x)y+f(1,1)xy+f(1,0)x(1-y)\n\n float value = (1 - lambda_x) * (1 - lambda_y) * v00 + lambda_x * (1 - lambda_y) * v10\n\n + (1 - lambda_x) * lambda_y * v01 + lambda_x * lambda_y * v11;\n\n return value;\n\n}\n\n\n\nQRgb BaseImage::getPixel(const QPoint& position) const\n\n{\n\n return _pImage->pixel(position);\n\n}\n\n\n\nQRgb BaseImage::getPixel(int x, int y) const\n\n{\n\n return _pImage->pixel(QPoint(x, y));\n\n}\n\n\n\nbool BaseImage::save(const QString& fileName)\n", "file_path": "Image/BaseImage.cpp", "rank": 87, "score": 52136.212413412475 }, { "content": "#include \"MonoImage.h\"\n\n\n\n#include <QFile>\n\n\n\n#include \"../Core/GlobalFunc.h\"\n\n#include \"ImageData.h\"\n\n#include \"MonoImageProxy.h\"\n\n\n\nMonoImage::MonoImage()\n\n : BaseImage()\n\n , _imageData(nullptr)\n\n , _axialProxy(nullptr)\n\n , _coronalProxy(nullptr)\n\n , _sagittalProxy(nullptr)\n\n , _currentViewType(AXIAL_VIEW)\n\n , _slice(1)\n\n , _currentAxialSlice(0)\n\n , _currentCoronalSlice(0)\n\n , _currentSagittalSlice(0)\n\n{\n", "file_path": "Image/MonoImage.cpp", "rank": 88, "score": 52135.26877886056 }, { "content": "}\n\n\n\nfloat MonoImage::getValue(const QPoint& position) const\n\n{\n\n if (position.x() < 0 || position.y() < 0)\n\n return 0;\n\n\n\n int index;\n\n if (_currentViewType == AXIAL_VIEW)\n\n {\n\n if (position.x() >= _width || position.y() >= _height)\n\n return 0;\n\n\n\n index = position.y() * _width + position.x();\n\n }\n\n else if (_currentViewType == CORONAL_VIEW)\n\n {\n\n if (position.x() >= _width || position.y() >= _slice)\n\n return 0;\n\n\n", "file_path": "Image/MonoImage.cpp", "rank": 89, "score": 52134.5735508534 }, { "content": "void DICOMImage::setSlice(int slice)\n\n{\n\n MonoImage::setSlice(slice);\n\n\n\n rescaleArray();\n\n}\n\n\n\nvoid DICOMImage::setSlice(int type, int slice)\n\n{\n\n MonoImage::setSlice(type, slice);\n\n\n\n rescaleArray(type);\n\n}\n\n\n\nvoid DICOMImage::initWindowWidthAndLevel()\n\n{\n\n if (_windowWidth == 0 && _windowLevel == 0)\n\n {\n\n _windowWidth = _imageData->getMaximumValue() - _imageData->getMinimumValue();\n\n _windowLevel = (_imageData->getMaximumValue() + _imageData->getMinimumValue()) / 2.0f;\n", "file_path": "Image/DicomImage.cpp", "rank": 90, "score": 52134.05087554477 }, { "content": " {\n\n assert((unsigned long)index < _pixelPerSlice);\n\n return _axialData[index];\n\n }\n\n else if (type == 1)\n\n {\n\n assert(index < _width * _slice);\n\n return _coronalData[index];\n\n }\n\n else/* if (type == 2)*/\n\n {\n\n assert(index < _height * _slice);\n\n return _sagittalData[index];\n\n }\n\n}\n\n\n\n// Set pixel value of processing data\n\ntemplate <class Type>\n\nvoid ImageDataTemplate<Type>::setProcessingValue(int type, int index, float value)\n\n{\n", "file_path": "Image/ImageDataTemplate.h", "rank": 91, "score": 52133.93993139379 }, { "content": " return _currentAxialSlice;\n\n }\n\n else if (type == CORONAL_VIEW)\n\n {\n\n return _currentCoronalSlice;\n\n }\n\n else/* if (type == SAGITTAL_VIEW)*/\n\n {\n\n return _currentSagittalSlice;\n\n }\n\n}\n\n\n\nvoid MonoImage::histogramStatistic()\n\n{\n\n memset(_grayPixelNumber, 0, sizeof(uint) * 256);\n\n memset(_redPixelNumber, 0, sizeof(uint) * 256);\n\n memset(_greenPixelNumber, 0, sizeof(uint) * 256);\n\n memset(_bluePixelNumber, 0, sizeof(uint) * 256);\n\n\n\n float minValue = _imageData->getMinimumValue();\n", "file_path": "Image/MonoImage.cpp", "rank": 92, "score": 52133.93222804387 }, { "content": "\n\nprotected:\n\n std::shared_ptr<Type> _originalData;\n\n\n\n float* _axialData;\n\n float* _coronalData;\n\n float* _sagittalData;\n\n\n\n int _currentAxialSlice;\n\n int _currentCoronalSlice;\n\n int _currentSagittalSlice;\n\n};\n\n\n\ntemplate <class Type>\n\nImageDataTemplate<Type>::ImageDataTemplate(int width, int height, int slice)\n\n : ImageData(width, height, slice)\n\n , _originalData(std::shared_ptr<Type>(new Type[_totalPixel]))\n\n , _axialData(nullptr)\n\n , _coronalData(nullptr)\n\n , _sagittalData(nullptr)\n", "file_path": "Image/ImageDataTemplate.h", "rank": 93, "score": 52133.71883219503 }, { "content": " for (int j = 0; j < _slice; j++)\n\n {\n\n qint64 offset = j * _pixelPerSlice;\n\n for (int i = 0; i < _height; i++)\n\n {\n\n _sagittalData[j * _height + i] = _originalData.get()[_width * i + _currentSagittalSlice + offset] * rescaleSlope + rescaleIntercept;\n\n }\n\n }\n\n }\n\n}\n\n\n\ntemplate <class Type>\n\nvoid ImageDataTemplate<Type>::rescaleArray(int type, float rescaleSlope, float rescaleIntercept)\n\n{\n\n if (type == 0)\n\n {\n\n for (unsigned long i = 0; i < _pixelPerSlice; i++)\n\n {\n\n _axialData[i] = _originalData.get()[i + _currentAxialSlice * _pixelPerSlice] * rescaleSlope + rescaleIntercept;\n\n }\n", "file_path": "Image/ImageDataTemplate.h", "rank": 94, "score": 52133.612576183164 }, { "content": " return true;\n\n}\n\n\n\n// Allocate memory\n\ntemplate <class Type>\n\nbool ImageDataTemplate<Type>::allocateMemory()\n\n{\n\n try\n\n {\n\n _axialData = new float[_pixelPerSlice];\n\n for (unsigned long i = 0; i < _pixelPerSlice; i++)\n\n {\n\n _axialData[i] = _originalData.get()[i + _currentAxialSlice * _pixelPerSlice];\n\n }\n\n\n\n _coronalData = new float[_width * _slice];\n\n for (int j = 0; j < _slice; j++)\n\n {\n\n qint64 offset = j * _pixelPerSlice;\n\n for (int i = 0; i < _width; i++)\n", "file_path": "Image/ImageDataTemplate.h", "rank": 95, "score": 52133.135657125786 }, { "content": " for (int j = 0; j < _height; j++)\n\n {\n\n for (int i = 0; i < _width; i++)\n\n {\n\n uchar* pixel = pData + j * pitch + i * depth;\n\n array[j * _width + i] = *pixel;\n\n }\n\n }\n\n}\n\n\n\nbool BaseImage::copyFromArray(uchar* array, int width, int height)\n\n{\n\n if (array == nullptr || _pImage == nullptr)\n\n return false;\n\n\n\n if (width != this->width() || height != this->height())\n\n return false;\n\n\n\n uchar* pData = _pImage->bits();\n\n int pitch = _pImage->bytesPerLine();\n", "file_path": "Image/BaseImage.cpp", "rank": 96, "score": 52133.10944747833 }, { "content": " memcpy(_redPixelNumber, src._redPixelNumber, sizeof(uint) * 256);\n\n memcpy(_greenPixelNumber, src._greenPixelNumber, sizeof(uint) * 256);\n\n memcpy(_bluePixelNumber, src._bluePixelNumber, sizeof(uint) * 256);\n\n\n\n return *this;\n\n}\n\n\n\nfloat BaseImage::getValue(float x, float y) const\n\n{\n\n int x0 = (int)floor(x);\n\n int x1 = (int)ceil(x);\n\n int y0 = (int)floor(y);\n\n int y1 = (int)ceil(y);\n\n\n\n float lambda_x = x - x0;\n\n float lambda_y = y - y0;\n\n\n\n float v00 = getValue(x0, y0);\n\n float v10 = getValue(x1, y0);\n\n float v01 = getValue(x0, y1);\n", "file_path": "Image/BaseImage.cpp", "rank": 97, "score": 52133.060180389024 }, { "content": " _imageData = new ImageDataTemplate<uint>(_width, _height, _slice);\n\n }\n\n\n\n // Copy data from first image\n\n void* firstSliceData = imageVector.first()->_imageData->getOriginalData();\n\n uchar* originalData = static_cast<uchar*>(_imageData->getOriginalData());\n\n memcpy(originalData, firstSliceData, elementSize * _width * _height);\n\n // Interpolate image data\n\n if (_slice > 1)\n\n {\n\n void* lastSliceData = imageVector.last()->_imageData->getOriginalData();\n\n uchar* originalData = static_cast<uchar*>(_imageData->getOriginalData());\n\n memcpy(originalData + (_slice - 1) * elementSize * _width * _height, lastSliceData, elementSize * _width * _height);\n\n\n\n float factor = _horzPixelSpacing / _sliceSpacing;\n\n for (int n = 1; n < _slice - 1; n++)\n\n {\n\n float index = n * factor;\n\n int integerIndex = floor(index);\n\n float ratio = index - integerIndex;\n", "file_path": "Image/DicomImage.cpp", "rank": 98, "score": 52132.931746194205 }, { "content": "\n\nfloat GeneralImage::getValue(int index) const\n\n{\n\n QPoint point(index % _width, index / _width);\n\n QRgb pixel = getPixel(point);\n\n return 0.299f * qRed(pixel) + 0.587f * qGreen(pixel) + 0.114f * qBlue(pixel);\n\n}\n\n\n\nBaseImage* GeneralImage::copyImage() const\n\n{\n\n return new GeneralImage(*this);\n\n}\n\n\n\nbool GeneralImage::copyToImage(BaseImage* image) const\n\n{\n\n GeneralImage* destImage = dynamic_cast<GeneralImage*>(image);\n\n if (!destImage)\n\n return false;\n\n\n\n *destImage = *this;\n", "file_path": "Image/GeneralImage.cpp", "rank": 99, "score": 52132.9095755147 } ]
C++
targets/TARGET_NORDIC/TARGET_NRF5x/TARGET_NRF52/TARGET_MCU_NRF52832/TARGET_RIOT_MICRO_MODULE/ONBOARD_RM1000_AT.cpp
yogpan01/mbed
1fb9dd7ddd94239f788683e864f2dac664f33a48
#if MBED_CONF_NSAPI_PRESENT #include "ONBOARD_RM1000_AT.h" #include "UARTSerial.h" #include "mbed-trace/mbed_trace.h" #ifndef TRACE_GROUP #define TRACE_GROUP "RIOTMICRO" #endif #include "gpio_api.h" #include "PinNames.h" #include "hal/serial_api.h" #include "platform/mbed_thread.h" using namespace mbed; ONBOARD_RM1000_AT::ONBOARD_RM1000_AT(FileHandle *fh) : RM1000_AT(fh) { } nsapi_error_t ONBOARD_RM1000_AT::hard_power_on() { tr_debug("Calling ONBOARD_RM1000_AT::hard_power_on"); return NSAPI_ERROR_OK; } nsapi_error_t ONBOARD_RM1000_AT::hard_power_off() { tr_debug("Calling ONBOARD_RM1000_AT::hard_power_off"); return NSAPI_ERROR_OK; } nsapi_error_t ONBOARD_RM1000_AT::soft_power_on() { tr_debug("Calling ONBOARD_RM1000_AT::soft_power_on"); onboard_modem_init(); return NSAPI_ERROR_OK; } nsapi_error_t ONBOARD_RM1000_AT::soft_power_off() { tr_debug("Calling ONBOARD_RM1000_AT::soft_power_off"); onboard_modem_deinit(); return NSAPI_ERROR_OK; } void ONBOARD_RM1000_AT::onboard_modem_init() { char promptEnd; tr_debug("onboard_modem_init"); gpio_t gpio; gpio_init_out_ex(&gpio, MDMCHEN, 0); gpio_init_out_ex(&gpio, MDMREMAP, 0); gpio_init_out_ex(&gpio, MDMRST, 0); thread_sleep_for(100); gpio_write(&gpio, 1); gpio_init_in_ex(&gpio, MDM_UART1_TXD, PullNone); gpio_init_in_ex(&gpio, MDM_UART1_RXD, PullNone); serial_t bootrom_uart; serial_init(&bootrom_uart, MDM_UART0_TXD, MDM_UART0_RXD); serial_baud(&bootrom_uart, 115200); tr_debug("%s: MODEM RESET", __func__); serial_getc(&bootrom_uart); tr_debug("%s: MODEM first activity after reset", __func__); for (int i = 0; i < 3; i++) { do { promptEnd = serial_getc(&bootrom_uart); } while ('.' != promptEnd); } serial_putc(&bootrom_uart, ' '); for (int i = 0; i < 2; i++) { do { promptEnd = serial_getc(&bootrom_uart); } while ('>' != promptEnd); } serial_putc(&bootrom_uart, '6'); serial_free(&bootrom_uart); tr_debug("%s: Wait for stack prompt", __func__); thread_sleep_for(100); serial_t cli_uart; serial_init(&cli_uart, MDM_UART3_TXD, MDM_UART3_RXD); serial_baud(&cli_uart, 230400); do { promptEnd = serial_getc(&cli_uart); } while ('>' != promptEnd); serial_free(&cli_uart); tr_debug("%s: MODEM CLI prompt reached", __func__); tr_debug("Reset RM1000 completed"); } void ONBOARD_RM1000_AT::onboard_modem_deinit() { tr_debug("onboard_modem_deinit"); gpio_t gpio; gpio_init_out_ex(&gpio, MDMRST, 0); } CellularDevice *CellularDevice::get_target_default_instance() { tr_debug("Calling CellularDevice::get_target_default_instance from ONBOARD_RM1000_AT"); static UARTSerial serial(MDM_UART3_TXD, MDM_UART3_RXD, 230400); #if DEVICE_SERIAL_FC if (MDM_UART3_RTS != NC && MDM_UART3_CTS != NC) { tr_debug("Modem flow control: RTS %d CTS %d", MDM_UART3_RTS, MDM_UART3_CTS); serial.set_flow_control(SerialBase::RTSCTS, MDM_UART3_RTS, MDM_UART3_CTS); } #endif static ONBOARD_RM1000_AT device(&serial); return &device; } #endif
#if MBED_CONF_NSAPI_PRESENT #include "ONBOARD_RM1000_AT.h" #include "UARTSerial.h" #include "mbed-trace/mbed_trace.h" #ifndef TRACE_GROUP #define TRACE_GROUP "RIOTMICRO" #endif #include "gpio_api.h" #include "PinNames.h" #include "hal/serial_api.h" #include "platform/mbed_thread.h" using namespace mbed; ONBOARD_RM1000_AT::ONBOARD_RM1000_AT(FileHandle *fh) : RM1000_AT(fh) { } nsapi_error_t ONBOARD_RM1000_AT::hard_power_on() { tr_debug("Calling ONBOARD_RM1000_AT::hard_power_on"); return NSAPI_ERROR_OK; } nsapi_error_t ONBOARD_RM1000_AT::hard_power_off() { tr_debug("Calling ONBOARD_RM1000_AT::hard_power_off"); return NSAPI_ERROR_OK; } nsapi_error_t ONBOARD_RM1000_AT::soft_power_on() { tr_debug("Calling ONBOARD_RM1000_AT::soft_power_on"); onboard_modem_init(); return NSAPI_ERROR_OK; } nsapi_error_t ONBOARD_RM1000_AT::soft_power_off() { tr_debug("Calling ONBOARD_RM1000_AT::soft_power_off"); onboard_modem_deinit(); return NSAPI_ERROR_OK; } void ONBOARD_RM1000_AT::onboard_modem_init() { char promptEnd; tr_debug("onboard_modem_init"); gpio_t gpio; gpio_init_out_ex(&gpio, MDMCHEN, 0); gpio_init_out_ex(&gpio, MDMREMAP, 0); gpio_init_out_ex(&gpio, MDMRST, 0); thread_sleep_for(100); gpio_write(&gpio, 1); gpio_init_in_ex(&gpio, MDM_UART1_TXD, PullNone); gpio_init_in_ex(&gpio, MDM_UART1_RXD, PullNone); serial_t bootrom_uart; serial_init(&bootrom_uart, MDM_UART0_TXD, MDM_UART0_RXD); serial_baud(&bootrom_uart, 115200); tr_debug("%s: MODEM RESET", __f
void ONBOARD_RM1000_AT::onboard_modem_deinit() { tr_debug("onboard_modem_deinit"); gpio_t gpio; gpio_init_out_ex(&gpio, MDMRST, 0); } CellularDevice *CellularDevice::get_target_default_instance() { tr_debug("Calling CellularDevice::get_target_default_instance from ONBOARD_RM1000_AT"); static UARTSerial serial(MDM_UART3_TXD, MDM_UART3_RXD, 230400); #if DEVICE_SERIAL_FC if (MDM_UART3_RTS != NC && MDM_UART3_CTS != NC) { tr_debug("Modem flow control: RTS %d CTS %d", MDM_UART3_RTS, MDM_UART3_CTS); serial.set_flow_control(SerialBase::RTSCTS, MDM_UART3_RTS, MDM_UART3_CTS); } #endif static ONBOARD_RM1000_AT device(&serial); return &device; } #endif
unc__); serial_getc(&bootrom_uart); tr_debug("%s: MODEM first activity after reset", __func__); for (int i = 0; i < 3; i++) { do { promptEnd = serial_getc(&bootrom_uart); } while ('.' != promptEnd); } serial_putc(&bootrom_uart, ' '); for (int i = 0; i < 2; i++) { do { promptEnd = serial_getc(&bootrom_uart); } while ('>' != promptEnd); } serial_putc(&bootrom_uart, '6'); serial_free(&bootrom_uart); tr_debug("%s: Wait for stack prompt", __func__); thread_sleep_for(100); serial_t cli_uart; serial_init(&cli_uart, MDM_UART3_TXD, MDM_UART3_RXD); serial_baud(&cli_uart, 230400); do { promptEnd = serial_getc(&cli_uart); } while ('>' != promptEnd); serial_free(&cli_uart); tr_debug("%s: MODEM CLI prompt reached", __func__); tr_debug("Reset RM1000 completed"); }
function_block-function_prefixed
[]
C++
rexec/RexecShell/Environment.cpp
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
#include <vcl\vcl.h> #pragma hdrstop #include "Environment.h" #include "..\mpirun\plugins\Plugin.h" #if ((BCBVER > 1)) #include <stdio.h> #endif extern "C" { __declspec(dllexport) char* GetEnvString(HostData *Proc,char *Name,char *value,DWORD *BufSize) { char *act, *pos; int res; DWORD lenAll,lenStName,lenGName,lenValue; if(!Proc || !Proc->ProcData) return 0; act=Proc->ProcData->Environment; if(value) *value=0; if(!Name) { return 0; } while(act&&*act) { lenAll=strlen(act); pos=strchr(act+1,'='); if(! pos) { act+=(lenAll+1); continue; } lenStName=(DWORD)(pos-act); lenGName=strlen(Name); res=strnicmp(act,Name,min(lenStName,lenGName)); if(!res) { if(lenStName > lenGName) res = 1; else if(lenStName < lenGName) res = -1; else { lenValue = strlen(pos+1)+1; if(value && lenValue<=*BufSize) strcpy(value,pos+1); *BufSize = lenValue; return act; } } if(res>0) { *BufSize = 0; return act; } act+=(lenAll+1); } *BufSize = 0; return act; } __declspec(dllexport) void PutEnvString(HostData *Proc,char *Name,char *value) { char *OldPos; DWORD oldLen,newLen,OldIndex,oldSize,namelen; if(!value) value=""; namelen = strlen(Name); newLen=namelen+strlen(value)+2; oldLen = 0; if(!Proc->ProcData) { Proc->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(Proc->ProcData,0,sizeof(TProcessData)); } if(!Proc->ProcData->Environment) { Proc->ProcData->Environment = (char*)malloc(128); Proc->ProcData->EnvAllocSize=128; *Proc->ProcData->Environment=0; Proc->ProcData->EnvSize=1; } OldPos=GetEnvString(Proc,Name,0,&oldLen); if(!OldPos) { return; } if(oldLen) oldLen += namelen+1; OldIndex=(DWORD)(OldPos-Proc->ProcData->Environment); if(oldLen>=newLen) { memmove(OldPos+newLen,OldPos+oldLen,Proc->ProcData->EnvSize-(OldIndex+oldLen)); Proc->ProcData->EnvSize-=(oldLen-newLen); } else { oldSize=Proc->ProcData->EnvSize; Proc->ProcData->EnvSize+=(newLen-oldLen); if(Proc->ProcData->EnvAllocSize<Proc->ProcData->EnvSize) { Proc->ProcData->EnvAllocSize= max(Proc->ProcData->EnvSize,2*Proc->ProcData->EnvAllocSize); Proc->ProcData->Environment= (char*)realloc(Proc->ProcData->Environment,Proc->ProcData->EnvAllocSize); OldPos=Proc->ProcData->Environment+OldIndex; } memmove(OldPos+newLen,OldPos+oldLen,oldSize-OldIndex-oldLen); } sprintf(OldPos,"%s=%s",Name,value); } __declspec(dllexport) void *GetContext(HostData *Host,DWORD size) { if(!Host) return 0; if(!Host->ProcData) { if(!size) return 0; Host->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(Host->ProcData,0,sizeof(TProcessData)); } if(Host->ProcData->ContextSize<size) { Host->ProcData->Context = realloc(Host->ProcData->Context,size); Host->ProcData->ContextSize = size; } return Host->ProcData->Context; } void EmptyEnvironment(HostData *Proc) { if(Proc && Proc->ProcData && Proc->ProcData->Environment) { *Proc->ProcData->Environment = 0; Proc->ProcData->EnvSize=1; } } void FreeEnvironment(HostData * Proc) { if(!Proc || !Proc->ProcData) return; if(Proc->ProcData->Environment) { free(Proc->ProcData->Environment); } Proc->ProcData->Environment = 0; Proc->ProcData->EnvSize=0; Proc->ProcData->EnvAllocSize=0; } void ProcSetString(char **str,const char *val,DWORD *size) { DWORD len; if(!val) { ProcStrRemove(str,size); return; } len = strlen(val)+1; if(*size<len) { *str = (char*)realloc(*str,len); *size = len; } strcpy(*str,val); } void ProcStrRemove(char **str,DWORD *size) { if(*str) { free(*str); *str = 0; } *size = 0; } __declspec(dllexport) void FreeContext(HostData *Host) { if(!Host || !Host->ProcData||!Host->ProcData->Context) return; free(Host->ProcData->Context); Host->ProcData->Context = 0; Host->ProcData->ContextSize = 0; } void FreeProcData(HostData *Proc) { if(!Proc || !Proc->ProcData) return; FreeContext(Proc); FreeEnvironment(Proc); ProcStrRemove(&Proc->ProcData->Commandline,&Proc->ProcData->CmdSize); ProcStrRemove(&Proc->ProcData->Executable,&Proc->ProcData->ExeSize); ProcStrRemove(&Proc->ProcData->WorkingDir,&Proc->ProcData->WDSize); ProcStrRemove(&Proc->ProcData->UserOptions,&Proc->ProcData->OptSize); ProcStrRemove(&Proc->ProcData->PluginOptions,&Proc->ProcData->PluginOptSize); free(Proc->ProcData); Proc->ProcData = 0; } void CopyProcData(HostData *dest,HostData *src) { TProcessData *d,*s; if(!src || !src->ProcData) { if(dest && dest->ProcData) FreeProcData(dest); return; } if(!dest->ProcData) { dest->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(dest->ProcData,0,sizeof(TProcessData)); } d = dest->ProcData; s = src->ProcData; d->LockIt = s->LockIt; d->PriorityClass = s->PriorityClass; d->LoadProfile = s->LoadProfile; ProcSetString(&d->Executable,s->Executable,&d->ExeSize); ProcSetString(&d->WorkingDir,s->WorkingDir,&d->WDSize); ProcSetString(&d->UserOptions,s->UserOptions,&d->OptSize); ProcSetString(&d->PluginOptions,s->PluginOptions,&d->PluginOptSize); if(s->Environment) { if(d->EnvAllocSize<s->EnvSize) { d->Environment=(char*)realloc(d->Environment,s->EnvSize); d->EnvAllocSize = s->EnvSize; } memcpy(d->Environment,s->Environment,s->EnvSize); d->EnvSize=s->EnvSize; } else if(d->Environment) FreeEnvironment(src); if(s->Context) { if(d->ContextSize!=s->ContextSize) { d->Context = realloc(d->Context,s->ContextSize); d->ContextSize = s->ContextSize; } memcpy(d->Context,s->Context,s->ContextSize); } else if(d->Context) FreeContext(dest); } __declspec(dllexport) void SetCommandline(HostData *Proc,char *commandline) { if(!Proc) return; if(!Proc->ProcData) { Proc->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(Proc->ProcData,0,sizeof(TProcessData)); } ProcSetString(&Proc->ProcData->Commandline,commandline,&Proc->ProcData->CmdSize); } }
#include <vcl\vcl.h> #pragma hdrstop #include "Environment.h" #include "..\mpirun\plugins\Plugin.h" #if ((BCBVER > 1)) #include <stdio.h> #endif extern "C" {
__declspec(dllexport) void PutEnvString(HostData *Proc,char *Name,char *value) { char *OldPos; DWORD oldLen,newLen,OldIndex,oldSize,namelen; if(!value) value=""; namelen = strlen(Name); newLen=namelen+strlen(value)+2; oldLen = 0; if(!Proc->ProcData) { Proc->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(Proc->ProcData,0,sizeof(TProcessData)); } if(!Proc->ProcData->Environment) { Proc->ProcData->Environment = (char*)malloc(128); Proc->ProcData->EnvAllocSize=128; *Proc->ProcData->Environment=0; Proc->ProcData->EnvSize=1; } OldPos=GetEnvString(Proc,Name,0,&oldLen); if(!OldPos) { return; } if(oldLen) oldLen += namelen+1; OldIndex=(DWORD)(OldPos-Proc->ProcData->Environment); if(oldLen>=newLen) { memmove(OldPos+newLen,OldPos+oldLen,Proc->ProcData->EnvSize-(OldIndex+oldLen)); Proc->ProcData->EnvSize-=(oldLen-newLen); } else { oldSize=Proc->ProcData->EnvSize; Proc->ProcData->EnvSize+=(newLen-oldLen); if(Proc->ProcData->EnvAllocSize<Proc->ProcData->EnvSize) { Proc->ProcData->EnvAllocSize= max(Proc->ProcData->EnvSize,2*Proc->ProcData->EnvAllocSize); Proc->ProcData->Environment= (char*)realloc(Proc->ProcData->Environment,Proc->ProcData->EnvAllocSize); OldPos=Proc->ProcData->Environment+OldIndex; } memmove(OldPos+newLen,OldPos+oldLen,oldSize-OldIndex-oldLen); } sprintf(OldPos,"%s=%s",Name,value); } __declspec(dllexport) void *GetContext(HostData *Host,DWORD size) { if(!Host) return 0; if(!Host->ProcData) { if(!size) return 0; Host->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(Host->ProcData,0,sizeof(TProcessData)); } if(Host->ProcData->ContextSize<size) { Host->ProcData->Context = realloc(Host->ProcData->Context,size); Host->ProcData->ContextSize = size; } return Host->ProcData->Context; } void EmptyEnvironment(HostData *Proc) { if(Proc && Proc->ProcData && Proc->ProcData->Environment) { *Proc->ProcData->Environment = 0; Proc->ProcData->EnvSize=1; } } void FreeEnvironment(HostData * Proc) { if(!Proc || !Proc->ProcData) return; if(Proc->ProcData->Environment) { free(Proc->ProcData->Environment); } Proc->ProcData->Environment = 0; Proc->ProcData->EnvSize=0; Proc->ProcData->EnvAllocSize=0; } void ProcSetString(char **str,const char *val,DWORD *size) { DWORD len; if(!val) { ProcStrRemove(str,size); return; } len = strlen(val)+1; if(*size<len) { *str = (char*)realloc(*str,len); *size = len; } strcpy(*str,val); } void ProcStrRemove(char **str,DWORD *size) { if(*str) { free(*str); *str = 0; } *size = 0; } __declspec(dllexport) void FreeContext(HostData *Host) { if(!Host || !Host->ProcData||!Host->ProcData->Context) return; free(Host->ProcData->Context); Host->ProcData->Context = 0; Host->ProcData->ContextSize = 0; } void FreeProcData(HostData *Proc) { if(!Proc || !Proc->ProcData) return; FreeContext(Proc); FreeEnvironment(Proc); ProcStrRemove(&Proc->ProcData->Commandline,&Proc->ProcData->CmdSize); ProcStrRemove(&Proc->ProcData->Executable,&Proc->ProcData->ExeSize); ProcStrRemove(&Proc->ProcData->WorkingDir,&Proc->ProcData->WDSize); ProcStrRemove(&Proc->ProcData->UserOptions,&Proc->ProcData->OptSize); ProcStrRemove(&Proc->ProcData->PluginOptions,&Proc->ProcData->PluginOptSize); free(Proc->ProcData); Proc->ProcData = 0; } void CopyProcData(HostData *dest,HostData *src) { TProcessData *d,*s; if(!src || !src->ProcData) { if(dest && dest->ProcData) FreeProcData(dest); return; } if(!dest->ProcData) { dest->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(dest->ProcData,0,sizeof(TProcessData)); } d = dest->ProcData; s = src->ProcData; d->LockIt = s->LockIt; d->PriorityClass = s->PriorityClass; d->LoadProfile = s->LoadProfile; ProcSetString(&d->Executable,s->Executable,&d->ExeSize); ProcSetString(&d->WorkingDir,s->WorkingDir,&d->WDSize); ProcSetString(&d->UserOptions,s->UserOptions,&d->OptSize); ProcSetString(&d->PluginOptions,s->PluginOptions,&d->PluginOptSize); if(s->Environment) { if(d->EnvAllocSize<s->EnvSize) { d->Environment=(char*)realloc(d->Environment,s->EnvSize); d->EnvAllocSize = s->EnvSize; } memcpy(d->Environment,s->Environment,s->EnvSize); d->EnvSize=s->EnvSize; } else if(d->Environment) FreeEnvironment(src); if(s->Context) { if(d->ContextSize!=s->ContextSize) { d->Context = realloc(d->Context,s->ContextSize); d->ContextSize = s->ContextSize; } memcpy(d->Context,s->Context,s->ContextSize); } else if(d->Context) FreeContext(dest); } __declspec(dllexport) void SetCommandline(HostData *Proc,char *commandline) { if(!Proc) return; if(!Proc->ProcData) { Proc->ProcData = (TProcessData*)malloc(sizeof(TProcessData)); memset(Proc->ProcData,0,sizeof(TProcessData)); } ProcSetString(&Proc->ProcData->Commandline,commandline,&Proc->ProcData->CmdSize); } }
__declspec(dllexport) char* GetEnvString(HostData *Proc,char *Name,char *value,DWORD *BufSize) { char *act, *pos; int res; DWORD lenAll,lenStName,lenGName,lenValue; if(!Proc || !Proc->ProcData) return 0; act=Proc->ProcData->Environment; if(value) *value=0; if(!Name) { return 0; } while(act&&*act) { lenAll=strlen(act); pos=strchr(act+1,'='); if(! pos) { act+=(lenAll+1); continue; } lenStName=(DWORD)(pos-act); lenGName=strlen(Name); res=strnicmp(act,Name,min(lenStName,lenGName)); if(!res) { if(lenStName > lenGName) res = 1; else if(lenStName < lenGName) res = -1; else { lenValue = strlen(pos+1)+1; if(value && lenValue<=*BufSize) strcpy(value,pos+1); *BufSize = lenValue; return act; } } if(res>0) { *BufSize = 0; return act; } act+=(lenAll+1); } *BufSize = 0; return act; }
function_block-full_function
[ { "content": "extern ADIOI_Flatlist_node *ADIOI_Flatlist;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 0, "score": 127407.15731490849 }, { "content": "extern MPI_Info *MPIR_Infotable;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 1, "score": 127396.53169566518 }, { "content": "extern ADIO_File *ADIOI_Ftable;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 2, "score": 127396.53169566518 }, { "content": "extern ADIO_Request *ADIOI_Reqtable;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 3, "score": 127396.53169566518 }, { "content": "extern int ADIOI_Ftable_ptr, ADIOI_Ftable_max;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 4, "score": 125363.62525090833 }, { "content": "extern int ADIOI_Reqtable_ptr, ADIOI_Reqtable_max;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 5, "score": 125363.62525090833 }, { "content": "extern int ADIOI_Direct_read, ADIOI_Direct_write;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 6, "score": 125363.62525090833 }, { "content": "extern int MPIR_Infotable_ptr, MPIR_Infotable_max;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 7, "score": 125363.62525090833 }, { "content": "extern ADIOI_Async_node *ADIOI_Async_avail_head, *ADIOI_Async_avail_tail;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 8, "score": 123394.57921801004 }, { "content": "extern ADIOI_Async_node *ADIOI_Async_list_head, *ADIOI_Async_list_tail; \n", "file_path": "romio/adio/include/adio_extern.h", "rank": 9, "score": 123394.57921801004 }, { "content": "extern MPI_Errhandler ADIOI_DFLT_ERR_HANDLER;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 10, "score": 123394.57921801004 }, { "content": "extern ADIOI_Req_node *ADIOI_Req_avail_head, *ADIOI_Req_avail_tail;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 11, "score": 123394.57921801004 }, { "content": "extern ADIOI_Malloc_req *ADIOI_Malloc_req_head, *ADIOI_Malloc_req_tail;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 12, "score": 123394.57921801004 }, { "content": "extern ADIOI_Malloc_async *ADIOI_Malloc_async_head, *ADIOI_Malloc_async_tail;\n", "file_path": "romio/adio/include/adio_extern.h", "rank": 13, "score": 123394.57921801004 }, { "content": "C\n", "file_path": "mpe/mpef.h", "rank": 14, "score": 121579.70511377504 }, { "content": "//---------------------------------------------------------------------------\n\nclass TIncludeForm : public TForm\n\n{\n\n__published:\t// IDE-verwaltete Komponenten\n\n\tTListBox *SelectedBox;\n\n\tTEdit *HostEdit;\n\n\tTButton *Button1;\n\n\tTButton *Button2;\n\n\tTButton *Button3;\n\n\tTLabel *Label1;\n\n\tTButton *Button4;\n\n\tvoid __fastcall FormShow(TObject *Sender);\n\n\tvoid __fastcall Button1Click(TObject *Sender);\n\n\tvoid __fastcall Button2Click(TObject *Sender);\n\n\tvoid __fastcall Button3Click(TObject *Sender);\n\n\tvoid __fastcall SelectedBoxDblClick(TObject *Sender);\n\n\t\n\n\tvoid __fastcall SelectedBoxKeyDown(TObject *Sender, WORD &Key,\n\n\tTShiftState Shift);\n\n\tvoid __fastcall FormCreate(TObject *Sender);\n\nprotected:\n", "file_path": "rexec/RexecShell/Include.h", "rank": 15, "score": 80801.78073224844 }, { "content": "", "file_path": "examples/basic/PiMfc/PiMfc.h", "rank": 16, "score": 77542.2655035066 }, { "content": "", "file_path": "examples/basic/PiMfc/PiMfcDlg.h", "rank": 17, "score": 77542.2655035066 }, { "content": "Module MPI\n\n!\n\n! \n\n! (C) 1993 by Argonne National Laboratory and Mississipi State University.\n\n! All rights reserved. See COPYRIGHT in top-level directory.\n\n!\n\n!\n\n! user include file for MPI programs, with no dependencies.\n\n! THIS IS AN UNTESTED F90 MODULE FILE. PLEASE SEND US ANY FIXES \n\n!\n\n! It really isn't possible to make a perfect include file that can\n\n! be used by both F77 and F90 compilers, but this is close. We've removed\n\n! continuation lines (allows free form input in F90); systems whose\n\n! Fortran compilers support ! instead of just C or * for comments can\n\n! globally replace a C in the first column with !; the resulting file\n\n! should work for both Fortran 77 and Fortran 90.\n\n!\n\n!\n\n! return codes \n\n Integer, parameter :: MPI_SUCCESS = 0, MPI_ERR_BUFFER=1,MPI_ERR_COUNT=2, &\n", "file_path": "include/mpif.f90", "rank": 18, "score": 74496.74385449744 }, { "content": " MPI_LXOR=108,MPI_BXOR=109,MPI_MINLOC=110, &\n\n MPI_MAXLOC=111, MPI_OP_NULL=0\n\n!\n\n Integer, parameter :: MPI_GROUP_EMPTY=90,MPI_COMM_WORLD=91,&\n\n MPI_COMM_SELF=92, MPI_TAG_UB=80,MPI_HOST=82,MPI_IO=84, &\n\n MPI_WTIME_IS_GLOBAL=86\n\n!\n\n Integer, parameter :: MPI_ANY_SOURCE = (-2), MPI_ANY_TAG = (-1)\n\n!\n\n Integer, parameter :: MPI_VERSION = 1, MPI_SUBVERSION = 1\n\n!\n\n! All other MPI routines are subroutines\n\n! This may cause some Fortran compilers to complain about defined and\n\n! not used. Such compilers should be improved.\n\n!\n\n double precision :: MPI_WTIME, MPI_WTICK\n\n external MPI_WTIME, MPI_WTICK\n\n!\n\n! The attribute copy/delete subroutines are symbols that can be passed\n\n! to MPI routines\n\n!\n\n external MPI_NULL_COPY_FN, MPI_NULL_DELETE_FN, MPI_DUP_FN\n\n\n\nEnd Module MPI\n", "file_path": "include/mpif.f90", "rank": 19, "score": 74491.64020826241 }, { "content": " MPI_ERR_TYPE=3, MPI_ERR_TAG=4, MPI_ERR_COMM=5, MPI_ERR_RANK=6, &\n\n MPI_ERR_ROOT=7,MPI_ERR_GROUP=8, MPI_ERR_OP=9,MPI_ERR_TOPOLOGY=10, &\n\n MPI_ERR_DIMS=11, MPI_ERR_ARG=12,MPI_ERR_UNKNOWN=13, &\n\n MPI_ERR_TRUNCATE=14,MPI_ERR_OTHER=15, MPI_ERR_INTERN=16, &\n\n MPI_ERR_IN_STATUS=17, MPI_ERR_PENDING=18, MPI_ERR_REQUEST=19, &\n\n MPI_ERR_LASTCODE=4114 \n\n!\n\n Integer, parameter :: MPI_UNDEFINED = (-32766)\n\n!\n\n Integer, parameter :: MPI_GRAPH = 1, MPI_CART = 2\n\n Integer, parameter :: MPI_PROC_NULL = (-1)\n\n!\n\n Integer, parameter :: MPI_BSEND_OVERHEAD = 512\n\n\n\n Integer, parameter :: MPI_SOURCE=2, MPI_TAG=3, MPI_ERROR=4\n\n Integer, parameter :: MPI_STATUS_SIZE=4\n\n Integer, parameter :: MPI_MAX_PROCESSOR_NAME=256\n\n Integer, parameter :: MPI_MAX_ERROR_STRING=512\n\n Integer, parameter :: MPI_MAX_NAME_STRING=63\n\n!\n", "file_path": "include/mpif.f90", "rank": 20, "score": 74487.88245014701 }, { "content": " Integer, parameter :: MPI_COMM_NULL=0\n\n!\n\n Integer, parameter :: MPI_DATATYPE_NULL = 0\n\n \n\n Integer, parameter :: MPI_ERRHANDLER_NULL = 0\n\n \n\n Integer, parameter :: MPI_GROUP_NULL = 0\n\n \n\n Integer, parameter :: MPI_KEYVAL_INVALID = 0\n\n \n\n Integer, parameter :: MPI_REQUEST_NULL = 0\n\n! \n\n Integer, parameter :: MPI_IDENT=0, MPI_CONGRUENT=1, MPI_SIMILAR=2, &\n\n MPI_UNEQUAL=3\n\n!\n\n! MPI_BOTTOM needs to be a known address; here we put it at the\n\n! beginning of the common block. The point-to-point and collective\n\n! routines know about MPI_BOTTOM, but MPI_TYPE_STRUCT as yet does not.\n\n!\n\n! The types MPI_INTEGER1,2,4 and MPI_REAL4,8 are OPTIONAL.\n", "file_path": "include/mpif.f90", "rank": 21, "score": 74487.88245014701 }, { "content": "! Their values are zero if they are not available. Note that\n\n! using these reduces the portability of code (though may enhance\n\n! portability between Crays and other systems)\n\n!\n\n Integer :: MPI_BOTTOM\n\n!\n\n Integer, parameter :: MPI_ERRORS_ARE_FATAL=119, MPI_ERRORS_RETURN=120\n\n!\n\n Integer, parameter :: MPI_COMPLEX=23,MPI_DOUBLE_COMPLEX=24,&\n\n MPI_LOGICAL=25, MPI_REAL=26,MPI_DOUBLE_PRECISION=27,MPI_INTEGER=28,&\n\n MPI_2INTEGER=29,MPI_2COMPLEX=30,MPI_2DOUBLE_COMPLEX=31,&\n\n MPI_2REAL=32,MPI_2DOUBLE_PRECISION=33,MPI_CHARACTER=1,&\n\n MPI_BYTE=3,MPI_UB=16,MPI_LB=15,MPI_PACKED=14\n\n\n\n Integer, parameter :: MPI_INTEGER1=0,MPI_INTEGER2=0,MPI_INTEGER4=0\n\n Integer, parameter :: MPI_REAL4=0,MPI_REAL8=0\n\n\n\n\n\n Integer, parameter :: MPI_MAX=100,MPI_MIN=101,MPI_SUM=102,MPI_PROD=103,&\n\n MPI_LAND=104,MPI_BAND=105,MPI_LOR=106,MPI_BOR=107, &\n", "file_path": "include/mpif.f90", "rank": 22, "score": 74487.88245014701 }, { "content": "//---------------------------------------------------------------------------\n\n#ifndef IncludeH\n\n#define IncludeH\n\n//---------------------------------------------------------------------------\n\n#include <vcl\\Classes.hpp>\n\n#include <vcl\\Controls.hpp>\n\n#include <vcl\\StdCtrls.hpp>\n\n#include <vcl\\Forms.hpp>\n\n\n\n#include \"NetState.h\"\n\n//---------------------------------------------------------------------------\n", "file_path": "rexec/RexecShell/Include.h", "rank": 23, "score": 73107.86341494322 }, { "content": "\tvoid __fastcall ParData(TMessage Message);\n\n \tBEGIN_MESSAGE_MAP\n\n \tMESSAGE_HANDLER(PAR_DATA,TMessage,ParData);\n\n MESSAGE_HANDLER(ENUM_START,TMessage,ParData);\n\n\t\tMESSAGE_HANDLER(ENUM_FINISH,TMessage,ParData);\n\n MESSAGE_HANDLER(REFRESH_START,TMessage,ParData);\n\n\t\tMESSAGE_HANDLER(REFRESH_FINISH,TMessage,ParData);\n\n \tEND_MESSAGE_MAP(TForm)\n\nprivate:\t// Benutzer-Deklarationen\n\n\tbool Disabled;\n\npublic:\t\t// Benutzer-Deklarationen\n\nTStringList *List;\n\n\t__fastcall TIncludeForm(TComponent* Owner);\n\n};\n\n//---------------------------------------------------------------------------\n\nextern TIncludeForm *IncludeForm;\n\n//---------------------------------------------------------------------------\n\n#endif\n", "file_path": "rexec/RexecShell/Include.h", "rank": 24, "score": 73107.48846385891 }, { "content": " // array of old signal handlers. \n\n struct sigaction oact[MAX_SIGNALS];\n\n\n\n // for GetExceptionInformation(). \n\n \n\n // is the handler for the signal(s) installed ?\n\n \n\n DWORD globalSignalMask;\n\n // When calling SetUnhandledExceptionFilter, a new signal handler\n\n // for all signals i with ((1<<i) & globalSignalMask) == (1<<i) is\n\n // installed.\n\n // See /usr/include/sys/signal.h for the signal codes. \n\n // For example, if you want to catch SIGSEGV's only, simply set\n\n // globalSignalMask to (1 << SIGSEGV) above.\n\n // See also MAX_SIGNALS above. \n\n};\n\n\n\n\n\nextern _UnixException UnixException;\n\n\n\n\n\n#endif\n", "file_path": "mpid/nt2unix/include/unixexception.h", "rank": 25, "score": 73106.24839983374 }, { "content": "#ifndef __UNIX_EXCEPTION_H__\n\n#define __UNIX_EXCEPTION_H__\n\n\n\n#define MAX_SIGNALS (SIGUSR2+1)\n\n\n", "file_path": "mpid/nt2unix/include/unixexception.h", "rank": 26, "score": 73099.9229852647 }, { "content": "#ifndef THREADSYNC_HEADER\n\n#define THREADSYNC_HEADER\n\n\n\n// A comfortable critical section object. \n", "file_path": "mpid/nt2unix/include/threadsync.h", "rank": 27, "score": 73099.9229852647 }, { "content": "//---------------------------------------------------------------------------\n\n#include <vcl\\vcl.h>\n\n#include <fstream.h>\n\n#include <dos.h>\n\n#pragma hdrstop\n\n\n\n#include \"Include.h\"\n\n#include \"NetState.h\"\n\n#include \"ParForm.h\"\n\n//---------------------------------------------------------------------------\n\n#pragma resource \"*.dfm\"\n\nTIncludeForm *IncludeForm;\n\n//---------------------------------------------------------------------------\n\n__fastcall TIncludeForm::TIncludeForm(TComponent* Owner)\n\n\t: TForm(Owner)\n\n{\n\n /*char filename[MAX_PATH];\n\n ifstream s;\n\n\n\n List=new TStringList;\n", "file_path": "rexec/RexecShell/Include.cpp", "rank": 28, "score": 71779.24213950809 }, { "content": " sprintf(filename,\"%sIncluded.rsh\",_argv[0]);\n\n /* does not work with CBuilder5 replace with SaveToFile\n\n s.open(filename);\n\n while(s.fail()&&res==IDRETRY) {\n\n\t\tres=Application->MessageBox(\"Could not open file Included.rsh\",\n\n \"File error\",MB_ICONERROR|MB_RETRYCANCEL);\n\n if(res==IDRETRY) s.open(filename);\n\n }\n\n for(int i=0;i<SelectedBox->Items->Count;i++) {\n\n \ts<<SelectedBox->Items->Strings[i]<<endl;\n\n }\n\n */\n\n SelectedBox->Items->SaveToFile(filename);\n\n}\n\n//---------------------------------------------------------------------------\n\nvoid __fastcall TIncludeForm::SelectedBoxDblClick(TObject *Sender)\n\n{\n\n\tint i=0;\n\n if(Disabled) {\n\n \tApplication->MessageBox(\"Cannot modify include list while refresh in progess\",\"Message\",\n", "file_path": "rexec/RexecShell/Include.cpp", "rank": 29, "score": 71771.17235554208 }, { "content": " \t sprintf(filename,\"%sIncluded.rsh\",_argv[0]);\n\n s.open(filename);\n\n \t if(!s.fail()) {\n\n \twhile(!s.eof()) {\n\n \t\ts>>filename;\n\n \t if(!filename[0]) continue;\n\n List->Add(filename);\n\n \t}\n\n \ts.close();\n\n \t}\n\n Disabled = false;\n\n if(ParWindow->Visible) ParWindow->FormShow(0); */\n\n}\n\n//---------------------------------------------------------------------------\n\nvoid __fastcall TIncludeForm::FormShow(TObject *Sender)\n\n{\n\n\tSelectedBox->Items->Assign(List);\n\n}\n\n//---------------------------------------------------------------------------\n\nvoid __fastcall TIncludeForm::Button1Click(TObject *Sender)\n", "file_path": "rexec/RexecShell/Include.cpp", "rank": 30, "score": 71768.53411336496 }, { "content": "void __fastcall TIncludeForm::FormCreate(TObject *Sender)\n\n{\n\n\tchar filename[MAX_PATH];\n\n ifstream s;\n\n\n\n List=new TStringList;\n\n \t sprintf(filename,\"%sIncluded.rsh\",_argv[0]);\n\n s.open(filename);\n\n \t if(!s.fail()) {\n\n \twhile(!s.eof()) {\n\n \t\ts>>filename;\n\n \t if(!filename[0]) continue;\n\n List->Add(filename);\n\n \t}\n\n \ts.close();\n\n \t}\n\n Disabled = false;\n\n if(ParWindow->Visible) ParWindow->FormShow(0);\n\n \n\n\tServers->RegisterClientWindow(Handle);\n", "file_path": "rexec/RexecShell/Include.cpp", "rank": 31, "score": 71767.64029032734 }, { "content": "{\n\n\tAnsiString Name = HostEdit->Text.Trim().UpperCase();\n\n\tif(Name.Length()>0 && SelectedBox->Items->IndexOf(Name)<0 &&\n\n Servers->IndexOf(Name.c_str())<0) {\n\n \tSelectedBox->Items->Add(Name);\n\n HostEdit->Text=\"\";\n\n }\n\n}\n\n//---------------------------------------------------------------------------\n\nvoid __fastcall TIncludeForm::Button2Click(TObject *Sender)\n\n{\n\n\tList->Assign(SelectedBox->Items);\n\n if(ParWindow->Visible) ParWindow->FormShow(0);\n\n}\n\n//---------------------------------------------------------------------------\n\nvoid __fastcall TIncludeForm::Button3Click(TObject *Sender)\n\n{\n\n\tofstream s;\n\n int res=IDRETRY;\n\n char filename[MAX_PATH];\n", "file_path": "rexec/RexecShell/Include.cpp", "rank": 32, "score": 71767.04757582025 }, { "content": "}\n\n\n\nvoid __fastcall TIncludeForm::ParData(TMessage Message) {\n\n\tswitch(Message.Msg) {\n\n case ENUM_START:\n\n case PAR_DATA:\n\n case REFRESH_START:\n\n \tDisabled = true;\n\n Button1->Enabled = false;\n\n break;\n\n\tdefault: Disabled = false;\n\n \t\t Button1->Enabled = true;\n\n }\n\n}\n\n//---------------------------------------------------------------------------", "file_path": "rexec/RexecShell/Include.cpp", "rank": 33, "score": 71766.76286540742 }, { "content": " \t\t\t\t\t\t MB_OK|MB_ICONWARNING);\n\n return;\n\n }\n\n\n\n SelectedBox->Items->BeginUpdate();\n\n while(SelectedBox->SelCount) {\n\n if(SelectedBox->Selected[i]) {\n\n Servers->Delete(Servers->IndexOf(SelectedBox->Items->Strings[i].c_str()));\n\n SelectedBox->Items->Delete(i);\n\n } else i++;\n\n }\n\n SelectedBox->Items->EndUpdate();\n\n}\n\n//---------------------------------------------------------------------------\n\nvoid __fastcall TIncludeForm::SelectedBoxKeyDown(TObject *Sender, WORD &Key,\n\n\tTShiftState Shift)\n\n{\n\n\tif(Key==46) SelectedBoxDblClick(this);\n\n}\n\n//---------------------------------------------------------------------------\n", "file_path": "rexec/RexecShell/Include.cpp", "rank": 34, "score": 71765.89258621981 }, { "content": "#include <mpi.h>\n\n\n\n#include <stdarg.h>\n\n#include \"mpi2c++/mpi2c++_map.h\"\n\n\n\n\n\n//JGS: this is used for implementing user functions for MPI::Op\n\nextern \"C\" void\n\nop_intercept(void *invec, void *outvec, int *len, MPI_Datatype *datatype);\n\n\n\n#if MPI2CPP_IBM_SP\n\n//Here's the sp2 typedeffrom their header file:\n\n// typedef void MPI_Handler_function(MPI_Comm *,int *,char *,int *,int *);\n\nextern \"C\" void\n\nerrhandler_intercept(MPI_Comm * mpi_comm, int * err, char*, int*, int*);\n\n\n\nextern \"C\" void\n\nthrow_excptn_fctn(MPI_Comm* comm, int* errcode, char*, int*, int*);\n\n\n\n#else\n", "file_path": "MPI-2-C++/src/mpi2c++/mpi++.h", "rank": 35, "score": 71719.98502444502 }, { "content": "// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n\n\n\n#include \"mpi++.h\"\n\n#if MPI2CPP_HPUX_OS & MPI2CPP_LAM61\n\n // #%$^#$%^#$%^$ LAM on HP'S!!!!\n\n#include <mpisys.h>\n\n#undef MIN\n\n#undef MAX\n\n#endif\n\n#include <stdio.h>\n\n\n\nextern \"C\" \n", "file_path": "MPI-2-C++/src/intercepts.cc", "rank": 36, "score": 71717.71002035802 }, { "content": "\n\n//JGS: this is used as the MPI_Handler_function for\n\n// the mpi_errhandler in ERRORS_THROW_EXCEPTIONS\n\nextern \"C\" void\n\nthrow_excptn_fctn(MPI_Comm* comm, int* errcode, ...);\n\n\n\nextern \"C\" void\n\nerrhandler_intercept(MPI_Comm * mpi_comm, int * err, ...);\n\n#endif\n\n\n\n\n\n//used for attr intercept functions\n", "file_path": "MPI-2-C++/src/mpi2c++/mpi++.h", "rank": 37, "score": 71715.87702669938 }, { "content": "// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n\n#ifndef MPIPP_H\n\n#define MPIPP_H\n\n\n\n// \n\n// Let's ensure that we're really in C++, and some errant programmer\n\n// hasn't included <mpi++.h> just \"for completeness\"\n\n//\n\n\n\n#if defined(__cplusplus) || defined(c_plusplus) \n\n\n\n#include \"mpi2c++_config.h\"\n", "file_path": "MPI-2-C++/src/mpi2c++/mpi++.h", "rank": 38, "score": 71712.93298395372 }, { "content": "// or the PMPI::XXX class based on the value of the macro _REAL_MPI_\n\n// which is set in mpi2c++_config.h.\n\n// If prototyping is enabled, there is a top layer that calls these\n\n// PMPI functions, and this top layer is in the XXX.cc files.\n\n//\n\n\n\n\n\n\n\n#include \"mpi2c++/datatype_inln.h\"\n\n#include \"mpi2c++/functions_inln.h\"\n\n#include \"mpi2c++/request_inln.h\"\n\n#include \"mpi2c++/comm_inln.h\"\n\n#include \"mpi2c++/intracomm_inln.h\"\n\n#include \"mpi2c++/topology_inln.h\"\n\n#include \"mpi2c++/intercomm_inln.h\"\n\n#include \"mpi2c++/group_inln.h\"\n\n#include \"mpi2c++/op_inln.h\"\n\n#include \"mpi2c++/errhandler_inln.h\"\n\n#include \"mpi2c++/status_inln.h\"\n\n\n\n#endif\n\n#endif\n", "file_path": "MPI-2-C++/src/mpi2c++/mpi++.h", "rank": 39, "score": 71712.35577192606 }, { "content": "#include \"mpi2c++/intercomm.h\"\n\n \n\n#if ! _MPIPP_USENAMESPACE_\n\nprivate:\n\n MPI() { }\n\n};\n\n#else\n\n}\n\n#endif\n\n\n\n#if _MPIPP_PROFILING_\n\n#include \"mpi2c++/pop_inln.h\"\n\n#include \"mpi2c++/pgroup_inln.h\"\n\n#include \"mpi2c++/pstatus_inln.h\"\n\n#include \"mpi2c++/prequest_inln.h\"\n\n#endif\n\n\n\n//\n\n// These are the \"real\" functions, whether prototyping is enabled\n\n// or not. These functions are assigned to either the MPI::XXX class\n", "file_path": "MPI-2-C++/src/mpi2c++/mpi++.h", "rank": 40, "score": 71712.01870125411 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/topology.cc", "rank": 41, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/intercomm.h", "rank": 42, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/pdatatype.h", "rank": 43, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/request.h", "rank": 44, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/intercomm.cc", "rank": 45, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/intracomm.cc", "rank": 46, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/pstatus.h", "rank": 47, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/pexception.h", "rank": 48, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/pmpi++.h", "rank": 49, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/prequest.h", "rank": 50, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/intercepts.cc", "rank": 51, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/topology.h", "rank": 52, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/request.cc", "rank": 53, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi++.cc", "rank": 54, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/exception.cc", "rank": 55, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/pintercomm.h", "rank": 56, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/pmpi++.cc", "rank": 57, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/comm.cc", "rank": 58, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/mpi++.h", "rank": 59, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/datatype.cc", "rank": 60, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/pop.h", "rank": 61, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/ptopology.h", "rank": 62, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/datatype.h", "rank": 63, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/status.h", "rank": 64, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/status.cc", "rank": 65, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/op.cc", "rank": 66, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/errhandler.cc", "rank": 67, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/mpi2c++/comm.h", "rank": 68, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/functions.cc", "rank": 69, "score": 71711.38589466465 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n", "file_path": "MPI-2-C++/src/group.cc", "rank": 70, "score": 71711.38589466465 }, { "content": "#if MPI2CPP_IBM_SP\n\n void throw_excptn_fctn(MPI_Comm *, int *errcode, char *, int *, int *)\n\n#else\n\n void throw_excptn_fctn(MPI_Comm *, int *errcode, ...)\n\n#endif\n\n{\n\n#if _MPIPP_USEEXCEPTIONS_\n\n throw(MPI::Exception(*errcode));\n\n#else\n\n // Ick. This is really ugly, but necesary if someone uses a C compiler\n\n // and -lmpi++ (which can legally happen in the LAM MPI implementation,\n\n // and probably in MPICH and others who include -lmpi++ by default in their\n\n // wrapper compilers)\n\n fprintf(stderr, \"MPI 2 C++ exception throwing is disabled, MPI::errno has the error code\\n\"); \n\n MPI::errno = *errcode;\n\n#endif \n\n}\n\n\n\n_REAL_MPI_::Comm::mpi_comm_map_t _REAL_MPI_::Comm::mpi_comm_map;\n\n_REAL_MPI_::Comm::mpi_err_map_t _REAL_MPI_::Comm::mpi_err_map;\n", "file_path": "MPI-2-C++/src/intercepts.cc", "rank": 71, "score": 71711.03408668411 }, { "content": "\n\n\n\nextern \"C\"\n\n#if MPI2CPP_IBM_SP\n\nvoid\n\nerrhandler_intercept(MPI_Comm *mpi_comm, int *err, char*, int*, int*)\n\n#else\n\nvoid\n\nerrhandler_intercept(MPI_Comm *mpi_comm, int *err, ...)\n\n#endif\n\n\n\n{\n\n _REAL_MPI_::Comm* comm = _REAL_MPI_::Comm::mpi_err_map[*mpi_comm];\n\n if (comm && comm->my_errhandler) {\n\n va_list ap;\n\n va_start(ap, err);\n\n comm->my_errhandler->handler_fn(*comm, err, ap);\n\n va_end(ap);\n\n }\n\n}\n", "file_path": "MPI-2-C++/src/intercepts.cc", "rank": 72, "score": 71710.96071605722 }, { "content": " graphcomm = _REAL_MPI_::Graphcomm(*comm_type->first);\n\n ret = copy_fn(graphcomm, keyval, extra_state,\n\n\t\t attribute_val_in, attribute_val_out, bflag);\n\n break;\n\n case eCartcomm:\n\n cartcomm = _REAL_MPI_::Cartcomm(*comm_type->first);\n\n ret = copy_fn(cartcomm, keyval, extra_state,\n\n\t\t attribute_val_in, attribute_val_out, bflag);\n\n break;\n\n }\n\n\n\n *flag = (int)bflag;\n\n return ret;\n\n}\n\n\n\nextern \"C\" int\n\ndelete_attr_intercept(MPI_Comm comm, int keyval, \n\n\t\t void *attribute_val, void *extra_state)\n\n{\n\n int ret = 0;\n", "file_path": "MPI-2-C++/src/intercepts.cc", "rank": 73, "score": 71710.5673755716 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"op.cc\"\n", "file_path": "MPI-2-C++/src/op.cpp", "rank": 74, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"group.cc\"\n", "file_path": "MPI-2-C++/src/group.cpp", "rank": 75, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"intercomm.cc\"\n", "file_path": "MPI-2-C++/src/intercomm.cpp", "rank": 76, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"comm.cc\"\n", "file_path": "MPI-2-C++/src/comm.cpp", "rank": 77, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"mpi++.cc\"\n", "file_path": "MPI-2-C++/src/mpi++.cpp", "rank": 78, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"errhandler.cc\"\n", "file_path": "MPI-2-C++/src/errhandler.cpp", "rank": 79, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"topology.cc\"\n", "file_path": "MPI-2-C++/src/topology.cpp", "rank": 80, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"pmpi++.cc\"\n", "file_path": "MPI-2-C++/src/pmpi++.cpp", "rank": 81, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"status.cc\"\n", "file_path": "MPI-2-C++/src/status.cpp", "rank": 82, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"intracomm.cc\"\n", "file_path": "MPI-2-C++/src/intracomm.cpp", "rank": 83, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"request.cc\"\n", "file_path": "MPI-2-C++/src/request.cpp", "rank": 84, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"exception.cc\"\n", "file_path": "MPI-2-C++/src/exception.cpp", "rank": 85, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"functions.cc\"\n", "file_path": "MPI-2-C++/src/functions.cpp", "rank": 86, "score": 71710.39697346752 }, { "content": "/* This file is required to make the .cc file compile with Microstoft Visual studio */\n\n#include \"datatype.cc\"\n", "file_path": "MPI-2-C++/src/datatype.cpp", "rank": 87, "score": 71710.39697346752 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/intracomm.h", "rank": 88, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/perrhandler.h", "rank": 89, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/errhandler.h", "rank": 90, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/pgroup.h", "rank": 91, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/group.h", "rank": 92, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/exception.h", "rank": 93, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/pintracomm.h", "rank": 94, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/pcomm.h", "rank": 95, "score": 71710.36560736572 }, { "content": "// -*- c++ -*-\n\n//\n\n// Copyright 1997-2000, University of Notre Dame.\n\n// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and\n\n// Andrew Lumsdaine\n\n// \n\n// This file is part of the Notre Dame C++ bindings for MPI.\n\n// \n\n// You should have received a copy of the License Agreement for the Notre\n\n// Dame C++ bindings for MPI along with the software; see the file\n\n// LICENSE. If not, contact Office of Research, University of Notre\n\n// Dame, Notre Dame, IN 46556.\n\n// \n\n// Permission to modify the code and to distribute modified code is\n\n// granted, provided the text of this NOTICE is retained, a notice that\n\n// the code was modified is included with the above COPYRIGHT NOTICE and\n\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n\n// file is distributed with the modified code.\n\n// \n\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n\n// By way of example, but not limitation, Licensor MAKES NO\n\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n\n// OR OTHER RIGHTS.\n\n// \n\n// Additional copyrights may follow.\n\n//\n\n\n", "file_path": "MPI-2-C++/src/mpi2c++/op.h", "rank": 96, "score": 71710.36560736572 }, { "content": "//---------------------------------------------------------------------------\n\n#include <vcl\\vcl.h>\n\n#pragma hdrstop\n\n\n\n#include <malloc.h>\n\n#include \"Details.h\"\n\n#include \"NetState.h\"\n\n#include \"PluginManager.h\"\n\n#include \"ProcWindow.h\"\n\n\n\n#if (BCBVER > 1)\n\n //CBuilder5\n\n #include <stdio.h>\n\n#endif\n\n\n\n\n\n//---------------------------------------------------------------------------\n\n#pragma resource \"*.dfm\"\n\nTDetailForm *DetailForm;\n\nextern \"C\" char *GetHostAccountName(HostData *Server,char *buffer,DWORD size);\n", "file_path": "rexec/RexecShell/Details.cpp", "rank": 97, "score": 28.407635722522635 }, { "content": "//---------------------------------------------------------------------------\n\n\n\n#if (!(BCBVER > 1))\n\n\t//CBuilder1\n\n\t#include <vcl\\shlobj.hpp>\n\n#else\n\n\t//CBuilder5\n\n #define NO_WIN32_LEAN_AND_MEAN\n\n #include \"shlobj.h\"\n\n#endif\n\n\n\n#include <vcl\\vcl.h>\n\n\n\n#pragma hdrstop \n\n\n\n#include \"IndividualConfig.h\"\n\n#include \"PluginManager.h\"\n\n#include \"Environment.h\"\n\n#include \"RexecClient.h\"\n\n#include \"ConfigDlg.h\" \n", "file_path": "rexec/RexecShell/IndividualConfig.cpp", "rank": 98, "score": 25.673741676861937 } ]
C++
image_processing/toolbox/classify/private/multiclassQuantizedTreeTrain1.cpp
bruceli-rw0/edge2pic-generation
e9ee6f89361d1a12b044c0ab665a09fca4a47089
#include <string.h> #include <stdint.h> #include <math.h> #include <mex.h> #include <iostream> #include <vector> #ifdef USEOMP #include <omp.h> #endif typedef unsigned char uint8; typedef unsigned int uint32; #define gini(p) p*p void constructCdfPerClass( uint8* data, uint32 *hs, float *wts, int nBins, int N, uint32 *dids, std::vector<std::vector<double> >& cdfs ) { for(int i=0; i<N; i++) { cdfs[hs[dids[i]]-1][data[dids[i]]] += wts[dids[i]]; } for (int h=0; h<cdfs.size(); h++) for(int i=1; i<nBins; i++) cdfs[h][i] += cdfs[h][i-1]; } void constructCdf( uint8* data, float *wts, int nBins, int N, uint32 *dids, std::vector<double>& cdf ) { for(int i=0; i<N; i++) cdf[data[dids[i]]] += wts[dids[i]]; for(int i=1; i<nBins; i++) cdf[i] += cdf[i-1]; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int H, N, N1, F1, F, split; uint8 *data; uint32* fids, *dids; float *wts, thr; double gain; uint32 *hs; double cfactor, *costs_factor; int nBins, nThreads; data = (uint8*) mxGetData(prhs[0]); hs = (uint32*) mxGetData(prhs[1]); wts = (float*) mxGetData(prhs[2]); nBins = (int) mxGetScalar(prhs[3]); dids = (uint32*) mxGetData(prhs[4]); fids = (uint32*) mxGetData(prhs[5]); H = (int) mxGetScalar(prhs[6]); split = (int) mxGetScalar(prhs[7]); costs_factor = (double*) mxGetData(prhs[8]); nThreads = (int) mxGetScalar(prhs[9]); N = (int) mxGetM(prhs[0]); F = (int) mxGetN(prhs[0]); N1 = (int) mxGetNumberOfElements(prhs[4]); F1 = (int) mxGetNumberOfElements(prhs[5]); plhs[0] = mxCreateNumericMatrix(1,F1,mxDOUBLE_CLASS,mxREAL); plhs[1] = mxCreateNumericMatrix(1,F1,mxDOUBLE_CLASS,mxREAL); plhs[2] = mxCreateNumericMatrix(1,F1,mxDOUBLE_CLASS,mxREAL); double *split_val = (double*) mxGetData(plhs[0]); double *thrs = (double*) mxGetData(plhs[1]); double *gains = (double*) mxGetData(plhs[2]); double vInit, w, g; std::vector<double> W(H, 0.0); vInit = 0; g = 0; w = 0; for(int j=0; j<N1; j++ ) { w+=wts[dids[j]]; W[hs[dids[j]]-1]+=wts[dids[j]]; } for(int i=0; i<H; i++ ) g+=gini((W[i]*costs_factor[i])/w); vInit=(1.-g); #ifdef USEOMP nThreads = std::min(nThreads,omp_get_max_threads()); #pragma omp parallel for num_threads(nThreads) #endif for(int i=0; i<F1; i++ ) { double wl, wr, gl, gr, v, pl, pr; double best = vInit; uint8* data1 = (uint8*)(data + (fids[i]*size_t(N))); std::vector<double> cdf(nBins, 0.0); std::vector<std::vector<double> > cdfs(H, cdf); constructCdfPerClass(data1,hs,wts,nBins,N1,dids,cdfs); constructCdf(data1,wts,nBins,N1,dids,cdf); for(int j=0; j<nBins-1; j++) { gl = 0.; gr = 0.; wl = cdf[j]; wr = cdf[nBins-1] - cdf[j]; for (int h=0; h<H; h++) { cfactor = costs_factor[h]; pl = (cdfs[h][j]); pl *= cfactor; pr = ((cdfs[h][nBins-1]-cdfs[h][j])); pr *= cfactor; gl += gini(pl); gr += gini(pr); } v = (wl-(gl/wl))/w + (wr-(gr/wr))/w; if( v<best ) { best = v; split_val[i] = best; gains[i] = vInit - best; thrs[i] = j; } } } }
#include <string.h> #include <stdint.h> #include <math.h> #include <mex.h> #include <iostream> #include <vector> #ifdef USEOMP #include <omp.h> #endif typedef unsigned char uint8; typedef unsigned int uint32; #define gini(p) p*p void constructCdfPerClass( uint8* data, uint32 *hs, float *wts, int nBins, int N, uint32 *dids, std::vector<std::vector<double> >& cdfs ) { for(int i=0; i<N; i++) { cdfs[hs[dids[i]]-1][data[dids[i]]] += wts[dids[i]]; } for (int h=0; h<cdfs.size(); h++) for(int i=1; i<nBins; i++) cdfs[h][i] += cdfs[h][i-1]; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int H, N, N1, F1, F, split; uint8 *data; uint32* fids, *dids; float *wts, thr; double gain; uint32 *hs; double cfactor, *costs_factor; int nBins, nThreads; data = (uint8*) mxGetData(prhs[0]); hs = (uint32*) mxGetData(prhs[1]); wts = (float*) mxGetData(prhs[2]); nBins = (int) mxGetScalar(prhs[3]); dids = (uint32*) mxGetData(prhs[4]); fids = (uint32*) mxGetData(prhs[5]); H = (int) mxGetScalar(prhs[6]); split = (int) mxGetScalar(prhs[7]); costs_factor = (double*) mxGetData(prhs[8]); nThreads = (int) mxGetScalar(prhs[9]); N = (int) mxGetM(prhs[0]); F = (int) mxGetN(prhs[0]); N1 = (int) mxGetNumberOfElements(prhs[4]); F1 = (int) mxGetNumberOfElements(prhs[5]); plhs[0] = mxCreateNumericMatrix(1,F1,mxDOUBLE_CLASS,mxREAL); plhs[1] = mxCreateNumericMatrix(1,F1,mxDOUBLE_CLASS,mxREAL); plhs[2] = mxCreateNumericMatrix(1,F1,mxDOUBLE_CLASS,mxREAL); double *split_val = (double*) mxGetData(plhs[0]); double *thrs = (double*) mxGetData(plhs[1]); double *gains = (double*) mxGetData(plhs[2]); double vInit, w, g; std::vector<double> W(H, 0.0); vInit = 0; g = 0; w = 0; for(int j=0; j<N1; j++ ) { w+=wts[dids[j]]; W[hs[dids[j]]-1]+=wts[dids[j]]; } for(int i=0; i<H; i++ ) g+=gini((W[i]*costs_factor[i])/w); vInit=(1.-g); #ifdef USEOMP nThreads = std::min(nThreads,omp_get_max_threads()); #pragma omp parallel for num_threads(nThreads) #endif for(int i=0; i<F1; i++ ) { double wl, wr, gl, gr, v, pl, pr; double best = vInit; uint8* data1 = (uint8*)(data + (fids[i]*size_t(N))); std::vector<double> cdf(nBins, 0.0); std::vector<std::vector<double> > cdfs(H, cdf); constructCdfPerClass(data1,hs,wts,nBins,N1,dids,cdfs); constructCdf(data1,wts,nBins,N1,dids,cdf); for(int j=0; j<nBins-1; j++) { gl = 0.; gr = 0.; wl = cdf[j]; wr = cdf[nBins-1] - cdf[j]; for (int h=0; h<H; h++) { cfactor = costs_factor[h]; pl = (cdfs[h][j]); pl *= cfactor; pr = ((cdfs[h][nBins-1]-cdfs[h][j])); pr *= cfactor; gl += gini(pl); gr += gini(pr); } v = (wl-(gl/wl))/w + (wr-(gr/wr))/w; if( v<best ) { best = v; split_val[i] = best; gains[i] = vInit - best; thrs[i] = j; } } } }
void constructCdf( uint8* data, float *wts, int nBins, int N, uint32 *dids, std::vector<double>& cdf ) { for(int i=0; i<N; i++) cdf[data[dids[i]]] += wts[dids[i]]; for(int i=1; i<nBins; i++) cdf[i] += cdf[i-1]; }
function_block-full_function
[ { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.01\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"string.h\"\n\n#include \"mex.h\"\n\n#include \"../../channels/private/sse.hpp\"\n\n\n\n// run nIter iterations of Horn & Schunk optical flow (alters Vx, Vy)\n\nvoid opticalFlowHsMex( float *Vx, float *Vy, const float *Ex, const float *Ey,\n\n const float *Et, const float *Z, const int h, const int w, const int nIter )\n\n{\n\n int x, y, x1, i, t, s; float my, mx, m, *Vx0, *Vy0;\n\n s=w*h*sizeof(float); Vx0=new float[s]; Vy0=new float[s];\n\n for( t=0; t<nIter; t++ ) {\n\n memcpy(Vx0,Vx,s); memcpy(Vy0,Vy,s);\n\n for( x=1; x<w-1; x++ ) {\n\n // do as much work as possible in SSE (assume non-aligned memory)\n\n for( y=1; y<h-4; y+=4 ) {\n", "file_path": "image_processing/toolbox/videos/private/opticalFlowHsMex.cpp", "rank": 0, "score": 30331.836670482426 }, { "content": " delete [] Vx0; delete [] Vy0;\n\n}\n\n\n\n// [Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter); - helper for opticalFlow\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n size_t h, w, nIter; float *Is[4], *Vx, *Vy;\n\n\n\n // Error checking on arguments\n\n if( nrhs!=5 ) mexErrMsgTxt(\"Five inputs expected.\");\n\n if( nlhs!=2 ) mexErrMsgTxt(\"Two outputs expected.\");\n\n h = mxGetM(prhs[0]); w = mxGetN(prhs[0]);\n\n for( int i=0; i<4; i++ ) {\n\n if(mxGetM(prhs[i])!=h || mxGetN(prhs[i])!=w) mexErrMsgTxt(\"Invalid dims.\");\n\n if(mxGetClassID(prhs[i])!=mxSINGLE_CLASS) mexErrMsgTxt(\"Invalid type.\");\n\n Is[i] = (float*) mxGetData(prhs[i]);\n\n }\n\n nIter = (int) mxGetScalar(prhs[4]);\n\n\n\n // create output matricies\n\n plhs[0] = mxCreateNumericMatrix(int(h),int(w),mxSINGLE_CLASS,mxREAL);\n\n plhs[1] = mxCreateNumericMatrix(int(h),int(w),mxSINGLE_CLASS,mxREAL);\n\n Vx = (float*) mxGetData(plhs[0]);\n\n Vy = (float*) mxGetData(plhs[1]);\n\n\n\n // run optical flow\n\n opticalFlowHsMex(Vx,Vy,Is[0],Is[1],Is[2],Is[3],int(h),int(w),nIter);\n\n}\n", "file_path": "image_processing/toolbox/videos/private/opticalFlowHsMex.cpp", "rank": 1, "score": 30331.694838383755 }, { "content": " x1=x*h; i=x1+y; __m128 _mx, _my, _m;\n\n _my=MUL(ADD(LDu(Vy0[x1-h+y]),LDu(Vy0[x1+h+y]),\n\n LDu(Vy0[x1+y-1]),LDu(Vy0[x1+y+1])),.25f);\n\n _mx=MUL(ADD(LDu(Vx0[x1-h+y]),LDu(Vx0[x1+h+y]),\n\n LDu(Vx0[x1+y-1]),LDu(Vx0[x1+y+1])),.25f);\n\n _m=MUL(ADD(MUL(LDu(Ey[i]),_my),MUL(LDu(Ex[i]),_mx),\n\n LDu(Et[i])),LDu(Z[i]));\n\n STRu(Vx[i],SUB(_mx,MUL(LDu(Ex[i]),_m)));\n\n STRu(Vy[i],SUB(_my,MUL(LDu(Ey[i]),_m)));\n\n }\n\n // do remainder of work in regular loop\n\n for( ; y<h-1; y++ ) {\n\n x1=x*h; i=x1+y;\n\n mx=.25f*(Vx0[x1-h+y]+Vx0[x1+h+y]+Vx0[x1+y-1]+Vx0[x1+y+1]);\n\n my=.25f*(Vy0[x1-h+y]+Vy0[x1+h+y]+Vy0[x1+y-1]+Vy0[x1+y+1]);\n\n m = (Ex[i]*mx + Ey[i]*my + Et[i])*Z[i];\n\n Vx[i]=mx-Ex[i]*m; Vy[i]=my-Ey[i]*m;\n\n }\n\n }\n\n }\n", "file_path": "image_processing/toolbox/videos/private/opticalFlowHsMex.cpp", "rank": 2, "score": 30317.968270484038 }, { "content": "def define_G(\n\n input_nc, \n\n output_nc, \n\n ngf, \n\n netG, \n\n norm='batch', \n\n use_dropout=False, \n\n init_type='normal', \n\n init_gain=0.02, \n\n device='cpu',\n\n gpu_ids=[]\n\n):\n\n \"\"\"Create a generator\n\n\n\n Parameters:\n\n input_nc (int) -- the number of channels in input images\n\n output_nc (int) -- the number of channels in output images\n\n ngf (int) -- the number of filters in the last conv layer\n\n netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128\n\n norm (str) -- the name of normalization layers used in the network: batch | instance | none\n\n use_dropout (bool) -- if use dropout layers.\n\n init_type (str) -- the name of our initialization method.\n\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n\n\n Returns a generator\n\n\n\n Our current implementation provides two types of generators:\n\n U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)\n\n The original U-Net paper: https://arxiv.org/abs/1505.04597\n\n\n\n Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)\n\n Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).\n\n\n\n\n\n The generator has been initialized by <init_net>. It uses RELU for non-linearity.\n\n \"\"\"\n\n net = None\n\n norm_layer = get_norm_layer(norm_type=norm)\n\n\n\n if netG == 'resnet_9blocks':\n\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n\n elif netG == 'resnet_6blocks':\n\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)\n\n elif netG == 'unet_128':\n\n net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n\n elif netG == 'unet_256':\n\n net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n\n else:\n\n raise NotImplementedError('Generator model name [%s] is not recognized' % netG)\n", "file_path": "generator/models/networks.py", "rank": 3, "score": 29372.622313294178 }, { "content": "def define_D(\n\n input_nc, \n\n ndf, \n\n netD, \n\n n_layers_D=3, \n\n norm='batch', \n\n init_type='normal', \n\n init_gain=0.02, \n\n device='cpu',\n\n gpu_ids=[]\n\n):\n\n \"\"\"Create a discriminator\n\n\n\n Parameters:\n\n input_nc (int) -- the number of channels in input images\n\n ndf (int) -- the number of filters in the first conv layer\n\n netD (str) -- the architecture's name: basic | n_layers | pixel\n\n n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'\n\n norm (str) -- the type of normalization layers used in the network.\n\n init_type (str) -- the name of the initialization method.\n\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n\n\n Returns a discriminator\n\n\n\n Our current implementation provides three types of discriminators:\n\n [basic]: 'PatchGAN' classifier described in the original pix2pix paper.\n\n It can classify whether 70×70 overlapping patches are real or fake.\n\n Such a patch-level discriminator architecture has fewer parameters\n\n than a full-image discriminator and can work on arbitrarily-sized images\n\n in a fully convolutional fashion.\n\n\n\n [n_layers]: With this mode, you can specify the number of conv layers in the discriminator\n\n with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)\n\n\n\n [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.\n\n It encourages greater color diversity but has no effect on spatial statistics.\n\n\n\n The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.\n\n \"\"\"\n\n net = None\n\n norm_layer = get_norm_layer(norm_type=norm)\n\n\n\n if netD == 'basic': # default PatchGAN classifier\n\n net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)\n\n elif netD == 'n_layers': # more options\n\n net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)\n\n elif netD == 'pixel': # classify if each pixel is real or fake\n\n net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)\n\n else:\n\n raise NotImplementedError('Discriminator model name [%s] is not recognized' % netD)\n", "file_path": "generator/models/networks.py", "rank": 4, "score": 29372.582305811564 }, { "content": "class NLayerDiscriminator(nn.Module):\n\n \"\"\"Defines a PatchGAN discriminator\"\"\"\n\n\n\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):\n\n \"\"\"Construct a PatchGAN discriminator\n\n\n\n Parameters:\n\n input_nc (int) -- the number of channels in input images\n\n ndf (int) -- the number of filters in the last conv layer\n\n n_layers (int) -- the number of conv layers in the discriminator\n\n norm_layer -- normalization layer\n\n \"\"\"\n\n super().__init__()\n\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n\n use_bias = norm_layer.func == nn.InstanceNorm2d\n\n else:\n\n use_bias = norm_layer == nn.InstanceNorm2d\n\n\n\n kw = 4\n\n padw = 1\n\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n\n nf_mult = 1\n\n nf_mult_prev = 1\n\n for n in range(1, n_layers): # gradually increase the number of filters\n\n nf_mult_prev = nf_mult\n\n nf_mult = min(2 ** n, 8)\n\n sequence += [\n\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n\n norm_layer(ndf * nf_mult),\n\n nn.LeakyReLU(0.2, True)\n\n ]\n\n\n\n nf_mult_prev = nf_mult\n\n nf_mult = min(2 ** n_layers, 8)\n\n sequence += [\n\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n\n norm_layer(ndf * nf_mult),\n\n nn.LeakyReLU(0.2, True)\n\n ]\n\n\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map\n\n self.model = nn.Sequential(*sequence)\n\n\n\n def forward(self, input):\n\n \"\"\"Standard forward.\"\"\"\n", "file_path": "generator/models/networks.py", "rank": 5, "score": 28514.380025527895 }, { "content": " def _getABImageData(self, path):\n\n # read image from path\n\n AB = Image.open(path).convert('RGB')\n\n # split AB image into A and B\n\n w, h = AB.size\n\n w2 = int(w / 2)\n\n edge = AB.crop((0, 0, w2, h))\n\n image = AB.crop((w2, 0, w, h))\n\n return {\n\n 'A': self.transform(edge), \n\n 'B': self.transform(image),\n\n 'A_path': path\n\n } if self.direction == 'AtoB' else {\n\n 'A': self.transform(image), \n\n 'B': self.transform(edge),\n\n 'A_path': path\n", "file_path": "generator/datasets.py", "rank": 6, "score": 28510.385883854837 }, { "content": " def _getImageEdgeData(self, path):\n\n pathe, pathi = path\n\n edge = Image.open(pathe).convert('RGB')\n\n image = Image.open(pathi).convert('RGB')\n\n return {\n\n 'A': self.transform(edge), \n\n 'B': self.transform(image),\n\n 'A_path': pathe\n\n } if self.direction == 'AtoB' else {\n\n 'A': self.transform(image), \n\n 'B': self.transform(edge),\n\n 'A_path': pathi\n", "file_path": "generator/datasets.py", "rank": 7, "score": 28510.385883854837 }, { "content": "function readInt($file)\n\n{\n\n $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));\n\n $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));\n\n return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;\n\n}\n\n\n", "file_path": "image_processing/toolbox/external/m2html/templates/brain/doxysearch.php", "rank": 8, "score": 28498.97361437684 }, { "content": "function readInt($file)\n\n{\n\n $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));\n\n $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));\n\n return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;\n\n}\n\n\n", "file_path": "image_processing/toolbox/external/m2html/templates/blue/doxysearch.php", "rank": 9, "score": 28498.97361437684 }, { "content": "function readInt($file)\n\n{\n\n $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));\n\n $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));\n\n return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;\n\n}\n\n\n", "file_path": "image_processing/toolbox/external/m2html/templates/frame/doxysearch.php", "rank": 10, "score": 28498.97361437684 }, { "content": "def define_D(\n\n input_nc, \n\n ndf, \n\n n_layers_D, \n\n num_D=1, \n\n norm='instance', \n\n init_type='normal', \n\n init_gain=0.02, \n\n use_sigmoid=False, \n\n getIntermFeat=False, \n\n device='cpu',\n\n gpu_ids=[],\n\n):\n\n norm_layer = get_norm_layer(norm_type=norm)\n\n netD = MultiscaleDiscriminator(input_nc, ndf, n_layers_D, norm_layer, use_sigmoid, num_D, getIntermFeat)\n", "file_path": "generator/models/networksHD.py", "rank": 11, "score": 28487.80868627176 }, { "content": "def define_G(\n\n input_nc, \n\n output_nc, \n\n ngf, \n\n netG, \n\n n_downsample_global=3, \n\n n_blocks_global=9, \n\n n_local_enhancers=1, \n\n n_blocks_local=3, \n\n norm='instance', \n\n init_type='normal', \n\n init_gain=0.02, \n\n device='cpu',\n\n gpu_ids=[]\n\n):\n\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netG == 'global':\n\n netG = GlobalGenerator(input_nc, output_nc, ngf, n_downsample_global, n_blocks_global, norm_layer)\n\n elif netG == 'local':\n\n netG = LocalEnhancer(input_nc, output_nc, ngf, n_downsample_global, n_blocks_global, n_local_enhancers, n_blocks_local, norm_layer)\n\n elif netG == 'encoder':\n\n netG = Encoder(input_nc, output_nc, ngf, n_downsample_global, norm_layer)\n\n else:\n\n raise('generator not implemented!')\n", "file_path": "generator/models/networksHD.py", "rank": 12, "score": 28487.80868627176 }, { "content": "class NLayerDiscriminator(nn.Module):\n\n def __init__(\n\n self, \n\n input_nc, \n\n ndf=64, \n\n n_layers=3, \n\n norm_layer=nn.BatchNorm2d, \n\n use_sigmoid=False, \n\n getIntermFeat=False\n\n ):\n\n super().__init__()\n\n self.getIntermFeat = getIntermFeat\n\n self.n_layers = n_layers\n\n\n\n kw = 4\n\n padw = int(np.ceil((kw-1.0)/2))\n\n sequence = [[\n\n nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), \n\n nn.LeakyReLU(0.2, True)\n\n ]]\n\n\n\n nf = ndf\n\n for n in range(1, n_layers):\n\n nf_prev = nf\n\n nf = min(nf * 2, 512)\n\n sequence += [[\n\n nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw),\n\n norm_layer(nf), \n\n nn.LeakyReLU(0.2, True)\n\n ]]\n\n\n\n nf_prev = nf\n\n nf = min(nf * 2, 512)\n\n sequence += [[\n\n nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw),\n\n norm_layer(nf),\n\n nn.LeakyReLU(0.2, True)\n\n ]]\n\n\n\n sequence += [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]]\n\n\n\n if use_sigmoid:\n\n sequence += [[nn.Sigmoid()]]\n\n\n\n if getIntermFeat:\n\n for n in range(len(sequence)):\n\n setattr(self, 'model'+str(n), nn.Sequential(*sequence[n]))\n\n else:\n\n sequence_stream = []\n\n for n in range(len(sequence)):\n\n sequence_stream += sequence[n]\n\n self.model = nn.Sequential(*sequence_stream)\n\n\n\n def forward(self, input):\n\n if self.getIntermFeat:\n\n res = [input]\n\n for n in range(self.n_layers+2):\n\n model = getattr(self, 'model'+str(n))\n\n res.append(model(res[-1]))\n\n return res[1:]\n\n else:\n", "file_path": "generator/models/networksHD.py", "rank": 13, "score": 27680.02327561431 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version NEW\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned char uint8;\n\ntypedef unsigned int uint32;\n\n#define min(x,y) ((x) < (y) ? (x) : (y))\n\n\n\n// construct cdf given data vector and wts\n\nvoid constructCdf( uint8* data, float *wts, int nBins,\n\n int N, int M, uint32 *ord, float *cdf )\n\n{\n\n int i; for( i=0; i<nBins; i++) cdf[i]=0;\n\n if(M) for( i=0; i<M; i++) cdf[data[ord[i]]] += wts[i];\n", "file_path": "image_processing/toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 14, "score": 34.95494210205236 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.24\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned char uint8;\n\ntypedef unsigned int uint32;\n\n#define min(x,y) ((x) < (y) ? (x) : (y))\n\n\n\ntemplate<typename T>\n\nvoid forestInds( uint32 *inds, const T *data, const T *thrs,\n\n const uint32 *fids, const uint32 *child, int N, int nThreads )\n\n{\n\n #ifdef USEOMP\n\n nThreads = min(nThreads,omp_get_max_threads());\n", "file_path": "image_processing/toolbox/classify/private/forestInds.cpp", "rank": 17, "score": 25.752049337655603 }, { "content": " - 1.72587999f / (0.3520887068f + mx.f);\n\n}\n\n\n\n// perform actual computation\n\nvoid forestFindThr( int H, int N, int F, const float *data,\n\n const uint32 *hs, const float *ws, const uint32 *order, const int split,\n\n uint32 &fid, float &thr, double &gain )\n\n{\n\n double *Wl, *Wr, *W; float *data1; uint32 *order1;\n\n int i, j, j1, j2, h; double vBst, vInit, v, w, wl, wr, g, gl, gr;\n\n Wl=new double[H]; Wr=new double[H]; W=new double[H];\n\n // perform initialization\n\n vBst = vInit = 0; g = 0; w = 0; fid = 1; thr = 0;\n\n for( i=0; i<H; i++ ) W[i] = 0;\n\n for( j=0; j<N; j++ ) { w+=ws[j]; W[hs[j]-1]+=ws[j]; }\n\n if( split==0 ) { for( i=0; i<H; i++ ) g+=gini(W[i]); vBst=vInit=(1-g/w/w); }\n\n if( split==1 ) { for( i=0; i<H; i++ ) g+=entropy(W[i]); vBst=vInit=g/w; }\n\n // loop over features, then thresholds (data is sorted by feature value)\n\n for( i=0; i<F; i++ ) {\n\n order1=(uint32*) order+i*N; data1=(float*) data+i*size_t(N);\n", "file_path": "image_processing/toolbox/classify/private/forestFindThr.cpp", "rank": 18, "score": 24.662785989596347 }, { "content": " v = - wl/w*wr/w*g*g;\n\n }\n\n if( v<vBst && data1[j2]-data1[j1]>=1e-6f ) {\n\n vBst=v; fid=i+1; thr=0.5f*(data1[j1]+data1[j2]); }\n\n }\n\n }\n\n delete [] Wl; delete [] Wr; delete [] W; gain = vInit-vBst;\n\n}\n\n\n\n// [fid,thr,gain] = mexFunction(data,hs,ws,order,H,split);\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n int H, N, F, split; float *data, *ws, thr;\n\n double gain; uint32 *hs, *order, fid;\n\n data = (float*) mxGetData(prhs[0]);\n\n hs = (uint32*) mxGetData(prhs[1]);\n\n ws = (float*) mxGetData(prhs[2]);\n\n order = (uint32*) mxGetData(prhs[3]);\n\n H = (int) mxGetScalar(prhs[4]);\n\n split = (int) mxGetScalar(prhs[5]);\n\n N = (int) mxGetM(prhs[0]);\n\n F = (int) mxGetN(prhs[0]);\n\n forestFindThr(H,N,F,data,hs,ws,order,split,fid,thr,gain);\n\n plhs[0] = mxCreateDoubleScalar(fid);\n\n plhs[1] = mxCreateDoubleScalar(thr);\n\n plhs[2] = mxCreateDoubleScalar(gain);\n\n}\n", "file_path": "image_processing/toolbox/classify/private/forestFindThr.cpp", "rank": 20, "score": 22.415207879088058 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.21\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"mex.h\"\n\n#include <vector>\n\n#include <cmath>\n\n#include <iostream>\n\nusing namespace std;\n\n\n\ntypedef unsigned int uint32;\n\n\n\ninline void getChild( float *chns1, uint32 *cids, uint32 *fids,\n\n float *thrs, uint32 offset, uint32 &k0, uint32 &k )\n\n{\n\n float ftr = chns1[cids[fids[k]]];\n\n k = (ftr<thrs[k]) ? 1 : 2;\n\n k0=k+=k0*2; k+=offset;\n\n}\n", "file_path": "image_processing/toolbox/detector/private/acfDetect1.cpp", "rank": 21, "score": 21.52742837938213 }, { "content": " else for( i=0; i<N; i++) cdf[data[i]] += wts[i];\n\n for(i=1; i<nBins; i++) cdf[i]+=cdf[i-1];\n\n}\n\n\n\n// [errs,thrs] = mexFunction( data0, data1, wts0, wts1,\n\n// nBins, prior, fids, nThreads, [ord0], [ord1] )\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n\n{\n\n // get inputs\n\n int nBins, nThreads, N0, N1, M0, M1, F; float prior, *wts0, *wts1;\n\n uint8 *data0, *data1; uint32 *fids, *ord0, *ord1;\n\n data0 = (uint8*) mxGetData(prhs[0]);\n\n data1 = (uint8*) mxGetData(prhs[1]);\n\n wts0 = (float*) mxGetData(prhs[2]);\n\n wts1 = (float*) mxGetData(prhs[3]);\n\n nBins = (int) mxGetScalar(prhs[4]);\n\n prior = (float) mxGetScalar(prhs[5]);\n\n fids = (uint32*) mxGetData(prhs[6]);\n\n nThreads = (int) mxGetScalar(prhs[7]);\n\n N0 = (int) mxGetM(prhs[0]);\n", "file_path": "image_processing/toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 22, "score": 21.274185786566317 }, { "content": "// [split_val,thrs,gains] = mexFunction(data,hs,ws,order,H,split);\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n int H, N, F, split; \n\n float *data, *ws, thr;\n\n double gain; uint32 *hs, *order;\n\n double cfactor, *costs_factor;\n\n data = (float*) mxGetData(prhs[0]);\n\n hs = (uint32*) mxGetData(prhs[1]);\n\n ws = (float*) mxGetData(prhs[2]);\n\n order = (uint32*) mxGetData(prhs[3]);\n\n H = (int) mxGetScalar(prhs[4]);\n\n split = (int) mxGetScalar(prhs[5]);\n\n costs_factor = (double*) mxGetData(prhs[6]); // Correction for class probabilities with costs\n\n N = (int) mxGetM(prhs[0]);\n\n F = (int) mxGetN(prhs[0]);\n\n \n\n // create output structures\n\n plhs[0] = mxCreateNumericMatrix(1,F,mxDOUBLE_CLASS,mxREAL);\n\n plhs[1] = mxCreateNumericMatrix(1,F,mxDOUBLE_CLASS,mxREAL);\n\n plhs[2] = mxCreateNumericMatrix(1,F,mxDOUBLE_CLASS,mxREAL);\n", "file_path": "image_processing/toolbox/classify/private/multiclassTreeTrain1.cpp", "rank": 23, "score": 21.23580023588363 }, { "content": "/*******************************************************************************\n\n* Added by Jose M. Buenaposada ([email protected])\n\n* Copyright 2016 \n\n* Please email me if you find bugs, or have suggestions or questions!\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"mex.h\"\n\n#include <vector>\n\n#include <cmath>\n\n#include <limits>\n\n#include <iostream>\n\n#include <blas.h>\n\nusing namespace std;\n\n\n\ntypedef unsigned int uint32;\n\n\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 25, "score": 18.6586477934227 }, { "content": "/*******************************************************************************\n\n* Piotr's Image&Video Toolbox Version 3.24\n\n* Copyright 2013 Piotr Dollar. [pdollar-at-caltech.edu]\n\n* Please email me if you find bugs, or have suggestions or questions!\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <string.h>\n\n#include <stdint.h>\n\n#include <math.h>\n\n#include <mex.h>\n\n#include <iostream>\n\n#include <vector>\n\n\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned int uint32;\n\n#define gini(p) p*p\n\n\n", "file_path": "image_processing/toolbox/classify/private/multiclassTreeTrain1.cpp", "rank": 26, "score": 18.513862511488103 }, { "content": " if(d==1 && h%2==0) O[j]=2*I[2*j+d];\n\n } else {\n\n if(d==0) { O[0]=2*I[0]; j++; if(k==0) k=4; }\n\n for( ; j<k; j++ ) O[j]=I[j-1+d]+I[j+d];\n\n for( ; j<h-4-d; j+=4 ) STR(O[j],C4(1,d) );\n\n for( ; j<h-d; j++ ) O[j]=I[j-1+d]+I[j+d];\n\n if(d==1) { O[j]=2*I[j]; j++; }\n\n }\n\n #undef C4\n\n}\n\n\n\n// convolve I by a [1 1; 1 1] filter (uses SSE)\n\nvoid conv11( float *I, float *O, int h, int w, int d, int side, int s ) {\n\n const float nrm = 0.25f; int i, j;\n\n float *I0, *I1, *T = (float*) alMalloc(h*sizeof(float),16);\n\n for( int d0=0; d0<d; d0++ ) for( i=s/2; i<w; i+=s ) {\n\n I0=I1=I+i*h+d0*h*w; if(side%2) { if(i<w-1) I1+=h; } else { if(i) I0-=h; }\n\n for( j=0; j<h-4; j+=4 ) STR( T[j], MUL(nrm,ADD(LDu(I0[j]),LDu(I1[j]))) );\n\n for( ; j<h; j++ ) T[j]=nrm*(I0[j]+I1[j]);\n\n conv11Y(T,O,h,side,s); O+=h/s;\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 27, "score": 17.978198344453276 }, { "content": "\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )\n\n{\n\n //cout << \"acfDetect1.cpp: 1=============================\" << endl;\n\n // get inputs\n\n float *chns = (float*) mxGetData(prhs[0]);\n\n mxArray *trees = (mxArray*) prhs[1];\n\n const int shrink = (int) mxGetScalar(prhs[2]);\n\n const int modelHt = (int) mxGetScalar(prhs[3]);\n\n const int modelWd = (int) mxGetScalar(prhs[4]);\n\n const int stride = (int) mxGetScalar(prhs[5]);\n\n const float cascThr = (float) mxGetScalar(prhs[6]);\n\n\n\n //cout << \"acfDetect1.cpp: 2=============================\" << endl;\n\n\n\n // extract relevant fields from trees\n\n float *thrs = (float*) mxGetData(mxGetField(trees,0,\"thrs\"));\n\n float *hs = (float*) mxGetData(mxGetField(trees,0,\"hs\"));\n\n uint32 *fids = (uint32*) mxGetData(mxGetField(trees,0,\"fids\"));\n\n uint32 *child = (uint32*) mxGetData(mxGetField(trees,0,\"child\"));\n", "file_path": "image_processing/toolbox/detector/private/acfDetect1.cpp", "rank": 29, "score": 17.607305480465232 }, { "content": " #pragma omp parallel for num_threads(nThreads)\n\n #endif\n\n for( int i = 0; i < N; i++ ) {\n\n uint32 k = 0;\n\n while( child[k] )\n\n if( data[i+fids[k]*size_t(N)] < thrs[k] )\n\n k = child[k]-1; else k = child[k];\n\n inds[i] = k+1;\n\n }\n\n}\n\n\n\n// inds=mexFunction(data,thrs,fids,child,[nThreads])\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n int N, nThreads; void *data, *thrs; uint32 *inds, *fids, *child;\n\n data = mxGetData(prhs[0]);\n\n thrs = mxGetData(prhs[1]);\n\n fids = (uint32*) mxGetData(prhs[2]);\n\n child = (uint32*) mxGetData(prhs[3]);\n\n nThreads = (nrhs<5) ? 100000 : (int) mxGetScalar(prhs[4]);\n\n N = (int) mxGetM(prhs[0]);\n", "file_path": "image_processing/toolbox/classify/private/forestInds.cpp", "rank": 30, "score": 17.53412374888797 }, { "content": " for(int i=0; i<F; i++ ) {\n\n std::vector<double> Wl(H), Wr(H);\n\n double wl, wr, gl, gr;\n\n float *data1 = (float*) data+i*size_t(N);\n\n uint32 *order1 = (uint32*) order+i*size_t(N); \n\n for(int j=0; j<H; j++ ) { Wl[j]=0; Wr[j]=W[j]; } gl=wl=0; gr=g; wr=w; \n\n \n\n double best = vInit;\n\n for(int j=0; j<N-1; j++) {\n\n double v;\n\n int j1, j2, h; \n\n j1=order1[j]; j2=order1[j+1]; h=hs[j1]-1; \n\n \n\n // gini = 1-\\sum_h p_h^2; v = gini_l*pl + gini_r*pr\n\n gl-=gini(Wl[h]*costs_factor[h]); // remove datum j1-th datum previous gini vaule\n\n gr-=gini(Wr[h]*costs_factor[h]); // remove datum j1-th datum previous gini vaule\n\n // We move the threshold one datum to the right (we are now between) \n\n // datum j1 and datum j2 in the ordered by order1. Therefore j1-th \n\n // datum is now on the left of the threshold.\n\n wl+=ws[j1]; // increase sum weights of j1-th datum from the left sum of weights\n", "file_path": "image_processing/toolbox/classify/private/multiclassTreeTrain1.cpp", "rank": 31, "score": 17.323960636888508 }, { "content": " double *split_val = (double*) mxGetData(plhs[0]);\n\n double *thrs = (double*) mxGetData(plhs[1]);\n\n double *gains = (double*) mxGetData(plhs[2]);\n\n \n\n double vInit, w, g;\n\n std::vector<double> W(H);\n\n \n\n // perform initialization\n\n vInit = 0; g = 0; w = 0; \n\n for(int i=0; i<H; i++ ) W[i] = 0;\n\n for(int j=0; j<N; j++ ) { w+=ws[j]; W[hs[j]-1]+=ws[j]; }\n\n for(int i=0; i<H; i++ ) g+=gini(W[i]*costs_factor[i]); vInit=(1.-(g)/w/w); \n\n \n\n // loop over features, then thresholds (data is sorted by feature value)\n\n // FIXME!: Take a look. Paralelise the search for the best of the F features.\n\n #ifdef USEOMP\n\n int nThreads = 4;\n\n nThreads = std::min(nThreads,omp_get_max_threads());\n\n #pragma omp parallel for num_threads(nThreads)\n\n #endif\n", "file_path": "image_processing/toolbox/classify/private/multiclassTreeTrain1.cpp", "rank": 32, "score": 17.128698373025703 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.00\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include \"string.h\"\n\n#include <math.h>\n\n#include <typeinfo>\n\n#include \"sse.hpp\"\n\n#include <iostream>\n\n\n\ntypedef unsigned char uchar;\n\n\n\n// compute interpolation values for single column for resapling\n\ntemplate<class T> void resampleCoef( int ha, int hb, int &n, int *&yas,\n\n int *&ybs, T *&wts, int bd[2], int pad=0 )\n\n{\n\n const T s = T(hb)/T(ha), sInv = 1/s; T wt, wt0=T(1e-3)*s;\n\n bool ds=ha>hb; int nMax; bd[0]=bd[1]=0;\n", "file_path": "image_processing/toolbox/channels/private/imResampleMex.cpp", "rank": 33, "score": 16.783213734772087 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.24\n\n* Copyright 2014 Piotr Dollar & Ron Appel. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include <string.h>\n\n#include \"sse.hpp\"\n\n\n\n// convolve one column of I by a 2rx1 ones filter\n\nvoid convBoxY( float *I, float *O, int h, int r, int s ) {\n\n float t; int j, p=r+1, q=2*h-(r+1), h0=r+1, h1=h-r, h2=h;\n\n t=0; for(j=0; j<=r; j++) t+=I[j]; t=2*t-I[r]; j=0;\n\n if( s==1 ) {\n\n for(; j<h0; j++) O[j]=t-=I[r-j]-I[r+j];\n\n for(; j<h1; j++) O[j]=t-=I[j-p]-I[r+j];\n\n for(; j<h2; j++) O[j]=t-=I[j-p]-I[q-j];\n\n } else {\n\n int k=(s-1)/2; h2=(h/s)*s; if(h0>h2) h0=h2; if(h1>h2) h1=h2;\n\n for(; j<h0; j++) { t-=I[r-j]-I[r+j]; k++; if(k==s) { k=0; *O++=t; } }\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 34, "score": 16.18623344845824 }, { "content": "void hog( float *M, float *O, float *H, int h, int w, int binSize,\n\n int nOrients, int softBin, bool full, float clip )\n\n{\n\n float *N, *R; const int hb=h/binSize, wb=w/binSize, nb=hb*wb;\n\n // compute unnormalized gradient histograms\n\n R = (float*) wrCalloc(wb*hb*nOrients,sizeof(float));\n\n gradHist( M, O, R, h, w, binSize, nOrients, softBin, full );\n\n // compute block normalization values\n\n N = hogNormMatrix( R, nOrients, hb, wb, binSize );\n\n // perform four normalizations per spatial block\n\n hogChannels( H, R, N, hb, wb, nOrients, clip, 0 );\n\n wrFree(N); wrFree(R);\n\n}\n\n\n\n// compute FHOG features\n\nvoid fhog( float *M, float *O, float *H, int h, int w, int binSize,\n\n int nOrients, int softBin, float clip )\n\n{\n\n const int hb=h/binSize, wb=w/binSize, nb=hb*wb, nbo=nb*nOrients;\n\n float *N, *R1, *R2; int o, x;\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 35, "score": 15.925767113517685 }, { "content": " N1 = (int) mxGetM(prhs[1]);\n\n F = (int) mxGetNumberOfElements(prhs[6]);\n\n\n\n // ord0 and ord1 are optional\n\n if( nrhs<10 ) M0=M1=0; else {\n\n ord0 = (uint32*) mxGetData(prhs[8]);\n\n ord1 = (uint32*) mxGetData(prhs[9]);\n\n M0 = (int) mxGetNumberOfElements(prhs[8]);\n\n M1 = (int) mxGetNumberOfElements(prhs[9]);\n\n }\n\n\n\n // create output structure\n\n plhs[0] = mxCreateNumericMatrix(1,F,mxSINGLE_CLASS,mxREAL);\n\n plhs[1] = mxCreateNumericMatrix(1,F,mxUINT8_CLASS,mxREAL);\n\n float *errs = (float*) mxGetData(plhs[0]);\n\n uint8 *thrs = (uint8*) mxGetData(plhs[1]);\n\n\n\n // find lowest error for each feature\n\n #ifdef USEOMP\n\n nThreads = min(nThreads,omp_get_max_threads());\n", "file_path": "image_processing/toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 36, "score": 15.876995708710039 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.24\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <string.h>\n\n#include <stdint.h>\n\n#include <math.h>\n\n#include <mex.h>\n\n\n\ntypedef unsigned int uint32;\n\n#define gini(p) p*p\n\n#define entropy(p) (-p*flog2(float(p)))\n\n\n\n// fast approximate log2(x) from Paul Mineiro <[email protected]>\n\ninline float flog2( float x ) {\n\n union { float f; uint32_t i; } vx = { x };\n\n union { uint32_t i; float f; } mx = { (vx.i & 0x007FFFFF) | 0x3f000000 };\n\n float y = float(vx.i); y *= 1.1920928955078125e-7f;\n\n return y - 124.22551499f - 1.498030302f * mx.f\n", "file_path": "image_processing/toolbox/classify/private/forestFindThr.cpp", "rank": 37, "score": 15.224575992602395 }, { "content": " plhs[0] = mxCreateNumericMatrix(N,1,mxUINT32_CLASS,mxREAL);\n\n inds = (uint32*) mxGetPr(plhs[0]);\n\n if(mxGetClassID(prhs[0])!=mxGetClassID(prhs[1]))\n\n mexErrMsgTxt(\"Mismatch between data types.\");\n\n if(mxGetClassID(prhs[0])==mxSINGLE_CLASS)\n\n forestInds(inds,(float*)data,(float*)thrs,fids,child,N,nThreads);\n\n else if(mxGetClassID(prhs[0])==mxDOUBLE_CLASS)\n\n forestInds(inds,(double*)data,(double*)thrs,fids,child,N,nThreads);\n\n else if(mxGetClassID(prhs[0])==mxUINT8_CLASS)\n\n forestInds(inds,(uint8*)data,(uint8*)thrs,fids,child,N,nThreads);\n\n else mexErrMsgTxt(\"Unknown data type.\");\n\n}\n", "file_path": "image_processing/toolbox/classify/private/forestInds.cpp", "rank": 38, "score": 14.950335142236675 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.30\n\n* Copyright 2014 Piotr Dollar & Ron Appel. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include <math.h>\n\n#include \"string.h\"\n\n#include \"sse.hpp\"\n\n#include <iostream>\n\n\n\n#define PI 3.14159265f\n\n\n\n// compute x and y gradients for just one column (uses sse)\n\nvoid grad1( float *I, float *Gx, float *Gy, int h, int w, int x ) {\n\n int y, y1; float *Ip, *In, r; __m128 *_Ip, *_In, *_G, _r;\n\n // compute column of Gx\n\n Ip=I-h; In=I+h; r=.5f;\n\n if(x==0) { r=1; Ip+=h; } else if(x==w-1) { r=1; In-=h; }\n\n if( h<4 || h%4>0 || (size_t(I)&15) || (size_t(Gx)&15) ) {\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 39, "score": 14.887940979954681 }, { "content": " uint32 *cids = new uint32[nFtrs]; int m=0;\n\n for( int z=0; z<nChns; z++ )\n\n for( int c=0; c<modelWd/shrink; c++ )\n\n for( int r=0; r<modelHt/shrink; r++ )\n\n cids[m++] = z*width*height + c*height + r;\n\n\n\n // cout << \"acfDetect1.cpp: 5=============================\" << endl;\n\n\n\n // apply classifier to each patch\n\n vector<int> rs, cs; vector<float> hs1;\n\n for( int c=0; c<width1; c++ ) for( int r=0; r<height1; r++ ) {\n\n float h=0, *chns1=chns+(r*stride/shrink) + (c*stride/shrink)*height;\n\n if( treeDepth==1 ) {\n\n // specialized case for treeDepth==1\n\n for( int t = 0; t < nTrees; t++ ) {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=0;\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n h += hs[k]; if( h<=cascThr ) break;\n\n }\n\n } else if( treeDepth==2 ) {\n", "file_path": "image_processing/toolbox/detector/private/acfDetect1.cpp", "rank": 40, "score": 14.579538089128288 }, { "content": " const int modelWd = (int) mxGetScalar(prhs[4]);\n\n const int stride = (int) mxGetScalar(prhs[5]);\n\n const float cascThr = (float) mxGetScalar(prhs[6]);\n\n \n\n// std::cout << \"cascThr=\" << cascThr << std::endl;\n\n\n\n // extract relevant fields from trees\n\n float *thrs = (float*) mxGetData(mxGetField(trees,0,\"thrs\"));\n\n float *hs = (float*) mxGetData(mxGetField(trees,0,\"hs\"));\n\n uint32 *fids = (uint32*) mxGetData(mxGetField(trees,0,\"fids\"));\n\n uint32 *child = (uint32*) mxGetData(mxGetField(trees,0,\"child\"));\n\n const int treeDepth = mxGetField(trees,0,\"treeDepth\")==NULL ? 0 :\n\n (int) mxGetScalar(mxGetField(trees,0,\"treeDepth\"));\n\n \n\n // Get the BAdaCost related fields from trees.\n\n double *Cprime = (double*) mxGetData(mxGetField(trees,0,\"Cprime\"));\n\n double *Y = (double*) mxGetData(mxGetField(trees,0,\"Y\"));\n\n // weak learner weights from boosting\n\n double *wl_weights = (double*) mxGetData(mxGetField(trees,0,\"wl_weights\"));\n\n// const double num_classes = mxGetField(trees,0,\"num_classes\")==NULL ? -1 :\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 41, "score": 14.57273087468463 }, { "content": " min_value = cost;\n\n h = j+1;\n\n }\n\n } \n\n}\n\n\n\ninline void getNegativeCost(int num_classes, double *Cprime, \n\n std::vector<double>& margin_vector, double& neg_cost)\n\n{\n\n // The index of the negative class is assumed 1. Therefore, its\n\n // column in Cprime is the first one (no need to move to its column).\n\n neg_cost = 0.0;\n\n double* cprime_column = Cprime;\n\n for(int i=0; i < num_classes; i++)\n\n {\n\n neg_cost += cprime_column[i] * margin_vector[i];\n\n }\n\n}\n\n\n\ninline void getChild( float *chns1, uint32 *cids, uint32 *fids,\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 42, "score": 14.432197642141155 }, { "content": " float *thrs, uint32 offset, uint32 &k0, uint32 &k )\n\n{\n\n float ftr = chns1[cids[fids[k]]];\n\n k = (ftr<thrs[k]) ? 1 : 2;\n\n k0=k+=k0*2; k+=offset;\n\n}\n\n\n\n// [bbs, labels] = acDetectImgMulticlass1(data, trees, \n\n// shrink, height, width, stride, cascThr,\n\n//\n\n// We assume that the label for the negative class is 1, the rest\n\n// of labels are subclasses of the positive metaclass (for example, \n\n// different possible views of cars).\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )\n\n{\n\n // get inputs\n\n float *chns = (float*) mxGetData(prhs[0]);\n\n mxArray *trees = (mxArray*) prhs[1];\n\n const int shrink = (int) mxGetScalar(prhs[2]);\n\n const int modelHt = (int) mxGetScalar(prhs[3]);\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 43, "score": 14.281594956800477 }, { "content": "/*******************************************************************************\n\n* Structured Edge Detection Toolbox Version 3.01\n\n* Code written by Piotr Dollar, 2014.\n\n* Licensed under the MSR-LA Full Rights License [see license.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#include <math.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\n// return I[x,y] via bilinear interpolation\n\ninline float interpolation(float *I, int h, int w, float x, float y)\n\n{\n\n x = x < 0 ? 0 : (x > w-1.001 ? w-1.001 : x);\n\n y = y < 0 ? 0 : (y > h-1.001 ? h-1.001 : y);\n\n int x0 = int(x);\n\n int y0 = int(y);\n\n int x1 = x0 + 1;\n\n int y1 = y0 + 1;\n", "file_path": "image_processing/edgesNmsMex.cpp", "rank": 44, "score": 14.154582969316191 }, { "content": " n=N1+x*hb1+y; *n=1/float(sqrt(n[0]+n[1]+n[hb1]+n[hb1+1]+eps)); }\n\n x=0; dx= 1; dy= 1; y=0; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=0; dx= 1; dy= 0; for(y=0; y<hb1; y++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=0; dx= 1; dy=-1; y=hb1-1; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=wb1-1; dx=-1; dy= 1; y=0; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=wb1-1; dx=-1; dy= 0; for( y=0; y<hb1; y++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=wb1-1; dx=-1; dy=-1; y=hb1-1; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n y=0; dx= 0; dy= 1; for(x=0; x<wb1; x++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n y=hb1-1; dx= 0; dy=-1; for(x=0; x<wb1; x++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n return N;\n\n}\n\n\n\n// HOG helper: compute HOG or FHOG channels\n\nvoid hogChannels( float *H, const float *R, const float *N,\n\n int hb, int wb, int nOrients, float clip, int type )\n\n{\n\n #define GETT(blk) t=R1[y]*N1[y-(blk)]; if(t>clip) t=clip; c++;\n\n const float r=.2357f; int o, x, y, c; float t;\n\n const int nb=wb*hb, nbo=nOrients*nb, hb1=hb+1;\n\n for( o=0; o<nOrients; o++ ) for( x=0; x<wb; x++ ) {\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 45, "score": 14.095020461299328 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.00\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include \"rgbConvertMex.cpp\"\n\n#include \"imPadMex.cpp\"\n\n#include \"convConst.cpp\"\n\n#include \"imResampleMex.cpp\"\n\n#include \"gradientMex.cpp\"\n\n\n\n// compile and test standalone channels source code\n\nint main(int argc, const char* argv[])\n\n{\n\n // initialize test array (misalign controls memory mis-alignment)\n\n const int h=12, w=12, misalign=1; int x, y, d;\n\n float I[h*w*3+misalign], *I0=I+misalign;\n\n for( x=0; x<h*w*3; x++ ) I0[x]=0;\n", "file_path": "image_processing/toolbox/channels/private/chnsTestCpp.cpp", "rank": 46, "score": 14.049647801777738 }, { "content": " float *chns1=chns+(r*stride/shrink) + (c*stride/shrink)*height;\n\n \n\n // Initialise the margin_vector memory to 0.0\n\n for(int i=0; i<num_classes; i++)\n\n {\n\n margin_vector[i] = 0.0;\n\n }\n\n \n\n// int t;\n\n if( treeDepth==1 ) \n\n {\n\n // specialized case for treeDepth==1\n\n for(int t = 0; t < nTrees; t++ ) \n\n {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=0;\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n\n\n // In the BadaCost case we have to:\n\n // 1) Codify as a margin vector class label\n\n // output from each tree (hs[k]) \n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 47, "score": 13.796189358251098 }, { "content": " alFree(O0); alFree(O1); alFree(M0); alFree(M1);\n\n // normalize boundary bins which only get 7/8 of weight of interior bins\n\n if( softBin%2!=0 ) for( int o=0; o<nOrients; o++ ) {\n\n x=0; for( y=0; y<hb; y++ ) H[o*nb+x*hb+y]*=8.f/7.f;\n\n y=0; for( x=0; x<wb; x++ ) H[o*nb+x*hb+y]*=8.f/7.f;\n\n x=wb-1; for( y=0; y<hb; y++ ) H[o*nb+x*hb+y]*=8.f/7.f;\n\n y=hb-1; for( x=0; x<wb; x++ ) H[o*nb+x*hb+y]*=8.f/7.f;\n\n }\n\n}\n\n\n\n/******************************************************************************/\n\n\n\n// HOG helper: compute 2x2 block normalization values (padded by 1 pixel)\n\nfloat* hogNormMatrix( float *H, int nOrients, int hb, int wb, int bin ) {\n\n float *N, *N1, *n; int o, x, y, dx, dy, hb1=hb+1, wb1=wb+1;\n\n float eps = 1e-4f/4/bin/bin/bin/bin; // precise backward equality\n\n N = (float*) wrCalloc(hb1*wb1,sizeof(float)); N1=N+hb1+1;\n\n for( o=0; o<nOrients; o++ ) for( x=0; x<wb; x++ ) for( y=0; y<hb; y++ )\n\n N1[x*hb1+y] += H[o*wb*hb+x*hb+y]*H[o*wb*hb+x*hb+y];\n\n for( x=0; x<wb-1; x++ ) for( y=0; y<hb-1; y++ ) {\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 48, "score": 13.79608117975983 }, { "content": " for(; j<h1; j++) { t-=I[j-p]-I[r+j]; k++; if(k==s) { k=0; *O++=t; } }\n\n for(; j<h2; j++) { t-=I[j-p]-I[q-j]; k++; if(k==s) { k=0; *O++=t; } }\n\n }\n\n}\n\n\n\n// convolve I by a 2r+1 x 2r+1 ones filter (uses SSE)\n\nvoid convBox( float *I, float *O, int h, int w, int d, int r, int s ) {\n\n float nrm = 1.0f/((2*r+1)*(2*r+1)); int i, j, k=(s-1)/2, h0, h1, w0;\n\n if(h%4==0) h0=h1=h; else { h0=h-(h%4); h1=h0+4; } w0=(w/s)*s;\n\n float *T=(float*) alMalloc(h1*sizeof(float),16);\n\n while(d-- > 0) {\n\n // initialize T\n\n memset( T, 0, h1*sizeof(float) );\n\n for(i=0; i<=r; i++) for(j=0; j<h0; j+=4) INC(T[j],LDu(I[j+i*h]));\n\n for(j=0; j<h0; j+=4) STR(T[j],MUL(nrm,SUB(MUL(2,LD(T[j])),LDu(I[j+r*h]))));\n\n for(i=0; i<=r; i++) for(j=h0; j<h; j++ ) T[j]+=I[j+i*h];\n\n for(j=h0; j<h; j++ ) T[j]=nrm*(2*T[j]-I[j+r*h]);\n\n // prepare and convolve each column in turn\n\n k++; if(k==s) { k=0; convBoxY(T,O,h,r,s); O+=h/s; }\n\n for( i=1; i<w0; i++ ) {\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 49, "score": 13.794690586086992 }, { "content": "}\n\n\n\n// convolve I by a 2rx1 triangle filter (uses SSE)\n\nvoid convTri( float *I, float *O, int h, int w, int d, int r, int s ) {\n\n r++; float nrm = 1.0f/(r*r*r*r); int i, j, k=(s-1)/2, h0, h1, w0;\n\n if(h%4==0) h0=h1=h; else { h0=h-(h%4); h1=h0+4; } w0=(w/s)*s;\n\n float *T=(float*) alMalloc(2*h1*sizeof(float),16), *U=T+h1;\n\n while(d-- > 0) {\n\n // initialize T and U\n\n for(j=0; j<h0; j+=4) STR(U[j], STR(T[j], LDu(I[j])));\n\n for(i=1; i<r; i++) for(j=0; j<h0; j+=4) INC(U[j],INC(T[j],LDu(I[j+i*h])));\n\n for(j=0; j<h0; j+=4) STR(U[j],MUL(nrm,(SUB(MUL(2,LD(U[j])),LD(T[j])))));\n\n for(j=0; j<h0; j+=4) STR(T[j],0);\n\n for(j=h0; j<h; j++ ) U[j]=T[j]=I[j];\n\n for(i=1; i<r; i++) for(j=h0; j<h; j++ ) U[j]+=T[j]+=I[j+i*h];\n\n for(j=h0; j<h; j++ ) { U[j] = nrm * (2*U[j]-T[j]); T[j]=0; }\n\n // prepare and convolve each column in turn\n\n k++; if(k==s) { k=0; convTriY(U,O,h,r-1,s); O+=h/s; }\n\n for( i=1; i<w0; i++ ) {\n\n float *Il=I+(i-1-r)*h; if(i<=r) Il=I+(r-i)*h; float *Im=I+(i-1)*h;\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 50, "score": 13.475334464269071 }, { "content": " o=O[i]*oMult; o0=(int) (o+.5f);\n\n o0*=nb; if(o0>=oMax) o0=0; O0[i]=o0;\n\n M0[i]=M[i]*norm; M1[i]=0; O1[i]=0;\n\n }\n\n}\n\n\n\n// compute nOrients gradient histograms per bin x bin block of pixels\n\nvoid gradHist( float *M, float *O, float *H, int h, int w,\n\n int bin, int nOrients, int softBin, bool full )\n\n{\n\n const int hb=h/bin, wb=w/bin, h0=hb*bin, w0=wb*bin, nb=wb*hb;\n\n const float s=(float)bin, sInv=1/s, sInv2=1/s/s;\n\n float *H0, *H1, *M0, *M1; int x, y; int *O0, *O1; float xb, init;\n\n O0=(int*)alMalloc(h*sizeof(int),16); M0=(float*) alMalloc(h*sizeof(float),16);\n\n O1=(int*)alMalloc(h*sizeof(int),16); M1=(float*) alMalloc(h*sizeof(float),16);\n\n\n\n // main loop\n\n for( x=0; x<w0; x++ ) {\n\n // compute target orientation bins for entire column - very fast\n\n gradQuantize(O+x*h,M+x*h,O0,O1,M0,M1,nb,h0,sInv2,nOrients,full,softBin>=0);\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 51, "score": 13.43756404452442 }, { "content": " }\n\n alFree(T);\n\n}\n\n\n\n// convolve one column of I by a 2rx1 triangle filter\n\nvoid convTriY( float *I, float *O, int h, int r, int s ) {\n\n r++; float t, u; int j, r0=r-1, r1=r+1, r2=2*h-r, h0=r+1, h1=h-r+1, h2=h;\n\n u=t=I[0]; for( j=1; j<r; j++ ) u+=t+=I[j]; u=2*u-t; t=0;\n\n if( s==1 ) {\n\n O[0]=u; j=1;\n\n for(; j<h0; j++) O[j] = u += t += I[r-j] + I[r0+j] - 2*I[j-1];\n\n for(; j<h1; j++) O[j] = u += t += I[j-r1] + I[r0+j] - 2*I[j-1];\n\n for(; j<h2; j++) O[j] = u += t += I[j-r1] + I[r2-j] - 2*I[j-1];\n\n } else {\n\n int k=(s-1)/2; h2=(h/s)*s; if(h0>h2) h0=h2; if(h1>h2) h1=h2;\n\n if(++k==s) { k=0; *O++=u; } j=1;\n\n for(;j<h0;j++) { u+=t+=I[r-j] +I[r0+j]-2*I[j-1]; if(++k==s){ k=0; *O++=u; }}\n\n for(;j<h1;j++) { u+=t+=I[j-r1]+I[r0+j]-2*I[j-1]; if(++k==s){ k=0; *O++=u; }}\n\n for(;j<h2;j++) { u+=t+=I[j-r1]+I[r2-j]-2*I[j-1]; if(++k==s){ k=0; *O++=u; }}\n\n }\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 52, "score": 13.214169810650858 }, { "content": " int h = (int) mxGetM(pr[0]);\n\n int w = (int) mxGetN(pr[0]);\n\n pl[0] = mxCreateNumericMatrix(h,w,mxSINGLE_CLASS,mxREAL);\n\n float *E = (float*) mxGetData(pl[0]);\n\n\n\n // suppress edges where edge is stronger in orthogonal direction\n\n #ifdef USEOMP\n\n nThreads = nThreads<omp_get_max_threads() ? nThreads : omp_get_max_threads();\n\n #pragma omp parallel for num_threads(nThreads)\n\n #endif\n\n\n\n for(int x = 0; x < w; x++) for(int y = 0; y < h; y++) \n\n {\n\n float e = E[x*h+y] = E0[x*h+y]; if(!e) continue; e *= m;\n\n float coso = cos(O[x*h+y]);\n\n float sino = sin(O[x*h+y]);\n\n for(int d = -r; d <= r; d++) if (d)\n\n {\n\n float e0 = interpolation(E0,h,w,x+d*coso,y+d*sino);\n\n if(e < e0) { E[x*h+y]=0; break; }\n", "file_path": "image_processing/edgesNmsMex.cpp", "rank": 53, "score": 13.144272258636393 }, { "content": " for( d=0; d<3; d++ ) I0[int(h*w/2+h/2)+d*h*w]=1;\n\n\n\n // initialize memory for results with given misalignment\n\n const int pad=2, rad=2, sf=sizeof(float); d=3;\n\n const int h1=h+2*pad, w1=w+2*pad, h2=h1/2, w2=w1/2, h3=h2/4, w3=w2/4;\n\n float *I1, *I2, *I3, *I4, *Gx, *Gy, *M, *O, *H, *G;\n\n I1 = (float*) wrCalloc(h1*w1*d+misalign,sf) + misalign;\n\n I3 = (float*) wrCalloc(h1*w1*d+misalign,sf) + misalign;\n\n I4 = (float*) wrCalloc(h2*w2*d+misalign,sf) + misalign;\n\n Gx = (float*) wrCalloc(h2*w2*d+misalign,sf) + misalign;\n\n Gy = (float*) wrCalloc(h2*w2*d+misalign,sf) + misalign;\n\n M = (float*) wrCalloc(h2*w2*d+misalign,sf) + misalign;\n\n O = (float*) wrCalloc(h2*w2*d+misalign,sf) + misalign;\n\n H = (float*) wrCalloc(h3*w3*d*6+misalign,sf) + misalign;\n\n G = (float*) wrCalloc(h3*w3*d*24+misalign,sf) + misalign;\n\n\n\n // perform tests of imPad, rgbConvert, convConst, resample and gradient\n\n imPad(I0,I1,h,w,d,pad,pad,pad,pad,0,0.0f);\n\n I2 = rgbConvert(I1,h1*w1,d,0,1.0f); d=1;\n\n convTri(I2,I3,h1,w1,d,rad,1);\n", "file_path": "image_processing/toolbox/channels/private/chnsTestCpp.cpp", "rank": 54, "score": 13.043195706172826 }, { "content": " for( ; j<h2; j++ ) O[j]=I[2*j]+p*I[2*j+1]+I[2*j+2];\n\n if( h%2==0 ) O[j]=I[2*j]+(1+p)*I[2*j+1];\n\n } else {\n\n O[j]=(1+p)*I[j]+I[j+1]; j++; if(k==0) k=(h<=4) ? h-1 : 4;\n\n for( ; j<k; j++ ) O[j]=I[j-1]+p*I[j]+I[j+1];\n\n for( ; j<h-4; j+=4 ) STR(O[j],C4(1,0));\n\n for( ; j<h-1; j++ ) O[j]=I[j-1]+p*I[j]+I[j+1];\n\n O[j]=I[j-1]+(1+p)*I[j];\n\n }\n\n #undef C4\n\n}\n\n\n\n// convolve I by a [1 p 1] filter (uses SSE)\n\nvoid convTri1( float *I, float *O, int h, int w, int d, float p, int s ) {\n\n const float nrm = 1.0f/((p+2)*(p+2)); int i, j, h0=h-(h%4);\n\n float *Il, *Im, *Ir, *T=(float*) alMalloc(h*sizeof(float),16);\n\n for( int d0=0; d0<d; d0++ ) for( i=s/2; i<w; i+=s ) {\n\n Il=Im=Ir=I+i*h+d0*h*w; if(i>0) Il-=h; if(i<w-1) Ir+=h;\n\n for( j=0; j<h0; j+=4 )\n\n STR(T[j],MUL(nrm,ADD(ADD(LDu(Il[j]),MUL(p,LDu(Im[j]))),LDu(Ir[j]))));\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 56, "score": 12.714964490317891 }, { "content": " if (trace <=cascThr) break; \n\n }\n\n } \n\n else \n\n {\n\n // general case (variable tree depth)\n\n for(int t = 0; t < nTrees; t++ ) \n\n {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=k;\n\n while( child[k] ) \n\n {\n\n float ftr = chns1[cids[fids[k]]];\n\n k = (ftr<thrs[k]) ? 1 : 0;\n\n k0 = k = child[k0]-k+offset;\n\n }\n\n\n\n // In the BadaCost case we have to:\n\n // 1) Codify as a margin vector class label\n\n // output from each tree (hs[k]) \n\n // 2) Add the margin vectors codified weighted \n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 57, "score": 12.622243252575394 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.00\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include \"string.h\"\n\n#include <iostream>\n\ntypedef unsigned char uchar;\n\n\n\n// pad A by [pt,pb,pl,pr] and store result in B\n\ntemplate<class T> void imPad( T *A, T *B, int h, int w, int d, int pt, int pb,\n\n int pl, int pr, int flag, T val )\n\n{\n\n int h1=h+pt, hb=h1+pb, w1=w+pl, wb=w1+pr, x, y, z, mPad;\n\n int ct=0, cb=0, cl=0, cr=0;\n\n if(pt<0) { ct=-pt; pt=0; } if(pb<0) { h1+=pb; cb=-pb; pb=0; }\n\n if(pl<0) { cl=-pl; pl=0; } if(pr<0) { w1+=pr; cr=-pr; pr=0; }\n\n int *xs, *ys; x=pr>pl?pr:pl; y=pt>pb?pt:pb; mPad=x>y?x:y;\n\n bool useLookup = ((flag==2 || flag==3) && (mPad>h || mPad>w))\n", "file_path": "image_processing/toolbox/channels/private/imPadMex.cpp", "rank": 58, "score": 12.28534792666633 }, { "content": "\n\n // extract input arguments\n\n I = mxGetPr(pr[0]);\n\n flag = (int) mxGetScalar(pr[1]);\n\n single = (bool) (mxGetScalar(pr[2])>0);\n\n idIn = mxGetClassID(pr[0]);\n\n\n\n // call rgbConvert() based on type of input and output array\n\n if(!((d==1 && flag==0) || flag==1 || (d/3)*3==d))\n\n mexErrMsgTxt(\"I must have third dimension d==1 or (d/3)*3==d.\");\n\n if( idIn == mxSINGLE_CLASS && !single )\n\n J = (void*) rgbConvert( (float*) I, n, d, flag, 1.0 );\n\n else if( idIn == mxSINGLE_CLASS && single )\n\n J = (void*) rgbConvert( (float*) I, n, d, flag, 1.0f );\n\n else if( idIn == mxDOUBLE_CLASS && !single )\n\n J = (void*) rgbConvert( (double*) I, n, d, flag, 1.0 );\n\n else if( idIn == mxDOUBLE_CLASS && single )\n\n J = (void*) rgbConvert( (double*) I, n, d, flag, 1.0f );\n\n else if( idIn == mxUINT8_CLASS && !single )\n\n J = (void*) rgbConvert( (unsigned char*) I, n, d, flag, 1.0/255 );\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 59, "score": 12.132049556467692 }, { "content": " const mwSize nTreeNodes = (mwSize) fidsSize[0];\n\n const mwSize nTrees = (mwSize) fidsSize[1];\n\n const mwSize height1 = (mwSize) ceil(float(height*shrink-modelHt+1)/stride);\n\n const mwSize width1 = (mwSize) ceil(float(width*shrink-modelWd+1)/stride);\n\n\n\n // Create the margin vector and costs vector for BAdaCost classification.\n\n std::vector<double> margin_vector(num_classes);\n\n std::vector<double> costs_vector(num_classes);\n\n\n\n // construct cids array\n\n int nFtrs = modelHt/shrink*modelWd/shrink*nChns;\n\n uint32 *cids = new uint32[nFtrs]; \n\n // 64 bits change\n\n //int m=0; \n\n mwSize m=0;\n\n for( int z=0; z<nChns; z++ )\n\n for( int c=0; c<modelWd/shrink; c++ )\n\n for( int r=0; r<modelHt/shrink; r++ )\n\n cids[m++] = z*width*height + c*height + r;\n\n\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 60, "score": 11.951769588107712 }, { "content": " float *Il=I+(i-1-r)*h; if(i<=r) Il=I+(r-i)*h;\n\n float *Ir=I+(i+r)*h; if(i>=w-r) Ir=I+(2*w-r-i-1)*h;\n\n for(j=0; j<h0; j+=4) DEC(T[j],MUL(nrm,SUB(LDu(Il[j]),LDu(Ir[j]))));\n\n for(j=h0; j<h; j++ ) T[j]-=nrm*(Il[j]-Ir[j]);\n\n k++; if(k==s) { k=0; convBoxY(T,O,h,r,s); O+=h/s; }\n\n }\n\n I+=w*h;\n\n }\n\n alFree(T);\n\n}\n\n\n\n// convolve one column of I by a [1; 1] filter (uses SSE)\n\nvoid conv11Y( float *I, float *O, int h, int side, int s ) {\n\n #define C4(m,o) ADD(LDu(I[m*j-1+o]),LDu(I[m*j+o]))\n\n int j=0, k=((~((size_t) O) + 1) & 15)/4;\n\n const int d = (side % 4 >= 2) ? 1 : 0, h2=(h-d)/2;\n\n if( s==2 ) {\n\n for( ; j<k; j++ ) O[j]=I[2*j+d]+I[2*j+d+1];\n\n for( ; j<h2-4; j+=4 ) STR(O[j],_mm_shuffle_ps(C4(2,d+1),C4(2,d+5),136));\n\n for( ; j<h2; j++ ) O[j]=I[2*j+d]+I[2*j+d+1];\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 61, "score": 11.772747772177777 }, { "content": " float dx0 = x - x0;\n\n float dy0 = y - y0;\n\n float dx1 = 1 - dx0;\n\n float dy1 = 1 - dy0;\n\n return I[x0*h+y0] * dx1 * dy1 + \n\n I[x1*h+y0] * dx0 * dy1 +\n\n I[x0*h+y1] * dx1 * dy0 + \n\n I[x1*h+y1] * dx0 * dy0;\n\n}\n\n\n\n// E = mexFunction(E,O,r,s,m,nThreads)\n\nvoid mexFunction(int nl, mxArray *pl[], int nr, const mxArray *pr[])\n\n{\n\n float *E0 = (float*) mxGetData(pr[0]); // original edge map\n\n float *O = (float*) mxGetData(pr[1]); // orientation map\n\n int r = (int) mxGetScalar(pr[2]); // radius for nms supr\n\n int s = (int) mxGetScalar(pr[3]); // radius for supr boundaries\n\n float m = (float) mxGetScalar(pr[4]); // multiplier for conservative supr\n\n int nThreads = (int) mxGetScalar(pr[5]); // number of threads for evaluation\n\n\n", "file_path": "image_processing/edgesNmsMex.cpp", "rank": 62, "score": 11.704744841083299 }, { "content": " h = (b-r)/(maxv-minv)+2;\n\n } else {\n\n maxv = b; minv = r<g ? r : g;\n\n h = (r-g)/(maxv-minv)+4;\n\n }\n\n h*=(oT) (1/6.0); s=1-minv/maxv; v=maxv*nrm;\n\n *(H++) = h; *(S++) = s; *(V++) = v;\n\n }\n\n}\n\n\n\n// Convert from rgb to gray\n\ntemplate<class iT, class oT> void rgb2gray( iT *I, oT *J, int n, oT nrm ) {\n\n oT *GR=J; iT *R=I, *G=R+n, *B=G+n; int i;\n\n oT mr=(oT).2989360213*nrm, mg=(oT).5870430745*nrm, mb=(oT).1140209043*nrm;\n\n for(i=0; i<n; i++) *(GR++)=(oT)*(R++)*mr + (oT)*(G++)*mg + (oT)*(B++)*mb;\n\n}\n\n\n\n// Convert from rgb (double) to gray (float)\n\ntemplate<> void rgb2gray( double *I, float *J, int n, float nrm ) {\n\n float *GR=J; double *R=I, *G=R+n, *B=G+n; int i;\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 63, "score": 10.94839438052377 }, { "content": " n=ns[0]*ns[1]*nCh; m=ms[0]*ms[1]*nCh;\n\n\n\n // perform resampling (w appropriate type)\n\n A=mxGetData(prhs[0]); B=mxGetData(plhs[0]);\n\n if( id==mxDOUBLE_CLASS ) {\n\n resample((double*)A, (double*)B, ns[0], ms[0], ns[1], ms[1], nCh, nrm);\n\n } else if( id==mxSINGLE_CLASS ) {\n\n resample((float*)A, (float*)B, ns[0], ms[0], ns[1], ms[1], nCh, float(nrm));\n\n } else if( id==mxUINT8_CLASS ) {\n\n float *A1 = (float*) mxMalloc(n*sizeof(float));\n\n float *B1 = (float*) mxCalloc(m,sizeof(float));\n\n for(int i=0; i<n; i++) A1[i]=(float) ((uchar*)A)[i];\n\n resample(A1, B1, ns[0], ms[0], ns[1], ms[1], nCh, float(nrm));\n\n for(int i=0; i<m; i++) ((uchar*)B)[i]=(uchar) (B1[i]+.5);\n\n } else {\n\n mexErrMsgTxt(\"Unsupported type.\");\n\n }\n\n}\n\n#endif\n", "file_path": "image_processing/toolbox/channels/private/imResampleMex.cpp", "rank": 64, "score": 10.856194367672476 }, { "content": "// int h, w, d, c, full; float *I, *M, *O=0;\n\n mwSize h, w, d;\n\n int c, full; float *I, *M, *O=0;\n\n checkArgs(nl,pl,nr,pr,1,2,3,3,&h,&w,&d,mxSINGLE_CLASS,(void**)&I);\n\n if(h<2 || w<2) mexErrMsgTxt(\"I must be at least 2x2.\");\n\n c = (int) mxGetScalar(pr[1]); full = (int) mxGetScalar(pr[2]);\n\n if( c>0 && c<=d ) { I += h*w*(c-1); d=1; }\n\n pl[0] = mxCreateMatrix3(h,w,1,mxSINGLE_CLASS,0,(void**)&M);\n\n if(nl>=2) pl[1] = mxCreateMatrix3(h,w,1,mxSINGLE_CLASS,0,(void**)&O);\n\n gradMag(I, M, O, h, w, d, full>0 );\n\n}\n\n\n\n// gradMagNorm( M, S, norm ) - operates on M - see gradientMag.m\n\nvoid mGradMagNorm( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n //int h, w, d; float *M, *S, norm;\n\n mwSize h, w, d; float *M, *S, norm;\n\n checkArgs(nl,pl,nr,pr,0,0,3,3,&h,&w,&d,mxSINGLE_CLASS,(void**)&M);\n\n if( mxGetM(pr[1])!=h || mxGetN(pr[1])!=w || d!=1 ||\n\n mxGetClassID(pr[1])!=mxSINGLE_CLASS ) mexErrMsgTxt(\"M or S is bad.\");\n\n S = (float*) mxGetPr(pr[1]); norm = (float) mxGetScalar(pr[2]);\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 65, "score": 10.850128550950927 }, { "content": " float *Ir=I+(i-1+r)*h; if(i>w-r) Ir=I+(2*w-r-i)*h;\n\n for( j=0; j<h0; j+=4 ) {\n\n INC(T[j],ADD(LDu(Il[j]),LDu(Ir[j]),MUL(-2,LDu(Im[j]))));\n\n INC(U[j],MUL(nrm,LD(T[j])));\n\n }\n\n for( j=h0; j<h; j++ ) U[j]+=nrm*(T[j]+=Il[j]+Ir[j]-2*Im[j]);\n\n k++; if(k==s) { k=0; convTriY(U,O,h,r-1,s); O+=h/s; }\n\n }\n\n I+=w*h;\n\n }\n\n alFree(T);\n\n}\n\n\n\n// convolve one column of I by a [1 p 1] filter (uses SSE)\n\nvoid convTri1Y( float *I, float *O, int h, float p, int s ) {\n\n #define C4(m,o) ADD(ADD(LDu(I[m*j-1+o]),MUL(p,LDu(I[m*j+o]))),LDu(I[m*j+1+o]))\n\n int j=0, k=((~((size_t) O) + 1) & 15)/4, h2=(h-1)/2;\n\n if( s==2 ) {\n\n for( ; j<k; j++ ) O[j]=I[2*j]+p*I[2*j+1]+I[2*j+2];\n\n for( ; j<h2-4; j+=4 ) STR(O[j],_mm_shuffle_ps(C4(2,1),C4(2,5),136));\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 66, "score": 10.837186557993844 }, { "content": " else if( treeDepth==2 ) \n\n {\n\n // specialized case for treeDepth==2\n\n for(int t = 0; t < nTrees; t++ ) \n\n {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=0;\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n \n\n // In the BadaCost case we have to:\n\n // 1) Codify as a margin vector class label\n\n // output from each tree (hs[k]) \n\n // 2) Add the margin vectors codified weighted \n\n // by the weak learner weight.\n\n h = static_cast<int>(hs[k]);\n\n // double* codified = Y + static_cast<size_t>(num_classes*(h-1)); \n\n double* codified = Y + static_cast<mwSize>(num_classes*(h-1)); \n\n for(int i=0; i<num_classes; i++)\n\n {\n\n margin_vector[i] += codified[i] * wl_weights[t];\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 67, "score": 10.795180242627366 }, { "content": " else if( idIn == mxUINT8_CLASS && single )\n\n J = (void*) rgbConvert( (unsigned char*) I, n, d, flag, 1.0f/255 );\n\n else\n\n mexErrMsgTxt(\"Unsupported image type.\");\n\n\n\n // create and set output array\n\n dims1[0]=dims[0]; dims1[1]=dims[1]; dims1[2]=(flag==0 ? (d==1?1:d/3) : d);\n\n idOut = single ? mxSINGLE_CLASS : mxDOUBLE_CLASS;\n\n pl[0] = mxCreateNumericMatrix(0,0,idOut,mxREAL);\n\n mxSetData(pl[0],J); mxSetDimensions(pl[0],(const mwSize*) dims1,3);\n\n}\n\n#endif\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 68, "score": 10.754476024669968 }, { "content": " // apply classifier to each patch\n\n// int num_windows = width1*height1;\n\n mwSize num_windows = width1*height1;\n\n if (num_windows < 0) // Detection window is too big for the image \n\n num_windows = 0; // Detect on 0 windows in this case (do nothing).\n\n vector<int> rs(num_windows), cs(num_windows); \n\n vector<float> hs1(num_windows), scores(num_windows);\n\n// cout << \"Process n= \" << width1*height1 << \" windows.\" << endl;\n\n\n\n #ifdef USEOMP\n\n int nThreads = omp_get_max_threads();\n\n #pragma omp parallel for num_threads(nThreads)\n\n #endif \n\n// for( int c=0; c<width1; c++ ) \n\n// for( int r=0; r<height1; r++ ) {\n\n for( mwSize c=0; c<width1; c++ ) \n\n for( mwSize r=0; r<height1; r++ ) { \n\n std::vector<double> margin_vector(num_classes);\n\n double trace;\n\n int h;\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 69, "score": 10.71802359019184 }, { "content": " gradMagNorm(M,S,h,w,norm);\n\n}\n\n\n\n// H=gradHist(M,O,[...]) - see gradientHist.m\n\nvoid mGradHist( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n //int h, w, d, hb, wb, nChns, binSize, nOrients, softBin, useHog;\n\n mwSize h, w, d, hb, wb;\n\n int nChns, binSize, nOrients, softBin, useHog;\n\n bool full; float *M, *O, *H, clipHog;\n\n checkArgs(nl,pl,nr,pr,1,3,2,8,&h,&w,&d,mxSINGLE_CLASS,(void**)&M);\n\n O = (float*) mxGetPr(pr[1]);\n\n if( mxGetM(pr[1])!=h || mxGetN(pr[1])!=w || d!=1 ||\n\n mxGetClassID(pr[1])!=mxSINGLE_CLASS ) mexErrMsgTxt(\"M or O is bad.\");\n\n binSize = (nr>=3) ? (int) mxGetScalar(pr[2]) : 8;\n\n nOrients = (nr>=4) ? (int) mxGetScalar(pr[3]) : 9;\n\n softBin = (nr>=5) ? (int) mxGetScalar(pr[4]) : 1;\n\n useHog = (nr>=6) ? (int) mxGetScalar(pr[5]) : 0;\n\n clipHog = (nr>=7) ? (float) mxGetScalar(pr[6]) : 0.2f;\n\n full = (nr>=8) ? (bool) (mxGetScalar(pr[7])>0) : false;\n\n hb = h/binSize; wb = w/binSize;\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 70, "score": 10.691312963391075 }, { "content": " for( ; y<h; y++ ) { y0=y-r; if(y0<0) y0=0; maxk(y0,h-1); }\n\n #undef maxk\n\n #undef max1\n\n}\n\n\n\n// convolve I by a 2rx1 max filter\n\nvoid convMax( float *I, float *O, int h, int w, int d, int r ) {\n\n if( r>w-1 ) r=w-1; if( r>h-1 ) r=h-1; int m=2*r+1;\n\n float *T=(float*) alMalloc(m*2*sizeof(float),16);\n\n for( int d0=0; d0<d; d0++ ) for( int x=0; x<w; x++ ) {\n\n float *Oc=O+d0*h*w+h*x, *Ic=I+d0*h*w+h*x;\n\n convMaxY(Ic,Oc,T,h,r);\n\n }\n\n alFree(T);\n\n}\n\n\n\n// B=convConst(type,A,r,s); fast 2D convolutions (see convTri.m and convBox.m)\n\n#ifdef MATLAB_MEX_FILE\n\nvoid mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) {\n\n int nDims; float *A, *B, p;\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 71, "score": 10.592480252876552 }, { "content": " oT r, g, b, x, y, z, l;\n\n r=(oT)*R++; g=(oT)*G++; b=(oT)*B++;\n\n x = mr[0]*r + mg[0]*g + mb[0]*b;\n\n y = mr[1]*r + mg[1]*g + mb[1]*b;\n\n z = mr[2]*r + mg[2]*g + mb[2]*b;\n\n l = lTable[(int)(y*1024)];\n\n *(L++) = l; z = 1/(x + 15*y + 3*z + (oT)1e-35);\n\n *(U++) = l * (13*4*x*z - 13*un) - minu;\n\n *(V++) = l * (13*9*y*z - 13*vn) - minv;\n\n }\n\n}\n\n\n\n// Convert from rgb to luv using sse\n\ntemplate<class iT> void rgb2luv_sse( iT *I, float *J, int n, float nrm ) {\n\n const int k=256; float R[k], G[k], B[k];\n\n if( (size_t(R)&15||size_t(G)&15||size_t(B)&15||size_t(I)&15||size_t(J)&15)\n\n || n%4>0 ) { rgb2luv(I,J,n,nrm); return; }\n\n int i=0, i1, n1; float minu, minv, un, vn, mr[3], mg[3], mb[3];\n\n float *lTable = rgb2luv_setup(nrm,mr,mg,mb,minu,minv,un,vn);\n\n while( i<n ) {\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 72, "score": 10.359666746071452 }, { "content": "}\n\n\n\nvoid HeapNode::operator =(double NewKeyVal) {\n\n HeapNode Tmp;\n\n Tmp.N = N = NewKeyVal;\n\n FHN_Assign(Tmp);\n\n}\n\n\n\nvoid HeapNode::operator =(FibHeapNode& RHS) {\n\n FHN_Assign(RHS);\n\n N = ((HeapNode&) RHS).N;\n\n}\n\n\n\nint HeapNode::operator ==(FibHeapNode& RHS) {\n\n if (FHN_Cmp(RHS)) return 0;\n\n return N == ((HeapNode&) RHS).N ? 1 : 0;\n\n}\n\n\n\nint HeapNode::operator <(FibHeapNode& RHS) {\n\n int X;\n", "file_path": "image_processing/toolbox/matlab/private/dijkstra1.cpp", "rank": 73, "score": 10.310732746124845 }, { "content": " int o, x, c, a=w*h; for(c=0; c<d; c++) for(x=0; x<w; x++) {\n\n o=c*a+x*h; grad1( I+o, Gx+o, Gy+o, h, w, x );\n\n }\n\n}\n\n\n\n// build lookup table a[] s.t. a[x*n]~=acos(x) for x in [-1,1]\n\nfloat* acosTable() {\n\n const int n=10000, b=10; int i;\n\n static float a[n*2+b*2]; static bool init=false;\n\n float *a1=a+n+b; if( init ) return a1;\n\n for( i=-n-b; i<-n; i++ ) a1[i]=PI;\n\n for( i=-n; i<n; i++ ) a1[i]=float(acos(i/float(n)));\n\n for( i=n; i<n+b; i++ ) a1[i]=0;\n\n for( i=-n-b; i<n/10; i++ ) if( a1[i] > PI-1e-6f ) a1[i]=PI-1e-6f;\n\n init=true; return a1;\n\n}\n\n\n\n// compute gradient magnitude and orientation at each location (uses sse)\n\nvoid gradMag( float *I, float *M, float *O, int h, int w, int d, bool full ) {\n\n int x, y, y1, c, h4, s; float *Gx, *Gy, *M2; __m128 *_Gx, *_Gy, *_M2, _m;\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 74, "score": 10.128723268934282 }, { "content": " #pragma omp parallel for num_threads(nThreads)\n\n #endif\n\n for( int f=0; f<F; f++ ) {\n\n float cdf0[256], cdf1[256], e0, e1, e; int thr=0;\n\n if(prior<.5) { e0=prior; e1=1-prior; } else { e0=1-prior; e1=prior; }\n\n constructCdf(data0+N0*size_t(fids[f]),wts0,nBins,N0,M0,ord0,cdf0);\n\n constructCdf(data1+N1*size_t(fids[f]),wts1,nBins,N1,M1,ord1,cdf1);\n\n for( int i=0; i<nBins; i++) {\n\n e = prior - cdf1[i] + cdf0[i];\n\n if(e<e0) { e0=e; e1=1-e; thr=i; } else if(e>e1) { e0=1-e; e1=e; thr=i; }\n\n }\n\n errs[f]=e0; thrs[f]=(uint8) thr;\n\n }\n\n}\n", "file_path": "image_processing/toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 75, "score": 9.947471980078916 }, { "content": "\n\n// normalize gradient magnitude at each location (uses sse)\n\nvoid gradMagNorm( float *M, float *S, int h, int w, float norm ) {\n\n __m128 *_M, *_S, _norm; int i=0, n=h*w, n4=n/4;\n\n _S = (__m128*) S; _M = (__m128*) M; _norm = SET(norm);\n\n bool sse = !(size_t(M)&15) && !(size_t(S)&15);\n\n if(sse) for(; i<n4; i++) { *_M=MUL(*_M,RCP(ADD(*_S++,_norm))); _M++; }\n\n if(sse) i*=4; for(; i<n; i++) M[i] /= (S[i] + norm);\n\n}\n\n\n\n// helper for gradHist, quantize O and M into O0, O1 and M0, M1 (uses sse)\n\nvoid gradQuantize( float *O, float *M, int *O0, int *O1, float *M0, float *M1,\n\n int nb, int n, float norm, int nOrients, bool full, bool interpolate )\n\n{\n\n // assumes all *OUTPUT* matrices are 4-byte aligned\n\n int i, o0, o1; float o, od, m;\n\n __m128i _o0, _o1, *_O0, *_O1; __m128 _o, _od, _m, *_M0, *_M1;\n\n // define useful constants\n\n const float oMult=(float)nOrients/(full?2*PI:PI); const int oMax=nOrients*nb;\n\n const __m128 _norm=SET(norm), _oMult=SET(oMult), _nbf=SET((float)nb);\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 76, "score": 9.785484895563703 }, { "content": " } else {\n\n // interpolate using trilinear interpolation\n\n float ms[4], xyd, yb, xd, yd; __m128 _m, _m0, _m1;\n\n bool hasLf, hasRt; int xb0, yb0;\n\n if( x==0 ) { init=(0+.5f)*sInv-0.5f; xb=init; }\n\n hasLf = xb>=0; xb0 = hasLf?(int)xb:-1; hasRt = xb0 < wb-1;\n\n xd=xb-xb0; xb+=sInv; yb=init; y=0;\n\n // macros for code conciseness\n\n #define GHinit yd=yb-yb0; yb+=sInv; H0=H+xb0*hb+yb0; xyd=xd*yd; \\\n\n ms[0]=1-xd-yd+xyd; ms[1]=yd-xyd; ms[2]=xd-xyd; ms[3]=xyd;\n\n #define GH(H,ma,mb) H1=H; STRu(*H1,ADD(LDu(*H1),MUL(ma,mb)));\n\n // leading rows, no top bin\n\n for( ; y<bin/2; y++ ) {\n\n yb0=-1; GHinit;\n\n if(hasLf) { H0[O0[y]+1]+=ms[1]*M0[y]; H0[O1[y]+1]+=ms[1]*M1[y]; }\n\n if(hasRt) { H0[O0[y]+hb+1]+=ms[3]*M0[y]; H0[O1[y]+hb+1]+=ms[3]*M1[y]; }\n\n }\n\n // main rows, has top and bottom bins, use SSE for minor speedup\n\n if( softBin<0 ) for( ; ; y++ ) {\n\n yb0 = (int) yb; if(yb0>=hb-1) break; GHinit; _m0=SET(M0[y]);\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 77, "score": 9.453391031832345 }, { "content": " // compute unnormalized constrast sensitive histograms\n\n R1 = (float*) wrCalloc(wb*hb*nOrients*2,sizeof(float));\n\n gradHist( M, O, R1, h, w, binSize, nOrients*2, softBin, true );\n\n // compute unnormalized contrast insensitive histograms\n\n R2 = (float*) wrCalloc(wb*hb*nOrients,sizeof(float));\n\n for( o=0; o<nOrients; o++ ) for( x=0; x<nb; x++ )\n\n R2[o*nb+x] = R1[o*nb+x]+R1[(o+nOrients)*nb+x];\n\n // compute block normalization values\n\n N = hogNormMatrix( R2, nOrients, hb, wb, binSize );\n\n // normalized histograms and texture channels\n\n hogChannels( H+nbo*0, R1, N, hb, wb, nOrients*2, clip, 1 );\n\n hogChannels( H+nbo*2, R2, N, hb, wb, nOrients*1, clip, 1 );\n\n hogChannels( H+nbo*3, R1, N, hb, wb, nOrients*2, clip, 2 );\n\n // Change from toolbox v3.5\n\n// wrFree(N); mxFree(R1); wrFree(R2);\n\n wrFree(N); wrFree(R1); wrFree(R2);\n\n}\n\n\n\n/******************************************************************************/\n\n#ifdef MATLAB_MEX_FILE\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 78, "score": 9.395726285698066 }, { "content": " // specialized case for treeDepth==2\n\n for( int t = 0; t < nTrees; t++ ) {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=0;\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n h += hs[k]; if( h<=cascThr ) break;\n\n }\n\n } else if( treeDepth>2) {\n\n // specialized case for treeDepth>2\n\n for( int t = 0; t < nTrees; t++ ) {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=0;\n\n for( int i=0; i<treeDepth; i++ )\n\n getChild(chns1,cids,fids,thrs,offset,k0,k);\n\n h += hs[k]; if( h<=cascThr ) break;\n\n }\n\n } else {\n\n // general case (variable tree depth)\n\n for( int t = 0; t < nTrees; t++ ) {\n\n uint32 offset=t*nTreeNodes, k=offset, k0=k;\n\n while( child[k] ) {\n", "file_path": "image_processing/toolbox/detector/private/acfDetect1.cpp", "rank": 79, "score": 9.38240466774798 }, { "content": " for( j=h0; j<h; j++ ) T[j]=nrm*(Il[j]+p*Im[j]+Ir[j]);\n\n convTri1Y(T,O,h,p,s); O+=h/s;\n\n }\n\n alFree(T);\n\n}\n\n\n\n// convolve one column of I by a 2rx1 max filter\n\nvoid convMaxY( float *I, float *O, float *T, int h, int r ) {\n\n int y, y0, y1, yi, m=2*r+1;\n\n #define max1(a,b) a>b ? a : b;\n\n #define maxk(y0,y1) { O[y]=I[y0]; \\\n\n for( yi=y0+1; yi<=y1; yi++ ) { if(I[yi]>O[y]) O[y]=I[yi]; }}\n\n for( y=0; y<r; y++ ) { y1=y+r; if(y1>h-1) y1=h-1; maxk(0,y1); }\n\n for( ; y<=h-m-r; y+=m ) {\n\n T[m-1] = I[y+r];\n\n for( yi=1; yi<m; yi++ ) T[m-1-yi] = max1( T[m-1-yi+1], I[y+r-yi] );\n\n for( yi=1; yi<m; yi++ ) T[m-1+yi] = max1( T[m-1+yi-1], I[y+r+yi] );\n\n for( yi=0; yi<m; yi++ ) O[y+yi] = max1( T[yi], T[yi+m-1] );\n\n }\n\n for( ; y<h-r; y++ ) { maxk(y-r,y+r); }\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 80, "score": 9.122704108293407 }, { "content": "// Here we asume that first label (h=1 at index 0) is the negative class \n\n// (the background in detection).\n\ninline void getMinPositiveCost(int num_classes, \n\n double *Cprime, \n\n std::vector<double>& margin_vector, \n\n double& min_value, \n\n int& h)\n\n{\n\n min_value = std::numeric_limits<double>::max();\n\n for(int j=1; j < num_classes; j++)\n\n {\n\n double cost = 0.0;\n\n double* cprime_column = Cprime + static_cast<size_t>(j*num_classes);\n\n for(int i=0; i < num_classes; i++)\n\n {\n\n cost += cprime_column[i] * margin_vector[i];\n\n }\n\n\n\n if (cost < min_value) \n\n {\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 81, "score": 9.098394569918266 }, { "content": " n1 = i+k; if(n1>n) n1=n; float *J1=J+i; float *R1, *G1, *B1;\n\n // convert to floats (and load input into cache)\n\n if( typeid(iT) != typeid(float) ) {\n\n R1=R; G1=G; B1=B; iT *Ri=I+i, *Gi=Ri+n, *Bi=Gi+n;\n\n for( i1=0; i1<(n1-i); i1++ ) {\n\n R1[i1] = (float) *Ri++; G1[i1] = (float) *Gi++; B1[i1] = (float) *Bi++;\n\n }\n\n } else { R1=((float*)I)+i; G1=R1+n; B1=G1+n; }\n\n // compute RGB -> XYZ\n\n for( int j=0; j<3; j++ ) {\n\n __m128 _mr, _mg, _mb, *_J=(__m128*) (J1+j*n);\n\n __m128 *_R=(__m128*) R1, *_G=(__m128*) G1, *_B=(__m128*) B1;\n\n _mr=SET(mr[j]); _mg=SET(mg[j]); _mb=SET(mb[j]);\n\n for( i1=i; i1<n1; i1+=4 ) *(_J++) = ADD( ADD(MUL(*(_R++),_mr),\n\n MUL(*(_G++),_mg)),MUL(*(_B++),_mb));\n\n }\n\n { // compute XZY -> LUV (without doing L lookup/normalization)\n\n __m128 _c15, _c3, _cEps, _c52, _c117, _c1024, _cun, _cvn;\n\n _c15=SET(15.0f); _c3=SET(3.0f); _cEps=SET(1e-35f);\n\n _c52=SET(52.0f); _c117=SET(117.0f), _c1024=SET(1024.0f);\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 82, "score": 9.061986932291266 }, { "content": " if( softBin<0 && softBin%2==0 ) {\n\n // no interpolation w.r.t. either orienation or spatial bin\n\n H1=H+(x/bin)*hb;\n\n #define GH H1[O0[y]]+=M0[y]; y++;\n\n if( bin==1 ) for(y=0; y<h0;) { GH; H1++; }\n\n else if( bin==2 ) for(y=0; y<h0;) { GH; GH; H1++; }\n\n else if( bin==3 ) for(y=0; y<h0;) { GH; GH; GH; H1++; }\n\n else if( bin==4 ) for(y=0; y<h0;) { GH; GH; GH; GH; H1++; }\n\n else for( y=0; y<h0;) { for( int y1=0; y1<bin; y1++ ) { GH; } H1++; }\n\n #undef GH\n\n } else if( softBin%2==0 || bin==1 ) {\n\n // interpolate w.r.t. orientation only, not spatial bin\n\n H1=H+(x/bin)*hb;\n\n #define GH H1[O0[y]]+=M0[y]; H1[O1[y]]+=M1[y]; y++;\n\n if( bin==1 ) for(y=0; y<h0;) { GH; H1++; }\n\n else if( bin==2 ) for(y=0; y<h0;) { GH; GH; H1++; }\n\n else if( bin==3 ) for(y=0; y<h0;) { GH; GH; GH; H1++; }\n\n else if( bin==4 ) for(y=0; y<h0;) { GH; GH; GH; GH; H1++; }\n\n else for( y=0; y<h0;) { for( int y1=0; y1<bin; y1++ ) { GH; } H1++; }\n\n #undef GH\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 83, "score": 9.002409787338062 }, { "content": " if(ya<0) { ya=0; bd[0]++; } if(ya>=ha-1) { ya=ha-1; bd[1]++; }\n\n ybs[yb]=yb; yas[yb]=ya; wts[yb]=wt;\n\n }\n\n}\n\n\n\n// resample A using bilinear interpolation and and store result in B\n\ntemplate<class T>\n\nvoid resample( T *A, T *B, int ha, int hb, int wa, int wb, int d, T r ) {\n\n int hn, wn, x, x1, y, z, xa, xb, ya; T *A0, *A1, *A2, *A3, *B0, wt, wt1;\n\n T *C = (T*) alMalloc((ha+4)*sizeof(T),16); for(y=ha; y<ha+4; y++) C[y]=0;\n\n bool sse = (typeid(T)==typeid(float)) && !(size_t(A)&15) && !(size_t(B)&15);\n\n // get coefficients for resampling along w and h\n\n int *xas, *xbs, *yas, *ybs; T *xwts, *ywts; int xbd[2], ybd[2];\n\n resampleCoef<T>( wa, wb, wn, xas, xbs, xwts, xbd, 0 );\n\n resampleCoef<T>( ha, hb, hn, yas, ybs, ywts, ybd, 4 );\n\n if( wa==2*wb ) r/=2; if( wa==3*wb ) r/=3; if( wa==4*wb ) r/=4;\n\n r/=T(1+1e-6); for( y=0; y<hn; y++ ) ywts[y] *= r;\n\n // resample each channel in turn\n\n for( z=0; z<d; z++ ) for( x=0; x<wb; x++ ) {\n\n if(x==0) x1=0; xa=xas[x1]; xb=xbs[x1]; wt=xwts[x1]; wt1=1-wt; y=0;\n", "file_path": "image_processing/toolbox/channels/private/imResampleMex.cpp", "rank": 84, "score": 8.958951013417204 }, { "content": " }\n\n }\n\n i = n1;\n\n }\n\n}\n\n\n\n// Convert from rgb to hsv\n\ntemplate<class iT, class oT> void rgb2hsv( iT *I, oT *J, int n, oT nrm ) {\n\n oT *H=J, *S=H+n, *V=S+n;\n\n iT *R=I, *G=R+n, *B=G+n;\n\n for(int i=0; i<n; i++) {\n\n const oT r=(oT)*(R++), g=(oT)*(G++), b=(oT)*(B++);\n\n oT h, s, v, minv, maxv;\n\n if( r==g && g==b ) {\n\n *(H++) = 0; *(S++) = 0; *(V++) = r*nrm; continue;\n\n } else if( r>=g && r>=b ) {\n\n maxv = r; minv = g<b ? g : b;\n\n h = (g-b)/(maxv-minv)+6; if(h>=6) h-=6;\n\n } else if( g>=r && g>=b ) {\n\n maxv = g; minv = r<b ? r : b;\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 85, "score": 8.805847883344274 }, { "content": " // In the BadaCost case we have to:\n\n // 1) Codify as a margin vector class label\n\n // output from each tree (hs[k]) \n\n // 2) Add the margin vectors codified weighted \n\n // by the weak learner weight.\n\n h = static_cast<int>(hs[k]);\n\n// double* codified = Y + static_cast<size_t>(num_classes*(h-1)); \n\n double* codified = Y + static_cast<mwSize>(num_classes*(h-1)); \n\n for(int i=0; i<num_classes; i++)\n\n {\n\n margin_vector[i] += codified[i] * wl_weights[t];\n\n } \n\n\n\n double min_pos_cost;\n\n double neg_cost;\n\n // Gets positive class min cost and label in h! \n\n getMinPositiveCost(num_classes, Cprime, margin_vector, min_pos_cost, h);\n\n getNegativeCost(num_classes, Cprime, margin_vector, neg_cost);\n\n trace = -(min_pos_cost - neg_cost);\n\n \n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 86, "score": 8.71580887271937 }, { "content": " double mr=.2989360213*nrm, mg=.5870430745*nrm, mb=.1140209043*nrm;\n\n for(i=0; i<n; i++) *(GR++) = (float) (*(R++)*mr + *(G++)*mg + *(B++)*mb);\n\n}\n\n\n\n// Copy and normalize only\n\ntemplate<class iT, class oT> void normalize( iT *I, oT *J, int n, oT nrm ) {\n\n for(int i=0; i<n; i++) *(J++)=(oT)*(I++)*nrm;\n\n}\n\n\n\n// Convert rgb to various colorspaces\n\ntemplate<class iT, class oT>\n\noT* rgbConvert( iT *I, int n, int d, int flag, oT nrm ) {\n\n oT *J = (oT*) wrMalloc(n*(flag==0 ? (d==1?1:d/3) : d)*sizeof(oT));\n\n int i, n1=d*(n<1000?n/10:100); oT thr = oT(1.001);\n\n if(flag>1 && nrm==1) for(i=0; i<n1; i++) if(I[i]>thr)\n\n wrError(\"For floats all values in I must be smaller than 1.\");\n\n bool useSse = n%4==0 && typeid(oT)==typeid(float);\n\n if( flag==2 && useSse )\n\n for(i=0; i<d/3; i++) rgb2luv_sse(I+i*n*3,(float*)(J+i*n*3),n,(float)nrm);\n\n else if( (flag==0 && d==1) || flag==1 ) normalize(I,J,n*d,nrm);\n", "file_path": "image_processing/toolbox/channels/private/rgbConvertMex.cpp", "rank": 87, "score": 8.641544912929898 }, { "content": " }\n\n }\n\n\n\n // suppress noisy edge estimates near boundaries\n\n s = s > w/2 ? w/2 : s; \n\n s = s > h/2 ? h/2 : s;\n\n for (int x = 0; x < s; x++) for (int y = 0; y < h; y++) \n\n {\n\n E[x*h+y] *= x/float(s); \n\n E[(w-1-x)*h+y] *= x/float(s); \n\n }\n\n for (int x = 0; x < w; x++) for (int y = 0; y < s; y++) \n\n {\n\n E[x*h+y] *= y/float(s); \n\n E[x*h+(h-1-y)] *= y/float(s); \n\n }\n\n}\n", "file_path": "image_processing/edgesNmsMex.cpp", "rank": 88, "score": 8.618886828283554 }, { "content": "// Create [hxwxd] mxArray array, initialize to 0 if c=true\n\nmxArray* mxCreateMatrix3( mwSize h, mwSize w, mwSize d, mxClassID id, bool c, void **I ){\n\n //const size_t dims[3]={size_t(h),size_t(w),size_t(d)}, n=h*w*d; int b; mxArray* M;\n\n const mwSize dims[3]={h,w,d}, n=h*w*d; int b; mxArray* M;\n\n if( id==mxINT32_CLASS ) b=sizeof(int);\n\n else if( id==mxDOUBLE_CLASS ) b=sizeof(double);\n\n else if( id==mxSINGLE_CLASS ) b=sizeof(float);\n\n else mexErrMsgTxt(\"Unknown mxClassID.\");\n\n *I = c ? mxCalloc(n,b) : mxMalloc(n*b);\n\n M = mxCreateNumericMatrix(0,0,id,mxREAL);\n\n mxSetData(M,*I); mxSetDimensions(M,dims,3); return M;\n\n}\n\n\n\n// Check inputs and outputs to mex, retrieve first input I\n\nvoid checkArgs( int nl, mxArray *pl[], int nr, const mxArray *pr[], int nl0,\n\n int nl1, int nr0, int nr1, mwSize *h, mwSize *w, mwSize *d, mxClassID id, void **I )\n\n{\n\n// const size_t *dims; int nDims;\n\n const mwSize *dims; int nDims;\n\n if( nl<nl0 || nl>nl1 ) mexErrMsgTxt(\"Incorrect number of outputs.\");\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 89, "score": 8.469001421248706 }, { "content": " nChns = useHog== 0 ? nOrients : (useHog==1 ? nOrients*4 : nOrients*3+5);\n\n pl[0] = mxCreateMatrix3(hb,wb,nChns,mxSINGLE_CLASS,1,(void**)&H);\n\n if( nOrients==0 ) return;\n\n if( useHog==0 ) {\n\n gradHist( M, O, H, h, w, binSize, nOrients, softBin, full );\n\n } else if(useHog==1) {\n\n hog( M, O, H, h, w, binSize, nOrients, softBin, full, clipHog );\n\n } else {\n\n fhog( M, O, H, h, w, binSize, nOrients, softBin, clipHog );\n\n }\n\n}\n\n\n\n// inteface to various gradient functions (see corresponding Matlab functions)\n\nvoid mexFunction( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n int f; char action[1024]; f=mxGetString(pr[0],action,1024); nr--; pr++;\n\n if(f) mexErrMsgTxt(\"Failed to get action.\");\n\n else if(!strcmp(action,\"gradient2\")) mGrad2(nl,pl,nr,pr);\n\n else if(!strcmp(action,\"gradientMag\")) mGradMag(nl,pl,nr,pr);\n\n else if(!strcmp(action,\"gradientMagNorm\")) mGradMagNorm(nl,pl,nr,pr);\n\n else if(!strcmp(action,\"gradientHist\")) mGradHist(nl,pl,nr,pr);\n\n else mexErrMsgTxt(\"Invalid action.\");\n\n}\n\n#endif\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 90, "score": 8.38784796730958 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.00\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#ifndef _WRAPPERS_HPP_\n\n#define _WRAPPERS_HPP_\n\n#ifdef MATLAB_MEX_FILE\n\n\n\n// wrapper functions if compiling from Matlab\n\n#include \"mex.h\"\n\ninline void wrError(const char *errormsg) { mexErrMsgTxt(errormsg); }\n\ninline void* wrCalloc( size_t num, size_t size ) { return mxCalloc(num,size); }\n\ninline void* wrMalloc( size_t size ) { return mxMalloc(size); }\n\ninline void wrFree( void * ptr ) { mxFree(ptr); }\n\n\n\n#else\n\n\n\n// wrapper functions if compiling from C/C++\n\ninline void wrError(const char *errormsg) { throw errormsg; }\n", "file_path": "image_processing/toolbox/channels/private/wrappers.hpp", "rank": 91, "score": 8.105061948992576 }, { "content": " for( y=0; y<h; y++ ) *Gx++=(*In++-*Ip++)*r;\n\n } else {\n\n _G=(__m128*) Gx; _Ip=(__m128*) Ip; _In=(__m128*) In; _r = SET(r);\n\n for(y=0; y<h; y+=4) *_G++=MUL(SUB(*_In++,*_Ip++),_r);\n\n }\n\n // compute column of Gy\n\n #define GRADY(r) *Gy++=(*In++-*Ip++)*r;\n\n Ip=I; In=Ip+1;\n\n // GRADY(1); Ip--; for(y=1; y<h-1; y++) GRADY(.5f); In--; GRADY(1);\n\n y1=((~((size_t) Gy) + 1) & 15)/4; if(y1==0) y1=4; if(y1>h-1) y1=h-1;\n\n GRADY(1); Ip--; for(y=1; y<y1; y++) GRADY(.5f);\n\n _r = SET(.5f); _G=(__m128*) Gy;\n\n for(; y+4<h-1; y+=4, Ip+=4, In+=4, Gy+=4)\n\n *_G++=MUL(SUB(LDu(*In),LDu(*Ip)),_r);\n\n for(; y<h-1; y++) GRADY(.5f); In--; GRADY(1);\n\n #undef GRADY\n\n}\n\n\n\n// compute x and y gradients at each location (uses sse)\n\nvoid grad2( float *I, float *Gx, float *Gy, int h, int w, int d ) {\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 92, "score": 8.075344532867959 }, { "content": " if( nr<nr0 || nr>nr1 ) mexErrMsgTxt(\"Incorrect number of inputs.\");\n\n nDims = mxGetNumberOfDimensions(pr[0]); dims = mxGetDimensions(pr[0]);\n\n *h=dims[0]; *w=dims[1]; *d=(nDims==2) ? 1 : dims[2]; *I = mxGetPr(pr[0]);\n\n if( nDims!=2 && nDims!=3 ) mexErrMsgTxt(\"I must be a 2D or 3D array.\");\n\n if( mxGetClassID(pr[0])!=id ) mexErrMsgTxt(\"I has incorrect type.\");\n\n}\n\n\n\n// [Gx,Gy] = grad2(I) - see gradient2.m\n\nvoid mGrad2( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n //int h, w, d; float *I, *Gx, *Gy;\n\n mwSize h, w, d; float *I, *Gx, *Gy;\n\n checkArgs(nl,pl,nr,pr,1,2,1,1,&h,&w,&d,mxSINGLE_CLASS,(void**)&I);\n\n if(h<2 || w<2) mexErrMsgTxt(\"I must be at least 2x2.\");\n\n pl[0]= mxCreateMatrix3( h, w, d, mxSINGLE_CLASS, 0, (void**) &Gx );\n\n pl[1]= mxCreateMatrix3( h, w, d, mxSINGLE_CLASS, 0, (void**) &Gy );\n\n grad2( I, Gx, Gy, h, w, d );\n\n}\n\n\n\n// [M,O] = gradMag( I, channel, full ) - see gradientMag.m\n\nvoid mGradMag( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n", "file_path": "image_processing/toolbox/channels/private/gradientMex.cpp", "rank": 93, "score": 8.072172043913485 }, { "content": " if(ds) { n=0; nMax=ha+(pad>2 ? pad : 2)*hb; } else { n=nMax=hb; }\n\n // initialize memory\n\n wts = (T*)alMalloc(nMax*sizeof(T),16);\n\n yas = (int*)alMalloc(nMax*sizeof(int),16);\n\n ybs = (int*)alMalloc(nMax*sizeof(int),16);\n\n if( ds ) for( int yb=0; yb<hb; yb++ ) {\n\n // create coefficients for downsampling\n\n T ya0f=yb*sInv, ya1f=ya0f+sInv, W=0;\n\n int ya0=int(ceil(ya0f)), ya1=int(ya1f), n1=0;\n\n for( int ya=ya0-1; ya<ya1+1; ya++ ) {\n\n wt=s; if(ya==ya0-1) wt=(ya0-ya0f)*s; else if(ya==ya1) wt=(ya1f-ya1)*s;\n\n if(wt>wt0 && ya>=0) { ybs[n]=yb; yas[n]=ya; wts[n]=wt; n++; n1++; W+=wt; }\n\n }\n\n if(W>1) for( int i=0; i<n1; i++ ) wts[n-n1+i]/=W;\n\n if(n1>bd[0]) bd[0]=n1;\n\n while( n1<pad ) { ybs[n]=yb; yas[n]=yas[n-1]; wts[n]=0; n++; n1++; }\n\n } else for( int yb=0; yb<hb; yb++ ) {\n\n // create coefficients for upsampling\n\n T yaf = (T(.5)+yb)*sInv-T(.5); int ya=(int) floor(yaf);\n\n wt=1; if(ya>=0 && ya<ha-1) wt=1-(yaf-ya);\n", "file_path": "image_processing/toolbox/channels/private/imResampleMex.cpp", "rank": 94, "score": 7.93387252614443 }, { "content": " // 2) Add the margin vectors codified weighted \n\n // by the weak learner weight.\n\n h = static_cast<int>(hs[k]);\n\n// double* codified = Y + static_cast<size_t>(num_classes*(h-1)); \n\n double* codified = Y + static_cast<mwSize>(num_classes*(h-1)); \n\n for(int i=0; i<num_classes; i++)\n\n {\n\n margin_vector[i] += codified[i] * wl_weights[t];\n\n } \n\n \n\n double min_pos_cost;\n\n double neg_cost;\n\n // Gets positive class min cost and label in h! \n\n getMinPositiveCost(num_classes, Cprime, margin_vector, min_pos_cost, h);\n\n getNegativeCost(num_classes, Cprime, margin_vector, neg_cost);\n\n trace = -(min_pos_cost - neg_cost);\n\n\n\n if (trace <=cascThr) break;\n\n }\n\n } \n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 95, "score": 7.773726125342298 }, { "content": "inline void* wrCalloc( size_t num, size_t size ) { return calloc(num,size); }\n\ninline void* wrMalloc( size_t size ) { return malloc(size); }\n\ninline void wrFree( void * ptr ) { free(ptr); }\n\n\n\n#endif\n\n\n\n// platform independent aligned memory allocation (see also alFree)\n\nvoid* alMalloc( size_t size, int alignment ) {\n\n const size_t pSize = sizeof(void*), a = alignment-1;\n\n void *raw = wrMalloc(size + a + pSize);\n\n void *aligned = (void*) (((size_t) raw + pSize + a) & ~a);\n\n *(void**) ((size_t) aligned-pSize) = raw;\n\n return aligned;\n\n}\n\n\n\n// platform independent alignned memory de-allocation (see also alMalloc)\n\nvoid alFree(void* aligned) {\n\n void* raw = *(void**)((char*)aligned-sizeof(void*));\n\n wrFree(raw);\n\n}\n\n\n\n#endif\n", "file_path": "image_processing/toolbox/channels/private/wrappers.hpp", "rank": 96, "score": 7.723487131659746 }, { "content": " // by the weak learner weight.\n\n h = static_cast<int>(hs[k]);\n\n double* codified = Y + static_cast<size_t>(num_classes*(h-1)); \n\n for(int i=0; i<num_classes; i++)\n\n {\n\n margin_vector[i] += codified[i] * wl_weights[t];\n\n } \n\n\n\n double min_pos_cost;\n\n double neg_cost;\n\n // Gets positive class min cost and label in h! \n\n getMinPositiveCost(num_classes, Cprime, margin_vector, min_pos_cost, h);\n\n getNegativeCost(num_classes, Cprime, margin_vector, neg_cost);\n\n trace = -(min_pos_cost - neg_cost);\n\n \n\n if (trace <=cascThr) break; \n\n }\n\n \n\n// cout << \"trees executed t=\" << t << \", of nTrees=\" << nTrees << endl;\n\n// cout << \"trace=\" << trace << endl;\n", "file_path": "image_processing/toolbox/detector/private/acfDetectBadacostTrees1.cpp", "rank": 97, "score": 7.6511707670481455 }, { "content": " ns = (mwSize*) mxGetDimensions(prhs[0]); nCh=(nDims==2) ? 1 : ns[2];\n\n \n\n if( (nDims!=2 && nDims!=3) ||\n\n (id!=mxSINGLE_CLASS && id!=mxDOUBLE_CLASS && id!=mxUINT8_CLASS) )\n\n mexErrMsgTxt(\"A should be 2D or 3D single, double or uint8 array.\");\n\n if( !mxIsDouble(prhs[1]) ) mexErrMsgTxt(\"Input pad must be a double array.\");\n\n\n\n // extract padding amounts\n\n k = (int) mxGetNumberOfElements(prhs[1]);\n\n p = (double*) mxGetData(prhs[1]);\n\n if(k==1) { pt=pb=pl=pr=int(p[0]); }\n\n else if (k==2) { pt=pb=int(p[0]); pl=pr=int(p[1]); }\n\n else if (k==4) { pt=int(p[0]); pb=int(p[1]); pl=int(p[2]); pr=int(p[3]); }\n\n else mexErrMsgTxt( \"Input pad must have 1, 2, or 4 values.\");\n\n\n\n // figure out padding type (flag and val)\n\n if( !mxGetString(prhs[2],type,1024) ) {\n\n if(!strcmp(type,\"replicate\")) flag=1;\n\n else if(!strcmp(type,\"symmetric\")) flag=2;\n\n else if(!strcmp(type,\"circular\")) flag=3;\n", "file_path": "image_processing/toolbox/channels/private/imPadMex.cpp", "rank": 98, "score": 7.618248958588779 }, { "content": " mwSize ms[3]; mwSize *ns, d, m, r, s;;\n\n mxClassID id; char type[1024];\n\n\n\n // error checking on arguments\n\n if(nrhs!=4) mexErrMsgTxt(\"Four inputs required.\");\n\n if(nlhs > 1) mexErrMsgTxt(\"One output expected.\");\n\n nDims = mxGetNumberOfDimensions(prhs[1]);\n\n id = mxGetClassID(prhs[1]);\n\n ns = (mwSize*) mxGetDimensions(prhs[1]);\n\n d = (nDims == 3) ? ns[2] : 1;\n\n m = (ns[0] < ns[1]) ? ns[0] : ns[1];\n\n if( (nDims!=2 && nDims!=3) || id!=mxSINGLE_CLASS || m<4 )\n\n mexErrMsgTxt(\"A must be a 4x4 or bigger 2D or 3D float array.\");\n\n\n\n // extract inputs\n\n if(mxGetString(prhs[0],type,1024))\n\n mexErrMsgTxt(\"Failed to get type.\");\n\n A = (float*) mxGetData(prhs[1]);\n\n p = (float) mxGetScalar(prhs[2]);\n\n r = (int) mxGetScalar(prhs[2]);\n", "file_path": "image_processing/toolbox/channels/private/convConst.cpp", "rank": 99, "score": 7.398211915234466 } ]
C++
cpp/src/simulator.cpp
mamariomiamo/online_dmpc
63a135ce6bf6f1c3a0970129a23e569797801b6c
#include "iostream" #include "simulator.h" using namespace Eigen; using namespace std; using namespace std::chrono; using json = nlohmann::json; Simulator::Simulator(std::ifstream& config_file) { Generator::Params p = parseJSON(config_file); _generator = std::make_unique<Generator>(p); _sim_model = std::make_unique<DoubleIntegrator3D>(p.mpc_params.Ts, p.model_params); _h = p.mpc_params.h; _Ts = p.mpc_params.Ts; _po = p.po; _pf = p.pf; _pmin = p.mpc_params.limits.pmin; _pmax = p.mpc_params.limits.pmax; _current_states.reserve(_Ncmd); _trajectories.reserve(_Ncmd); _ellipses = _generator->getEllipses(); for (int i = 0; i < _Ncmd; i++) { State3D agent_i = {_po.col(i), VectorXd::Zero(_po.rows())}; _current_states.push_back(addRandomNoise(agent_i)); } } Generator::Params Simulator::parseJSON(std::ifstream& config_file) { json j; config_file >> j; _N = j["N"]; _Ncmd = j["Ncmd"]; std::string solver_name = j["solver"]; Solver qp_solver; if (!solver_name.compare("qpoases")) qp_solver = kQpoases; else throw std::invalid_argument("Invalid solver '" + solver_name + " '"); _bezier_params = {j["d"], j["num_segments"], j["dim"], j["deg_poly"], j["t_segment"]}; _model_params = {j["zeta_xy"], j["tau_xy"], j["zeta_z"], j["tau_z"]}; VectorXd energy_weights = VectorXd::Zero(static_cast<int>(j["d"]) + 1); energy_weights(2) = j["acc_cost"]; TuningParams tune = {j["s_free"], j["s_obs"], j["s_repel"], j["spd_f"], j["spd_o"], j["spd_r"], j["lin_coll"], j["quad_coll"], energy_weights}; vector<double> pmin_vec = j["pmin"]; vector<double> pmax_vec = j["pmax"]; vector<double> amin_vec = j["amin"]; vector<double> amax_vec = j["amax"]; Vector3d pmin(pmin_vec.data()); Vector3d pmax(pmax_vec.data()); Vector3d amin(amin_vec.data()); Vector3d amax(amax_vec.data()); PhysicalLimits limits = {pmax, pmin, amax, amin}; _mpc_params = {j["h"], j["ts"], j["k_hor"], tune, limits}; EllipseParams ellipse_params; ellipse_params.order = j["order"]; ellipse_params.rmin = j["rmin"]; ellipse_params.c = (Eigen::Vector3d() << 1.0, 1.0, j["height_scaling"]).finished(); std::vector<EllipseParams> ellipse_vec(_Ncmd, ellipse_params); EllipseParams ellipse_params_obs; ellipse_params_obs.order = j["order_obs"]; ellipse_params_obs.rmin = j["rmin_obs"]; ellipse_params_obs.c = (Eigen::Vector3d() << 1.0, 1.0, j["height_scaling_obs"]).finished(); std::vector<EllipseParams> ellipse_vec_obs(_N - _Ncmd, ellipse_params_obs); ellipse_vec.insert(ellipse_vec.end(), ellipse_vec_obs.begin(), ellipse_vec_obs.end()); _pos_std = j["std_position"]; _vel_std = j["std_velocity"]; std::string test_type = j["test"]; if (!test_type.compare("default")) { vector<vector<double>> po_vec = j["po"]; _po = MatrixXd::Zero(j["dim"], _N); for (int i = 0; i < _N; i++) { Vector3d poi(po_vec[i].data()); _po.col(i) = poi; } vector<vector<double>> pf_vec = j["pf"]; _pf = MatrixXd::Zero(j["dim"], _Ncmd); for (int i = 0; i < _Ncmd; i++) { Vector3d pfi(pf_vec[i].data()); _pf.col(i) = pfi; } } else if (!test_type.compare("random")) { _po = generateRandomPoints(_N, limits.pmin.array() + 0.3, limits.pmax.array() - 0.3, ellipse_params.rmin + 0.2); _pf = generateRandomPoints(_Ncmd, limits.pmin.array() + 0.3, limits.pmax.array() - 0.3, ellipse_params.rmin + 0.2); } else throw std::invalid_argument("Invalid test type '" + test_type + " '"); Generator::Params p = {_bezier_params, _model_params, ellipse_vec, _mpc_params, _po, _pf, qp_solver}; return p; } void Simulator::run(int duration) { auto K = static_cast<int>(floor(duration / _Ts)); for (int i = 0; i < _Ncmd; i++) { _trajectories.push_back(MatrixXd::Zero(_po.rows(), K)); } auto max_count = static_cast<int>(_h / _Ts); int count = max_count; high_resolution_clock::time_point t1, t2; for (int k = 0; k < K; k++) { if (count == max_count) { t1 = high_resolution_clock::now(); _inputs = _generator->getNextInputs(_current_states); t2 = high_resolution_clock::now(); auto mpc_duration = duration_cast<microseconds>( t2 - t1 ).count(); cout << "Solving frequency = " << 1000000.0 / mpc_duration << " Hz" << endl; count = 0; } for (int i = 0; i < _Ncmd; i++) { State3D sim_states = _sim_model->applyInput(_current_states[i], _inputs[i].col(count)); _current_states[i] = addRandomNoise(sim_states); _trajectories[i].col(k) = _current_states[i].pos; } count++; } collisionCheck(_trajectories); goalCheck(_current_states); } bool Simulator::collisionCheck(const std::vector<Eigen::MatrixXd> &trajectories) { float rmin_check = 0.15; int order = 2; VectorXd c_check = (Eigen::Vector3d() << 1.0, 1.0, 3.0).finished(); MatrixXd E_check = c_check.asDiagonal(); MatrixXd E1_check = E_check.inverse(); MatrixXd differ; VectorXd dist; bool violation = false; double min_dist; int pos; for (int i = 0; i < _Ncmd; i++) { for (int j = i + 1; j < _Ncmd; j++) { if (i != j) { differ = E1_check * (trajectories[i] - trajectories[j]); dist = pow(((differ.array().pow(order)).colwise().sum()),1.0 / order); min_dist = dist.minCoeff(&pos); if (min_dist < rmin_check) { violation = true; cout << "Collision constraint violation: "; cout << "Vehicles " << i << " and " << j; cout << " will be " << min_dist << "m"; cout << " apart @ t = " << (float)pos * _Ts << "s" << endl; } } } } if (!violation) cout << "No collisions found!" << endl; return violation; } bool Simulator::goalCheck(const std::vector<State3D> &states) { Vector3d diff; double dist; bool reached_goal = true; float goal_tolerance = 0.1; for (int i = 0; i < _Ncmd; i++) { diff = states[i].pos - _pf.col(i); dist = pow(((diff.array().pow(2)).sum()),1.0 / 2); if (dist > goal_tolerance){ cout << "Vehicle " << i << " did not reached its goal by " << dist << " m" << endl; reached_goal = false; } } if (reached_goal) cout << "All the vehicles reached their goals!" << endl; return reached_goal; } State3D Simulator::addRandomNoise(const State3D &states) { std::random_device rd; std::mt19937 gen(rd()); VectorXd state_vector = VectorXd::Zero(6); state_vector << states.pos, states.vel; double sample = 0.0; std::normal_distribution<double> distribution_position(0.0, _pos_std); std::normal_distribution<double> distribution_velocity(0.0, _vel_std); for (int i = 0; i < 6; i++) { if (i < 3) sample = distribution_position(gen); else sample = distribution_velocity(gen); state_vector[i] += sample; } State3D result = {state_vector.segment(0, 3), state_vector.segment(3, 3)}; return result; } void Simulator::saveDataToFile(char const *pathAndName) { ofstream file(pathAndName, ios::out | ios::trunc); if(file) { cout << "Writing solution to text file..." << endl; file << _N << " " << _Ncmd << " " << _pmin.transpose() << " " << _pmax.transpose() << endl; file << _po << endl; file << _pf << endl; for(int i=0; i < _Ncmd; ++i) file << _trajectories[i] << endl; file.close(); } else { cerr << "Error while trying to open file" << endl; } } MatrixXd Simulator::generateRandomPoints(int N, const Vector3d &pmin, const Vector3d &pmax, float rmin) { MatrixXd pts = MatrixXd::Zero(3, N); Vector3d candidate = MatrixXd::Zero(3, 1); VectorXd dist; bool pass = false; pts.col(0) = pmin.array() + (pmax - pmin).array() * ((MatrixXd::Random(3, 1).array() + 1) / 2); for (int n = 1; n < N; ++n) { while (!pass) { candidate = pmin.array() + (pmax - pmin).array() * ((MatrixXd::Random(3, 1).array() + 1) / 2); dist = ((((pts.leftCols(n)).colwise() - candidate).array().square()).colwise().sum()).array().sqrt(); for (int k = 0; k < n; ++k) { pass = dist[k] > rmin; if (!pass) break; } if (pass) pts.col(n) = candidate.array(); } pass = false; } return pts; }
#include "iostream" #include "simulator.h" using namespace Eigen; using namespace std; using namespace std::chrono; using json = nlohmann::json; Simulator::Simulator(std::ifstream& config_file) { Generator::Params p = parseJSON(config_file); _generator = std::make_unique<Generator>(p); _sim_model = std::make_unique<DoubleIntegrator3D>(p.mpc_params.Ts, p.model_params); _h = p.mpc_params.h; _Ts = p.mpc_params.Ts; _po = p.po; _pf = p.pf; _pmin = p.mpc_params.limits.pmin; _pmax = p.mpc_params.limits.pmax; _current_states.reserve(_Ncmd); _trajectories.reserve(_Ncmd); _ellipses = _generator->getEllipses(); for (int i = 0; i < _Ncmd; i++) { State3D agent_i = {_po.col(i), VectorXd::Zero(_po.rows())}; _current_states.push_back(addRandomNoise(agent_i)); } } Generator::Params Simulator::parseJSON(std::ifstream& config_file) { json j; config_file >> j; _N = j["N"]; _Ncmd = j["Ncmd"]; std::string solver_name = j["solver"]; Solver qp_solver; if (!solver_name.compare("qpoases")) qp_solver = kQpoases; else throw std::invalid_argument("Invalid solver '" + solver_name + " '"); _bezier_params = {j["d"], j["num_segments"], j["dim"], j["deg_poly"], j["t_segment"]}; _model_params = {j["zeta_xy"], j["tau_xy"], j["zeta_z"], j["tau_z"]}; VectorXd energy_weights = VectorXd::Zero(static_cast<int>(j["d"]) + 1); energy_weights(2) = j["acc_cost"]; TuningParams tune = {j["s_free"], j["s_obs"], j["s_repel"], j["spd_f"], j["spd_o"], j["spd_r"], j["lin_coll"], j["quad_coll"], energy_weights}; vector<double> pmin_vec = j["pmin"]; vector<double> pmax_vec = j["pmax"]; vector<double> amin_vec = j["amin"]; vector<double> amax_vec = j["amax"]; Vector3d pmin(pmin_vec.data()); Vector3d pmax(pmax_vec.data()); Vector3d amin(amin_vec.data()); Vector3d amax(amax_vec.data()); PhysicalLimits limits = {pmax, pmin, amax, amin}; _mpc_params = {j["h"], j["ts"], j["k_hor"], tune, limits}; EllipseParams ellipse_params; ellipse_params.order = j["order"]; ellipse_params.rmin = j["rmin"]; ellipse_params.c = (Eigen::Vector3d() << 1.0, 1.0, j["height_scaling"]).finished(); std::vector<EllipseParams> ellipse_vec(_Ncmd, ellipse_params); EllipseParams ellipse_params_obs; ellipse_params_obs.order = j["order_obs"]; ellipse_params_obs.rmin = j["rmin_obs"]; ellipse_params_obs.c = (Eigen::Vector3d() << 1.0, 1.0, j["height_scaling_obs"]).finished(); std::vector<EllipseParams> ellipse_vec_obs(_N - _Ncmd, ellipse_params_obs); ellipse_vec.insert(ellipse_vec.end(), ellipse_vec_obs.begin(), ellipse_vec_obs.end()); _pos_std = j["std_position"]; _vel_std = j["std_velocity"]; std::string test_type = j["test"]; if (!test_type.compare("default")) { vector<vector<double>> po_vec = j["po"]; _po = MatrixXd::Zero(j["dim"], _N); for (int i = 0; i < _N; i++) { Vector3d poi(po_vec[i].data()); _po.col(i) = poi; } vector<vector<double>> pf_vec = j["pf"]; _pf = MatrixXd::Zero(j["dim"], _Ncmd); for (int i = 0; i < _Ncmd; i++) { Vector3d pfi(pf_vec[i].data()); _pf.col(i) = pfi; } } else if (!test_type.compare("random")) { _po = generateRandomPoints(_N, limits.pmin.array() + 0.3, limits.pmax.array() - 0.3, ellipse_params.rmin + 0.2); _pf = generateRandomPoints(_Ncmd, limits.pmin.array() + 0.3, limits.pmax.array() - 0.3, ellipse_params.rmin + 0.2); } else throw std::invalid_argument("Invalid test type '" + test_type + " '"); Generator::Params p = {_bezier_params, _model_params, ellipse_vec, _mpc_params, _po, _pf, qp_solver}; return p; } void Simulator::run(int duration) { auto K = static_cast<int>(floor(duration / _Ts)); for (int i = 0; i < _Ncmd; i++) { _trajectories.push_back(MatrixXd::Zero(_po.rows(), K)); } auto max_count = static_cast<int>(_h / _Ts); int count = max_count; high_resolution_clock::time_point t1, t2; for (int k = 0; k < K; k++) { if (count == max_count) { t1 = high_resolution_clock::now(); _inputs = _generator->getNextInputs(_current_states); t2 = high_resolution_clock::now(); auto mpc_duration = duration_cast<microseconds>( t2 - t1 ).count(); cout << "Solving frequency = " << 1000000.0 / mpc_duration << " Hz" << endl; count = 0; } for (int i = 0; i < _Ncmd; i++) { State3D sim_states = _sim_model->applyInput(_current_states[i], _inputs[i].col(count)); _current_states[i] = addRandomNoise(sim_states); _trajectories[i].col(k) = _current_states[i].pos; } count++; } collisionCheck(_trajectories); goalCheck(_current_states); } bool Simulator::collisionCheck(const std::vector<Eigen::MatrixXd> &trajectories) { float rmin_check = 0.15; int order = 2; VectorXd c_check = (Eigen::Vector3d() << 1.0, 1.0, 3.0).finished(); MatrixXd E_check = c_check.asDiagonal(); MatrixXd E1_check = E_check.inverse(); MatrixXd differ; VectorXd dist; bool violation = false; double min_dist; int pos; for (int i = 0; i < _Ncmd; i++) { for (int j = i + 1; j < _Ncmd; j++) { if (i != j) { differ = E1_check * (trajectories[i] - trajectories[j]); dist = pow(((differ.array().pow(order)).colwise().sum()),1.0 / order); min_dist = dist.minCoeff(&pos); if (min_dist < rmin_check) { violation = true; cout << "Collision constraint violation: "; cout << "Vehicles " << i << " and " << j; cout << " will be " << min_dist << "m"; cout << " apart @ t = " << (float)pos * _Ts << "s" << endl; } } } } if (!violation) cout << "No collisions found!" << endl; return violation; } bool Simulator::goalCheck(const std::vector<State3D> &states) { Vector3d diff; double dist; bool reached_goal = true; float goal_tolerance = 0.1; for (int i = 0; i < _Ncmd; i++) { diff = states[i].pos - _pf.col(i); dist = pow(((diff.array().pow(2)).sum()),1.0 / 2); if (dist > goal_tolerance){ cout << "Vehicle " << i << " did not reached its goal by " << dist << " m" << endl; reached_goal = false; } } if (reached_goal) cout << "All the vehicles reached their goals!" << endl; return reached_goal; } State3D Simulator::addRandomNoise(const State3D &states) { std::random_device rd; std::mt19937 gen(rd()); VectorXd state_vector = VectorXd::Zero(6); state_vector << states.pos, states.vel; double sample = 0.0; std::normal_distribution<double> distribution_position(0.0, _pos_std); std::normal_distribution<double> distribution_velocity(0.0, _vel_std); for (int i = 0; i < 6; i++) { if (i < 3) sample = distribution_position(gen); else sample = distribution_velocity(gen); state_vector[i] += sample; } State3D result = {state_vector.segment(0, 3), state_vector.segment(3, 3)}; return result; } void Simulator::saveDataToFile(char const *pathAndName) { ofstream file(pathAndName, ios::out | ios::trunc); if(file) { cout << "Writing solution to text file..." << endl; file << _N << " " << _Ncmd << " " << _pmin.transpose() << " " << _pmax.transpose() << endl;
MatrixXd Simulator::generateRandomPoints(int N, const Vector3d &pmin, const Vector3d &pmax, float rmin) { MatrixXd pts = MatrixXd::Zero(3, N); Vector3d candidate = MatrixXd::Zero(3, 1); VectorXd dist; bool pass = false; pts.col(0) = pmin.array() + (pmax - pmin).array() * ((MatrixXd::Random(3, 1).array() + 1) / 2); for (int n = 1; n < N; ++n) { while (!pass) { candidate = pmin.array() + (pmax - pmin).array() * ((MatrixXd::Random(3, 1).array() + 1) / 2); dist = ((((pts.leftCols(n)).colwise() - candidate).array().square()).colwise().sum()).array().sqrt(); for (int k = 0; k < n; ++k) { pass = dist[k] > rmin; if (!pass) break; } if (pass) pts.col(n) = candidate.array(); } pass = false; } return pts; }
file << _po << endl; file << _pf << endl; for(int i=0; i < _Ncmd; ++i) file << _trajectories[i] << endl; file.close(); } else { cerr << "Error while trying to open file" << endl; } }
function_block-function_prefix_line
[ { "content": "struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleObjectType,\n\n typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 0, "score": 123715.87774488093 }, { "content": " class StringType = std::string, class BooleanType = bool,\n", "file_path": "cpp/include/json.hpp", "rank": 1, "score": 114487.01417738685 }, { "content": " class NumberFloatType = double,\n\n template<typename U> class AllocatorType = std::allocator,\n\n template<typename T, typename SFINAE = void> class JSONSerializer =\n\n adl_serializer>\n", "file_path": "cpp/include/json.hpp", "rank": 2, "score": 113819.6841490909 }, { "content": "struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};\n\n\n\n//////////////////////////\n\n// aliases for detected //\n\n//////////////////////////\n\n\n\ntemplate <typename T>\n\nusing mapped_type_t = typename T::mapped_type;\n\n\n\ntemplate <typename T>\n\nusing key_type_t = typename T::key_type;\n\n\n\ntemplate <typename T>\n\nusing value_type_t = typename T::value_type;\n\n\n\ntemplate <typename T>\n\nusing difference_type_t = typename T::difference_type;\n\n\n\ntemplate <typename T>\n\nusing pointer_t = typename T::pointer;\n", "file_path": "cpp/include/json.hpp", "rank": 3, "score": 108114.05384049391 }, { "content": "struct has_from_json : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename T>\n", "file_path": "cpp/include/json.hpp", "rank": 4, "score": 104162.05589022176 }, { "content": "struct has_to_json : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename T>\n", "file_path": "cpp/include/json.hpp", "rank": 5, "score": 104162.05589022176 }, { "content": "struct is_complete_type : std::false_type {};\n\n\n\ntemplate <typename T>\n", "file_path": "cpp/include/json.hpp", "rank": 6, "score": 103072.427649824 }, { "content": "struct is_compatible_type_impl: std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleType>\n", "file_path": "cpp/include/json.hpp", "rank": 7, "score": 98685.04805035671 }, { "content": "struct has_non_default_from_json : std::false_type {};\n\n\n\ntemplate<typename BasicJsonType, typename T>\n", "file_path": "cpp/include/json.hpp", "rank": 8, "score": 95006.39195518833 }, { "content": "struct is_compatible_string_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleStringType>\n", "file_path": "cpp/include/json.hpp", "rank": 9, "score": 94693.44850100316 }, { "content": "struct is_constructible_array_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleArrayType>\n", "file_path": "cpp/include/json.hpp", "rank": 10, "score": 94693.44850100318 }, { "content": "struct is_compatible_integer_type_impl : std::false_type {};\n\n\n\ntemplate <typename RealIntegerType, typename CompatibleNumberIntegerType>\n", "file_path": "cpp/include/json.hpp", "rank": 11, "score": 94693.44850100316 }, { "content": "struct is_constructible_string_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "cpp/include/json.hpp", "rank": 12, "score": 94693.44850100318 }, { "content": "struct is_compatible_array_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleArrayType>\n", "file_path": "cpp/include/json.hpp", "rank": 13, "score": 94693.44850100316 }, { "content": "struct is_compatible_object_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleObjectType>\n", "file_path": "cpp/include/json.hpp", "rank": 14, "score": 94693.44850100316 }, { "content": "struct is_constructible_object_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleObjectType>\n", "file_path": "cpp/include/json.hpp", "rank": 15, "score": 94693.44850100318 }, { "content": " class NumberIntegerType = std::int64_t,\n", "file_path": "cpp/include/json.hpp", "rank": 16, "score": 91176.77483878152 }, { "content": "struct is_iterator_traits : std::false_type {};\n\n\n\ntemplate <typename T>\n", "file_path": "cpp/include/json.hpp", "rank": 17, "score": 91176.77483878152 }, { "content": " class NumberUnsignedType = std::uint64_t,\n", "file_path": "cpp/include/json.hpp", "rank": 18, "score": 91176.77483878152 }, { "content": " class NumberUnsignedType, class NumberFloatType, \\\n\n template<typename> class AllocatorType, \\\n\n template<typename, typename = void> class JSONSerializer>\n\n\n\n#define NLOHMANN_BASIC_JSON_TPL \\\n\n basic_json<ObjectType, ArrayType, StringType, BooleanType, \\\n\n NumberIntegerType, NumberUnsignedType, NumberFloatType, \\\n\n AllocatorType, JSONSerializer>\n\n\n\n// #include <nlohmann/detail/meta/cpp_future.hpp>\n\n\n\n\n\n#include <ciso646> // not\n\n#include <cstddef> // size_t\n\n#include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n\n// alias templates to reduce boilerplate\n\ntemplate<bool B, typename T = void>\n\nusing enable_if_t = typename std::enable_if<B, T>::type;\n\n\n\ntemplate<typename T>\n\nusing uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;\n\n\n\n// implementation of C++14 index_sequence and affiliates\n\n// source: https://stackoverflow.com/a/32223343\n\ntemplate<std::size_t... Ints>\n", "file_path": "cpp/include/json.hpp", "rank": 19, "score": 86187.93755717744 }, { "content": "struct Constraint {\n\n Eigen::MatrixXd A;\n\n Eigen::VectorXd b;\n\n};\n\n\n", "file_path": "cpp/include/bezier.h", "rank": 20, "score": 70760.94884813867 }, { "content": "struct has_from_json<BasicJsonType, T,\n\n enable_if_t<not is_basic_json<T>::value>>\n\n{\n\n using serializer = typename BasicJsonType::template json_serializer<T, void>;\n\n\n\n static constexpr bool value =\n\n is_detected_exact<void, from_json_function, serializer,\n\n const BasicJsonType&, T&>::value;\n\n};\n\n\n\n// This trait checks if JSONSerializer<T>::from_json(json const&) exists\n\n// this overload is used for non-default-constructible user-defined-types\n\ntemplate <typename BasicJsonType, typename T, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 21, "score": 70671.08821537829 }, { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n\n\n#include <ciso646> // not\n\n#include <limits> // numeric_limits\n\n#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type\n\n#include <utility> // declval\n\n\n\n// #include <nlohmann/detail/iterators/iterator_traits.hpp>\n\n\n", "file_path": "cpp/include/json.hpp", "rank": 22, "score": 69089.01673826629 }, { "content": " class AlwaysVoid,\n\n template <class...> class Op,\n\n class... Args>\n", "file_path": "cpp/include/json.hpp", "rank": 23, "score": 69081.35312202724 }, { "content": "struct iterator_types <\n\n It,\n\n void_t<typename It::difference_type, typename It::value_type, typename It::pointer,\n\n typename It::reference, typename It::iterator_category >>\n\n{\n\n using difference_type = typename It::difference_type;\n\n using value_type = typename It::value_type;\n\n using pointer = typename It::pointer;\n\n using reference = typename It::reference;\n\n using iterator_category = typename It::iterator_category;\n\n};\n\n\n\n// This is required as some compilers implement std::iterator_traits in a way that\n\n// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.\n\ntemplate <typename T, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 24, "score": 68909.33041932802 }, { "content": "struct iterator_types {};\n\n\n\ntemplate <typename It>\n", "file_path": "cpp/include/json.hpp", "rank": 25, "score": 68909.33041932802 }, { "content": "struct is_compatible_type\n\n : is_compatible_type_impl<BasicJsonType, CompatibleType> {};\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/value_t.hpp>\n\n\n\n\n\n#include <array> // array\n\n#include <ciso646> // and\n\n#include <cstddef> // size_t\n\n#include <cstdint> // uint8_t\n\n#include <string> // string\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n\n///////////////////////////\n\n// JSON type enumeration //\n", "file_path": "cpp/include/json.hpp", "rank": 26, "score": 68909.33041932802 }, { "content": "class exception : public std::exception\n\n{\n\n public:\n\n /// returns the explanatory string\n\n const char* what() const noexcept override\n\n {\n\n return m.what();\n\n }\n\n\n\n /// the id of the exception\n\n const int id;\n\n\n\n protected:\n\n exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}\n\n\n\n static std::string name(const std::string& ename, int id_)\n\n {\n\n return \"[json.exception.\" + ename + \".\" + std::to_string(id_) + \"] \";\n\n }\n\n\n", "file_path": "cpp/include/json.hpp", "rank": 27, "score": 68171.44474153106 }, { "content": "enum class value_t : std::uint8_t\n\n{\n\n null, ///< null value\n\n object, ///< object (unordered set of name/value pairs)\n\n array, ///< array (ordered collection of values)\n\n string, ///< string value\n\n boolean, ///< boolean value\n\n number_integer, ///< number value (signed integer)\n\n number_unsigned, ///< number value (unsigned integer)\n\n number_float, ///< number value (floating-point)\n\n discarded ///< discarded by the the parser callback function\n\n};\n\n\n\n/*!\n\n@brief comparison operator for JSON types\n\n\n\nReturns an ordering that is similar to Python:\n\n- order: null < boolean < number < object < array < string\n\n- furthermore, each type is not smaller than itself\n\n- discarded values are not comparable\n", "file_path": "cpp/include/json.hpp", "rank": 28, "score": 68171.44474153106 }, { "content": " class StringType, class BooleanType, class NumberIntegerType, \\\n", "file_path": "cpp/include/json.hpp", "rank": 29, "score": 65786.02525834061 }, { "content": " /// token types for the parser\n\n enum class token_type\n\n {\n\n uninitialized, ///< indicating the scanner is uninitialized\n\n literal_true, ///< the `true` literal\n\n literal_false, ///< the `false` literal\n\n literal_null, ///< the `null` literal\n\n value_string, ///< a string -- use get_string() for actual value\n\n value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value\n\n value_integer, ///< a signed integer -- use get_number_integer() for actual value\n\n value_float, ///< an floating point number -- use get_number_float() for actual value\n\n begin_array, ///< the character for array begin `[`\n\n begin_object, ///< the character for object begin `{`\n\n end_array, ///< the character for array end `]`\n\n end_object, ///< the character for object end `}`\n\n name_separator, ///< the name separator `:`\n\n value_separator, ///< the value separator `,`\n\n parse_error, ///< indicating a parse error\n\n end_of_input, ///< indicating the end of the input buffer\n\n literal_or_value ///< a literal or the begin of a value (only for diagnostics)\n\n };\n", "file_path": "cpp/include/json.hpp", "rank": 30, "score": 64724.114423545456 }, { "content": "struct is_constructible_array_type\n\n : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};\n\n\n\ntemplate <typename RealIntegerType, typename CompatibleNumberIntegerType,\n\n typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 31, "score": 64719.22764130028 }, { "content": "struct is_constructible_string_type\n\n : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleArrayType, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 32, "score": 64719.22764130028 }, { "content": "struct is_compatible_string_type\n\n : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType,\n\n typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 33, "score": 64719.22764130028 }, { "content": "struct is_constructible_object_type\n\n : is_constructible_object_type_impl<BasicJsonType,\n\n ConstructibleObjectType> {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleStringType,\n\n typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 34, "score": 64719.22764130028 }, { "content": "struct is_compatible_type_impl <\n\n BasicJsonType, CompatibleType,\n\n enable_if_t<is_complete_type<CompatibleType>::value >>\n\n{\n\n static constexpr bool value =\n\n has_to_json<BasicJsonType, CompatibleType>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleType>\n", "file_path": "cpp/include/json.hpp", "rank": 35, "score": 64719.22764130028 }, { "content": "struct is_compatible_integer_type\n\n : is_compatible_integer_type_impl<RealIntegerType,\n\n CompatibleNumberIntegerType> {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleType, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 36, "score": 64719.22764130028 }, { "content": "struct is_compatible_array_type\n\n : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleArrayType, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 37, "score": 64719.22764130028 }, { "content": "struct is_compatible_object_type\n\n : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleObjectType,\n\n typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 38, "score": 64719.22764130028 }, { "content": "class BaseSolver {\n\npublic:\n\n BaseSolver(){};\n\n virtual ~BaseSolver(){};\n\n\n\n virtual bool solveQP(const QuadraticProblem& problem) = 0;\n\n virtual Eigen::VectorXd getSolution() = 0;\n\n};\n\n\n", "file_path": "cpp/include/solver.h", "rank": 39, "score": 64161.05059208256 }, { "content": "class json_reverse_iterator : public std::reverse_iterator<Base>\n\n{\n\n public:\n\n using difference_type = std::ptrdiff_t;\n\n /// shortcut to the reverse iterator adapter\n\n using base_iterator = std::reverse_iterator<Base>;\n\n /// the reference type for the pointed-to element\n\n using reference = typename Base::reference;\n\n\n\n /// create reverse iterator from iterator\n\n explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept\n\n : base_iterator(it) {}\n\n\n\n /// create reverse iterator from base class\n\n explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}\n\n\n\n /// post-increment (it++)\n\n json_reverse_iterator const operator++(int)\n\n {\n\n return static_cast<json_reverse_iterator>(base_iterator::operator++(1));\n", "file_path": "cpp/include/json.hpp", "rank": 40, "score": 63579.777818492985 }, { "content": "struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>\n\n{\n\n using serializer = typename BasicJsonType::template json_serializer<T, void>;\n\n\n\n static constexpr bool value =\n\n is_detected_exact<void, to_json_function, serializer, BasicJsonType&,\n\n T>::value;\n\n};\n\n\n\n\n\n///////////////////\n\n// is_ functions //\n\n///////////////////\n\n\n\ntemplate <typename T, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 41, "score": 61292.868053304235 }, { "content": "struct is_constructible_string_type_impl <\n\n BasicJsonType, ConstructibleStringType,\n\n enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,\n\n value_type_t, ConstructibleStringType>::value >>\n\n{\n\n static constexpr auto value =\n\n std::is_constructible<ConstructibleStringType,\n\n typename BasicJsonType::string_t>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "cpp/include/json.hpp", "rank": 42, "score": 61009.48320594353 }, { "content": "struct is_compatible_string_type_impl <\n\n BasicJsonType, CompatibleStringType,\n\n enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,\n\n value_type_t, CompatibleStringType>::value >>\n\n{\n\n static constexpr auto value =\n\n std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "cpp/include/json.hpp", "rank": 43, "score": 61009.48320594353 }, { "content": "struct is_compatible_array_type_impl <\n\n BasicJsonType, CompatibleArrayType,\n\n enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and\n\n is_detected<iterator_t, CompatibleArrayType>::value and\n\n// This is needed because json_reverse_iterator has a ::iterator type...\n\n// Therefore it is detected as a CompatibleArrayType.\n\n// The real fix would be to have an Iterable concept.\n\n not is_iterator_traits<\n\n iterator_traits<CompatibleArrayType>>::value >>\n\n{\n\n static constexpr bool value =\n\n std::is_constructible<BasicJsonType,\n\n typename CompatibleArrayType::value_type>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleArrayType>\n", "file_path": "cpp/include/json.hpp", "rank": 44, "score": 61009.48320594353 }, { "content": "struct is_compatible_object_type_impl <\n\n BasicJsonType, CompatibleObjectType,\n\n enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and\n\n is_detected<key_type_t, CompatibleObjectType>::value >>\n\n{\n\n\n\n using object_t = typename BasicJsonType::object_t;\n\n\n\n // macOS's is_constructible does not play well with nonesuch...\n\n static constexpr bool value =\n\n std::is_constructible<typename object_t::key_type,\n\n typename CompatibleObjectType::key_type>::value and\n\n std::is_constructible<typename object_t::mapped_type,\n\n typename CompatibleObjectType::mapped_type>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleObjectType>\n", "file_path": "cpp/include/json.hpp", "rank": 45, "score": 61009.48320594353 }, { "content": "struct is_constructible_array_type_impl <\n\n BasicJsonType, ConstructibleArrayType,\n\n enable_if_t<not std::is_same<ConstructibleArrayType,\n\n typename BasicJsonType::value_type>::value and\n\n is_detected<value_type_t, ConstructibleArrayType>::value and\n\n is_detected<iterator_t, ConstructibleArrayType>::value and\n\n is_complete_type<\n\n detected_t<value_type_t, ConstructibleArrayType>>::value >>\n\n{\n\n static constexpr bool value =\n\n // This is needed because json_reverse_iterator has a ::iterator type,\n\n // furthermore, std::back_insert_iterator (and other iterators) have a base class `iterator`...\n\n // Therefore it is detected as a ConstructibleArrayType.\n\n // The real fix would be to have an Iterable concept.\n\n not is_iterator_traits <\n\n iterator_traits<ConstructibleArrayType >>::value and\n\n\n\n (std::is_same<typename ConstructibleArrayType::value_type, typename BasicJsonType::array_t::value_type>::value or\n\n has_from_json<BasicJsonType,\n\n typename ConstructibleArrayType::value_type>::value or\n\n has_non_default_from_json <\n\n BasicJsonType, typename ConstructibleArrayType::value_type >::value);\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleArrayType>\n", "file_path": "cpp/include/json.hpp", "rank": 46, "score": 61009.48320594353 }, { "content": "struct is_compatible_integer_type_impl <\n\n RealIntegerType, CompatibleNumberIntegerType,\n\n enable_if_t<std::is_integral<RealIntegerType>::value and\n\n std::is_integral<CompatibleNumberIntegerType>::value and\n\n not std::is_same<bool, CompatibleNumberIntegerType>::value >>\n\n{\n\n // is there an assert somewhere on overflows?\n\n using RealLimits = std::numeric_limits<RealIntegerType>;\n\n using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;\n\n\n\n static constexpr auto value =\n\n std::is_constructible<RealIntegerType,\n\n CompatibleNumberIntegerType>::value and\n\n CompatibleLimits::is_integer and\n\n RealLimits::is_signed == CompatibleLimits::is_signed;\n\n};\n\n\n\ntemplate <typename RealIntegerType, typename CompatibleNumberIntegerType>\n", "file_path": "cpp/include/json.hpp", "rank": 47, "score": 61009.48320594353 }, { "content": "struct is_constructible_object_type_impl <\n\n BasicJsonType, ConstructibleObjectType,\n\n enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and\n\n is_detected<key_type_t, ConstructibleObjectType>::value >>\n\n{\n\n using object_t = typename BasicJsonType::object_t;\n\n\n\n static constexpr bool value =\n\n (std::is_constructible<typename ConstructibleObjectType::key_type, typename object_t::key_type>::value and\n\n std::is_same<typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type>::value) or\n\n (has_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value or\n\n has_non_default_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type >::value);\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleObjectType>\n", "file_path": "cpp/include/json.hpp", "rank": 48, "score": 61009.48320594353 }, { "content": "class type_error : public exception\n\n{\n\n public:\n\n static type_error create(int id_, const std::string& what_arg)\n\n {\n\n std::string w = exception::name(\"type_error\", id_) + what_arg;\n\n return type_error(id_, w.c_str());\n\n }\n\n\n\n private:\n\n type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}\n\n};\n\n\n\n/*!\n\n@brief exception indicating access out of the defined range\n\n\n\nThis exception is thrown in case a library function is called on an input\n\nparameter that exceeds the expected range, for instance in case of array\n\nindices or nonexisting object keys.\n\n\n", "file_path": "cpp/include/json.hpp", "rank": 49, "score": 61009.48320594353 }, { "content": "struct wide_string_input_helper<WideStringType, 2>\n\n{\n\n // UTF-16\n\n static void fill_buffer(const WideStringType& str,\n\n size_t& current_wchar,\n\n std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,\n\n size_t& utf8_bytes_index,\n\n size_t& utf8_bytes_filled)\n\n {\n\n utf8_bytes_index = 0;\n\n\n\n if (current_wchar == str.size())\n\n {\n\n utf8_bytes[0] = std::char_traits<char>::eof();\n\n utf8_bytes_filled = 1;\n\n }\n\n else\n\n {\n\n // get the current character\n\n const auto wc = static_cast<unsigned int>(str[current_wchar++]);\n", "file_path": "cpp/include/json.hpp", "rank": 50, "score": 60639.288673575575 }, { "content": "//\n\n// Created by carlos on 06/04/19.\n\n//\n\n\n\n#ifndef ONLINE_PLANNING_SOLVER_H\n\n#define ONLINE_PLANNING_SOLVER_H\n\n\n\n#include \"iostream\"\n\n#include \"bezier.h\"\n\n#include \"model.h\"\n\n#include \"qpOASES.hpp\"\n\n\n", "file_path": "cpp/include/solver.h", "rank": 51, "score": 60443.929760642175 }, { "content": "struct external_constructor<value_t::number_float>\n\n{\n\n template<typename BasicJsonType>\n\n static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept\n\n {\n\n j.m_type = value_t::number_float;\n\n j.m_value = val;\n\n j.assert_invariant();\n\n }\n\n};\n\n\n\ntemplate<>\n", "file_path": "cpp/include/json.hpp", "rank": 52, "score": 57846.01708435014 }, { "content": "struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>\n\n{\n\n using serializer = typename BasicJsonType::template json_serializer<T, void>;\n\n\n\n static constexpr bool value =\n\n is_detected_exact<T, from_json_function, serializer,\n\n const BasicJsonType&>::value;\n\n};\n\n\n\n// This trait checks if BasicJsonType::json_serializer<T>::to_json exists\n\n// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.\n\ntemplate <typename BasicJsonType, typename T, typename = void>\n", "file_path": "cpp/include/json.hpp", "rank": 53, "score": 57474.85369486241 }, { "content": "class QpOASES : public BaseSolver {\n\npublic:\n\n QpOASES(){};\n\n ~QpOASES(){};\n\n\n\n bool solveQP(const QuadraticProblem& problem);\n\n Eigen::VectorXd getSolution(){return _solution;};\n\n\n\nprivate:\n\n Eigen::VectorXd _solution;\n\n};\n\n\n\n#endif //ONLINE_PLANNING_SOLVER_H\n", "file_path": "cpp/include/solver.h", "rank": 54, "score": 55179.69657759163 }, { "content": " function returns successfully, token_buffer is *not* null-terminated (as it\n\n may contain \\0 bytes), and token_buffer.size() is the number of bytes in the\n\n string.\n\n\n\n @return token_type::value_string if string could be successfully scanned,\n\n token_type::parse_error otherwise\n\n\n\n @note In case of errors, variable error_message contains a textual\n\n description.\n\n */\n\n token_type scan_string()\n\n {\n\n // reset token_buffer (ignore opening quote)\n\n reset();\n\n\n\n // we entered the function by reading an open quote\n\n assert(current == '\\\"');\n\n\n\n while (true)\n\n {\n", "file_path": "cpp/include/json.hpp", "rank": 55, "score": 54877.36409005938 }, { "content": "struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>\n\n{\n\n using iterator_category = std::random_access_iterator_tag;\n\n using value_type = T;\n\n using difference_type = ptrdiff_t;\n\n using pointer = T*;\n\n using reference = T&;\n\n};\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/macro_scope.hpp>\n\n\n\n// #include <nlohmann/detail/meta/cpp_future.hpp>\n\n\n\n// #include <nlohmann/detail/meta/detected.hpp>\n\n\n\n\n\n#include <type_traits>\n\n\n\n// #include <nlohmann/detail/meta/void_t.hpp>\n\n\n\n\n\n// http://en.cppreference.com/w/cpp/experimental/is_detected\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n", "file_path": "cpp/include/json.hpp", "rank": 56, "score": 54352.64152385542 }, { "content": "struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>\n\n : iterator_types<T>\n\n{\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "cpp/include/json.hpp", "rank": 57, "score": 54352.64152385542 }, { "content": "struct hash<nlohmann::json>\n\n{\n\n /*!\n\n @brief return a hash value for a JSON object\n\n\n\n @since version 1.0.0\n\n */\n\n std::size_t operator()(const nlohmann::json& j) const\n\n {\n\n // a naive hashing via the string representation\n\n const auto& h = hash<nlohmann::json::string_t>();\n\n return h(j.dump());\n\n }\n\n};\n\n\n\n/// specialization for std::less<value_t>\n\n/// @note: do not remove the space after '<',\n\n/// see https://github.com/nlohmann/json/pull/679\n\ntemplate<>\n", "file_path": "cpp/include/json.hpp", "rank": 58, "score": 53747.52749240211 }, { "content": "struct cached_power // c = f * 2^e ~= 10^k\n\n{\n\n std::uint64_t f;\n\n int e;\n\n int k;\n\n};\n\n\n\n/*!\n\nFor a normalized diyfp w = f * 2^e, this function returns a (normalized) cached\n\npower-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c\n\nsatisfies (Definition 3.2 from [1])\n\n\n\n alpha <= e_c + e + q <= gamma.\n\n*/\n\ninline cached_power get_cached_power_for_binary_exponent(int e)\n\n{\n\n // Now\n\n //\n\n // alpha <= e_c + e + q <= gamma (1)\n\n // ==> f_c * 2^alpha <= c * 2^e * 2^q\n", "file_path": "cpp/include/json.hpp", "rank": 59, "score": 53244.00220231361 }, { "content": "class DoubleIntegrator2D : public DoubleIntegrator {\n\npublic:\n\n // To be used for ground robots or quadcopters flying in the plane\n\n struct Params {\n\n float zeta_x, tau_x, zeta_y, tau_y;\n\n };\n\n\n\n DoubleIntegrator2D (float time_step, const DoubleIntegrator2D::Params& p);\n\n ~DoubleIntegrator2D(){};\n\n};\n\n\n\n#endif //ONLINE_PLANNING_MODEL_H\n", "file_path": "cpp/include/model.h", "rank": 60, "score": 52744.61246562967 }, { "content": "class DoubleIntegrator3D : public DoubleIntegrator {\n\npublic:\n\n // Define parameters to create a 3D double integrator model\n\n // We assume identical dynamics for X and Y, based on quadcopter experiments\n\n struct Params {\n\n float zeta_xy, tau_xy, zeta_z, tau_z;\n\n };\n\n DoubleIntegrator3D (float time_step, const DoubleIntegrator3D::Params& p);\n\n ~DoubleIntegrator3D(){};\n\n State3D applyInput(const State3D& states, const Eigen::VectorXd& u);\n\n};\n\n\n", "file_path": "cpp/include/model.h", "rank": 61, "score": 52744.61246562967 }, { "content": "class file_input_adapter : public input_adapter_protocol\n\n{\n\n public:\n\n explicit file_input_adapter(std::FILE* f) noexcept\n\n : m_file(f)\n\n {}\n\n\n\n // make class move-only\n\n file_input_adapter(const file_input_adapter&) = delete;\n\n file_input_adapter(file_input_adapter&&) = default;\n\n file_input_adapter& operator=(const file_input_adapter&) = delete;\n\n file_input_adapter& operator=(file_input_adapter&&) = default;\n\n ~file_input_adapter() override = default;\n\n\n\n std::char_traits<char>::int_type get_character() noexcept override\n\n {\n\n return std::fgetc(m_file);\n\n }\n\n\n\n private:\n", "file_path": "cpp/include/json.hpp", "rank": 62, "score": 52193.31495422519 }, { "content": "struct detector<Default, void_t<Op<Args...>>, Op, Args...>\n\n{\n\n using value_t = std::true_type;\n\n using type = Op<Args...>;\n\n};\n\n\n\ntemplate <template <class...> class Op, class... Args>\n\nusing is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;\n\n\n\ntemplate <template <class...> class Op, class... Args>\n\nusing detected_t = typename detector<nonesuch, void, Op, Args...>::type;\n\n\n\ntemplate <class Default, template <class...> class Op, class... Args>\n\nusing detected_or = detector<Default, void, Op, Args...>;\n\n\n\ntemplate <class Default, template <class...> class Op, class... Args>\n\nusing detected_or_t = typename detected_or<Default, Op, Args...>::type;\n\n\n\ntemplate <class Expected, template <class...> class Op, class... Args>\n\nusing is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;\n", "file_path": "cpp/include/json.hpp", "rank": 63, "score": 52187.525473422924 }, { "content": "struct PhysicalLimits {\n\n Eigen::VectorXd pmax, pmin, amax, amin;\n\n};\n\n\n", "file_path": "cpp/include/generator.h", "rank": 64, "score": 52085.76245772974 }, { "content": "// Define a struct for lifted matrices in position and velocity separately\n\nstruct StatePropagator {\n\n Eigen::MatrixXd pos, vel;\n\n};\n\n\n", "file_path": "cpp/include/model.h", "rank": 65, "score": 52085.76245772974 }, { "content": "struct TuningParams {\n\n float s_free, s_obs, s_repel;\n\n int spd_f, spd_o, spd_r;\n\n double lin_coll, quad_coll;\n\n Eigen::VectorXd energy_weights;\n\n};\n\n\n", "file_path": "cpp/include/generator.h", "rank": 66, "score": 52085.76245772974 }, { "content": "struct CollisionConstraint {\n\n Constraint constraint;\n\n Eigen::VectorXd distance;\n\n};\n\n\n", "file_path": "cpp/include/avoidance.h", "rank": 67, "score": 52077.56833093456 }, { "content": "struct InequalityConstraint {\n\n Eigen::MatrixXd A_full;\n\n Eigen::VectorXd b_full;\n\n Eigen::MatrixXd A;\n\n Eigen::VectorXd lower_bound;\n\n Eigen::VectorXd upper_bound;\n\n};\n\n\n", "file_path": "cpp/include/bezier.h", "rank": 68, "score": 52077.56833093456 }, { "content": "class DoubleIntegrator {\n\npublic:\n\n DoubleIntegrator(){};\n\n ~DoubleIntegrator(){};\n\n\n\n StatePropagator get_lambda(int K);\n\n StatePropagator get_A0(int K);\n\n\n\nprotected:\n\n Eigen::MatrixXd _model_A;\n\n Eigen::MatrixXd _model_B;\n\n int _dim;\n\n};\n\n\n", "file_path": "cpp/include/model.h", "rank": 69, "score": 52073.703600189314 }, { "content": "struct QuadraticProblem {\n\n Eigen::MatrixXd H, Aeq, Ain_full, Ain;\n\n Eigen::VectorXd f, beq, bin_full, bin_lower, bin_upper;\n\n};\n\n\n", "file_path": "cpp/include/solver.h", "rank": 70, "score": 52062.280274802426 }, { "content": " // the valid JSON Patch operations\n\n enum class patch_operations {add, remove, replace, move, copy, test, invalid};\n\n\n\n const auto get_op = [](const std::string & op)\n\n {\n\n if (op == \"add\")\n\n {\n\n return patch_operations::add;\n\n }\n\n if (op == \"remove\")\n\n {\n\n return patch_operations::remove;\n\n }\n\n if (op == \"replace\")\n\n {\n\n return patch_operations::replace;\n\n }\n\n if (op == \"move\")\n\n {\n\n return patch_operations::move;\n\n }\n", "file_path": "cpp/include/json.hpp", "rank": 71, "score": 49315.91112384134 }, { "content": "struct diyfp // f * 2^e\n\n{\n\n static constexpr int kPrecision = 64; // = q\n\n\n\n std::uint64_t f = 0;\n\n int e = 0;\n\n\n\n constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}\n\n\n\n /*!\n\n @brief returns x - y\n\n @pre x.e == y.e and x.f >= y.f\n\n */\n\n static diyfp sub(const diyfp& x, const diyfp& y) noexcept\n\n {\n\n assert(x.e == y.e);\n\n assert(x.f >= y.f);\n\n\n\n return {x.f - y.f, x.e};\n\n }\n", "file_path": "cpp/include/json.hpp", "rank": 72, "score": 49063.987319604625 }, { "content": "struct from_json_fn\n\n{\n\n template<typename BasicJsonType, typename T>\n\n auto operator()(const BasicJsonType& j, T& val) const\n\n noexcept(noexcept(from_json(j, val)))\n\n -> decltype(from_json(j, val), void())\n\n {\n\n return from_json(j, val);\n\n }\n\n};\n\n} // namespace detail\n\n\n\n/// namespace to hold default `from_json` function\n\n/// to see why this is required:\n\n/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html\n\nnamespace\n\n{\n\nconstexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;\n\n} // namespace\n\n} // namespace nlohmann\n", "file_path": "cpp/include/json.hpp", "rank": 73, "score": 47565.28577727563 }, { "content": "class json_pointer\n\n{\n\n // allow basic_json to access private members\n\n NLOHMANN_BASIC_JSON_TPL_DECLARATION\n\n friend class basic_json;\n\n\n\n public:\n\n /*!\n\n @brief create JSON pointer\n\n\n\n Create a JSON pointer according to the syntax described in\n\n [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).\n\n\n\n @param[in] s string representing the JSON pointer; if omitted, the empty\n\n string is assumed which references the whole JSON value\n\n\n\n @throw parse_error.107 if the given JSON pointer @a s is nonempty and does\n\n not begin with a slash (`/`); see example below\n\n\n\n @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is\n", "file_path": "cpp/include/json.hpp", "rank": 74, "score": 47565.28577727563 }, { "content": "struct to_json_fn\n\n{\n\n template<typename BasicJsonType, typename T>\n\n auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))\n\n -> decltype(to_json(j, std::forward<T>(val)), void())\n\n {\n\n return to_json(j, std::forward<T>(val));\n\n }\n\n};\n\n} // namespace detail\n\n\n\n/// namespace to hold default `to_json` function\n\nnamespace\n\n{\n\nconstexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;\n\n} // namespace\n\n} // namespace nlohmann\n\n\n\n\n\nnamespace nlohmann\n\n{\n\n\n\ntemplate<typename, typename>\n", "file_path": "cpp/include/json.hpp", "rank": 75, "score": 47565.28577727563 }, { "content": "class basic_json\n\n{\n\n private:\n\n template<detail::value_t> friend struct detail::external_constructor;\n\n friend ::nlohmann::json_pointer<basic_json>;\n\n friend ::nlohmann::detail::parser<basic_json>;\n\n friend ::nlohmann::detail::serializer<basic_json>;\n\n template<typename BasicJsonType>\n\n friend class ::nlohmann::detail::iter_impl;\n\n template<typename BasicJsonType, typename CharType>\n\n friend class ::nlohmann::detail::binary_writer;\n\n template<typename BasicJsonType, typename SAX>\n\n friend class ::nlohmann::detail::binary_reader;\n\n template<typename BasicJsonType>\n\n friend class ::nlohmann::detail::json_sax_dom_parser;\n\n template<typename BasicJsonType>\n\n friend class ::nlohmann::detail::json_sax_dom_callback_parser;\n\n\n\n /// workaround type for MSVC\n\n using basic_json_t = NLOHMANN_BASIC_JSON_TPL;\n", "file_path": "cpp/include/json.hpp", "rank": 76, "score": 47565.28577727563 }, { "content": "struct json_sax\n\n{\n\n /// type for (signed) integers\n\n using number_integer_t = typename BasicJsonType::number_integer_t;\n\n /// type for unsigned integers\n\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n\n /// type for floating-point numbers\n\n using number_float_t = typename BasicJsonType::number_float_t;\n\n /// type for strings\n\n using string_t = typename BasicJsonType::string_t;\n\n\n\n /*!\n\n @brief a null value was read\n\n @return whether parsing should proceed\n\n */\n\n virtual bool null() = 0;\n\n\n\n /*!\n\n @brief a boolean value was read\n\n @param[in] val boolean value\n", "file_path": "cpp/include/json.hpp", "rank": 77, "score": 47565.28577727563 }, { "content": "class json_pointer;\n\n\n\n/*!\n\n@brief default JSON class\n\n\n\nThis type is the default specialization of the @ref basic_json class which\n\nuses the standard template types.\n\n\n\n@since version 1.0.0\n\n*/\n\nusing json = basic_json<>;\n\n} // namespace nlohmann\n\n\n\n#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_\n\n\n\n\n\nnamespace nlohmann\n\n{\n\n/*!\n\n@brief detail namespace with internal helper functions\n", "file_path": "cpp/include/json.hpp", "rank": 78, "score": 47565.28577727563 }, { "content": "class json_ref\n\n{\n\n public:\n\n using value_type = BasicJsonType;\n\n\n\n json_ref(value_type&& value)\n\n : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)\n\n {}\n\n\n\n json_ref(const value_type& value)\n\n : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)\n\n {}\n\n\n\n json_ref(std::initializer_list<json_ref> init)\n\n : owned_value(init), value_ref(&owned_value), is_rvalue(true)\n\n {}\n\n\n\n template <\n\n class... Args,\n\n enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >\n", "file_path": "cpp/include/json.hpp", "rank": 79, "score": 47565.28577727563 }, { "content": "class basic_json;\n\n\n\n/*!\n\n@brief JSON Pointer\n\n\n\nA JSON pointer defines a string syntax for identifying a specific value\n\nwithin a JSON document. It can be used with functions `at` and\n\n`operator[]`. Furthermore, JSON pointers are the base for JSON patches.\n\n\n\n@sa [RFC 6901](https://tools.ietf.org/html/rfc6901)\n\n\n\n@since version 2.0.0\n\n*/\n\ntemplate<typename BasicJsonType>\n", "file_path": "cpp/include/json.hpp", "rank": 80, "score": 47565.28577727563 }, { "content": "class output_stream_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept\n\n : stream(s)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n stream.put(c);\n\n }\n\n\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n stream.write(s, static_cast<std::streamsize>(length));\n\n }\n\n\n\n private:\n\n std::basic_ostream<CharType>& stream;\n\n};\n\n\n\n/// output adapter for basic_string\n\ntemplate<typename CharType, typename StringType = std::basic_string<CharType>>\n", "file_path": "cpp/include/json.hpp", "rank": 81, "score": 47419.04466856492 }, { "content": "class output_string_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_string_adapter(StringType& s) noexcept\n\n : str(s)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n str.push_back(c);\n\n }\n\n\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n str.append(s, length);\n\n }\n\n\n\n private:\n\n StringType& str;\n\n};\n\n\n\ntemplate<typename CharType, typename StringType = std::basic_string<CharType>>\n", "file_path": "cpp/include/json.hpp", "rank": 82, "score": 47419.04466856492 }, { "content": "class output_vector_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_vector_adapter(std::vector<CharType>& vec) noexcept\n\n : v(vec)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n v.push_back(c);\n\n }\n\n\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n std::copy(s, s + length, std::back_inserter(v));\n\n }\n\n\n\n private:\n\n std::vector<CharType>& v;\n\n};\n\n\n\n/// output adapter for output streams\n\ntemplate<typename CharType>\n", "file_path": "cpp/include/json.hpp", "rank": 83, "score": 47419.04466856492 }, { "content": "class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>\n\n : public std::integral_constant<std::size_t, 2> {};\n\n\n\ntemplate <std::size_t N, typename IteratorType>\n", "file_path": "cpp/include/json.hpp", "rank": 84, "score": 47419.04466856492 }, { "content": "class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>\n\n{\n\n public:\n\n using type = decltype(\n\n get<N>(std::declval <\n\n ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));\n\n};\n\n#if defined(__clang__)\n\n #pragma clang diagnostic pop\n\n#endif\n\n} // namespace std\n\n\n\n// #include <nlohmann/detail/meta/cpp_future.hpp>\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n// #include <nlohmann/detail/value_t.hpp>\n\n\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n\n//////////////////\n\n// constructors //\n\n//////////////////\n\n\n\ntemplate<value_t> struct external_constructor;\n\n\n\ntemplate<>\n", "file_path": "cpp/include/json.hpp", "rank": 85, "score": 45396.542938678205 }, { "content": "class json_sax_acceptor\n\n{\n\n public:\n\n using number_integer_t = typename BasicJsonType::number_integer_t;\n\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n\n using number_float_t = typename BasicJsonType::number_float_t;\n\n using string_t = typename BasicJsonType::string_t;\n\n\n\n bool null()\n\n {\n\n return true;\n\n }\n\n\n\n bool boolean(bool /*unused*/)\n\n {\n\n return true;\n\n }\n\n\n\n bool number_integer(number_integer_t /*unused*/)\n\n {\n", "file_path": "cpp/include/json.hpp", "rank": 86, "score": 45166.95469331019 }, { "content": " static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)\n\n {\n\n std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,\n\n [](size_t result, const typename BasicJsonType::object_t::value_type & el)\n\n {\n\n return result += calc_bson_element_size(el.first, el.second);\n\n });\n\n\n\n return sizeof(std::int32_t) + document_size + 1ul;\n\n }\n\n\n\n /*!\n\n @param[in] j JSON value to serialize\n\n @pre j.type() == value_t::object\n\n */\n\n void write_bson_object(const typename BasicJsonType::object_t& value)\n\n {\n\n write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));\n\n\n\n for (const auto& el : value)\n", "file_path": "cpp/include/json.hpp", "rank": 87, "score": 45128.839632213254 }, { "content": " }\n\n\n\n void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)\n\n {\n\n char* begin = number_buffer.data();\n\n char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);\n\n\n\n o->write_characters(begin, static_cast<size_t>(end - begin));\n\n }\n\n\n\n void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)\n\n {\n\n // get number of digits for a float -> text -> float round-trip\n\n static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;\n\n\n\n // the actual conversion\n\n std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), \"%.*g\", d, x);\n\n\n\n // negative value indicates an error\n\n assert(len > 0);\n", "file_path": "cpp/include/json.hpp", "rank": 88, "score": 45128.649381311145 }, { "content": " */\n\n void dump_float(number_float_t x)\n\n {\n\n // NaN / inf\n\n if (not std::isfinite(x))\n\n {\n\n o->write_characters(\"null\", 4);\n\n return;\n\n }\n\n\n\n // If number_float_t is an IEEE-754 single or double precision number,\n\n // use the Grisu2 algorithm to produce short numbers which are\n\n // guaranteed to round-trip, using strtof and strtod, resp.\n\n //\n\n // NB: The test below works if <long double> == <double>.\n\n static constexpr bool is_ieee_single_or_double\n\n = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or\n\n (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);\n\n\n\n dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());\n", "file_path": "cpp/include/json.hpp", "rank": 89, "score": 45128.41770186242 }, { "content": " template<typename NumberType, typename std::enable_if<\n\n std::is_floating_point<NumberType>::value, int>::type = 0>\n\n void write_number_with_ubjson_prefix(const NumberType n,\n\n const bool add_prefix)\n\n {\n\n if (add_prefix)\n\n {\n\n oa->write_character(get_ubjson_float_prefix(n));\n\n }\n\n write_number(n);\n\n }\n\n\n\n // UBJSON: write number (unsigned integer)\n\n template<typename NumberType, typename std::enable_if<\n\n std::is_unsigned<NumberType>::value, int>::type = 0>\n\n void write_number_with_ubjson_prefix(const NumberType n,\n\n const bool add_prefix)\n\n {\n\n if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))\n\n {\n", "file_path": "cpp/include/json.hpp", "rank": 90, "score": 45128.27938927808 }, { "content": " JSON_THROW(out_of_range::create(407, \"integer number \" + std::to_string(n) + \" cannot be represented by UBJSON as it does not fit int64\"));\n\n }\n\n }\n\n\n\n // UBJSON: write number (signed integer)\n\n template<typename NumberType, typename std::enable_if<\n\n std::is_signed<NumberType>::value and\n\n not std::is_floating_point<NumberType>::value, int>::type = 0>\n\n void write_number_with_ubjson_prefix(const NumberType n,\n\n const bool add_prefix)\n\n {\n\n if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())\n\n {\n\n if (add_prefix)\n\n {\n\n oa->write_character(to_char_type('i')); // int8\n\n }\n\n write_number(static_cast<std::int8_t>(n));\n\n }\n\n else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n and n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))\n", "file_path": "cpp/include/json.hpp", "rank": 91, "score": 45128.281171032555 }, { "content": " @param[in] j JSON value to serialize\n\n @param[in] use_count whether to use '#' prefixes (optimized format)\n\n @param[in] use_type whether to use '$' prefixes (optimized format)\n\n @param[in] add_prefix whether prefixes need to be used for this value\n\n */\n\n void write_ubjson(const BasicJsonType& j, const bool use_count,\n\n const bool use_type, const bool add_prefix = true)\n\n {\n\n switch (j.type())\n\n {\n\n case value_t::null:\n\n {\n\n if (add_prefix)\n\n {\n\n oa->write_character(to_char_type('Z'));\n\n }\n\n break;\n\n }\n\n\n\n case value_t::boolean:\n", "file_path": "cpp/include/json.hpp", "rank": 92, "score": 45127.73350136697 }, { "content": " {\n\n prefix_required = false;\n\n oa->write_character(to_char_type('$'));\n\n oa->write_character(first_prefix);\n\n }\n\n }\n\n\n\n if (use_count)\n\n {\n\n oa->write_character(to_char_type('#'));\n\n write_number_with_ubjson_prefix(j.m_value.array->size(), true);\n\n }\n\n\n\n for (const auto& el : *j.m_value.array)\n\n {\n\n write_ubjson(el, use_count, use_type, prefix_required);\n\n }\n\n\n\n if (not use_count)\n\n {\n", "file_path": "cpp/include/json.hpp", "rank": 93, "score": 45126.93414639397 }, { "content": " oa->write_character(to_char_type(']'));\n\n }\n\n\n\n break;\n\n }\n\n\n\n case value_t::object:\n\n {\n\n if (add_prefix)\n\n {\n\n oa->write_character(to_char_type('{'));\n\n }\n\n\n\n bool prefix_required = true;\n\n if (use_type and not j.m_value.object->empty())\n\n {\n\n assert(use_count);\n\n const CharType first_prefix = ubjson_prefix(j.front());\n\n const bool same_prefix = std::all_of(j.begin(), j.end(),\n\n [this, first_prefix](const BasicJsonType & v)\n", "file_path": "cpp/include/json.hpp", "rank": 94, "score": 45126.56491582324 }, { "content": "\n\n case value_t::array:\n\n {\n\n if (add_prefix)\n\n {\n\n oa->write_character(to_char_type('['));\n\n }\n\n\n\n bool prefix_required = true;\n\n if (use_type and not j.m_value.array->empty())\n\n {\n\n assert(use_count);\n\n const CharType first_prefix = ubjson_prefix(j.front());\n\n const bool same_prefix = std::all_of(j.begin() + 1, j.end(),\n\n [this, first_prefix](const BasicJsonType & v)\n\n {\n\n return ubjson_prefix(v) == first_prefix;\n\n });\n\n\n\n if (same_prefix)\n", "file_path": "cpp/include/json.hpp", "rank": 95, "score": 45124.94623988573 }, { "content": " // Use digits10 here to increase compatibility with version 2.\n\n constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;\n\n\n\n assert(last - first >= kMaxExp + 2);\n\n assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);\n\n assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);\n\n\n\n return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);\n\n}\n\n\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/exceptions.hpp>\n\n\n\n// #include <nlohmann/detail/macro_scope.hpp>\n\n\n\n// #include <nlohmann/detail/meta/cpp_future.hpp>\n\n\n\n// #include <nlohmann/detail/output/binary_writer.hpp>\n", "file_path": "cpp/include/json.hpp", "rank": 96, "score": 45124.85073668735 }, { "content": " }\n\n\n\n return true;\n\n }\n\n\n\n bool start_array(std::size_t len)\n\n {\n\n const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);\n\n keep_stack.push_back(keep);\n\n\n\n auto val = handle_value(BasicJsonType::value_t::array, true);\n\n ref_stack.push_back(val.second);\n\n\n\n // check array limit\n\n if (ref_stack.back() and JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))\n\n {\n\n JSON_THROW(out_of_range::create(408, \"excessive array size: \" + std::to_string(len)));\n\n }\n\n\n\n return true;\n", "file_path": "cpp/include/json.hpp", "rank": 97, "score": 45124.844551549264 }, { "content": "\n\n bool start_object(std::size_t len)\n\n {\n\n // check callback for object start\n\n const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);\n\n keep_stack.push_back(keep);\n\n\n\n auto val = handle_value(BasicJsonType::value_t::object, true);\n\n ref_stack.push_back(val.second);\n\n\n\n // check object limit\n\n if (ref_stack.back() and JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))\n\n {\n\n JSON_THROW(out_of_range::create(408, \"excessive object size: \" + std::to_string(len)));\n\n }\n\n\n\n return true;\n\n }\n\n\n\n bool key(string_t& val)\n", "file_path": "cpp/include/json.hpp", "rank": 98, "score": 45124.51426924701 } ]
C++
net/ias/mmc/nap/logcompd.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
#include "Precompiled.h" #include "LogCompD.h" #include "LogMacNd.h" #include "LocalFileLoggingNode.h" #include "LoggingMethodsNode.h" #include "LogComp.h" #include <stdio.h> #include "ChangeNotification.h" CLoggingComponentData::CLoggingComponentData() { ATLTRACE(_T("+NAPMMC+:# +++ CLoggingComponentData::CLoggingComponentData\n")); m_pComponentData = this; } CLoggingComponentData::~CLoggingComponentData() { ATLTRACE(_T("+NAPMMC+:# --- CLoggingComponentData::~CLoggingComponentData\n")); } STDMETHODIMP CLoggingComponentData::Initialize (LPUNKNOWN pUnknown) { ATLTRACE(_T("+NAPMMC+:# CLoggingComponentData::Initialize\n")); m_CLoggingMachineNode.m_pComponentData = this; HRESULT hr = IComponentDataImpl<CLoggingComponentData, CLoggingComponent >::Initialize(pUnknown); if (FAILED(hr)) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- Base class initialization\n")); return hr; } CComPtr<IImageList> spImageList; if (m_spConsole->QueryScopeImageList(&spImageList) != S_OK) { ATLTRACE(_T("+NAPMMC+:***FAILED***: IConsole::QueryScopeImageList failed\n")); return E_UNEXPECTED; } HBITMAP hBitmap16 = LoadBitmap(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_NAPSNAPIN_16)); if (hBitmap16 == NULL) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- LoadBitmap\n")); return S_OK; } HBITMAP hBitmap32 = LoadBitmap(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_NAPSNAPIN_32)); if (hBitmap32 == NULL) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- LoadBitmap\n")); return S_OK; } if (spImageList->ImageListSetStrip((LONG_PTR*)hBitmap16, (LONG_PTR*)hBitmap32, 0, RGB(255, 0, 255)) != S_OK) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- ImageListSetStrip\n")); return E_UNEXPECTED; } INITCOMMONCONTROLSEX initCommCtrlsEx; initCommCtrlsEx.dwSize = sizeof(INITCOMMONCONTROLSEX); initCommCtrlsEx.dwICC = ICC_WIN95_CLASSES ; if (!InitCommonControlsEx(&initCommCtrlsEx)) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- InitCommonControlsEx()\n")); return E_UNEXPECTED; } return S_OK; } STDMETHODIMP CLoggingComponentData::CompareObjects( LPDATAOBJECT lpDataObjectA , LPDATAOBJECT lpDataObjectB ) { ATLTRACE(_T("+NAPMMC+:# CLoggingComponentData::CompareObjects\n")); HRESULT hr; CSnapInItem *pDataA, *pDataB; DATA_OBJECT_TYPES typeA, typeB; hr = GetDataClass(lpDataObjectA, &pDataA, &typeA); if ( FAILED( hr ) ) { return hr; } hr = GetDataClass(lpDataObjectB, &pDataB, &typeB); if ( FAILED( hr ) ) { return hr; } if( pDataA == pDataB ) { return S_OK; } else { return S_FALSE; } } STDMETHODIMP CLoggingComponentData::CreateComponent(LPCOMPONENT *ppComponent) { ATLTRACE(_T("# CLoggingComponentData::CreateComponent\n")); HRESULT hr = E_POINTER; ATLASSERT(ppComponent != NULL); if (ppComponent == NULL) ATLTRACE(_T("# IComponentData::CreateComponent called with ppComponent == NULL\n")); else { *ppComponent = NULL; CComObject< CLoggingComponent >* pComponent; hr = CComObject< CLoggingComponent >::CreateInstance(&pComponent); ATLASSERT(SUCCEEDED(hr)); if (FAILED(hr)) ATLTRACE(_T("# IComponentData::CreateComponent : Could not create IComponent object\n")); else { hr = pComponent->QueryInterface(IID_IComponent, (void**)ppComponent); pComponent->m_pComponentData = this; } } return hr; } STDMETHODIMP CLoggingComponentData::Notify ( LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM param) { ATLTRACE(_T("# CLoggingComponentData::Notify\n")); HRESULT hr; if ( NULL == lpDataObject ) { switch( event ) { case MMCN_PROPERTY_CHANGE: hr = OnPropertyChange( arg, param ); break; default: ATLTRACE(_T("# CLoggingComponent::Notify - called with lpDataObject == NULL and no event handler\n")); hr = E_NOTIMPL; break; } return hr; } CSnapInItem* pItem; DATA_OBJECT_TYPES type; hr = m_pComponentData->GetDataClass(lpDataObject, &pItem, &type); ATLASSERT(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = pItem->Notify( event, arg, param, this, NULL, type ); } return hr; } HRESULT CLoggingComponentData::OnPropertyChange( LPARAM arg , LPARAM lParam ) { ATLTRACE(_T("# CLoggingComponentData::OnPropertyChange\n")); _ASSERTE( m_spConsole != NULL ); HRESULT hr = S_FALSE; if( lParam != NULL ) { CChangeNotification * pChangeNotification = (CChangeNotification *) lParam; hr = pChangeNotification->m_pNode->Notify( MMCN_PROPERTY_CHANGE , NULL , NULL , NULL , NULL , (DATA_OBJECT_TYPES) 0 ); hr = m_spConsole->UpdateAllViews( NULL, lParam, 0); pChangeNotification->Release(); } return hr; }
#include "Precompiled.h" #include "LogCompD.h" #include "LogMacNd.h" #include "LocalFileLoggingNode.h" #include "LoggingMethodsNode.h" #include "LogComp.h" #include <stdio.h> #include "ChangeNotification.h" CLoggingComponentData::CLoggingComponentData() { ATLTRACE(_T("+NAPMMC+:# +++ CLoggingComponentData::CLoggingComponentData\n")); m_pComponentData = this; } CLoggingComponentData::~CLoggingComponentData() { ATLTRACE(_T("+NAPMMC+:# --- CLoggingComponentData::~CLoggingComponentData\n")); } STDMETHODIMP CLoggingComponentData::Initialize (LPUNKNOWN pUnknown) { ATLTRACE(_T("+NAPMMC+:# CLoggingComponentData::Initialize\n")); m_CLoggingMachineNode.m_pComponentData = this; HRESULT hr = IComponentDataImpl<CLoggingComponentData, CLoggingComponent >::Initialize(pUnknown); if (FAILED(hr)) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- Base class initialization\n")); return hr; } CComPtr<IImageList> spImageList; if (m_spConsole->QueryScopeImageList(&spImageList) != S_OK) { ATLTRACE(_T("+NAPMMC+:***FAILED***: IConsole::QueryScopeImageList failed\n")); return E_UNEXPECTED; } HBITMAP hBitmap16 = LoadBitmap(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_NAPSNAPIN_16)); if (hBitmap16 == NULL) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- LoadBitmap\n")); return S_OK; } HBITMAP hBitmap32 = LoadBitmap(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_NAPSNAPIN_32)); if (hBitmap32 == NULL) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- LoadBitmap\n")); return S_OK; } if (spImageList->ImageListSetStrip((LONG_PTR*)hBitmap16, (LONG_PTR*)hBitmap32, 0, RGB(255, 0, 255)) != S_OK) { ATLTRACE(_T("+NAPMMC+:*
, LPARAM lParam ) { ATLTRACE(_T("# CLoggingComponentData::OnPropertyChange\n")); _ASSERTE( m_spConsole != NULL ); HRESULT hr = S_FALSE; if( lParam != NULL ) { CChangeNotification * pChangeNotification = (CChangeNotification *) lParam; hr = pChangeNotification->m_pNode->Notify( MMCN_PROPERTY_CHANGE , NULL , NULL , NULL , NULL , (DATA_OBJECT_TYPES) 0 ); hr = m_spConsole->UpdateAllViews( NULL, lParam, 0); pChangeNotification->Release(); } return hr; }
**FAILED***: CLoggingComponentData::Initialize -- ImageListSetStrip\n")); return E_UNEXPECTED; } INITCOMMONCONTROLSEX initCommCtrlsEx; initCommCtrlsEx.dwSize = sizeof(INITCOMMONCONTROLSEX); initCommCtrlsEx.dwICC = ICC_WIN95_CLASSES ; if (!InitCommonControlsEx(&initCommCtrlsEx)) { ATLTRACE(_T("+NAPMMC+:***FAILED***: CLoggingComponentData::Initialize -- InitCommonControlsEx()\n")); return E_UNEXPECTED; } return S_OK; } STDMETHODIMP CLoggingComponentData::CompareObjects( LPDATAOBJECT lpDataObjectA , LPDATAOBJECT lpDataObjectB ) { ATLTRACE(_T("+NAPMMC+:# CLoggingComponentData::CompareObjects\n")); HRESULT hr; CSnapInItem *pDataA, *pDataB; DATA_OBJECT_TYPES typeA, typeB; hr = GetDataClass(lpDataObjectA, &pDataA, &typeA); if ( FAILED( hr ) ) { return hr; } hr = GetDataClass(lpDataObjectB, &pDataB, &typeB); if ( FAILED( hr ) ) { return hr; } if( pDataA == pDataB ) { return S_OK; } else { return S_FALSE; } } STDMETHODIMP CLoggingComponentData::CreateComponent(LPCOMPONENT *ppComponent) { ATLTRACE(_T("# CLoggingComponentData::CreateComponent\n")); HRESULT hr = E_POINTER; ATLASSERT(ppComponent != NULL); if (ppComponent == NULL) ATLTRACE(_T("# IComponentData::CreateComponent called with ppComponent == NULL\n")); else { *ppComponent = NULL; CComObject< CLoggingComponent >* pComponent; hr = CComObject< CLoggingComponent >::CreateInstance(&pComponent); ATLASSERT(SUCCEEDED(hr)); if (FAILED(hr)) ATLTRACE(_T("# IComponentData::CreateComponent : Could not create IComponent object\n")); else { hr = pComponent->QueryInterface(IID_IComponent, (void**)ppComponent); pComponent->m_pComponentData = this; } } return hr; } STDMETHODIMP CLoggingComponentData::Notify ( LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM param) { ATLTRACE(_T("# CLoggingComponentData::Notify\n")); HRESULT hr; if ( NULL == lpDataObject ) { switch( event ) { case MMCN_PROPERTY_CHANGE: hr = OnPropertyChange( arg, param ); break; default: ATLTRACE(_T("# CLoggingComponent::Notify - called with lpDataObject == NULL and no event handler\n")); hr = E_NOTIMPL; break; } return hr; } CSnapInItem* pItem; DATA_OBJECT_TYPES type; hr = m_pComponentData->GetDataClass(lpDataObject, &pItem, &type); ATLASSERT(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = pItem->Notify( event, arg, param, this, NULL, type ); } return hr; } HRESULT CLoggingComponentData::OnPropertyChange( LPARAM arg
random
[]
C++
include/El/core/Grid.hpp
pjt1988/Elemental
71d3e2b98829594e9f52980a8b1ef7c1e99c724b
#ifndef EL_GRID_HPP #define EL_GRID_HPP namespace El { class Grid { public: explicit Grid ( mpi::Comm comm=mpi::COMM_WORLD, GridOrder order=COLUMN_MAJOR ); explicit Grid( mpi::Comm comm, int height, GridOrder order=COLUMN_MAJOR ); ~Grid(); int Row() const EL_NO_RELEASE_EXCEPT; int Col() const EL_NO_RELEASE_EXCEPT; int Height() const EL_NO_EXCEPT; int Width() const EL_NO_EXCEPT; int Size() const EL_NO_EXCEPT; int Rank() const EL_NO_RELEASE_EXCEPT; GridOrder Order() const EL_NO_EXCEPT; mpi::Comm ColComm() const EL_NO_EXCEPT; mpi::Comm RowComm() const EL_NO_EXCEPT; mpi::Comm Comm() const EL_NO_EXCEPT; int MCRank() const EL_NO_RELEASE_EXCEPT; int MRRank() const EL_NO_RELEASE_EXCEPT; int MDRank() const EL_NO_RELEASE_EXCEPT; int MDPerpRank() const EL_NO_RELEASE_EXCEPT; int VCRank() const EL_NO_RELEASE_EXCEPT; int VRRank() const EL_NO_RELEASE_EXCEPT; int MCSize() const EL_NO_EXCEPT; int MRSize() const EL_NO_EXCEPT; int MDSize() const EL_NO_EXCEPT; int MDPerpSize() const EL_NO_EXCEPT; int VCSize() const EL_NO_EXCEPT; int VRSize() const EL_NO_EXCEPT; mpi::Comm MCComm() const EL_NO_EXCEPT; mpi::Comm MRComm() const EL_NO_EXCEPT; mpi::Comm VCComm() const EL_NO_EXCEPT; mpi::Comm VRComm() const EL_NO_EXCEPT; mpi::Comm MDComm() const EL_NO_EXCEPT; mpi::Comm MDPerpComm() const EL_NO_EXCEPT; explicit Grid ( mpi::Comm viewers, mpi::Group owners, int height, GridOrder order=COLUMN_MAJOR ); int GCD() const EL_NO_EXCEPT; int LCM() const EL_NO_EXCEPT; bool InGrid() const EL_NO_RELEASE_EXCEPT; bool HaveViewers() const EL_NO_EXCEPT; int OwningRank() const EL_NO_RELEASE_EXCEPT; int ViewingRank() const EL_NO_RELEASE_EXCEPT; mpi::Group OwningGroup() const EL_NO_EXCEPT; mpi::Comm OwningComm() const EL_NO_EXCEPT; mpi::Comm ViewingComm() const EL_NO_EXCEPT; int Diag() const EL_NO_RELEASE_EXCEPT; int Diag( int vcRank ) const EL_NO_EXCEPT; int DiagRank() const EL_NO_RELEASE_EXCEPT; int DiagRank( int vcRank ) const EL_NO_EXCEPT; int VCToVR( int vcRank ) const EL_NO_EXCEPT; int VRToVC( int vrRank ) const EL_NO_EXCEPT; int CoordsToVC ( Dist colDist, Dist rowDist, int distRank, int crossRank=0, int redundant=0 ) const EL_NO_RELEASE_EXCEPT; int VCToViewing( int VCRank ) const EL_NO_EXCEPT; #ifdef EL_HAVE_SCALAPACK int BlacsVCHandle() const; int BlacsVRHandle() const; int BlacsMCMRContext() const; #endif static int DefaultHeight( int gridSize ) EL_NO_EXCEPT; static void InitializeDefault(); static void InitializeTrivial(); static void FinalizeDefault(); static void FinalizeTrivial(); static const Grid& Default() EL_NO_RELEASE_EXCEPT; static const Grid& Trivial() EL_NO_RELEASE_EXCEPT; private: bool haveViewers_; int height_, size_, gcd_; bool inGrid_; GridOrder order_; static Grid* defaultGrid; static Grid* trivialGrid; vector<int> diagsAndRanks_; vector<int> vcToViewing_; mpi::Group viewingGroup_, owningGroup_; mpi::Comm viewingComm_, owningComm_, cartComm_, mcComm_, mrComm_, mdComm_, mdPerpComm_, vcComm_, vrComm_; int viewingRank_, owningRank_, mcRank_, mrRank_, mdRank_, mdPerpRank_, vcRank_, vrRank_; #ifdef EL_HAVE_SCALAPACK int blacsVCHandle_, blacsVRHandle_; int blacsMCMRContext_; #endif void SetUpGrid(); const Grid& operator=( Grid& ); Grid( const Grid& ); }; bool operator==( const Grid& A, const Grid& B ) EL_NO_EXCEPT; bool operator!=( const Grid& A, const Grid& B ) EL_NO_EXCEPT; inline void AssertSameGrids( const Grid& ) { } inline void AssertSameGrids( const Grid& g1, const Grid& g2 ) { if( g1 != g2 ) LogicError("Grids did not match"); } template<typename... Args> inline void AssertSameGrids( const Grid& g1, const Grid& g2, Args&... args ) { if( g1 != g2 ) LogicError("Grids did not match"); AssertSameGrids( g2, args... ); } inline bool GridCompare ( const Grid & g1, const Grid & g2 ) { if( g1.Height() != g2.Height() ) return false; if( g1.Order() != g2.Order() ) return false; if( !Congruent( g1.ViewingComm(), g2.ViewingComm() ) ) return false; if( !Congruent( g1.OwningGroup(), g2.OwningGroup() ) ) return false; return true; } } #endif
#ifndef EL_GRID_HPP #define EL_GRID_HPP namespace El { class Grid { public: explicit Grid ( mpi::Comm comm=mpi::COMM_WORLD, GridOrder order=COLUMN_MAJOR ); explicit Grid( mpi::Comm comm, int height, GridOrder order=COLUMN_MAJOR ); ~Grid(); int Row() const EL_NO_RELEASE_EXCEPT; int Col() const EL_NO_RELEASE_EXCEPT; int Height() const EL_NO_EXCEPT; int Width() const EL_NO_EXCEPT; int Size() const EL_NO_EXCEPT; int Rank() const EL_NO_RELEASE_EXCEPT; GridOrder Order() const EL_NO_EXCEPT; mpi::Comm ColComm() const EL_NO_EXCEPT; mpi::Comm RowComm() const EL_NO_EXCEPT; mpi::Comm Comm() const EL_NO_EXCEPT; int MCRank() const EL_NO_RELEASE_EXCEPT; int MRRank() const EL_NO_RELEASE_EXCEPT; int MDRank() const EL_NO_RELEASE_EXCEPT; int MDPerpRank() const EL_NO_RELEASE_EXCEPT; int VCRank() const EL_NO_RELEASE_EXCEPT; int VRRank() const EL_NO_RELEASE_EXCEPT; int MCSize() const EL_NO_EXCEPT; int MRSize() const EL_NO_EXCEPT; int MDSize() const EL_NO_EXCEPT; int MDPerpSize() const EL_NO_EXCEPT; int VCSize() const EL_NO_EXCEPT; int VRSize() const EL_NO_EXCEPT; mpi::Comm MCComm() const EL_NO_EXCEPT; mpi::Comm MRComm() const EL_NO_EXCEPT; mpi::Comm VCComm() const EL_NO_EXCEPT; mpi::Comm VRComm() const EL_NO_EXCEPT; mpi::Comm MDComm() const EL_NO_EXCEPT; mpi::Comm MDPerpComm() const EL_NO_EXCEPT; explicit Grid ( mpi::Comm viewers, mpi::Group owners, int height, GridOrder order=COLUMN_MAJOR ); int GCD() const EL_NO_EXCEPT; int LCM() const EL_NO_EXCEPT; bool InGrid() const EL_NO_RELEASE_EXCEPT; bool HaveViewers() const EL_NO_EXCEPT; int OwningRank() const EL_NO_RELEASE_EXCEPT; int ViewingRank() const EL_NO_RELEASE_EXCEPT; mpi::Group OwningGroup() const EL_NO_EXCEPT; mpi::Comm OwningComm() const EL_NO_EXCEPT; mpi::Comm ViewingComm() const EL_NO_EXCEPT; int Diag() const EL_NO_RELEASE_EXCEPT; int Diag( int vcRank ) const EL_NO_EXCEPT; int DiagRank() const EL_NO_RELEASE_EXCEPT; int DiagRank( int vcRank ) const EL_NO_EXCEPT; int VCToVR( int vcRank ) const EL_NO_EXCEPT; int VRToVC( int vrRank ) const EL_NO_EXCEPT; int CoordsToVC ( Dist colDist, Dist rowDist, int distRank, int crossRank=0, int redundant=0 ) const EL_NO_RELEASE_EXCEPT; int VCToViewing( int VCRank ) const EL_NO_EXCEPT; #ifdef EL_HAVE_SCALAPACK int BlacsVCHandle() const; int BlacsVRHandle() const; int BlacsMCMRContext() const; #endif static int DefaultHeight( int gridSize ) EL_NO_EXCEPT; static void InitializeDefault(); static void InitializeTrivial(); static void FinalizeDefault(); static void FinalizeTrivial(); static const Grid& Default() EL_NO_RELEASE_EXCEPT; static const Grid& Trivial() EL_NO_RELEASE_EXCEPT; private: bool haveViewers_; int height_, size_, gcd_; bool inGrid_; GridOrder order_; static Grid* defaultGrid; static Grid* trivialGrid; vector<int> diagsAndRanks_; vector<int> vcToViewing_; mpi::Group viewingGroup_, owningGroup_; mpi::Comm viewingComm_, owningComm_, cartComm_, mcComm_, mrComm_, mdComm_, mdPerpComm_, vcComm_, vrComm_; int viewingRank_, owningRank_, mcRank_, mrRank_, mdRank_, mdPerpRank_, vcRank_, vrRank_; #ifdef EL_HAVE_SCALAPACK int blacsVCHandle_, blacsVRHandle_; int blacsMCMRContext_; #endif void SetUpGrid(); const Grid& operator=( Grid& ); Grid( const Grid& ); }; bool operator==( const Grid& A, const Grid& B ) EL_NO_EXCEPT; bool operator!=( const Grid& A, const Grid& B ) EL_NO_EXCEPT; inline void AssertSameGrids( const Grid& ) { } inline void AssertSameGrids( const Grid& g1, const Grid& g2 ) { if( g1 != g2 ) LogicError("Grids did not match"); } template<typename... Args> inline void AssertSameGrids( const Grid& g1, const Grid& g2, Args&... args ) { if( g1 != g2 ) LogicError("Grids did not match"); AssertSameGrids( g2, args... ); }
} #endif
inline bool GridCompare ( const Grid & g1, const Grid & g2 ) { if( g1.Height() != g2.Height() ) return false; if( g1.Order() != g2.Order() ) return false; if( !Congruent( g1.ViewingComm(), g2.ViewingComm() ) ) return false; if( !Congruent( g1.OwningGroup(), g2.OwningGroup() ) ) return false; return true; }
function_block-full_function
[ { "content": "struct IsIntegral<BigInt> { static const bool value = true; };\n\n#endif\n\n\n\n// For querying whether an element's type is a scalar\n\n// --------------------------------------------------\n\ntemplate<typename T> struct IsScalar\n\n{ static const bool value=false; };\n\ntemplate<> struct IsScalar<unsigned>\n\n{ static const bool value=true; };\n\ntemplate<> struct IsScalar<int>\n\n{ static const bool value=true; };\n\ntemplate<> struct IsScalar<unsigned long>\n\n{ static const bool value=true; };\n\ntemplate<> struct IsScalar<long int>\n\n{ static const bool value=true; };\n\ntemplate<> struct IsScalar<unsigned long long>\n\n{ static const bool value=true; };\n\ntemplate<> struct IsScalar<long long int>\n\n{ static const bool value=true; };\n\ntemplate<> struct IsScalar<float>\n", "file_path": "include/El/core.hpp", "rank": 0, "score": 294438.4629640886 }, { "content": "// For getting the MPI argument instance (for internal usage)\n\nclass Args : public choice::MpiArgs\n\n{\n\npublic:\n\n Args\n\n ( int argc, char** argv,\n\n mpi::Comm comm=mpi::COMM_WORLD, ostream& error=cerr )\n\n : choice::MpiArgs(argc,argv,comm,error)\n\n { }\n\n virtual ~Args() { }\n\nprotected:\n\n virtual void HandleVersion( ostream& os=cout ) const;\n\n virtual void HandleBuild( ostream& os=cout ) const;\n\n};\n\nArgs& GetArgs();\n\n\n\n// For processing command-line arguments\n\ntemplate<typename T>\n\nT Input( string name, string desc );\n\ntemplate<typename T>\n\nT Input( string name, string desc, T defaultVal );\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 1, "score": 262179.14333678543 }, { "content": "class ElementalMatrix : public AbstractDistMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef ElementalMatrix<Ring> type;\n\n typedef AbstractDistMatrix<Ring> absType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n // Move constructor\n\n ElementalMatrix( type&& A ) EL_NO_EXCEPT;\n\n\n\n virtual ~ElementalMatrix();\n\n\n\n virtual type* Copy() const override = 0;\n\n virtual type* Construct\n\n ( const El::Grid& grid, int root ) const override = 0;\n\n virtual type* ConstructTranspose\n\n ( const El::Grid& grid, int root ) const override = 0;\n", "file_path": "include/El/core/DistMatrix/Element.hpp", "rank": 3, "score": 246979.53897355648 }, { "content": "class BlockMatrix : public AbstractDistMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef BlockMatrix<Ring> type;\n\n typedef AbstractDistMatrix<Ring> absType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n // Move constructor\n\n BlockMatrix( type&& A ) EL_NO_EXCEPT;\n\n\n\n virtual ~BlockMatrix();\n\n\n\n virtual type* Copy() const override = 0;\n\n virtual type* Construct\n\n ( const El::Grid& grid, int root ) const override = 0;\n\n virtual type* ConstructTranspose\n\n ( const El::Grid& grid, int root ) const override = 0;\n", "file_path": "include/El/core/DistMatrix/Block.hpp", "rank": 4, "score": 246979.53897355648 }, { "content": "struct Helper<Ret(Class::*)(Args...) const>\n\n{ using type = std::function<Ret(Args...)>; };\n\n\n\n} // namespace make_function\n\n\n\ntemplate<typename Function>\n\ntypename make_function::Helper<decltype(&Function::operator())>::type\n\nMakeFunction(Function const& func) { return func; }\n\n*/\n\n\n\n// Handles generic types that are functors, delegate to its 'operator()'\n\ntemplate<typename T>\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 5, "score": 241403.85494936607 }, { "content": "class ArgException : public std::logic_error\n\n{\n\npublic:\n\n ArgException( const char* msg=\"\" ) : std::logic_error( msg ) { }\n\n};\n\n\n\nnamespace choice {\n\n\n\nusing std::cerr;\n\nusing std::cout;\n\nusing std::endl;\n\nusing std::ostream;\n\nusing std::string;\n\nusing std::stringstream;\n\nusing std::vector;\n\n\n\ntemplate<typename TOut,typename TIn>\n\ninline TOut Cast( const TIn& input )\n\n{\n\n stringstream stream;\n", "file_path": "include/El/core/imports/choice.hpp", "rank": 6, "score": 240873.11665974045 }, { "content": "struct IsIntegral { static const bool value = std::is_integral<T>::value; };\n\n#ifdef EL_HAVE_MPC\n\ntemplate<>\n", "file_path": "include/El/core.hpp", "rank": 7, "score": 232116.665639862 }, { "content": "class DistMatrix<Ring,STAR,STAR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,STAR,STAR> type;\n\n typedef DistMatrix<Ring,STAR,STAR> transType;\n\n typedef DistMatrix<Ring,STAR,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& g=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& g=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/STAR_STAR.hpp", "rank": 8, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,MD,STAR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,MD,STAR> type;\n\n typedef DistMatrix<Ring,STAR,MD> transType;\n\n typedef DistMatrix<Ring,MD,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/MD_STAR.hpp", "rank": 9, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,STAR,MC> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,STAR,MC> type;\n\n typedef DistMatrix<Ring,MC,STAR> transType;\n\n typedef DistMatrix<Ring,MC,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/STAR_MC.hpp", "rank": 10, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,STAR,MD> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,STAR,MD> type;\n\n typedef DistMatrix<Ring,MD,STAR> transType;\n\n typedef DistMatrix<Ring,MD,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/STAR_MD.hpp", "rank": 11, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,MC,STAR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,MC,STAR> type;\n\n typedef DistMatrix<Ring,STAR,MC> transType;\n\n typedef DistMatrix<Ring,MC,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/MC_STAR.hpp", "rank": 12, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,MR,MC> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,MR,MC> type;\n\n typedef DistMatrix<Ring,MC,MR> transType;\n\n typedef DistMatrix<Ring,MD,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/MR_MC.hpp", "rank": 13, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,STAR,MR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,STAR,MR> type;\n\n typedef DistMatrix<Ring,MR,STAR> transType;\n\n typedef DistMatrix<Ring,MR,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/STAR_MR.hpp", "rank": 14, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,MC,MR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,MC,MR> type;\n\n typedef DistMatrix<Ring,MR,MC> transType;\n\n typedef DistMatrix<Ring,MD,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/MC_MR.hpp", "rank": 15, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,VC,STAR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,VC,STAR> type;\n\n typedef DistMatrix<Ring,STAR,VC> transType;\n\n typedef DistMatrix<Ring,VC,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/VC_STAR.hpp", "rank": 16, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,VR,STAR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,VR,STAR> type;\n\n typedef DistMatrix<Ring,STAR,VR> transType;\n\n typedef DistMatrix<Ring,VR,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/VR_STAR.hpp", "rank": 17, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,STAR,VR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,STAR,VR> type;\n\n typedef DistMatrix<Ring,VR,STAR> transType;\n\n typedef DistMatrix<Ring,VR,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/STAR_VR.hpp", "rank": 18, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,STAR,VC> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,STAR,VC> type;\n\n typedef DistMatrix<Ring,VC,STAR> transType;\n\n typedef DistMatrix<Ring,VC,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/STAR_VC.hpp", "rank": 19, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,CIRC,CIRC> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,CIRC,CIRC> type;\n\n typedef DistMatrix<Ring,CIRC,CIRC> transType;\n\n typedef DistMatrix<Ring,CIRC,CIRC> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/CIRC_CIRC.hpp", "rank": 20, "score": 218741.76709120168 }, { "content": "class DistMatrix<Ring,MR,STAR> : public ElementalMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef ElementalMatrix<Ring> elemType;\n\n typedef DistMatrix<Ring,MR,STAR> type;\n\n typedef DistMatrix<Ring,STAR,MR> transType;\n\n typedef DistMatrix<Ring,MR,STAR> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a height x width distributed matrix\n\n DistMatrix\n\n ( Int height, Int width, const El::Grid& grid=Grid::Default(), int root=0 );\n", "file_path": "include/El/core/DistMatrix/Element/MR_STAR.hpp", "rank": 21, "score": 218741.76709120168 }, { "content": " ElDist colDist, rowDist;\n", "file_path": "include/El/core/DistMatrix.h", "rank": 22, "score": 216362.85268685123 }, { "content": "// TODO(poulson): Convert to accepting Grid rather than mpi::Comm\n\nclass DistPermutation\n\n{\n\npublic:\n\n DistPermutation( const Grid& g=Grid::Default() );\n\n\n\n void SetGrid( const Grid& g );\n\n\n\n void Empty();\n\n void MakeIdentity( Int size );\n\n\n\n void ReserveSwaps( Int maxSwaps );\n\n void MakeArbitrary() const;\n\n\n\n const DistPermutation& operator=( const Permutation& p );\n\n const DistPermutation& operator=( const DistPermutation& p );\n\n\n\n void Swap( Int origin, Int dest );\n\n void SwapSequence( const DistPermutation& perm, Int offset=0 );\n\n void SwapSequence\n\n ( const ElementalMatrix<Int>& swapOrigins,\n", "file_path": "include/El/core/DistPermutation.hpp", "rank": 23, "score": 215164.89332833287 }, { "content": "class DistMatrixReadProxy<T,T,U,V,BLOCK,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,BLOCK> proxType;\n\n\n\n bool locked_;\n\n bool madeCopy_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n\n\n DistMatrixReadProxy\n\n ( const AbstractDistMatrix<T>& A,\n\n const ProxyCtrl& ctrl=ProxyCtrl() )\n\n { \n\n if( A.ColDist() == U && A.RowDist() == V && A.Wrap() == BLOCK )\n\n {\n\n const bool colMisalign = \n\n ( ctrl.colConstrain && \n", "file_path": "include/El/core/Proxy.hpp", "rank": 24, "score": 214507.64732857162 }, { "content": "class DistMatrixReadProxy<S,T,U,V,BLOCK,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,BLOCK> proxType;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n\n\n DistMatrixReadProxy\n\n ( const AbstractDistMatrix<S>& A,\n\n const ProxyCtrl& ctrl=ProxyCtrl() )\n\n { \n\n prox_ = new proxType(A.Grid());\n\n if( ctrl.rootConstrain )\n\n prox_->SetRoot( ctrl.root );\n\n if( ctrl.colConstrain )\n\n prox_->AlignCols( ctrl.blockHeight, ctrl.colAlign, ctrl.colCut );\n\n if( ctrl.rowConstrain )\n\n prox_->AlignRows( ctrl.blockWidth, ctrl.rowAlign, ctrl.rowCut );\n", "file_path": "include/El/core/Proxy.hpp", "rank": 25, "score": 214507.64732857162 }, { "content": "class DistMatrixReadProxy<T,T,U,V,ELEMENT,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,ELEMENT> proxType;\n\n\n\n bool locked_;\n\n bool madeCopy_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n\n\n DistMatrixReadProxy\n\n ( const AbstractDistMatrix<T>& A,\n\n const ElementalProxyCtrl& ctrl=ElementalProxyCtrl() )\n\n { \n\n if( A.ColDist() == U && A.RowDist() == V && A.Wrap() == ELEMENT )\n\n {\n\n const bool colMisalign = \n\n ( ctrl.colConstrain && A.ColAlign() != ctrl.colAlign );\n", "file_path": "include/El/core/Proxy.hpp", "rank": 26, "score": 214507.64732857162 }, { "content": "class DistMatrixWriteProxy<S,T,U,V,BLOCK,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,BLOCK> proxType;\n\n\n\n AbstractDistMatrix<S>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixWriteProxy\n\n ( AbstractDistMatrix<S>& A,\n\n const ProxyCtrl& ctrl=ProxyCtrl() )\n\n : orig_(A)\n\n { \n\n prox_ = new proxType(A.Grid());\n\n if( ctrl.rootConstrain )\n\n prox_->SetRoot( ctrl.root );\n\n if( ctrl.colConstrain )\n\n prox_->AlignCols( ctrl.blockHeight, ctrl.colAlign, ctrl.colCut );\n", "file_path": "include/El/core/Proxy.hpp", "rank": 27, "score": 214507.64732857162 }, { "content": "class DistMatrixWriteProxy<T,T,U,V,ELEMENT,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,ELEMENT> proxType;\n\n\n\n bool madeCopy_;\n\n AbstractDistMatrix<T>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixWriteProxy\n\n ( AbstractDistMatrix<T>& A,\n\n const ElementalProxyCtrl& ctrl=ElementalProxyCtrl() )\n\n : orig_(A)\n\n { \n\n if( A.ColDist() == U && A.RowDist() == V && A.Wrap() == ELEMENT )\n\n {\n\n const bool colMisalign = \n\n ( ctrl.colConstrain && A.ColAlign() != ctrl.colAlign );\n", "file_path": "include/El/core/Proxy.hpp", "rank": 28, "score": 214507.64732857162 }, { "content": "class DistMatrixReadProxy<S,T,U,V,ELEMENT,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,ELEMENT> proxType;\n\n\n\n bool locked_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n\n\n DistMatrixReadProxy\n\n ( const AbstractDistMatrix<S>& A,\n\n const ElementalProxyCtrl& ctrl=ElementalProxyCtrl() )\n\n { \n\n prox_ = new proxType(A.Grid());\n\n if( ctrl.rootConstrain )\n\n prox_->SetRoot( ctrl.root );\n\n if( ctrl.colConstrain )\n\n prox_->AlignCols( ctrl.colAlign ); \n", "file_path": "include/El/core/Proxy.hpp", "rank": 29, "score": 214507.64732857162 }, { "content": "class DistMatrixWriteProxy<S,T,U,V,ELEMENT,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,ELEMENT> proxType;\n\n\n\n AbstractDistMatrix<S>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixWriteProxy\n\n ( AbstractDistMatrix<S>& A,\n\n const ElementalProxyCtrl& ctrl=ElementalProxyCtrl() )\n\n : orig_(A)\n\n { \n\n prox_ = new proxType(A.Grid());\n\n if( ctrl.rootConstrain )\n\n prox_->SetRoot( ctrl.root );\n\n if( ctrl.colConstrain )\n\n prox_->AlignCols( ctrl.colAlign ); \n", "file_path": "include/El/core/Proxy.hpp", "rank": 30, "score": 214507.64732857162 }, { "content": "class DistMatrixWriteProxy<T,T,U,V,BLOCK,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,BLOCK> proxType;\n\n\n\n bool madeCopy_;\n\n AbstractDistMatrix<T>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixWriteProxy\n\n ( AbstractDistMatrix<T>& A,\n\n const ProxyCtrl& ctrl=ProxyCtrl() )\n\n : orig_(A)\n\n { \n\n if( A.ColDist() == U && A.RowDist() == V && A.Wrap() == BLOCK )\n\n {\n\n const bool colMisalign = \n\n ( ctrl.colConstrain && \n", "file_path": "include/El/core/Proxy.hpp", "rank": 31, "score": 214507.64732857162 }, { "content": "class DistMatrix<Ring,VC,STAR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,VC,STAR,BLOCK> type;\n\n typedef DistMatrix<Ring,STAR,VC,BLOCK> transType;\n\n typedef DistMatrix<Ring,VC,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/VC_STAR.hpp", "rank": 32, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,MD,STAR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,MD,STAR,BLOCK> type;\n\n typedef DistMatrix<Ring,STAR,MD,BLOCK> transType;\n\n typedef DistMatrix<Ring,MD,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/MD_STAR.hpp", "rank": 33, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,STAR,MC,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,STAR,MC,BLOCK> type;\n\n typedef DistMatrix<Ring,MC,STAR,BLOCK> transType;\n\n typedef DistMatrix<Ring,MC,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/STAR_MC.hpp", "rank": 34, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,MR,MC,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,MR,MC,BLOCK> type;\n\n typedef DistMatrix<Ring,MC,MR,BLOCK> transType;\n\n typedef DistMatrix<Ring,MD,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/MR_MC.hpp", "rank": 35, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,MR,STAR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,MR,STAR,BLOCK> type;\n\n typedef DistMatrix<Ring,STAR,MR,BLOCK> transType;\n\n typedef DistMatrix<Ring,MR,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/MR_STAR.hpp", "rank": 36, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,MC,MR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,MC,MR,BLOCK> type;\n\n typedef DistMatrix<Ring,MR,MC,BLOCK> transType;\n\n typedef DistMatrix<Ring,MD,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n", "file_path": "include/El/core/DistMatrix/Block/MC_MR.hpp", "rank": 37, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,STAR,STAR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,STAR,STAR,BLOCK> type;\n\n typedef DistMatrix<Ring,STAR,STAR,BLOCK> transType;\n\n typedef DistMatrix<Ring,STAR,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n", "file_path": "include/El/core/DistMatrix/Block/STAR_STAR.hpp", "rank": 38, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,STAR,MD,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,STAR,MD,BLOCK> type;\n\n typedef DistMatrix<Ring,MD,STAR,BLOCK> transType;\n\n typedef DistMatrix<Ring,MD,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/STAR_MD.hpp", "rank": 39, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,CIRC,CIRC,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,CIRC,CIRC,BLOCK> type;\n\n typedef DistMatrix<Ring,CIRC,CIRC,BLOCK> transType;\n\n typedef DistMatrix<Ring,CIRC,CIRC,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n", "file_path": "include/El/core/DistMatrix/Block/CIRC_CIRC.hpp", "rank": 40, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,MC,STAR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,MC,STAR,BLOCK> type;\n\n typedef DistMatrix<Ring,STAR,MC,BLOCK> transType;\n\n typedef DistMatrix<Ring,MC,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/MC_STAR.hpp", "rank": 41, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,STAR,VR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,STAR,VR,BLOCK> type;\n\n typedef DistMatrix<Ring,VR,STAR,BLOCK> transType;\n\n typedef DistMatrix<Ring,VR,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/STAR_VR.hpp", "rank": 42, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,STAR,MR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,STAR,MR,BLOCK> type;\n\n typedef DistMatrix<Ring,MR,STAR,BLOCK> transType;\n\n typedef DistMatrix<Ring,MR,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/STAR_MR.hpp", "rank": 43, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,STAR,VC,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,STAR,VC,BLOCK> type;\n\n typedef DistMatrix<Ring,VC,STAR,BLOCK> transType;\n\n typedef DistMatrix<Ring,VC,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/STAR_VC.hpp", "rank": 44, "score": 212470.645264201 }, { "content": "class DistMatrix<Ring,VR,STAR,BLOCK> : public BlockMatrix<Ring>\n\n{\n\npublic:\n\n typedef AbstractDistMatrix<Ring> absType;\n\n typedef BlockMatrix<Ring> blockType;\n\n typedef DistMatrix<Ring,VR,STAR,BLOCK> type;\n\n typedef DistMatrix<Ring,STAR,VR,BLOCK> transType;\n\n typedef DistMatrix<Ring,VR,STAR,BLOCK> diagType;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n\n\n // Create a 0 x 0 distributed matrix with default (and unpinned) block size\n\n DistMatrix( const El::Grid& grid=Grid::Default(), int root=0 );\n\n\n\n // Create a 0 x 0 distributed matrix with fixed block size\n\n DistMatrix\n\n ( const El::Grid& grid, Int blockHeight, Int blockWidth, int root=0 );\n\n\n\n // Create a height x width distributed matrix with default block size\n", "file_path": "include/El/core/DistMatrix/Block/VR_STAR.hpp", "rank": 45, "score": 212470.645264201 }, { "content": "// Use a simple 1d distribution where each process owns a fixed number of\n\n// indices,\n\n// if last process, height - (commSize-1)*floor(height/commSize)\n\n// otherwise, floor(height/commSize)\n\nclass DistMap\n\n{\n\npublic:\n\n // Constructors and destructors\n\n DistMap( const El::Grid& grid=El::Grid::Default() );\n\n DistMap( Int numSources, const El::Grid& grid=El::Grid::Default() );\n\n // TODO(poulson): Constructor for building from a DistMap\n\n ~DistMap();\n\n\n\n // Map manipulation\n\n // Collectively map each process's local set of indices\n\n void Translate( vector<Int>& localInds ) const;\n\n void Translate\n\n ( vector<Int>& localInds, const vector<int>& origOwners ) const;\n\n\n\n // composite(i) := second(first(i))\n\n void Extend( DistMap& firstMap ) const;\n\n void Extend( const DistMap& firstMap, DistMap& compositeMap ) const;\n\n\n\n // High-level information\n", "file_path": "include/El/core/DistMap/decl.hpp", "rank": 46, "score": 210833.21877490857 }, { "content": "// Use a simple 1d distribution where each process owns a fixed number of\n\n// sources:\n\n// if last process, numSources - (commSize-1)*floor(numSources/commSize)\n\n// otherwise, floor(numSources/commSize)\n\nclass DistGraph\n\n{\n\npublic:\n\n // Constructors and destructors\n\n // ============================\n\n DistGraph( const El::Grid& grid=El::Grid::Default() );\n\n DistGraph( Int numSources, const El::Grid& grid=El::Grid::Default() );\n\n DistGraph\n\n ( Int numSources, Int numTargets,\n\n const El::Grid& grid=El::Grid::Default() );\n\n DistGraph( const Graph& graph );\n\n // TODO: Move constructor\n\n DistGraph( const DistGraph& graph );\n\n ~DistGraph();\n\n\n\n // Assignment and reconfiguration\n\n // ==============================\n\n\n\n // Making a copy\n\n // -------------\n", "file_path": "include/El/core/DistGraph/decl.hpp", "rank": 47, "score": 210825.2272426486 }, { "content": "class DistMultiVec;\n\n\n\n} // namespace El\n\n\n\n#include <El/core/DistMatrix/Abstract.hpp>\n\n\n\n#include <El/core/DistMatrix/Element.hpp>\n\n#include <El/core/DistMatrix/Element/CIRC_CIRC.hpp>\n\n#include <El/core/DistMatrix/Element/MC_MR.hpp>\n\n#include <El/core/DistMatrix/Element/MC_STAR.hpp>\n\n#include <El/core/DistMatrix/Element/MD_STAR.hpp>\n\n#include <El/core/DistMatrix/Element/MR_MC.hpp>\n\n#include <El/core/DistMatrix/Element/MR_STAR.hpp>\n\n#include <El/core/DistMatrix/Element/STAR_MC.hpp>\n\n#include <El/core/DistMatrix/Element/STAR_MD.hpp>\n\n#include <El/core/DistMatrix/Element/STAR_MR.hpp>\n\n#include <El/core/DistMatrix/Element/STAR_STAR.hpp>\n\n#include <El/core/DistMatrix/Element/STAR_VC.hpp>\n\n#include <El/core/DistMatrix/Element/STAR_VR.hpp>\n\n#include <El/core/DistMatrix/Element/VC_STAR.hpp>\n", "file_path": "include/El/core/DistMatrix.hpp", "rank": 48, "score": 210809.595762662 }, { "content": "#endif\n\n#ifdef EL_HAVE_MPC\n\nclass BigInt;\n", "file_path": "include/El/core.hpp", "rank": 49, "score": 210652.68108393543 }, { "content": "class DistMatrixReadWriteProxy<S,T,U,V,ELEMENT,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,ELEMENT> proxType;\n\n\n\n AbstractDistMatrix<S>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixReadWriteProxy\n\n ( AbstractDistMatrix<S>& A,\n\n const ElementalProxyCtrl& ctrl=ElementalProxyCtrl() )\n\n : orig_(A)\n\n { \n\n prox_ = new proxType(A.Grid());\n\n if( ctrl.rootConstrain )\n\n prox_->SetRoot( ctrl.root );\n\n if( ctrl.colConstrain )\n\n prox_->AlignCols( ctrl.colAlign ); \n", "file_path": "include/El/core/Proxy.hpp", "rank": 50, "score": 210197.64430400674 }, { "content": "class DistMatrixReadWriteProxy<T,T,U,V,ELEMENT,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,ELEMENT> proxType;\n\n\n\n bool madeCopy_;\n\n AbstractDistMatrix<T>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixReadWriteProxy\n\n ( AbstractDistMatrix<T>& A,\n\n const ElementalProxyCtrl& ctrl=ElementalProxyCtrl() )\n\n : orig_(A)\n\n { \n\n if( A.ColDist() == U && A.RowDist() == V && A.Wrap() == ELEMENT )\n\n {\n\n const bool colMisalign = \n\n ( ctrl.colConstrain && A.ColAlign() != ctrl.colAlign );\n", "file_path": "include/El/core/Proxy.hpp", "rank": 51, "score": 210197.64430400674 }, { "content": "class DistMatrixReadWriteProxy<T,T,U,V,BLOCK,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,BLOCK> proxType;\n\n\n\n bool madeCopy_;\n\n AbstractDistMatrix<T>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixReadWriteProxy\n\n ( AbstractDistMatrix<T>& A,\n\n const ProxyCtrl& ctrl=ProxyCtrl() )\n\n : orig_(A)\n\n { \n\n if( A.ColDist() == U && A.RowDist() == V && A.Wrap() == BLOCK )\n\n {\n\n const bool colMisalign = \n\n ( ctrl.colConstrain && \n", "file_path": "include/El/core/Proxy.hpp", "rank": 52, "score": 210197.64430400674 }, { "content": "class DistMatrixReadWriteProxy<S,T,U,V,BLOCK,void>\n\n{\n\nprivate:\n\n typedef DistMatrix<T,U,V,BLOCK> proxType;\n\n\n\n AbstractDistMatrix<S>& orig_;\n\n proxType* prox_;\n\n\n\npublic:\n\n // TODO: Add try-catch statements into constructors?\n\n DistMatrixReadWriteProxy\n\n ( AbstractDistMatrix<S>& A,\n\n const ProxyCtrl& ctrl=ProxyCtrl() )\n\n : orig_(A)\n\n { \n\n prox_ = new proxType(A.Grid());\n\n if( ctrl.rootConstrain )\n\n prox_->SetRoot( ctrl.root );\n\n if( ctrl.colConstrain )\n\n prox_->AlignCols( ctrl.blockHeight, ctrl.colAlign, ctrl.colCut );\n", "file_path": "include/El/core/Proxy.hpp", "rank": 53, "score": 210197.64430400674 }, { "content": "class DistMatrix;\n\n\n\n} // namespace El\n\n\n\n#include <El/core/Matrix/decl.hpp>\n\n#include <El/core/Graph/decl.hpp>\n\n#include <El/core/DistMap/decl.hpp>\n\n#include <El/core/DistGraph/decl.hpp>\n\n#include <El/core/SparseMatrix/decl.hpp>\n\n#include <El/core/DistSparseMatrix/decl.hpp>\n\n#include <El/core/DistMultiVec/decl.hpp>\n\n#include <El/core/View/decl.hpp>\n\n#include <El/blas_like/level1/decl.hpp>\n\n\n\n#include <El/core/Matrix/impl.hpp>\n\n#include <El/core/Grid.hpp>\n\n#include <El/core/DistMatrix.hpp>\n\n#include <El/core/Proxy.hpp>\n\n\n\n// Implement the intertwined parts of the library\n", "file_path": "include/El/core.hpp", "rank": 54, "score": 210080.71076209657 }, { "content": "struct function_traits<ReturnType(ClassType::*)(Args...) const>\n\n{\n\n enum { arity = sizeof...(Args) };\n\n typedef function<ReturnType (Args...)> f_type;\n\n};\n\n\n\n// Handles pointers to member functions\n\ntemplate<typename ClassType,typename ReturnType,typename... Args>\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 55, "score": 208224.2545627339 }, { "content": " def DefaultHeight(numProcs):\n\n factor = c_int()\n\n lib.ElGridDefaultHeight(numProcs,pointer(factor))\n", "file_path": "python/core/Grid.py", "rank": 56, "score": 207065.78754172014 }, { "content": " def DiagRank(self,vcRank):\n\n pathRank = c_int()\n\n lib.ElGridDiagRank(self.obj,vcRank,pointer(pathRank))\n", "file_path": "python/core/Grid.py", "rank": 57, "score": 207061.8250711353 }, { "content": " def ColComm(self):\n\n colComm = mpi.Comm()\n\n lib.ElGridColComm(self.obj,pointer(colComm))\n", "file_path": "python/core/Grid.py", "rank": 58, "score": 207022.29625431783 }, { "content": " def RowComm(self):\n\n rowComm = mpi.Comm()\n\n lib.ElGridRowComm(self.obj,pointer(rowComm))\n", "file_path": "python/core/Grid.py", "rank": 59, "score": 207018.33085453557 }, { "content": "class AbstractDistMatrix\n\n{\n\npublic:\n\n // Typedefs\n\n // ========\n\n typedef AbstractDistMatrix<Ring> type;\n\n\n\n // Constructors and destructors\n\n // ============================\n\n // Move constructor\n\n AbstractDistMatrix( type&& A ) EL_NO_EXCEPT;\n\n\n\n virtual ~AbstractDistMatrix();\n\n\n\n virtual type* Copy() const = 0;\n\n virtual type* Construct\n\n ( const El::Grid& grid, int root ) const = 0;\n\n virtual type* ConstructTranspose\n\n ( const El::Grid& grid, int root ) const = 0;\n\n virtual type* ConstructDiagonal\n", "file_path": "include/El/core/DistMatrix/Abstract.hpp", "rank": 60, "score": 206678.90499139944 }, { "content": "class Args\n\n{\n\npublic:\n\n Args( int argc, char** argv, ostream& error=cerr );\n\n virtual ~Args() { }\n\n\n\n template<typename T>\n\n T Input( string name, string desc );\n\n template<typename T>\n\n T Input( string name, string desc, T defaultVal );\n\n\n\n void Process( ostream& os=cout ) const;\n\n void PrintReport( ostream& os=cout ) const;\n\n\n\nprotected:\n\n int argc_;\n\n char** argv_;\n\n vector<bool> usedArgs_;\n\n ostream& error_;\n\n\n", "file_path": "include/El/core/imports/choice.hpp", "rank": 61, "score": 205445.28899000422 }, { "content": " ElConstGrid grid;\n", "file_path": "include/El/core/DistMatrix.h", "rank": 62, "score": 205041.46868641942 }, { "content": "class DistMultiVec\n\n{\n\npublic:\n\n // Constructors and destructors\n\n // ============================\n\n DistMultiVec( const El::Grid& grid=El::Grid::Default() );\n\n DistMultiVec\n\n ( Int height, Int width, const El::Grid& grid=El::Grid::Default() );\n\n DistMultiVec( const DistMultiVec<Ring>& A );\n\n ~DistMultiVec();\n\n\n\n // Assignment and reconfiguration\n\n // ===============================\n\n\n\n // Change the matrix size\n\n // ----------------------\n\n void Empty( bool freeMemory=true );\n\n void Resize( Int height, Int width );\n\n\n\n // Change the distribution\n", "file_path": "include/El/core/DistMultiVec/decl.hpp", "rank": 63, "score": 202743.8846107414 }, { "content": "class DistSparseMatrix\n\n{\n\npublic:\n\n // Constructors and destructors\n\n // ============================\n\n DistSparseMatrix\n\n ( const El::Grid& grid=El::Grid::Default() );\n\n DistSparseMatrix\n\n ( Int height, Int width, const El::Grid& grid=El::Grid::Default() );\n\n DistSparseMatrix( const DistSparseMatrix<Ring>& A );\n\n // TODO(poulson): Move constructor\n\n ~DistSparseMatrix();\n\n\n\n // Assignment and reconfiguration\n\n // ==============================\n\n\n\n // Change the size of the matrix\n\n // -----------------------------\n\n void Empty( bool freeMemory=true );\n\n void Resize( Int height, Int width );\n", "file_path": "include/El/core/DistSparseMatrix/decl.hpp", "rank": 64, "score": 202743.8846107414 }, { "content": " def ColComm(self):\n\n comm = mpi.Comm()\n\n args = [self.obj,pointer(comm)]\n\n if self.tag == iTag: lib.ElDistMatrixColComm_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixColComm_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixColComm_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixColComm_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixColComm_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 65, "score": 202118.9357532702 }, { "content": " def RowComm(self):\n\n comm = mpi.Comm()\n\n args = [self.obj,pointer(comm)]\n\n if self.tag == iTag: lib.ElDistMatrixRowComm_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixRowComm_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixRowComm_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixRowComm_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixRowComm_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 66, "score": 202115.0777525586 }, { "content": "class SpyWindow : public QWidget\n\n{\n\npublic:\n\n SpyWindow( QWidget* parent=0 ); \n\n ~SpyWindow();\n\n\n\n void Spy\n\n ( const Matrix<Int>* A, \n\n QString title=QString(\"Default title\") );\n\n\n\nprivate:\n\n QScrollArea *scroll_;\n\n SpyWidget *spy_;\n\n const Matrix<Int> *matrix_;\n\n};\n\n\n\n} // namespace El\n\n\n\n#endif // ifdef EL_HAVE_QT5\n\n#endif // ifndef EL_SPYWINDOW_HPP\n", "file_path": "include/El/io/SpyWindow.hpp", "rank": 67, "score": 200770.71869816148 }, { "content": "class DisplayWidget : public QWidget\n\n{\n\npublic:\n\n DisplayWidget( QWidget* parent=0 );\n\n ~DisplayWidget();\n\n // TODO: Generalize to function which displays f(A), where f is functor\n\n void DisplayReal( const Matrix<T>* A );\n\n void DisplayReal( const Matrix<T>* A, Base<T> minVal, Base<T> maxVal );\n\n void DisplayImag( const Matrix<T>* A );\n\n void DisplayImag( const Matrix<T>* A, Base<T> minVal, Base<T> maxVal );\n\n // TODO: Add colorbar\n\n\n\n void SavePng( string basename ) const;\n\n\n\nprotected:\n\n void paintEvent( QPaintEvent* event );\n\n\n\nprivate:\n\n QPixmap pixmap_;\n\n};\n\n\n\n} // namespace El\n\n\n\n#endif // ifdef EL_HAVE_QT5\n\n#endif // ifndef EL_DISPLAYWIDGET_HPP\n", "file_path": "include/El/io/DisplayWidget.hpp", "rank": 68, "score": 200770.71869816148 }, { "content": "class SpyWidget : public QWidget\n\n{\n\npublic:\n\n SpyWidget( QWidget* parent=0 );\n\n ~SpyWidget();\n\n void Spy( const Matrix<Int>* A );\n\n // TODO: Change style\n\nprotected:\n\n void paintEvent( QPaintEvent* event );\n\n\n\nprivate:\n\n QPixmap pixmap_;\n\n};\n\n\n\n} // namespace El\n\n\n\n#endif // ifdef EL_HAVE_QT5\n\n#endif // ifndef EL_SPYWIDGET_HPP\n", "file_path": "include/El/io/SpyWidget.hpp", "rank": 69, "score": 200770.71869816148 }, { "content": "// This is defined in choice.hpp\n\nclass ArgException;\n\n\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 70, "score": 200541.99389465142 }, { "content": "class BigInt\n\n{\n\nprivate:\n\n mpz_t mpzInt_;\n\n\n\n void Init( int numBits=mpfr::NumIntBits() );\n\n\n\npublic:\n\n mpz_ptr Pointer();\n\n mpz_srcptr LockedPointer() const;\n\n void SetNumLimbs( int numLimbs );\n\n void SetMinBits( int minBits );\n\n int NumLimbs() const;\n\n int NumBits() const;\n\n\n\n BigInt();\n\n BigInt( const BigInt& a, int numBits=mpfr::NumIntBits() );\n\n BigInt( const unsigned& a, int numBits=mpfr::NumIntBits() );\n\n BigInt( const unsigned long& a, int numBits=mpfr::NumIntBits() );\n\n BigInt( const unsigned long long& a, int numBits=mpfr::NumIntBits() );\n", "file_path": "include/El/core/imports/mpfr.hpp", "rank": 71, "score": 200513.85119090544 }, { "content": "// Forward declaration\n\nclass DistGraph;\n\ntemplate<typename T>\n", "file_path": "include/El/core/Graph/decl.hpp", "rank": 72, "score": 199994.24798176019 }, { "content": "// Unfortunately Q_OBJECT does not support templates...\n\nclass DisplayWindow : public QWidget\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n DisplayWindow( QWidget* parent=0 ); \n\n ~DisplayWindow();\n\n\n\n void Display\n\n ( const Matrix<double>* A, \n\n QString title=QString(\"Default title\") );\n\n void Display\n\n ( const Matrix<double>* A, \n\n double minVal, double maxVal,\n\n QString title=QString(\"Default title\") );\n\n\n\nprivate:\n\n QScrollArea *scroll_;\n\n DisplayWidget<double> *display_;\n\n const Matrix<double> *matrix_;\n", "file_path": "include/El/io/DisplayWindow-premoc.hpp", "rank": 73, "score": 196829.87871489342 }, { "content": "class MpiArgs\n\n{\n\npublic:\n\n MpiArgs\n\n ( int argc, char** argv,\n\n mpi::Comm comm=mpi::COMM_WORLD, ostream& error=cerr );\n\n virtual ~MpiArgs() { }\n\n\n\n template<typename T>\n\n T Input( string name, string desc );\n\n template<typename T>\n\n T Input( string name, string desc, T defaultVal );\n\n\n\n void Process( ostream& os=cout ) const;\n\n void PrintReport( ostream& os=cout ) const;\n\n\n\nprotected:\n\n int argc_;\n\n char** argv_;\n\n vector<bool> usedArgs_;\n", "file_path": "include/El/core/imports/mpi_choice.hpp", "rank": 74, "score": 195897.6951381695 }, { "content": "class DistMatrixReadProxy; \n\n\n\ntemplate<typename S,typename T,Dist U,Dist V>\n", "file_path": "include/El/core/Proxy.hpp", "rank": 75, "score": 195372.19720161776 }, { "content": "class DistMatrixWriteProxy;\n\n\n\ntemplate<typename S,typename T,Dist U,Dist V>\n", "file_path": "include/El/core/Proxy.hpp", "rank": 76, "score": 195372.19720161776 }, { "content": "class DistSparseMatrix;\n\n\n", "file_path": "include/El/core/Graph/decl.hpp", "rank": 77, "score": 195372.19720161776 }, { "content": "class MatrixWriteProxy<T,T,void>\n\n{\n\nprivate:\n\n Matrix<T>& orig_;\n\n\n\npublic:\n\n MatrixWriteProxy( Matrix<T>& A )\n\n : orig_(A)\n\n { }\n\n\n\n ~MatrixWriteProxy() { }\n\n\n\n const Matrix<T>& GetLocked() const { return orig_; }\n\n Matrix<T>& Get() { return orig_; }\n\n};\n\n\n\ntemplate<typename S,typename T,typename=EnableIf<CanBidirectionalCast<S,T>>>\n", "file_path": "include/El/core/Proxy.hpp", "rank": 78, "score": 194570.0249939296 }, { "content": "class MatrixReadProxy<T,T,void>\n\n{\n\nprivate:\n\n bool locked_;\n\n Matrix<T>& orig_;\n\n\n\npublic:\n\n MatrixReadProxy( const Matrix<T>& A )\n\n : locked_(true),\n\n orig_(const_cast<Matrix<T>&>(A))\n\n { }\n\n\n\n MatrixReadProxy( Matrix<T>& A )\n\n : locked_(false),\n\n orig_(A)\n\n { }\n\n\n\n ~MatrixReadProxy() { }\n\n\n\n const Matrix<T>& GetLocked() const { return orig_; }\n\n\n\n Matrix<T>& Get()\n\n {\n\n if( locked_ )\n\n LogicError(\"Attempted to extract mutable from immutable\");\n\n return orig_;\n\n }\n\n};\n\n\n\ntemplate<typename S,typename T,typename=EnableIf<CanCast<T,S>>>\n", "file_path": "include/El/core/Proxy.hpp", "rank": 79, "score": 194570.0249939296 }, { "content": "class DistMatrixReadWriteProxy; \n\n\n\ntemplate<typename S,typename T,Dist U,Dist V>\n", "file_path": "include/El/core/Proxy.hpp", "rank": 80, "score": 191000.5140946288 }, { "content": "class MatrixReadWriteProxy<T,T,void>\n\n{\n\nprivate:\n\n Matrix<T>& orig_;\n\n\n\npublic:\n\n MatrixReadWriteProxy( Matrix<T>& A )\n\n : orig_(A)\n\n { }\n\n\n\n ~MatrixReadWriteProxy() { }\n\n\n\n const Matrix<T>& GetLocked() const { return orig_; }\n\n Matrix<T>& Get() { return orig_; }\n\n};\n\n\n", "file_path": "include/El/core/Proxy.hpp", "rank": 81, "score": 190628.95589571202 }, { "content": "class UnrecoverableException : public std::runtime_error\n\n{\n\npublic:\n\n UnrecoverableException( const char* msg=\"Unrecoverable exception\" )\n\n : std::runtime_error( msg ) { }\n\n};\n\n\n\ntemplate<typename... ArgPack>\n\nvoid UnrecoverableError( const ArgPack& ... args );\n\ntemplate<typename... ArgPack>\n\nvoid LogicError( const ArgPack& ... args );\n\ntemplate<typename... ArgPack>\n\nvoid RuntimeError( const ArgPack& ... args );\n\n\n\n// This is the only place that Elemental is currently using duck-typing.\n\n// I'm not sure if it's a good idea to use it more often.\n\ntemplate<class MatType>\n\nstring DimsString( const MatType& A, string label=\"Matrix\" );\n\n\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 82, "score": 190588.53837522282 }, { "content": "// Unfortunately Q_OBJECT does not support templates...\n\nclass ComplexDisplayWindow : public QWidget\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n ComplexDisplayWindow( QWidget* parent=0 ); \n\n ~ComplexDisplayWindow();\n\n\n\n void Display\n\n ( const Matrix<Complex<double>>* A, \n\n QString title=QString(\"Default title\") );\n\n void Display\n\n ( const Matrix<Complex<double>>* A, \n\n double minRealVal, double maxRealVal,\n\n double minImagVal, double maxImagVal,\n\n QString title=QString(\"Default title\") );\n\n\n\nprivate:\n\n QScrollArea *realScroll_, *imagScroll_;\n\n DisplayWidget<Complex<double>> *realDisplay_, *imagDisplay_;\n", "file_path": "include/El/io/ComplexDisplayWindow-premoc.hpp", "rank": 83, "score": 189526.00479717128 }, { "content": "// An exception which signifies that a matrix was unexpectedly singular.\n\nclass SingularMatrixException : public std::runtime_error\n\n{\n\npublic:\n\n SingularMatrixException( const char* msg=\"Matrix was singular\" )\n\n : std::runtime_error( msg ) { }\n\n};\n\n\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 84, "score": 186845.1248536163 }, { "content": "// An exception which signifies a zero pivot was chosen, though the matrix\n\n// may not actually be singular\n\nclass ZeroPivotException : public std::runtime_error\n\n{\n\npublic:\n\n ZeroPivotException( const char* msg=\"Zero pivot was chosen\" )\n\n : std::runtime_error( msg ) { }\n\n};\n\n\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 85, "score": 186845.1248536163 }, { "content": "// An exception which signifies that a matrix was unexpectedly non-HPSD\n\nclass NonHPSDMatrixException : public std::runtime_error\n\n{\n\npublic:\n\n NonHPSDMatrixException( const char* msg=\"Matrix was not HPSD\" )\n\n : std::runtime_error( msg ) { }\n\n};\n\n\n\nEL_DEBUG_ONLY(\n\n void EnableTracing();\n\n void DisableTracing();\n\n\n\n void PushCallStack( string s );\n\n void PopCallStack();\n\n void DumpCallStack( ostream& os=cerr );\n\n\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 86, "score": 183284.66445750068 }, { "content": "// An exception which signifies that a matrix was unexpectedly non-HPD\n\nclass NonHPDMatrixException : public std::runtime_error\n\n{\n\npublic:\n\n NonHPDMatrixException( const char* msg=\"Matrix was not HPD\" )\n\n : std::runtime_error( msg ) { }\n\n};\n\n\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 87, "score": 183284.66445750068 }, { "content": "class DistSparseLDLFactorization\n\n{\n\npublic:\n\n DistSparseLDLFactorization();\n\n\n\n // Find a reordering and initialize the frontal tree.\n\n void Initialize\n\n ( const DistSparseMatrix<Field>& A,\n\n bool hermitian=true,\n\n const BisectCtrl& bisectCtrl=BisectCtrl() );\n\n\n\n // Avoid explicit calls to a graph partitioner by making use of analytic\n\n // bisections of a grid graph.\n\n //\n\n // NOTE: These routines should *only* be called on lexicographically-ordered\n\n // grid graphs.\n\n void Initialize2DGridGraph\n\n ( Int gridDim0,\n\n Int gridDim1,\n\n const DistSparseMatrix<Field>& A,\n", "file_path": "include/El/lapack_like/factor/ldl/sparse/numeric.hpp", "rank": 88, "score": 179199.52867523965 }, { "content": "class Complex<float> : public std::complex<float>\n\n{\n\npublic:\n\n typedef float realType;\n\n // TODO: Extend operators to other types?\n\n using std::complex<realType>::operator=;\n\n using std::complex<realType>::operator-=;\n\n using std::complex<realType>::operator+=;\n\n using std::complex<realType>::operator*=;\n\n using std::complex<realType>::operator/=;\n\n\n\n template<typename S>\n\n inline Complex( const S& a );\n\n template<typename S>\n\n inline Complex( const Complex<S>& a );\n\n \n\n template<typename S,typename T>\n\n inline Complex( const S& a, const T& b );\n\n\n\n inline Complex();\n\n inline Complex( const std::complex<realType>& a );\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/El/core/Element/Complex/decl.hpp", "rank": 89, "score": 178266.49130784266 }, { "content": "class Complex<double> : public std::complex<double>\n\n{\n\npublic:\n\n typedef double realType;\n\n // TODO: Extend operators to other types?\n\n using std::complex<realType>::operator=;\n\n using std::complex<realType>::operator-=;\n\n using std::complex<realType>::operator+=;\n\n using std::complex<realType>::operator*=;\n\n using std::complex<realType>::operator/=;\n\n\n\n template<typename S>\n\n inline Complex( const S& a );\n\n template<typename S>\n\n inline Complex( const Complex<S>& a );\n\n\n\n template<typename S,typename T>\n\n inline Complex( const S& a, const T& b );\n\n\n\n inline Complex();\n\n inline Complex( const std::complex<realType>& a );\n\n};\n\n\n\n#ifdef EL_HAVE_QUAD\n\ntemplate<>\n", "file_path": "include/El/core/Element/Complex/decl.hpp", "rank": 90, "score": 178266.49130784266 }, { "content": "class Complex<Quad> : public std::complex<Quad>\n\n{\n\npublic:\n\n typedef Quad realType;\n\n // TODO: Extend operators to other types?\n\n using std::complex<realType>::operator=;\n\n using std::complex<realType>::operator-=;\n\n using std::complex<realType>::operator+=;\n\n using std::complex<realType>::operator*=;\n\n using std::complex<realType>::operator/=;\n\n\n\n template<typename S>\n\n inline Complex( const S& a );\n\n template<typename S>\n\n inline Complex( const Complex<S>& a );\n\n\n\n template<typename S,typename T>\n\n inline Complex( const S& a, const T& b );\n\n\n\n inline Complex();\n\n inline Complex( const std::complex<realType>& a );\n\n};\n\n#endif\n\n\n\n#ifdef EL_HAVE_QD\n\ntemplate<>\n", "file_path": "include/El/core/Element/Complex/decl.hpp", "rank": 91, "score": 178266.49130784266 }, { "content": "enum GridOrder\n\n{\n\n ROW_MAJOR,\n\n COLUMN_MAJOR\n\n};\n\n}\n\nusing namespace GridOrderNS;\n\n\n\nnamespace LeftOrRightNS {\n", "file_path": "include/El/core/types.hpp", "rank": 92, "score": 171483.22970019942 }, { "content": " def DistRank(self):\n\n rank = c_int()\n\n args = [self.obj,pointer(rank)]\n\n if self.tag == iTag: lib.ElDistMatrixDistRank_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixDistRank_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixDistRank_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixDistRank_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixDistRank_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 93, "score": 164825.96530938282 }, { "content": " def ColOwner(self,j):\n\n owner = c_int()\n\n args = [self.obj,j,pointer(owner)]\n\n if self.tag == iTag: lib.ElDistMatrixColOwner_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixColOwner_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixColOwner_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixColOwner_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixColOwner_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 94, "score": 158483.75390666618 }, { "content": " def RowOwner(self,i):\n\n owner = c_int()\n\n args = [self.obj,i,pointer(owner)]\n\n if self.tag == iTag: lib.ElDistMatrixRowOwner_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixRowOwner_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixRowOwner_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixRowOwner_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixRowOwner_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 95, "score": 158479.89590595456 }, { "content": " def ColRank(self):\n\n rank = c_int()\n\n args = [self.obj,pointer(rank)]\n\n if self.tag == iTag: lib.ElDistMatrixColRank_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixColRank_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixColRank_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixColRank_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixColRank_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 96, "score": 158477.83287285155 }, { "content": "struct function_traits : public function_traits<decltype(&T::operator())>\n\n{};\n\n\n\n// Handles pointers to member functions\n\ntemplate<typename ClassType,typename ReturnType,typename... Args>\n", "file_path": "include/El/core/environment/decl.hpp", "rank": 97, "score": 158477.03000559815 }, { "content": " def RowRank(self):\n\n rank = c_int()\n\n args = [self.obj,pointer(rank)]\n\n if self.tag == iTag: lib.ElDistMatrixRowRank_i(*args)\n\n elif self.tag == sTag: lib.ElDistMatrixRowRank_s(*args)\n\n elif self.tag == dTag: lib.ElDistMatrixRowRank_d(*args)\n\n elif self.tag == cTag: lib.ElDistMatrixRowRank_c(*args)\n\n elif self.tag == zTag: lib.ElDistMatrixRowRank_z(*args)\n\n else: DataExcept()\n", "file_path": "python/core/DistMatrix.py", "rank": 98, "score": 158473.97487213995 }, { "content": "ElError ElSizeOfCBool( unsigned* boolSize )\n", "file_path": "src/core/global.c", "rank": 99, "score": 157576.20628783022 } ]
C++
packages/utility/stats/src/Utility_SampleMoment.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
#ifndef UTILITY_SAMPLE_MOMENT_HPP #define UTILITY_SAMPLE_MOMENT_HPP #include <type_traits> #include "Utility_QuantityTraits.hpp" namespace Utility{ template<size_t N, typename T, typename Enabled = void> class SampleMoment { }; template<size_t N, typename T> class SampleMoment<N,T,typename std::enable_if<(N>0) && std::is_floating_point<typename QuantityTraits<T>::RawType>::value>::type> { public: typedef typename QuantityTraits<T>::template GetQuantityToPowerType<N>::type ValueType; static ValueType processRawScore( const T& raw_score ); SampleMoment(); SampleMoment( const ValueType& starting_score ); SampleMoment( const SampleMoment& other_moment ); SampleMoment& operator=( const SampleMoment& other_moment ); ~SampleMoment() { } const ValueType& getCurrentScore() const; ValueType get( const size_t number_of_samples ) const; void addRawScore( const T& raw_score ); void addProcessedScore( const ValueType& processed_score ); private: ValueType d_current_score; }; template<typename T> T calculateMean( const SampleMoment<1,T>& first_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::template GetQuantityToPowerType<2>::type calculateVariance( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> T calculateStdDev( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::template GetQuantityToPowerType<2>::type calculateVarianceOfMean( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> T calculateStdDevOfMean( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::RawType calculateRelativeError( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::RawType calculateRelativeVOV( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const SampleMoment<3,T>& third_moment, const SampleMoment<4,T>& fourth_moment, const size_t number_of_samples ); template<typename T> typename std::enable_if<std::is_floating_point<T>::value,T>::type calculateFOM( const T relative_error, const T time ); } #include "Utility_SampleMoment_def.hpp" #endif
#ifndef UTILITY_SAMPLE_MOMENT_HPP #define UTILITY_SAMPLE_MOMENT_HPP #include <type_traits> #include "Utility_QuantityTraits.hpp" namespace Utility{ template<size_t N, typename T, typename Enabled = void> class SampleMoment { }; template<size_t N, typename T> class SampleMoment<N,T,typename std::enable_if<(N>0) && std::is_floating_point<typename QuantityTraits<T>::RawType>::value>::type> { public: typedef typ
t<1,T>& first_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::template GetQuantityToPowerType<2>::type calculateVariance( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> T calculateStdDev( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::template GetQuantityToPowerType<2>::type calculateVarianceOfMean( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> T calculateStdDevOfMean( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::RawType calculateRelativeError( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const size_t number_of_samples ); template<typename T> typename QuantityTraits<T>::RawType calculateRelativeVOV( const SampleMoment<1,T>& first_moment, const SampleMoment<2,T>& second_moment, const SampleMoment<3,T>& third_moment, const SampleMoment<4,T>& fourth_moment, const size_t number_of_samples ); template<typename T> typename std::enable_if<std::is_floating_point<T>::value,T>::type calculateFOM( const T relative_error, const T time ); } #include "Utility_SampleMoment_def.hpp" #endif
ename QuantityTraits<T>::template GetQuantityToPowerType<N>::type ValueType; static ValueType processRawScore( const T& raw_score ); SampleMoment(); SampleMoment( const ValueType& starting_score ); SampleMoment( const SampleMoment& other_moment ); SampleMoment& operator=( const SampleMoment& other_moment ); ~SampleMoment() { } const ValueType& getCurrentScore() const; ValueType get( const size_t number_of_samples ) const; void addRawScore( const T& raw_score ); void addProcessedScore( const ValueType& processed_score ); private: ValueType d_current_score; }; template<typename T> T calculateMean( const SampleMomen
random
[ { "content": "struct RawRationalPowerHelper<N,D,T,typename std::enable_if<N<0 && D<0 && N!=D>::type> : public RawRationalPowerHelper<-N,-D,T>\n\n{ /* ... */ };\n\n\n\n/*! The true or false type\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<bool is_true>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 1, "score": 331264.2529635063 }, { "content": "class Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type> : public OStreamableObject\n\n{\n\n\n\nprivate:\n\n\n\n // The quantity traits typedef\n\n typedef QuantityTraits<T> QT;\n\n\n\npublic:\n\n\n\n //! The typedef for this type\n\n typedef Measurement<T> ThisType;\n\n\n\n //! The typedef for the value type\n\n typedef T ValueType;\n\n\n\n //! Constructor\n\n explicit Measurement( const ValueType& value = QT::zero(),\n\n const ValueType& uncertainty = QT::zero() );\n\n\n", "file_path": "packages/utility/stats/src/Utility_Measurement.hpp", "rank": 2, "score": 315591.0843188716 }, { "content": "class SampleMomentCollection<T,N,Ns...> : public SampleMomentCollection<T,Ns...>\n\n{\n\n // The base type\n\n typedef SampleMomentCollection<T,Ns...> BaseType;\n\n \n\n // The underlying container type\n\n typedef std::vector<typename SampleMoment<N,T>::ValueType> ContainerType;\n\n\n\npublic:\n\n\n\n //! The starting moment value type\n\n typedef typename ContainerType::value_type ValueType;\n\n\n\n //! Default constructor\n\n SampleMomentCollection();\n\n\n\n //! Constructor\n\n SampleMomentCollection( const size_t i );\n\n\n\n //! Constructor\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollection.hpp", "rank": 3, "score": 298888.21009738324 }, { "content": "struct RawRationalPowerHelper<N, 1, T, typename std::enable_if<(N>1 && N%2==0)>::type>\n\n{\n\n //! The return type\n\n typedef typename ToFloatingPointHelper<T>::type ReturnType;\n\n\n\n //! Calculate the value raised to the integer power N\n\n static inline ReturnType calculateRationalPower( const T& value )\n\n {\n\n ReturnType tmp_value =\n\n RawRationalPowerHelper<N/2,1,T>::calculateRationalPower( value );\n\n\n\n return tmp_value*tmp_value;\n\n }\n\n};\n\n\n\n/*! The partial specialization of RawRationalPowerHelper for N>1, N%2==1, D==1\n\n *\n\n * When the rational power is a positive integer value we can use an efficient\n\n * recursive exponentiation algorithm which calculates the value raised to N in\n\n * log(N) multiplications.\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<boost::units::integer_type N, typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 4, "score": 296456.7640681865 }, { "content": "struct RawRationalPowerHelper<N, 1, std::complex<T>, typename std::enable_if<(N>1 && N%2==1)>::type>\n\n{\n\n //! The return type\n\n typedef typename ToFloatingPointHelper<std::complex<T> >::type ReturnType;\n\n\n\n //! Calculate the value raised to the integer power N\n\n static inline ReturnType calculateRationalPower( const std::complex<T>& value )\n\n {\n\n ReturnType tmp_value =\n\n RawRationalPowerHelper<N/2,1,std::complex<T>>::calculateRationalPower( value );\n\n\n\n return tmp_value*tmp_value*ReturnType(value.real(), value.imag());\n\n }\n\n};\n\n\n\n/*! The partial specialization of RawRationalPowerHelper for N==1, D==2\n\n *\n\n * The std::sqrt method will be used instead of std::pow.\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 5, "score": 287936.54627453967 }, { "content": "struct RawRationalPowerHelper<N, D, T, typename std::enable_if<(N>1 && D>1 && N!=D && boost::integer::static_gcd<N,D>::value>1)>::type> : public RawRationalPowerHelper<N/boost::integer::static_gcd<N,D>::value,D/boost::integer::static_gcd<N,D>::value,T>\n\n{ /* ... */ };\n\n\n\n/*! The partial specialization of RawRationalPowerHelper for N<0, D>0\n\n *\n\n * Instead of using the std::pow method, 1 over the value calculated from\n\n * RawRationalPowerHelper for N>0, D>0 will be returned (any specializations\n\n * for abs(N), D can be taken advantage of this way).\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<boost::units::integer_type N,\n\n boost::units::integer_type D,\n\n typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 6, "score": 286108.0491683553 }, { "content": "struct RawRationalPowerHelper<N, 1, T, typename std::enable_if<(N>1 && N%2==1) && std::is_arithmetic<T>::value>::type>\n\n{\n\n //! The return type\n\n typedef typename ToFloatingPointHelper<T>::type ReturnType;\n\n\n\n //! Calculate the value raised to the integer power N\n\n static inline ReturnType calculateRationalPower( const T& value )\n\n {\n\n ReturnType tmp_value =\n\n RawRationalPowerHelper<N/2,1,T>::calculateRationalPower( value );\n\n\n\n return tmp_value*tmp_value*value;\n\n }\n\n};\n\n\n\n/*! The partial specialization of RawRationalPowerHelper for N>1, N%2==1, D==1\n\n *\n\n * When the rational power is a positive integer value we can use an efficient\n\n * recursive exponentiation algorithm which calculates the value raised to N in\n\n * log(N) multiplications.\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<boost::units::integer_type N, typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 7, "score": 280039.65161536547 }, { "content": "struct RawRationalPowerHelper<N,D,T,typename std::enable_if<(N<0 && D>0)>::type>\n\n{\n\n //! The return type\n\n typedef typename ToFloatingPointHelper<T>::type ReturnType;\n\n\n\n //! Calculate the value raised to the rational power -(N/D)\n\n static inline ReturnType calculateRationalPower( const T& value )\n\n {\n\n return static_cast<ReturnType>(1)/RawRationalPowerHelper<-N,D,T>::calculateRationalPower( value );\n\n }\n\n};\n\n\n\n/*! The partial specialization of RawRationalPowerHelper for N>0, D<0\n\n *\n\n * Instead of using the std::pow method, 1 over the value calculated from\n\n * RawRationalPowerHelper for N>0, D>0 will be returned (any specializations\n\n * for N, abs(D) can be taken advantage of this way).\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<boost::units::integer_type N,\n\n boost::units::integer_type D,\n\n typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 8, "score": 277917.97464249714 }, { "content": "struct RawRationalPowerHelper<N,D,T,typename std::enable_if<(N>0 && D<0)>::type>\n\n{\n\n //! The return type\n\n typedef typename ToFloatingPointHelper<T>::type ReturnType;\n\n\n\n //! Calculate the value raised to the rational power -(N/D)\n\n static inline ReturnType calculateRationalPower( const T& value )\n\n {\n\n return static_cast<ReturnType>(1)/RawRationalPowerHelper<N,-D,T>::calculateRationalPower( value );\n\n }\n\n};\n\n\n\n/*! The partial specialization of RawRationalPowerHelper for N<0, D<0\n\n *\n\n * The partial specialization of RawRationalPowerHelper for N>0, D>0 will be\n\n * used.\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<boost::units::integer_type N,\n\n boost::units::integer_type D,\n\n typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 9, "score": 277917.97464249714 }, { "content": "struct QuantityToPowerTypeHelper<N,D,boost::units::quantity<Unit,T>, typename std::enable_if<N!=D && N!=0>::type>\n\n{\n\n //! The quantity to the rational power N/D type\n\n typedef boost::units::quantity<typename Utility::UnitTraits<Unit>::template GetUnitToPowerType<N,D>::type,T> QuantityToRpowType;\n\n\n\n //! Compute the quantity raised to the rational power N/D\n\n static inline QuantityToRpowType rpow( const boost::units::quantity<Unit,T>& a )\n\n {\n\n return QuantityToRpowType::from_value( RawRationalPowerHelper<N,D,T>::calculateRationalPower( a.value() ) );\n\n }\n\n};\n\n\n\n/*! Partial specialization of QuantityToPowerTypeHelper for N!=D, N==0\n\n * \\ingroup quantity_traits\n\n */\n\ntemplate<boost::units::integer_type D, typename Unit, typename T>\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 10, "score": 275703.03715137823 }, { "content": "//! The base class for input/output streamable objects\n\nclass StreamableObject : public OStreamableObject, public IStreamableObject\n\n{ /* ... */ };\n\n \n\n} // end Utility namespace\n\n\n\n#endif // end UTILITY_STREAMABLE_OBJECT_HPP\n\n\n\n//---------------------------------------------------------------------------//\n\n// end Utility_StreamableObject.hpp\n\n//---------------------------------------------------------------------------//\n", "file_path": "packages/utility/core/src/Utility_StreamableObject.hpp", "rank": 11, "score": 275172.9644666813 }, { "content": "class NullCommunicator : public Communicator\n\n{\n\n\n\npublic:\n\n\n\n //! Get the null communicator\n\n static std::shared_ptr<const NullCommunicator> get()\n\n {\n\n if( !s_null_comm )\n\n s_null_comm.reset( new NullCommunicator );\n\n\n\n return s_null_comm;\n\n }\n\n\n\n //! Destructor\n\n ~NullCommunicator()\n\n { /* ... */ }\n\n\n\n //! Determine the rank of the executing process\n\n int rank() const\n", "file_path": "packages/utility/mpi/src/Utility_Communicator.cpp", "rank": 12, "score": 274524.007701599 }, { "content": "class SerialCommunicator : public Communicator\n\n{\n\n\n\npublic:\n\n\n\n //! Get the serial communicator\n\n static std::shared_ptr<const SerialCommunicator> get();\n\n\n\n //! Destructor\n\n ~SerialCommunicator();\n\n\n\n //! Determine the rank of the executing process\n\n int rank() const override;\n\n\n\n //! Determine the number of processes in a communicator\n\n int size() const override;\n\n\n\n //! The any source value\n\n int anySourceValue() const override;\n\n\n", "file_path": "packages/utility/mpi/src/Utility_SerialCommunicator.hpp", "rank": 13, "score": 271379.12033036107 }, { "content": "class StandardTimer : public Timer\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n StandardTimer();\n\n\n\n //! Destructor\n\n ~StandardTimer();\n\n\n\n //! Check if the timer is stopped\n\n bool isStopped() const override;\n\n\n\n //! Get the elapsed time (in seconds)\n\n std::chrono::duration<double> elapsed() const override;\n\n\n\n //! Start the timer\n\n void start() override;\n\n\n", "file_path": "packages/utility/core/src/Utility_StandardTimer.hpp", "rank": 14, "score": 271379.12033036107 }, { "content": "class TetMesh : public Mesh\n\n{\n\n\n\npublic:\n\n\n\n //! The mesh element handle\n\n typedef Mesh::ElementHandle ElementHandle;\n\n\n\n //! The plane index\n\n typedef size_t PlaneIndex;\n\n\n\n //! Iterator over all mesh elements\n\n typedef Mesh::ElementHandleIterator ElementHandleIterator;\n\n\n\n //! The mesh element handle, primary intersection point, track length tuple array\n\n typedef Mesh::ElementHandleTrackLengthArray ElementHandleTrackLengthArray;\n\n\n\n //! The mesh element handle, volume map\n\n typedef Mesh::ElementHandleVolumeMap ElementHandleVolumeMap;\n\n\n", "file_path": "packages/utility/mesh/src/Utility_TetMesh.hpp", "rank": 15, "score": 271379.12033036107 }, { "content": "class MPICommunicator : public Communicator\n\n{\n\n\n\npublic:\n\n\n\n //! Destructor\n\n ~MPICommunicator()\n\n { /* ... */ }\n\n\n\n //! Determine the rank of the executing process\n\n int rank() const override;\n\n\n\n //! Determine the number of processes in a communicator\n\n int size() const override;\n\n\n\n //! The any source value\n\n int anySourceValue() const override;\n\n\n\n //! The any tag value\n\n int anyTagValue() const override;\n", "file_path": "packages/utility/mpi/src/Utility_MPICommunicator.hpp", "rank": 16, "score": 271379.12033036107 }, { "content": "class SampleMomentCollectionSnapshots<T,SnapshotContainer,N,Ns...> : public SampleMomentCollectionSnapshots<T,SnapshotContainer,Ns...>\n\n{\n\n // The base type\n\n typedef SampleMomentCollectionSnapshots<T,SnapshotContainer,Ns...> BaseType;\n\n\n\npublic:\n\n\n\n // The snapshot moment container type\n\n typedef SnapshotContainer<typename Utility::SampleMoment<N,T>::ValueType> MomentSnapshotContainerType;\n\n\n\n //! The snapshot indices container type\n\n typedef SnapshotContainer<uint64_t> SummationIndexContainerType;\n\n\n\n //! The snapshot sampling time container type\n\n typedef SnapshotContainer<double> SamplingTimeContainerType;\n\n\n\n //! The moment value type\n\n typedef typename MomentSnapshotContainerType::value_type MomentValueType;\n\n\n\n //! The summation index type\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollectionSnapshots.hpp", "rank": 17, "score": 269952.00154165947 }, { "content": "class MPITimer : public Timer\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n MPITimer() noexcept\n\n : d_raw_timer(),\n\n d_duration( std::chrono::duration<double>::zero() )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~MPITimer()\n\n { /* ... */ }\n\n\n\n //! Check if the timer is stopped\n\n bool isStopped() const override\n\n { return d_raw_timer == NULL; }\n\n\n\n //! Get the elapsed time (in seconds)\n", "file_path": "packages/utility/core/src/Utility_GlobalMPISession.cpp", "rank": 18, "score": 268333.7885879007 }, { "content": "class Communicator : public OStreamableObject\n\n{\n\n\n\npublic:\n\n\n", "file_path": "packages/utility/mpi/src/Utility_CommunicatorDecl.hpp", "rank": 19, "score": 268333.7885879007 }, { "content": "class StandardHashBasedGridSearcher : public HashBasedGridSearcher<typename STLCompliantArray::value_type>\n\n{\n\n\n\n // The base type\n\n typedef HashBasedGridSearcher<typename STLCompliantArray::value_type> BaseType;\n\n\n\npublic:\n\n\n\n //! This type\n\n typedef StandardHashBasedGridSearcher<STLCompliantArray,processed_grid> ThisType;\n\n\n\n //! The value type\n\n typedef typename BaseType::ValueType ValueType;\n\n\n\n //! Basic constructor (copy grid)\n\n StandardHashBasedGridSearcher( const STLCompliantArray& grid,\n\n\t\t\t\t const size_t hash_grid_bins );\n\n\n\n //! Basic constructor (share grid)\n\n StandardHashBasedGridSearcher(\n", "file_path": "packages/utility/grid/src/Utility_StandardHashBasedGridSearcher.hpp", "rank": 20, "score": 265602.7599078414 }, { "content": "//! The output formatter class\n\nclass OutputFormatter : public OStreamableObject\n\n{\n\n\n\npublic:\n\n\n\n //! Default constructor\n\n OutputFormatter();\n\n\n\n //! Destructor\n\n virtual ~OutputFormatter()\n\n { /* ... */ }\n\n\n\n //! Place the formatted string in the output stream\n\n void toStream( std::ostream& os ) const;\n\n\n\n //! Place the string in the output stream\n\n void toStream( std::ostream& os, const bool use_formatted_output ) const;\n\n\n\n //! Get the formatted string\n\n const std::string& getFormattedOutput() const;\n", "file_path": "packages/utility/core/src/Utility_OutputFormatter.hpp", "rank": 21, "score": 265391.07560298033 }, { "content": "//! The physical constants class\n\nclass PhysicalConstants : public RawPhysicalConstants\n\n{\n\nprivate:\n\n\n\n // The MeV-s unit\n\n typedef UnitTraits<Units::MegaElectronVolt>::template GetMultipliedUnitType<boost::units::cgs::time>::type MeVSecond;\n\n\n\n // The MeV/K unit\n\n typedef UnitTraits<Units::MegaElectronVolt>::template GetMultipliedUnitType<UnitTraits<boost::units::si::temperature>::InverseUnit>::type MeVPerK;\n\n\n\npublic:\n\n\n\n //! The speed of light (cm/s)\n\n static const boost::units::quantity<boost::units::cgs::velocity> speed_of_light_q;\n\n\n\n //! Planck's constant (MeV-s)\n\n static const boost::units::quantity<MeVSecond> planck_constant_q;\n\n\n\n //! Plank's constant by pi (MeV-s)\n\n static const boost::units::quantity<MeVSecond> h_bar_q;\n", "file_path": "packages/utility/core/src/Utility_PhysicalConstants.hpp", "rank": 22, "score": 265391.07560298033 }, { "content": "class FakeGenerator : public LinearCongruentialGenerator\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n FakeGenerator( const std::vector<double>& fake_stream );\n\n\n\n //! Destructor\n\n ~FakeGenerator()\n\n { /* ... */ }\n\n\n\n //! Return a random number from the fake stream\n\n double getRandomNumber();\n\n\n\nprivate:\n\n\n\n // Verify that all numbers in the stream are valid - in [0,1)\n\n static bool validStream( const std::vector<double>& stream );\n\n\n", "file_path": "packages/utility/prng/src/Utility_FakeGenerator.hpp", "rank": 23, "score": 265383.2088950656 }, { "content": "class StructuredHexMesh : public Mesh\n\n{\n\n\n\npublic:\n\n\n\n //! The mesh element handle\n\n typedef Mesh::ElementHandle ElementHandle;\n\n\n\n //! The plane index\n\n typedef size_t PlaneIndex;\n\n\n\n //! Iterator over all mesh elements\n\n typedef Mesh::ElementHandleIterator ElementHandleIterator;\n\n\n\n //! The mesh element handle, primary intersection point, track length tuple array\n\n typedef Mesh::ElementHandleTrackLengthArray ElementHandleTrackLengthArray;\n\n\n\n //! The mesh element handle, volume map\n\n typedef Mesh::ElementHandleVolumeMap ElementHandleVolumeMap;\n\n\n", "file_path": "packages/utility/mesh/src/Utility_StructuredHexMesh.hpp", "rank": 24, "score": 265383.2088950656 }, { "content": "class OpenMPTimer : public Timer\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n OpenMPTimer() noexcept\n\n : d_start_time_point( 0.0 ),\n\n d_duration( std::chrono::duration<double>::zero() ),\n\n d_is_running( false )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~OpenMPTimer()\n\n { /* ... */ }\n\n\n\n //! Check if the timer is stopped\n\n bool isStopped() const override\n\n { return !d_is_running; }\n\n\n", "file_path": "packages/utility/core/src/Utility_OpenMPProperties.cpp", "rank": 25, "score": 265383.2088950656 }, { "content": "//! The dynamic output formatter class\n\nclass DynamicOutputFormatter : public OutputFormatter\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n DynamicOutputFormatter( const std::string& raw_output );\n\n\n\n //! Destructor\n\n ~DynamicOutputFormatter()\n\n { /* ... */ }\n\n\n\n //! Format a keyword in the output\n\n template<typename TextFormatPolicy,\n\n typename TextColorPolicy,\n\n typename TextBackgroundColorPolicy>\n\n void formatKeyword( const std::string& keyword );\n\n\n\n //! Make the keyword bold in the output\n\n void boldKeyword( const std::string& keyword );\n", "file_path": "packages/utility/core/src/Utility_DynamicOutputFormatter.hpp", "rank": 26, "score": 262530.6765884614 }, { "content": "class TemplateUnitTest : public UnitTest\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n TemplateUnitTest( const std::string& group_name,\n\n const std::string& test_name );\n\n\n\n //! Constructor with template parameter name\n\n TemplateUnitTest( const std::string& group_name,\n\n const std::string& test_name,\n\n const std::string& template_param_pack_name );\n\n\n\n //! Destructor\n\n ~TemplateUnitTest()\n\n { /* ... */ }\n\n \n\n //! Get the Nth template parameter\n\n template<size_t N>\n\n struct _T\n\n {\n\n typedef typename Utility::TupleElement<N,std::tuple<Types...> >::type get;\n\n };\n\n};\n\n\n\n/*! Partial specialization of TemplateUnitTest for std::tuple type\n\n * \\ingroup unit_test_framework\n\n */\n\ntemplate<typename... Types>\n", "file_path": "packages/utility/core/src/Utility_TemplateUnitTest.hpp", "rank": 27, "score": 262522.8888291969 }, { "content": "class HDF5CommonArchive : public HDF5File\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n HDF5CommonArchive( const std::string& hdf5_filename,\n\n const HDF5File::OpenMode mode = HDF5File::READ_WRITE );\n\n\n\n //! Destructor\n\n virtual ~HDF5CommonArchive();\n\n\n\n //! Return the archive properties directory\n\n static const std::string& getPropertiesDir();\n\n\n\n //! Return the hdf5 data directory\n\n static const std::string& getDataDir();\n\n\n\n //! Return the hdf5 tracked objects directory\n\n static const std::string& getTrackedObjectsDir();\n", "file_path": "packages/utility/archive/src/Utility_HDF5CommonArchive.hpp", "rank": 28, "score": 262522.8888291969 }, { "content": "class StaticOutputFormatter : public OutputFormatter\n\n{\n\n \n\npublic:\n\n\n\n //! General constructor\n\n template<typename T>\n\n StaticOutputFormatter( const T& raw_string_contents );\n\n\n\n //! Destructor\n\n ~StaticOutputFormatter()\n\n { /* ... */ }\n\n};\n\n\n\n//! Default formatter\n\ntypedef StaticOutputFormatter<DefaultTextFormat,DefaultTextColor,DefaultTextBackgroundColor> Default;\n\n\n\n//! Bold formatter\n\ntypedef StaticOutputFormatter<BoldTextFormat,DefaultTextColor,DefaultTextBackgroundColor> Bold;\n\n\n", "file_path": "packages/utility/core/src/Utility_StaticOutputFormatter.hpp", "rank": 29, "score": 262522.8888291969 }, { "content": "class DataUnitTest : public UnitTest\n\n{\n\n \n\npublic:\n\n\n\n //! Constructor\n\n DataUnitTest( const std::string& group_name,\n\n const std::string& test_name,\n\n const std::string& data_table_row_name,\n\n const std::shared_ptr<const UnitTestDataTable>& data_table );\n\n\n\n //! Destructor\n\n ~DataUnitTest()\n\n { /* ... */ }\n\n\n\n //! Get the data table element for the desired column\n\n const Utility::Variant& getDataTableElement(\n\n const std::string& column_name ) const;\n\n \n\n //! Get the concrete data table element for the desired column\n", "file_path": "packages/utility/core/src/Utility_DataUnitTest.hpp", "rank": 30, "score": 262522.8888291969 }, { "content": "class IntersectionFunctor : public SetOperationFunctor\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n IntersectionFunctor()\n\n : SetOperationFunctor()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~IntersectionFunctor()\n\n { /* ... */ }\n\n\n\n //! Function evaluation operator\n\n bool operator()( const bool first, const bool second ) { return first && second; }\n\n};\n\n\n", "file_path": "packages/utility/core/src/Utility_SetOperationFunctor.hpp", "rank": 31, "score": 262522.8888291969 }, { "content": "class UnionFunctor : public SetOperationFunctor\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n UnionFunctor()\n\n : SetOperationFunctor()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~UnionFunctor()\n\n { /* ... */ }\n\n\n\n //! Function evaluation operator\n\n bool operator()( const bool first, const bool second ) { return first || second; }\n\n\n\n};\n\n\n\n\n", "file_path": "packages/utility/core/src/Utility_SetOperationFunctor.hpp", "rank": 32, "score": 262522.8888291969 }, { "content": "struct HDF5TypeTraits<void> : public Details::BasicHDF5TypeTraits<void,1>\n\n{\n\n //! Check if the type has an opaque data type\n\n typedef std::true_type UsesOpaqueDataType;\n\n \n\n //! Returns the HDF5 data type object corresponding to void\n\n static inline HDF5_ENABLED_DISABLED_SWITCH(const H5::PredType&,int) dataType()\n\n { return HDF5_ENABLED_DISABLED_SWITCH(H5::PredType::NATIVE_OPAQUE,0); }\n\n};\n\n\n\n// Constructor\n\nHDF5File::Exception::Exception( const std::string& message )\n\n : std::runtime_error( message )\n\n{ /* ... */ }\n\n\n\n// Constructor (extra details)\n\nHDF5File::Exception::Exception( const std::string& file,\n\n const size_t line,\n\n const std::string& hdf5_function_name,\n\n const std::string& hdf5_error_message,\n", "file_path": "packages/utility/core/src/Utility_HDF5File.cpp", "rank": 33, "score": 261740.8018784226 }, { "content": "class ArrayView : public View<T*>\n\n{\n\n\n\npublic:\n\n\n\n //! Default constructor\n\n ArrayView();\n\n\n\n //! Iterator constructor\n\n ArrayView( T* start, T* end );\n\n\n\n //! Range constructor\n\n ArrayView( T* array_start, const typename ArrayView<T>::size_type array_size );\n\n\n\n //! Vector constructor\n\n explicit ArrayView( std::vector<T>& vector );\n\n\n\n //! Const vector constructor\n\n template<typename U>\n\n explicit ArrayView( const std::vector<U>& vector );\n", "file_path": "packages/utility/core/src/Utility_ArrayView.hpp", "rank": 34, "score": 261242.11808652425 }, { "content": "class UnitAwareUnivariateDistribution : public OStreamableObject\n\n{\n\n // Typedef for this type\n\n typedef UnitAwareUnivariateDistribution<IndependentUnit,DependentUnit> ThisType;\n\n\n\nprotected:\n\n\n\n //! The independent unit traits typedef\n\n typedef UnitTraits<IndependentUnit> IndepUnitTraits;\n\n\n\n //! The inverse independent unit traits typedef\n\n typedef UnitTraits<typename UnitTraits<IndependentUnit>::InverseUnit> InverseIndepUnitTraits;\n\n\n\n //! The dependent unit traits typedef\n\n typedef UnitTraits<DependentUnit> DepUnitTraits;\n\n\n\n //! The distribution normalization unit traits typedef\n\n typedef UnitTraits<typename UnitTraits<typename UnitTraits<DependentUnit>::InverseUnit>::template GetMultipliedUnitType<typename UnitTraits<IndependentUnit>::InverseUnit>::type> DistNormUnitTraits;\n\n\n\n //! The distribution normalization quantity type\n", "file_path": "packages/utility/distribution/src/Utility_UnivariateDistribution.hpp", "rank": 35, "score": 259748.62193822028 }, { "content": "//! Exception class to be thrown when a MOAB error is detected\n\nclass MOABException : public std::runtime_error\n\n{\n\npublic:\n\n MOABException( const std::string &msg )\n\n : std::runtime_error( msg )\n\n { /* ... */ }\n\n\n\n virtual ~MOABException() throw()\n\n { /* ... */ }\n\n};\n\n\n\n} // end Utility namespace\n\n\n\n#endif // end UTILITY_EXCEPTION_HPP\n\n\n\n//---------------------------------------------------------------------------//\n\n// end Utility_MOABException.hpp\n\n//---------------------------------------------------------------------------//\n", "file_path": "packages/utility/mesh/src/Utility_MOABException.hpp", "rank": 36, "score": 258299.17291598668 }, { "content": "//! Exception class to be thrown when a Integrator error is detected\n\nclass IntegratorException : public std::runtime_error\n\n{\n\npublic:\n\n IntegratorException( const std::string& msg )\n\n : std::runtime_error( msg )\n\n { /* ... */ }\n\n\n\n virtual ~IntegratorException() throw()\n\n { /* ... */ }\n\n};\n\n\n\n} // end Utility namespace\n\n\n\n#endif // end UTILITY_INTEGRATOR_EXCEPTION_HPP\n\n\n\n//---------------------------------------------------------------------------//\n\n// end Utility_IntegratorException.hpp\n\n//---------------------------------------------------------------------------//\n", "file_path": "packages/utility/integrator/src/Utility_IntegratorException.hpp", "rank": 37, "score": 258299.17291598668 }, { "content": "class InvalidCommunicator : public std::logic_error\n\n{\n\npublic:\n\n\n\n //! Constructor\n\n InvalidCommunicator( const std::string& details )\n\n : std::logic_error( details )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~InvalidCommunicator()\n\n { /* ... */ }\n\n};\n\n\n\n/*! The communication error exception\n\n * \\ingroup mpi\n\n */\n", "file_path": "packages/utility/mpi/src/Utility_CommunicatorDecl.hpp", "rank": 38, "score": 258291.5383936891 }, { "content": "class ContractException : public std::logic_error\n\n{\n\npublic:\n\n ContractException( const std::string &msg )\n\n : std::logic_error( msg )\n\n { /* ... */ }\n\n\n\n virtual ~ContractException() throw()\n\n { /* ... */ }\n\n};\n\n\n\n} // end Utility namespace\n\n\n\n//---------------------------------------------------------------------------//\n\n// Design-by-Contract Macros.\n\n//---------------------------------------------------------------------------//\n\n#if HAVE_FRENSIE_DBC\n\n\n\n/*! Test a function precondition\n\n * \\ingroup contract_exceptions_macros\n", "file_path": "packages/utility/core/src/Utility_DesignByContract.hpp", "rank": 39, "score": 258291.5383936891 }, { "content": "class CommunicationError : public std::runtime_error\n\n{\n\npublic:\n\n\n\n //! Constructor\n\n CommunicationError( const std::string& details )\n\n : std::runtime_error( details )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~CommunicationError()\n\n { /* ... */ }\n\n};\n\n\n\n/*! The maximum operator\n\n * \\ingroup mpi\n\n */\n\ntemplate<typename T>\n", "file_path": "packages/utility/mpi/src/Utility_CommunicatorDecl.hpp", "rank": 40, "score": 258291.5383936891 }, { "content": "struct SampleMomentCollectionDataExtractor<N,SampleMomentCollection<T,M,Ms...>,typename std::enable_if<N!=M>::type>\n\n{\n\n //! The collection type\n\n typedef Utility::SampleMomentCollection<T,M,Ms...> CollectionType;\n\n\n\n //! The moment type\n\n typedef SampleMoment<N,T> MomentType;\n\n\n\n //! The value type\n\n typedef typename MomentType::ValueType ValueType;\n\n\n\n //! The base collection type\n\n typedef Utility::SampleMomentCollection<T,Ms...> BaseCollectionType;\n\n \n\n //! Get the current scores\n\n static inline const ValueType* getCurrentScores(\n\n const CollectionType& collection )\n\n { return SampleMomentCollectionDataExtractor<N,BaseCollectionType>::getCurrentScores( collection ); }\n\n\n\n //! Get the current scores\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollection_def.hpp", "rank": 41, "score": 258025.13823616575 }, { "content": "struct SampleMomentCollectionDataExtractor<N,SampleMomentCollection<T,M,Ms...>,typename std::enable_if<N==M>::type>\n\n{\n\n //! The collection type\n\n typedef Utility::SampleMomentCollection<T,M,Ms...> CollectionType;\n\n\n\n //! The sample moment type\n\n typedef Utility::SampleMoment<M,T> MomentType;\n\n\n\n //! The value type\n\n typedef typename MomentType::ValueType ValueType;\n\n \n\n //! Get the current scores\n\n static inline const ValueType* getCurrentScores(\n\n const CollectionType& collection )\n\n { return &collection.d_current_scores[0]; }\n\n\n\n //! Get the current scores\n\n static inline ValueType* getCurrentScores( CollectionType& collection )\n\n { return &collection.d_current_scores[0]; }\n\n\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollection_def.hpp", "rank": 42, "score": 258025.13823616575 }, { "content": "//! The distributed unit test manager\n\nclass DistributedUnitTestManager : public UnitTestManager\n\n{\n\n \n\npublic:\n\n \n\n // Constructor\n\n DistributedUnitTestManager();\n\n\n\n // Destructor\n\n ~DistributedUnitTestManager()\n\n { /* ... */ }\n\n\n\nprotected:\n\n\n\n //! Print the help message\n\n void printHelpMessage() override;\n\n\n\n //! Print the test details\n\n void printTestDetails() override;\n\n\n", "file_path": "packages/utility/core/src/Utility_UnitTestManager.cpp", "rank": 43, "score": 257056.4649876489 }, { "content": "class Polygon : public Utility::PrintableObject, public ThreeSpaceObject\n\n{\n\n\n\npublic:\n\n\n\n //@{\n\n //! Typedefs\n\n //! Typedef for ordinal type\n\n typedef OrdinalType ordinalType;\n\n //! Typedef for scalar type\n\n typedef ScalarType scalarType;\n\n //! Typedef\n\n //@}\n\n\n\nprotected:\n\n\n\n //! Typedef for projected point\n\n typedef Utility::Pair<ScalarType,ScalarType> PointProjection;\n\n\n\nprivate:\n", "file_path": "packages/geometry/legacy/src/Geometry_Polygon.hpp", "rank": 44, "score": 256297.76091945678 }, { "content": "class Surface : public Utility::PrintableObject, public ThreeSpaceObject\n\n{\n\n\n\npublic:\n\n\n\n //@{\n\n //! Typedefs\n\n //! Typedef for ordinal type (only used for surface ids)\n\n typedef OrdinalType ordinalType;\n\n //! Typedef for scalar type\n\n typedef ScalarType scalarType;\n\n //@}\n\n\n\nprivate:\n\n\n\n //! Typedef for scalar traits\n\n typedef Teuchos::ScalarTraits<ScalarType> ST;\n\n //! Typedef for ordinal traits\n\n typedef Teuchos::OrdinalTraits<OrdinalType> OT;\n\n //! Typedef for Teuchos::Tuple index\n", "file_path": "packages/geometry/legacy/src/Geometry_Surface.hpp", "rank": 45, "score": 256297.76091945678 }, { "content": "class Cell : public Utility::PrintableObject, public ThreeSpaceObject\n\n{\n\n\n\nprivate:\n\n\n\n //! Typedef for surface-sense pair\n\n typedef Utility::Pair<Teuchos::RCP<Surface<SurfaceOrdinalType,ScalarType> >,\n\n\t\t\tSurfaceSense> SurfaceSensePair;\n\n\n\n //! Typedef for surface-sense pairs container\n\n typedef Teuchos::Array<SurfaceSensePair> SurfaceSensePairContainer;\n\n\n\npublic:\n\n\n\n //@{\n\n //! Typedefs\n\n //! Typedef for cell ordinal type (only used for cell ids)\n\n typedef CellOrdinalType ordinalType;\n\n //! Typedef for surface ordinal type (only used for surface ids)\n\n typedef SurfaceOrdinalType surfaceOrdinalType;\n", "file_path": "packages/geometry/legacy/src/Geometry_Cell.hpp", "rank": 46, "score": 256297.76091945678 }, { "content": "class Vector : public Utility::PrintableObject, public ThreeSpaceObject\n\n{\n\n\n\npublic:\n\n\n\n //!@{\n\n //! Typedefs\n\n //! Typedef for scalar type\n\n typedef ScalarType scalarType;\n\n //! Typedef for ordinal type\n\n typedef int ordinalType;\n\n //@}\n\n\n\nprivate:\n\n\n\n // Typedef for ScalarTraits\n\n typedef Teuchos::ScalarTraits<ScalarType> ST;\n\n\n\npublic:\n\n\n", "file_path": "packages/geometry/legacy/src/Geometry_Vector.hpp", "rank": 47, "score": 256297.76091945678 }, { "content": "//---------------------------------------------------------------------------//\n\n// Testing structs\n\n//---------------------------------------------------------------------------//\n\nclass TestUnitTest : public Utility::UnitTest\n\n{\n\n\n\npublic:\n\n\n\n // Constructor\n\n TestUnitTest( const std::string& group_name,\n\n const std::string& test_name,\n\n const std::string& data_name )\n\n : Utility::UnitTest( group_name, test_name, data_name )\n\n { /* ... */ }\n\n\n\n // Destructor\n\n ~TestUnitTest()\n\n { /* ... */ }\n\n\n\n // Return the file where the unit test object is located\n\n std::string getFile() const override\n\n { return \"tstUnitTest.cpp\"; }\n\n\n", "file_path": "packages/utility/core/test/tstUnitTest.cpp", "rank": 48, "score": 255431.21832782042 }, { "content": "//---------------------------------------------------------------------------//\n\n// Testing Structs.\n\n//---------------------------------------------------------------------------//\n\nclass TestDataProcessor : public Utility::DataProcessor\n\n{\n\npublic:\n\n TestDataProcessor()\n\n { /* ... */ }\n\n\n\n virtual ~TestDataProcessor()\n\n { /* ... */ }\n\n\n\n void processDataFiles()\n\n { /* ... */ }\n\n\n\n // Allow public access to the DataProcessor protected member functions\n\n using Utility::DataProcessor::processContinuousData;\n\n using Utility::DataProcessor::removeElementsLessThanValue;\n\n using Utility::DataProcessor::removeElementsGreaterThanValue;\n\n using Utility::DataProcessor::coarsenConstantRegions;\n\n using Utility::DataProcessor::calculateSlopes;\n\n using Utility::DataProcessor::calculateContinuousCDF;\n\n using Utility::DataProcessor::calculateDiscreteCDF;\n\n using Utility::DataProcessor::copyTupleMemberData;\n\n using Utility::DataProcessor::swapTupleMemberData;\n\n using Utility::DataProcessor::uintToShellStr;\n\n};\n\n\n\ntypedef Utility::LogLogDataProcessing LogLogDataProcessing;\n\ntypedef Utility::SqrSqrDataProcessing SqrSqrDataProcessing;\n\n\n\ntemplate<typename ProcessingPolicy>\n", "file_path": "packages/utility/core/test/tstDataProcessor.cpp", "rank": 49, "score": 255431.21832782042 }, { "content": "struct RawRationalPowerHelper<N,D,T,typename std::enable_if<(D%2==1 && D>1 && boost::integer::static_gcd<N,D>::value==1 && ((N==1 && D>3) || N>1) && std::is_signed<T>::value)>::type>\n\n{\n\n //! The return type\n\n typedef typename ToFloatingPointHelper<T>::type ReturnType;\n\n\n\n //! Calculate the value raised to the rational power N/D\n\n static inline ReturnType calculateRationalPower( const T& value )\n\n {\n\n if( value < 0 )\n\n {\n\n ReturnType tmp_value_to_n_over_d =\n\n std::pow( -static_cast<ReturnType>( value ),\n\n static_cast<ReturnType>( N )/D );\n\n\n\n if( N%2 == 1 )\n\n return -tmp_value_to_n_over_d;\n\n else\n\n return tmp_value_to_n_over_d;\n\n }\n\n else\n", "file_path": "packages/utility/core/src/Utility_QuantityTraits.hpp", "rank": 50, "score": 254929.30067995546 }, { "content": "class VoidAtomicReaction : public BaseReactionType\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n VoidAtomicReaction()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n virtual ~VoidAtomicReaction()\n\n { /* ... */ }\n\n\n\n //! Test if two Atomic reactions share the same energy grid\n\n bool isEnergyGridShared( const Reaction& other_reaction ) const final override;\n\n\n\n //! Test if the energy falls within the energy grid\n\n bool isEnergyWithinEnergyGrid( const double energy ) const final override;\n\n\n\n //! Return the threshold energy\n", "file_path": "packages/monte_carlo/collision/core/src/MonteCarlo_VoidAtomicReaction.hpp", "rank": 51, "score": 254811.8853177041 }, { "content": "//! The dynamic output formatter factory class\n\nclass DynamicOutputFormatterFactory : public OutputFormatterFactory\n\n{\n\n\n\npublic:\n\n\n\n //! The formatting function type\n\n typedef std::function<void(DynamicOutputFormatter&)> FormattingFunction;\n\n\n\n //! The formatting function array\n\n typedef std::vector<FormattingFunction> FormattingFunctionArray;\n\n\n\n //! Constructor\n\n DynamicOutputFormatterFactory( FormattingFunctionArray& formatting_functions );\n\n\n\n //! Destructor\n\n ~DynamicOutputFormatterFactory()\n\n { /* ... */ }\n\n\n\n //! Create an output formatter\n\n std::shared_ptr<const OutputFormatter> createOutputFormatter(\n", "file_path": "packages/utility/core/src/Utility_DynamicOutputFormatterFactory.hpp", "rank": 52, "score": 254450.427748269 }, { "content": "class UnitAwareBasicBivariateDistribution : public OStreamableObject\n\n{\n\n\n\n // Typedef for this type\n\n typedef UnitAwareBasicBivariateDistribution<PrimaryIndependentUnit,SecondaryIndependentUnit,DependentUnit> ThisType;\n\n\n\nprotected:\n\n\n\n //! The primary independent unit traits typedef\n\n typedef UnitTraits<PrimaryIndependentUnit> PrimaryIndepUnitTraits;\n\n\n\n //! The secondary independent unit traits typedef\n\n typedef UnitTraits<SecondaryIndependentUnit> SecondaryIndepUnitTraits;\n\n\n\n //! The inverse primary independent unit traits typedef\n\n typedef UnitTraits<typename UnitTraits<PrimaryIndependentUnit>::InverseUnit> InversePrimaryIndepUnitTraits;\n\n\n\n //! The inverse secondary independent unit traits typedef\n\n typedef UnitTraits<typename UnitTraits<SecondaryIndependentUnit>::InverseUnit> InverseSecondaryIndepUnitTraits;\n\n\n", "file_path": "packages/utility/distribution/src/Utility_BasicBivariateDistribution.hpp", "rank": 53, "score": 254442.71736877508 }, { "content": "//! The unit test data table\n\nclass UnitTestDataTable : public OStreamableObject\n\n{\n\n \n\npublic:\n\n\n", "file_path": "packages/utility/core/src/Utility_UnitTestDataTable.hpp", "rank": 54, "score": 254442.71736877508 }, { "content": "class StaticOutputFormatterFactory : public OutputFormatterFactory\n\n{\n\n\n\npublic:\n\n\n\n //! Default constructor\n\n StaticOutputFormatterFactory()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~StaticOutputFormatterFactory()\n\n { /* ... */ }\n\n\n\n //! Create an output formatter\n\n std::shared_ptr<const OutputFormatter> createOutputFormatter(\n\n const std::string& raw_output ) const override;\n\n};\n\n\n\n// Create an output formatter\n\ntemplate<typename TextFormatPolicy,\n", "file_path": "packages/utility/core/src/Utility_StaticOutputFormatterFactory.hpp", "rank": 55, "score": 254442.71736877508 }, { "content": "struct IsHashable<const std::bitset<N> > : public IsHashable<std::bitset<N> >\n\n{ /* ... */ };\n\n\n\n/*! Partial specialization of IsHashable for std::unique_ptr types\n\n * \\ingroup type_traits\n\n */\n\ntemplate<typename T>\n", "file_path": "packages/utility/core/src/Utility_TypeTraits.hpp", "rank": 56, "score": 253693.5417961736 }, { "content": "class StandardSerializableObject : public virtual SerializableObject\n\n{\n\n\n\npublic:\n\n\n\n // Add the packDataInString member function to the public interface\n\n};\n\n\n\n//! The base class for standard serializable objects\n\ntemplate<typename DerivedType>\n", "file_path": "packages/utility/core/src/Utility_StandardSerializableObject.hpp", "rank": 57, "score": 252656.95143684378 }, { "content": "class PropertyTreeConversionException : public std::runtime_error\n\n{\n\npublic:\n\n PropertyTreeConversionException( const std::string& msg )\n\n : std::runtime_error( msg )\n\n { /* ... */ }\n\n\n\n ~PropertyTreeConversionException() throw()\n\n { /* ... */ }\n\n};\n\n\n\n/*! The comment node key\n\n *\n\n * Currently, the boost property tree JSON parser does not have\n\n * support for normal comment syntax. Users can instead use this comment node\n\n * key to create comments that will be ignored by our custom property tree\n\n * conversion methods. This also means that developers must ensure that\n\n * new property tree conversion methods ignore any node that is assigned\n\n * to this key.\n\n * \\ingroup ptree\n", "file_path": "packages/utility/core/src/Utility_PropertyTree.hpp", "rank": 58, "score": 252656.95143684378 }, { "content": "class ArchivableObject : public OArchivableObject<DerivedType>,\n\n public IArchivableObject<DerivedType>\n\n{\n\n\n\npublic:\n\n\n\n \n\n //! Constructor\n\n ArchivableObject()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n virtual ~ArchivableObject()\n\n { /* ... */ }\n\n\n\n //! The name that will be used when archiving the object\n\n virtual const char* getArchiveName() const = 0;\n\n\n\n //! The name that will be used when loading the object from an archive\n\n const char* getIArchiveName() const override\n", "file_path": "packages/utility/archive/src/Utility_ArchivableObject.hpp", "rank": 59, "score": 252656.95143684378 }, { "content": "class StringConversionException : public std::runtime_error\n\n{\n\npublic:\n\n StringConversionException( const std::string& msg )\n\n : std::runtime_error( msg )\n\n { /* ... */ }\n\n\n\n ~StringConversionException() throw()\n\n { /* ... */ }\n\n};\n\n\n\n/*! Traits class used to convert a string to a type\n\n * \\ingroup from_string_traits\n\n */\n\ntemplate<typename T, typename Enabled = void>\n", "file_path": "packages/utility/core/src/Utility_FromStringTraitsDecl.hpp", "rank": 60, "score": 252656.95143684378 }, { "content": "class HDF5IArchive : public HDF5IArchiveImpl<HDF5IArchive>\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n HDF5IArchive( const std::string& hdf5_filename,\n\n unsigned flags = 0 )\n\n : HDF5IArchiveImpl<HDF5IArchive>( hdf5_filename, flags )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~HDF5IArchive()\n\n { /* ... */ }\n\n\n\nprotected:\n\n\n\n /*! Constructor\n\n *\n\n * This constructor is provided so that this archive can be used with the\n", "file_path": "packages/utility/archive/src/Utility_HDF5IArchive.hpp", "rank": 61, "score": 252656.95143684378 }, { "content": "class BadUnivariateDistributionParameter : public std::logic_error\n\n{\n\npublic:\n\n BadUnivariateDistributionParameter( const std::string& msg )\n\n : std::logic_error( msg )\n\n { /* ... */ }\n\n\n\n ~BadUnivariateDistributionParameter() throw()\n\n { /* ... */ }\n\n};\n\n\n\n} // end Utility namespace\n\n\n\nBOOST_SERIALIZATION_ASSUME_ABSTRACT_DISTRIBUTION2( UnitAwareUnivariateDistribution );\n\nBOOST_SERIALIZATION_DISTRIBUTION2_VERSION( UnitAwareUnivariateDistribution, 0 );\n\n\n\n//---------------------------------------------------------------------------//\n\n// Template Includes\n\n//---------------------------------------------------------------------------//\n\n\n", "file_path": "packages/utility/distribution/src/Utility_UnivariateDistribution.hpp", "rank": 62, "score": 252656.95143684378 }, { "content": "class HDF5OArchive : public HDF5OArchiveImpl<HDF5OArchive>\n\n{\n\n \n\npublic:\n\n\n\n //! Constructor\n\n HDF5OArchive( const std::string& hdf5_filename, unsigned flags = 0 )\n\n : HDF5OArchiveImpl<HDF5OArchive>( hdf5_filename, flags )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~HDF5OArchive()\n\n { /* ... */ }\n\n\n\nprotected:\n\n\n\n /*! Stream Constructor\n\n *\n\n * This constructor is provided so that this archive can be used with the\n\n * boost::archive::detail::polymorphic_oarchive_route wrapper to construct\n", "file_path": "packages/utility/archive/src/Utility_HDF5OArchive.hpp", "rank": 63, "score": 252656.95143684378 }, { "content": "class IntersectionPoint : public Utility::PrintableObject, public ThreeSpaceObject\n\n{\n\n\n\npublic:\n\n\n\n //!@{\n\n //! Typedefs\n\n //! Typedef for ordinal type\n\n typedef OrdinalType ordinalType;\n\n //! Typedef for scalar type\n\n typedef ScalarType scalarType;\n\n //@}\n\n\n\nprivate:\n\n\n\n // Typedef for OrdinalTraits\n\n typedef Teuchos::OrdinalTraits<OrdinalType> OT;\n\n // Typedef for ScalarTraits\n\n typedef Teuchos::ScalarTraits<ScalarType> ST;\n\n\n", "file_path": "packages/geometry/legacy/src/Geometry_IntersectionPoint.hpp", "rank": 64, "score": 251003.17678549147 }, { "content": "class BadBivariateDistributionParameter : public std::logic_error\n\n{\n\npublic:\n\n BadBivariateDistributionParameter( const std::string& msg )\n\n : std::logic_error( msg )\n\n { /* ... */ }\n\n\n\n ~BadBivariateDistributionParameter() throw()\n\n { /* ... */ }\n\n};\n\n\n\n} // end Utility namespace\n\n\n\nBOOST_SERIALIZATION_ASSUME_ABSTRACT_DISTRIBUTION3( UnitAwareBasicBivariateDistribution );\n\nBOOST_SERIALIZATION_DISTRIBUTION3_VERSION( UnitAwareBasicBivariateDistribution, 0 );\n\n\n\n//---------------------------------------------------------------------------//\n\n// Template Includes\n\n//---------------------------------------------------------------------------//\n\n\n\n#include \"Utility_BasicBivariateDistribution_def.hpp\"\n\n\n\n//---------------------------------------------------------------------------//\n\n\n\n#endif // end UTILITY_BASIC_BIVARIATE_DISTRIBUTION_HPP\n\n\n\n//---------------------------------------------------------------------------//\n\n// end Utility_BivariateDistribution.hpp\n\n//---------------------------------------------------------------------------//\n", "file_path": "packages/utility/distribution/src/Utility_BasicBivariateDistribution.hpp", "rank": 65, "score": 249964.79448627244 }, { "content": "class VoidAdjointAtomicReaction : public BaseReactionType\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n VoidAdjointAtomicReaction()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n virtual ~VoidAdjointAtomicReaction()\n\n { /* ... */ }\n\n\n\n //! Test if two Atomic reactions share the same energy grid\n\n bool isEnergyGridShared( const Reaction& other_reaction ) const final override;\n\n\n\n //! Test if the energy falls within the energy grid\n\n bool isEnergyWithinEnergyGrid( const double energy ) const final override;\n\n\n\n //! Return the threshold energy\n", "file_path": "packages/monte_carlo/collision/core/src/MonteCarlo_VoidAdjointAtomicReaction.hpp", "rank": 66, "score": 249886.6727604986 }, { "content": "class VoidAtomicRelaxationModel : public AtomicRelaxationModel\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n VoidAtomicRelaxationModel()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~VoidAtomicRelaxationModel()\n\n { /* ... */ }\n\n\n\n //! Relax atom\n\n void relaxAtom( const Data::SubshellType vacancy_shell,\n\n const ParticleState& particle,\n\n ParticleBank& bank ) const;\n\n};\n\n\n\n// Relax atom\n", "file_path": "packages/monte_carlo/collision/core/src/MonteCarlo_VoidAtomicRelaxationModel.hpp", "rank": 67, "score": 249886.6727604986 }, { "content": "class HDF5File::Exception : public std::runtime_error\n\n{\n\npublic:\n\n\n\n //! Constructor\n\n Exception( const std::string& message );\n\n\n\n //! Constructor (extra details)\n\n Exception( const std::string& file,\n\n const size_t line,\n\n const std::string& hdf5_function_name,\n\n const std::string& hdf5_error_message,\n\n const std::string& message );\n\n\n\n //! Destructor\n\n ~Exception() throw()\n\n { /* ... */ }\n\n\n\nprivate:\n\n\n", "file_path": "packages/utility/core/src/Utility_HDF5File.hpp", "rank": 68, "score": 249634.75859144417 }, { "content": "class StandardJustInTimeInitializationObject : public JustInTimeInitializationObject\n\n{\n\n \n\npublic:\n\n\n\n //! Constructor\n\n StandardJustInTimeInitializationObject( T& raw_object )\n\n : d_raw_object( raw_object )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~StandardJustInTimeInitializationObject()\n\n { /* ... */ }\n\n\n\n //! Initialize the object\n\n void initialize() final override\n\n { this->redirectObjectInitialization( d_raw_object.get() ); }\n\n\n\nprivate:\n\n\n", "file_path": "packages/utility/archive/src/Utility_JustInTimeInitializer_def.hpp", "rank": 69, "score": 249436.75052769008 }, { "content": "//---------------------------------------------------------------------------//\n\n// Testing structs\n\n//---------------------------------------------------------------------------//\n\nclass TestDataUnitTest : public Utility::DataUnitTest\n\n{\n\n\n\npublic:\n\n\n\n // Constructor\n\n TestDataUnitTest( const std::string& group_name,\n\n const std::string& test_name,\n\n const std::string& data_name,\n\n const std::shared_ptr<const Utility::UnitTestDataTable>& data_table )\n\n : Utility::DataUnitTest( group_name, test_name, data_name, data_table )\n\n { /* ... */ }\n\n\n\n // Destructor\n\n ~TestDataUnitTest()\n\n { /* ... */ }\n\n\n\n // Return the file where the unit test object is located\n\n std::string getFile() const override\n\n { return \"tstUnitTest.cpp\"; }\n", "file_path": "packages/utility/core/test/tstDataUnitTest.cpp", "rank": 70, "score": 247351.0468673986 }, { "content": "class VoidAbsorptionElectroatomicReaction : public VoidAtomicReaction<ElectroatomicReaction>\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n VoidAbsorptionElectroatomicReaction()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~VoidAbsorptionElectroatomicReaction()\n\n { /* ... */ }\n\n\n\n //! Return the reaction type\n\n ElectroatomicReactionType getReactionType() const final override;\n\n\n\n //! Return the differential cross section\n\n double getDifferentialCrossSection( const double incoming_energy,\n\n const double secondary_variable ) const final override;\n\n\n", "file_path": "packages/monte_carlo/collision/electron/src/MonteCarlo_VoidAbsorptionElectroatomicReaction.hpp", "rank": 71, "score": 247089.7761899614 }, { "content": "class VoidAbsorptionPositronatomicReaction : public VoidAtomicReaction<PositronatomicReaction>\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n VoidAbsorptionPositronatomicReaction()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~VoidAbsorptionPositronatomicReaction()\n\n { /* ... */ }\n\n\n\n //! Return the reaction type\n\n PositronatomicReactionType getReactionType() const final override;\n\n\n\n //! Return the differential cross section\n\n double getDifferentialCrossSection( const double incoming_energy,\n\n const double secondary_variable ) const final override;\n\n\n", "file_path": "packages/monte_carlo/collision/electron/src/MonteCarlo_VoidAbsorptionPositronatomicReaction.hpp", "rank": 72, "score": 247089.77618996147 }, { "content": "//! The spherical directional coordinate conversion policy class\n\nclass SphericalDirectionalCoordinateConversionPolicy : public DirectionalCoordinateConversionPolicy\n\n{\n\n\n\nprotected:\n\n\n\n //! The local coordinate system traits\n\n typedef DirectionalCoordinateSystemTraits<SPHERICAL_DIRECTIONAL_COORDINATE_SYSTEM> LocalCSTraits;\n\n\n\npublic:\n\n\n\n //! Convert the Cartesian direction to spherical coords (on unit sphere)\n\n static void convertFromCartesianDirection(\n\n const double cartesian_direction[3],\n\n double spherical_coords[3] );\n\n\n\n //! Convert the Cartesian direction to spherical coords (on unit sphere)\n\n static void convertFromCartesianDirection( const double x_direction,\n\n const double y_direction,\n\n const double z_direction,\n\n double& r_directional_coord,\n", "file_path": "packages/utility/system/src/Utility_SphericalDirectionalCoordinateConversionPolicy.hpp", "rank": 73, "score": 247045.81812333615 }, { "content": "//! The cylindrical spatial coordinate conversion policy class\n\nclass CylindricalSpatialCoordinateConversionPolicy : public SpatialCoordinateConversionPolicy\n\n{\n\n\n\nprotected:\n\n\n\n //! The local coordinate system traits\n\n typedef SpatialCoordinateSystemTraits<CYLINDRICAL_SPATIAL_COORDINATE_SYSTEM> LocalCSTraits;\n\n\n\npublic:\n\n\n\n //! Convert the Cartesian coordinates to cylindrical coordinates\n\n static void convertFromCartesianPosition( const double cartesian_coords[3],\n\n double cylindrical_coords[3] );\n\n\n\n //! Convert the Cartesian coordinates to cylindrical coordinates\n\n static void convertFromCartesianPosition( const double x_spatial_coord,\n\n const double y_spatial_coord,\n\n const double z_spatial_coord_in,\n\n double& r_spatial_coord,\n\n double& theta_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.hpp", "rank": 74, "score": 247045.81812333615 }, { "content": "//! The spherical spatial coordinate conversion policy class\n\nclass SphericalSpatialCoordinateConversionPolicy : public SpatialCoordinateConversionPolicy\n\n{\n\n\n\nprotected:\n\n\n\n //! The local coordinate system traits\n\n typedef SpatialCoordinateSystemTraits<SPHERICAL_SPATIAL_COORDINATE_SYSTEM> LocalCSTraits;\n\n\n\npublic:\n\n\n\n //! Convert the Cartesian coordinates to spherical coordinates\n\n static void convertFromCartesianPosition( const double cartesian_coords[3],\n\n double spherical_coords[3] );\n\n\n\n //! Convert the Cartesian coordinates to spherical coordinates\n\n static void convertFromCartesianPosition( const double x_spatial_coord,\n\n const double y_spatial_coord,\n\n const double z_spatial_coord,\n\n double& r_spatial_coord,\n\n double& theta_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_SphericalSpatialCoordinateConversionPolicy.hpp", "rank": 75, "score": 247045.81812333615 }, { "content": "//! The Cartesian spatial coordinate conversion policy\n\nclass CartesianSpatialCoordinateConversionPolicy : public SpatialCoordinateConversionPolicy\n\n{\n\n\n\nprotected:\n\n\n\n //! The local coordinate system traits\n\n typedef SpatialCoordinateSystemTraits<CARTESIAN_SPATIAL_COORDINATE_SYSTEM> LocalCSTraits;\n\n\n\npublic:\n\n\n\n //! Convert the Cartesian coordinates to Cartesian coordinates\n\n static void convertFromCartesianPosition( const double input_coords[3],\n\n double output_coords[3] );\n\n\n\n //! Convert the Cartesian coordinates to Cartesian coordinates\n\n static void convertFromCartesianPosition( const double input_x_spatial_coord,\n\n const double input_y_spatial_coord,\n\n const double input_z_spatial_coord,\n\n double& output_x_spatial_coord,\n\n double& output_y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_CartesianSpatialCoordinateConversionPolicy.hpp", "rank": 76, "score": 247038.1836010386 }, { "content": "//! The Cartesian directional coordinate conversion policy\n\nclass CartesianDirectionalCoordinateConversionPolicy : public DirectionalCoordinateConversionPolicy\n\n{\n\n\n\nprotected:\n\n\n\n //! The local coordinate system traits\n\n typedef DirectionalCoordinateSystemTraits<CARTESIAN_DIRECTIONAL_COORDINATE_SYSTEM> LocalCSTraits;\n\n\n\npublic:\n\n\n\n //! Convert the Cartesian direction to Cartesian direction\n\n static void convertFromCartesianDirection(\n\n const double input_direction[3],\n\n double output_direction[3] );\n\n\n\n //! Convert the Cartesian direction to Cartesian direction\n\n static void convertFromCartesianDirection( const double input_x_direction,\n\n const double input_y_direction,\n\n const double input_z_direction,\n\n double& output_x_direction,\n", "file_path": "packages/utility/system/src/Utility_CartesianDirectionalCoordinateConversionPolicy.hpp", "rank": 77, "score": 247038.1836010386 }, { "content": "struct SampleMomentCollectionSnapshotsDataExtractor<N,SampleMomentCollectionSnapshots<T,Container,M,Ms...>,typename std::enable_if<N!=M>::type>\n\n{\n\n //! This type\n\n typedef SampleMomentCollectionSnapshotsDataExtractor<N,SampleMomentCollectionSnapshots<T,Container,M,Ms...>,typename std::enable_if<N!=M>::type> ThisType;\n\n \n\n //! The collection snapshots type\n\n typedef Utility::SampleMomentCollectionSnapshots<T,Container,M,Ms...> CollectionSnapshotsType;\n\n\n\n //! The base collection type\n\n typedef Utility::SampleMomentCollectionSnapshots<T,Container,Ms...> BaseCollectionSnapshotsType;\n\n\n\n //! The container type\n\n typedef Container<typename Utility::SampleMoment<N,T>::ValueType> ContainerType;\n\n\n\n //! The sample moment type\n\n typedef Utility::SampleMoment<N,T> MomentType;\n\n\n\n //! The value type\n\n typedef typename MomentType::ValueType ValueType;\n\n\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollectionSnapshots_def.hpp", "rank": 78, "score": 246766.50026750803 }, { "content": "struct SampleMomentCollectionSnapshotsDataExtractor<N,SampleMomentCollectionSnapshots<T,Container,M,Ms...>,typename std::enable_if<N==M>::type>\n\n{\n\n //! This type\n\n typedef SampleMomentCollectionSnapshotsDataExtractor<N,SampleMomentCollectionSnapshots<T,Container,M,Ms...>,typename std::enable_if<N==M>::type> ThisType;\n\n \n\n //! The collection snapshots type\n\n typedef Utility::SampleMomentCollectionSnapshots<T,Container,M,Ms...> CollectionSnapshotsType;\n\n\n\n //! The container type\n\n typedef Container<typename Utility::SampleMoment<M,T>::ValueType> ContainerType;\n\n\n\n //! The sample moment type\n\n typedef Utility::SampleMoment<M,T> MomentType;\n\n\n\n //! The value type\n\n typedef typename MomentType::ValueType ValueType;\n\n\n\n //! Get the moment snapshots from the collection\n\n static inline const ContainerType& getScoreSnapshots(\n\n const CollectionSnapshotsType& collection,\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollectionSnapshots_def.hpp", "rank": 79, "score": 246766.50026750803 }, { "content": "class CloseComparisonPolicyHelper<T,typename std::enable_if<!std::is_floating_point<typename QuantityTraits<T>::RawType>::value>::type>\n\n{\n\npublic:\n\n\n\n //! Get the comparison operator name\n\n static inline std::string getOperatorName()\n\n { return Utility::EqualityComparisonPolicy::getOperatorName<T>(); }\n\n \n\n //! Create the comparison details\n\n static inline std::string createComparisonDetails(\n\n const std::string& left_name,\n\n const bool report_left_name,\n\n const T& left_value,\n\n const std::string& right_name,\n\n const bool report_right_name,\n\n const T& right_value,\n\n const std::string& name_suffix,\n\n const typename QuantityTraits<T>::RawType& )\n\n {\n\n return Utility::EqualityComparisonPolicy::createComparisonDetails(\n", "file_path": "packages/utility/core/src/Utility_ComparisonPolicy_def.hpp", "rank": 80, "score": 244927.48786252527 }, { "content": "#define FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN() \\\n\n class CustomUnitTestManagerInitializer : public Utility::UnitTestManager::Initializer \\\n\n { \\\n\n public: \\\n\n CustomUnitTestManagerInitializer() \\\n\n : Utility::UnitTestManager::Initializer( __LINE__ ) \\\n\n { Utility::UnitTestManager::getInstance().setInitializer( *this ); } \\\n\n ~CustomUnitTestManagerInitializer() { /* ... */ } \\\n\n protected: \\\n\n void __dummy__()\n\n\n\n//! End the custom unit test setup\n\n#define FRENSIE_CUSTOM_UNIT_TEST_SETUP_END() \\\n\n }; \\\n\n CustomUnitTestManagerInitializer custom_initializer_instance\n\n\n\n//! Set custom command line options for a unit test\n\n#define FRENSIE_CUSTOM_UNIT_TEST_COMMAND_LINE_OPTIONS() \\\n\n size_t getCustomCommandLineOptionsStartCheckpoint() const override \\\n\n { return __LINE__; } \\\n\n void setCustomCommandLineOptions( size_t& __CHECKPOINT__ ) override \\\n", "file_path": "packages/utility/core/src/Utility_UnitTestMacros.hpp", "rank": 81, "score": 244823.0904459683 }, { "content": "//---------------------------------------------------------------------------//\n\n// Testing structs\n\n//---------------------------------------------------------------------------//\n\nclass TestDataUnitTest : public Utility::DataUnitTest\n\n{\n\n\n\npublic:\n\n\n\n // Constructor\n\n TestDataUnitTest( const std::string& data_name,\n\n const std::shared_ptr<const Utility::UnitTestDataTable>& data_table )\n\n : Utility::DataUnitTest( \"Test Group\", \"Test Name\", data_name, data_table )\n\n { /* ... */ }\n\n\n\n // Destructor\n\n ~TestDataUnitTest()\n\n { /* ... */ }\n\n\n\n // Return the file where the unit test object is located\n\n std::string getFile() const override\n\n { return \"tstUnitTest.cpp\"; }\n\n\n\n // Return the line number where the unit test object run impl. was defined\n", "file_path": "packages/utility/core/test/tstDataUnitTestWrapper.cpp", "rank": 82, "score": 244812.23192924238 }, { "content": "class BadUnitTestDataTable : public std::logic_error\n\n{\n\npublic:\n\n BadUnitTestDataTable( const std::string& msg )\n\n : std::logic_error( msg )\n\n { /* ... */ }\n\n\n\n ~BadUnitTestDataTable() throw()\n\n { /* ... */ }\n\n};\n\n\n\n// Get a concrete table element\n\ntemplate<typename T>\n\ninline T UnitTestDataTable::getConcreteElement(\n\n const std::string& row_name,\n\n const std::string& column_name ) const\n\n{\n\n return Utility::variant_cast<T>( this->getElement( row_name, column_name ) );\n\n}\n\n\n", "file_path": "packages/utility/core/src/Utility_UnitTestDataTable.hpp", "rank": 83, "score": 244812.23192924238 }, { "content": "//! The rotation spherical coordinate conversion policy class\n\nclass RotationSphericalCoordinateConversionPolicy : public SphericalSpatialCoordinateConversionPolicy,\n\n public SphericalDirectionalCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n RotationSphericalCoordinateConversionPolicy( const double axis[3] );\n\n\n\n //! Destructor\n\n ~RotationSphericalCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n\n double& y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_RotationSphericalCoordinateConversionPolicy.hpp", "rank": 84, "score": 244712.93565432643 }, { "content": "//! The rotation Cartesian coordinate conversion policy class\n\nclass RotationCartesianCoordinateConversionPolicy : public CartesianSpatialCoordinateConversionPolicy,\n\n public CartesianDirectionalCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n RotationCartesianCoordinateConversionPolicy( const double axis[3] );\n\n\n\n //! Destructor\n\n ~RotationCartesianCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n\n double& y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_RotationCartesianCoordinateConversionPolicy.hpp", "rank": 85, "score": 244712.93565432643 }, { "content": "//! The basic Cartesian coordinate conversion policy class\n\nclass BasicCartesianCoordinateConversionPolicy : public CartesianSpatialCoordinateConversionPolicy,\n\n public CartesianDirectionalCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n BasicCartesianCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~BasicCartesianCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_BasicCartesianCoordinateConversionPolicy.hpp", "rank": 86, "score": 244712.93565432643 }, { "content": "//! The basic spherical coordinate conversion policy class\n\nclass BasicSphericalCoordinateConversionPolicy : public SphericalSpatialCoordinateConversionPolicy,\n\n public SphericalDirectionalCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n BasicSphericalCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~BasicSphericalCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_BasicSphericalCoordinateConversionPolicy.hpp", "rank": 87, "score": 244712.93565432643 }, { "content": "class MPICommunicatorStatusImpl : public Communicator::Status::Impl\n\n{\n\n\n\npublic:\n\n\n\n //! boost::mpi::status constructor\n\n MPICommunicatorStatusImpl( const boost::mpi::status& status )\n\n : Communicator::Status::Impl(),\n\n d_status( status )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~MPICommunicatorStatusImpl()\n\n { /* ... */ }\n\n\n\n //! Check if the communication was cancelled successfully\n\n bool cancelled() const override\n\n { return d_status.cancelled(); }\n\n\n\n //! Retrieve the source of the message\n", "file_path": "packages/utility/mpi/src/Utility_MPICommunicator_def.hpp", "rank": 88, "score": 244168.33474989617 }, { "content": "class MPICommunicatorRequestImpl : public Communicator::Request::Impl\n\n{\n\n\n\npublic:\n\n\n\n //! boost::mpi::request constructor\n\n MPICommunicatorRequestImpl( const boost::mpi::request& request )\n\n : Communicator::Request::Impl(),\n\n d_request( request )\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~MPICommunicatorRequestImpl()\n\n { /* ... */ }\n\n\n\n /*! Wait until the communicator associated with this request has completed\n\n * \\details This will throw a std::exception if the wait fails.\n\n */\n\n MPICommunicatorStatusImpl<T>* wait() override\n\n { return new MPICommunicatorStatusImpl<T>( d_request.wait() ); }\n", "file_path": "packages/utility/mpi/src/Utility_MPICommunicator_def.hpp", "rank": 89, "score": 244168.3347498962 }, { "content": "struct IsHashable<T,typename std::enable_if<std::is_pointer<T>::value>::type> : public std::true_type\n\n{ /* ... */ };\n\n\n\n/*! Partial specialization of IsHashable for arithemtic types\n\n * \\ingroup type_traits\n\n */\n\ntemplate<typename T>\n", "file_path": "packages/utility/core/src/Utility_TypeTraits.hpp", "rank": 90, "score": 243971.11286350238 }, { "content": "struct IsHashable<T,typename std::enable_if<std::is_arithmetic<T>::value>::type> : public std::true_type\n\n{ /* ... */ };\n\n\n\n/*! Specialization of IsHashable for std::string\n\n * \\ingroup type_traits\n\n */\n\ntemplate<>\n", "file_path": "packages/utility/core/src/Utility_TypeTraits.hpp", "rank": 91, "score": 243971.11286350232 }, { "content": "//! The void Compton profile subshell-to-index converter\n\nclass VoidComptonProfileSubshellConverter : public ComptonProfileSubshellConverter\n\n{\n\n\n\npublic:\n\n\n\n //! Default Constructor\n\n VoidComptonProfileSubshellConverter()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~VoidComptonProfileSubshellConverter()\n\n { /* ... */ }\n\n\n\n //! Convert a subshell enum to a compton profile subshell index\n\n unsigned convertSubshellToIndex( const Data::SubshellType subshell ) const;\n\n\n\n //! Test if a subshell enum is valid\n\n bool isSubshellValid( const Data::SubshellType subshell ) const;\n\n};\n\n\n", "file_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_VoidComptonProfileSubshellConverter.hpp", "rank": 92, "score": 242997.03343081416 }, { "content": "struct SampleMomentCollectionDataExtractor<N,const T> : public SampleMomentCollectionDataExtractor<N,T>\n\n{ /* ... */ };\n\n\n\n/*! \\brief Specialization of the sample moment collection data extractor class\n\n * for volatile types\n\n */\n\ntemplate<size_t N, typename T>\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollection_def.hpp", "rank": 93, "score": 242468.7633974672 }, { "content": "struct SampleMomentCollectionDataExtractor<N,volatile T> : public SampleMomentCollectionDataExtractor<N,T>\n\n{ /* ... */ };\n\n\n\n/*! \\brief Specialization of the sample moment collection data extractor class\n\n * for const volatile types\n\n */\n\ntemplate<size_t N, typename T>\n", "file_path": "packages/utility/stats/src/Utility_SampleMomentCollection_def.hpp", "rank": 94, "score": 242468.76339746718 }, { "content": "class RelativeErrorComparisonPolicyHelper<T,typename std::enable_if<!std::is_floating_point<typename QuantityTraits<T>::RawType>::value>::type>\n\n{\n\npublic:\n\n\n\n //! Get the operator name\n\n static inline std::string getOperatorName()\n\n { return Utility::EqualityComparisonPolicy::getOperatorName<T>(); }\n\n \n\n //! Create the comparison details\n\n static inline std::string createComparisonDetails(\n\n const std::string& left_name,\n\n const bool report_left_name,\n\n const T& left_value,\n\n const std::string& right_name,\n\n const bool report_right_name,\n\n const T& right_value,\n\n const std::string& name_suffix,\n\n const typename QuantityTraits<T>::RawType& )\n\n {\n\n return Utility::EqualityComparisonPolicy::createComparisonDetails(\n", "file_path": "packages/utility/core/src/Utility_ComparisonPolicy_def.hpp", "rank": 95, "score": 242353.22683996626 }, { "content": "//! The translation spherical coordinate conversion policy class\n\nclass TranslationSphericalSpatialCoordinateConversionPolicy : public SphericalSpatialCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n TranslationSphericalSpatialCoordinateConversionPolicy(\n\n const double origin[3] );\n\n\n\n //! Destructor\n\n ~TranslationSphericalSpatialCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n\n double& y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_TranslationSphericalSpatialCoordinateConversionPolicy.hpp", "rank": 96, "score": 240233.4339322209 }, { "content": "//! The translation cylindrical coordinate conversion policy class\n\nclass TranslationCylindricalSpatialCoordinateConversionPolicy : public CylindricalSpatialCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n TranslationCylindricalSpatialCoordinateConversionPolicy(\n\n const double origin[3] );\n\n\n\n //! Destructor\n\n ~TranslationCylindricalSpatialCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n\n double& y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_TranslationCylindricalSpatialCoordinateConversionPolicy.hpp", "rank": 97, "score": 240233.4339322209 }, { "content": "//! The basic cylindrical coordinate conversion policy class\n\nclass BasicCylindricalSpatialCoordinateConversionPolicy : public CylindricalSpatialCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n // Constructor\n\n BasicCylindricalSpatialCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Destructor\n\n ~BasicCylindricalSpatialCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n\n double& y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_BasicCylindricalSpatialCoordinateConversionPolicy.hpp", "rank": 98, "score": 240233.4339322209 }, { "content": "//! The translation Cartesian coordinate conversion policy class\n\nclass TranslationCartesianSpatialCoordinateConversionPolicy : public CartesianSpatialCoordinateConversionPolicy\n\n{\n\n\n\npublic:\n\n\n\n //! Constructor\n\n TranslationCartesianSpatialCoordinateConversionPolicy(\n\n const double origin[3] );\n\n\n\n //! Destructor\n\n ~TranslationCartesianSpatialCoordinateConversionPolicy()\n\n { /* ... */ }\n\n\n\n //! Convert the spatial coordinates to cartesian coordinates\n\n void convertToCartesianSpatialCoordinates(\n\n const double primary_spatial_coord,\n\n const double secondary_spatial_coord,\n\n const double tertiary_spatial_coord,\n\n double& x_spatial_coord,\n\n double& y_spatial_coord,\n", "file_path": "packages/utility/system/src/Utility_TranslationCartesianSpatialCoordinateConversionPolicy.hpp", "rank": 99, "score": 240233.4339322209 } ]
C++
src/csapex_remote/src/io/protocol/core_requests.cpp
betwo/csapex
f2c896002cf6bd4eb7fba2903ebeea4a1e811191
#include <csapex/io/protcol/core_requests.h> #include <csapex/serialization/request_serializer.h> #include <csapex/serialization/io/std_io.h> #include <csapex/io/feedback.h> #include <csapex/utility/uuid_provider.h> #include <csapex/model/graph_facade_impl.h> #include <csapex/serialization/parameter_serializer.h> #include <csapex/serialization/snippet.h> #include <iostream> CSAPEX_REGISTER_REQUEST_SERIALIZER(CoreRequests) using namespace csapex; CoreRequests::CoreRequest::CoreRequest(CoreRequestType request_type) : RequestImplementation(0), request_type_(request_type) { } CoreRequests::CoreRequest::CoreRequest(uint8_t request_id) : RequestImplementation(request_id) { } ResponsePtr CoreRequests::CoreRequest::execute(const SessionPtr& session, CsApexCore& core) const { switch (request_type_) { case CoreRequestType::SettingsSavePersistent: core.getSettings().savePersistent(); break; case CoreRequestType::SettingsLoadPersistent: core.getSettings().loadPersistent(); break; case CoreRequestType::CoreSave: { int args = parameters_.size(); if (args == 0) { core.saveAs(core.getSettings().get<std::string>("config")); } else if (args == 1) { core.saveAs(std::any_cast<std::string>(parameters_.at(0))); } else { core.saveAs(std::any_cast<std::string>(parameters_.at(0)), std::any_cast<bool>(parameters_.at(1))); } } break; case CoreRequestType::CoreLoad: { int args = parameters_.size(); if (args == 0) { core.load(core.getSettings().get<std::string>("config")); } else { core.load(std::any_cast<std::string>(parameters_.at(0))); } } break; case CoreRequestType::CoreSerialize: { int args = parameters_.size(); if (args == 2) { SnippetPtr snippet = core.serializeNodes(std::any_cast<AUUID>(parameters_.at(0)), std::any_cast<std::vector<UUID>>(parameters_.at(1))); return std::make_shared<CoreResponse>(request_type_, snippet, getRequestID()); } } break; case CoreRequestType::CoreStep: core.step(); break; case CoreRequestType::CoreShutdown: core.shutdown(); break; case CoreRequestType::CoreResetActivity: core.getRoot()->resetActivity(); break; case CoreRequestType::CoreClearBlock: core.getRoot()->clearBlock(); break; case CoreRequestType::CoreReset: core.reset(); break; case CoreRequestType::CoreSetSteppingMode: core.setSteppingMode(std::any_cast<bool>(parameters_.at(0))); break; case CoreRequestType::CoreSetPause: core.setPause(std::any_cast<bool>(parameters_.at(0))); break; case CoreRequestType::CoreSendNotification: core.sendNotification(std::any_cast<std::string>(parameters_.at(0)), static_cast<ErrorState::ErrorLevel>(std::any_cast<uint8_t>(parameters_.at(1)))); break; case CoreRequestType::CoreGetSteppingMode: return std::make_shared<CoreResponse>(request_type_, core.isSteppingMode(), getRequestID()); case CoreRequestType::CoreGetPause: return std::make_shared<CoreResponse>(request_type_, core.isPaused(), getRequestID()); default: return std::make_shared<Feedback>(std::string("unknown core request type ") + std::to_string((int)request_type_), getRequestID()); } return std::make_shared<CoreResponse>(request_type_, getRequestID()); } void CoreRequests::CoreRequest::serialize(SerializationBuffer& data, SemanticVersion& version) const { data << request_type_; data << parameters_; } void CoreRequests::CoreRequest::deserialize(const SerializationBuffer& data, const SemanticVersion& version) { data >> request_type_; data >> parameters_; } CoreRequests::CoreResponse::CoreResponse(CoreRequestType request_type, uint8_t request_id) : ResponseImplementation(request_id), request_type_(request_type) { } CoreRequests::CoreResponse::CoreResponse(CoreRequestType request_type, std::any result, uint8_t request_id) : ResponseImplementation(request_id), request_type_(request_type), result_(result) { } CoreRequests::CoreResponse::CoreResponse(uint8_t request_id) : ResponseImplementation(request_id) { } void CoreRequests::CoreResponse::serialize(SerializationBuffer& data, SemanticVersion& version) const { data << request_type_; data << result_; } void CoreRequests::CoreResponse::deserialize(const SerializationBuffer& data, const SemanticVersion& version) { data >> request_type_; data >> result_; }
#include <csapex/io/protcol/core_requests.h> #include <csapex/serialization/request_serializer.h> #include <csapex/serialization/io/std_io.h> #include <csapex/io/feedback.h> #include <csapex/utility/uuid_provider.h> #include <csapex/model/graph_facade_impl.h> #include <csapex/serialization/parameter_serializer.h> #include <csapex/serialization/snippet.h> #include <iostream> CSAPEX_REGISTER_REQUEST_SERIALIZER(CoreRequests) using namespace csapex; CoreRequests::CoreRequest::CoreRequest(CoreRequestType request_type) : RequestImplementation(0), request_type_(request_type) { } CoreRequests::CoreRequest::CoreRequest(uint8_t request_id) : RequestImplementation(request_id) { } ResponsePtr CoreRequests::CoreRequest::execute(const SessionPtr& session, CsApexCore& core) const { switch (request_type_) { case CoreRequestType::SettingsSavePersistent: core.getSettings().savePersistent(); break; case CoreRequestType::SettingsLoadPersistent: core.getSettings().loadPersistent(); break; case CoreRequestType::CoreSave: { int args = parameters_.size(); if (args == 0) { core.saveAs(core.getSettings().get<std::string>("config")); } else
} break; case CoreRequestType::CoreLoad: { int args = parameters_.size(); if (args == 0) { core.load(core.getSettings().get<std::string>("config")); } else { core.load(std::any_cast<std::string>(parameters_.at(0))); } } break; case CoreRequestType::CoreSerialize: { int args = parameters_.size(); if (args == 2) { SnippetPtr snippet = core.serializeNodes(std::any_cast<AUUID>(parameters_.at(0)), std::any_cast<std::vector<UUID>>(parameters_.at(1))); return std::make_shared<CoreResponse>(request_type_, snippet, getRequestID()); } } break; case CoreRequestType::CoreStep: core.step(); break; case CoreRequestType::CoreShutdown: core.shutdown(); break; case CoreRequestType::CoreResetActivity: core.getRoot()->resetActivity(); break; case CoreRequestType::CoreClearBlock: core.getRoot()->clearBlock(); break; case CoreRequestType::CoreReset: core.reset(); break; case CoreRequestType::CoreSetSteppingMode: core.setSteppingMode(std::any_cast<bool>(parameters_.at(0))); break; case CoreRequestType::CoreSetPause: core.setPause(std::any_cast<bool>(parameters_.at(0))); break; case CoreRequestType::CoreSendNotification: core.sendNotification(std::any_cast<std::string>(parameters_.at(0)), static_cast<ErrorState::ErrorLevel>(std::any_cast<uint8_t>(parameters_.at(1)))); break; case CoreRequestType::CoreGetSteppingMode: return std::make_shared<CoreResponse>(request_type_, core.isSteppingMode(), getRequestID()); case CoreRequestType::CoreGetPause: return std::make_shared<CoreResponse>(request_type_, core.isPaused(), getRequestID()); default: return std::make_shared<Feedback>(std::string("unknown core request type ") + std::to_string((int)request_type_), getRequestID()); } return std::make_shared<CoreResponse>(request_type_, getRequestID()); } void CoreRequests::CoreRequest::serialize(SerializationBuffer& data, SemanticVersion& version) const { data << request_type_; data << parameters_; } void CoreRequests::CoreRequest::deserialize(const SerializationBuffer& data, const SemanticVersion& version) { data >> request_type_; data >> parameters_; } CoreRequests::CoreResponse::CoreResponse(CoreRequestType request_type, uint8_t request_id) : ResponseImplementation(request_id), request_type_(request_type) { } CoreRequests::CoreResponse::CoreResponse(CoreRequestType request_type, std::any result, uint8_t request_id) : ResponseImplementation(request_id), request_type_(request_type), result_(result) { } CoreRequests::CoreResponse::CoreResponse(uint8_t request_id) : ResponseImplementation(request_id) { } void CoreRequests::CoreResponse::serialize(SerializationBuffer& data, SemanticVersion& version) const { data << request_type_; data << result_; } void CoreRequests::CoreResponse::deserialize(const SerializationBuffer& data, const SemanticVersion& version) { data >> request_type_; data >> result_; }
if (args == 1) { core.saveAs(std::any_cast<std::string>(parameters_.at(0))); } else { core.saveAs(std::any_cast<std::string>(parameters_.at(0)), std::any_cast<bool>(parameters_.at(1))); }
if_condition
[ { "content": "struct ArgumentExtractor<0, Arg, Args...>\n\n{\n\n using type = Arg;\n\n};\n\n\n\ntemplate <int pos, typename Signature>\n", "file_path": "src/csapex_util/include/csapex/utility/slim_signal_invoker.hpp", "rank": 0, "score": 173639.98887121578 }, { "content": "struct function_traits<ReturnType (ClassType::*)(Args...) const>\n\n{\n\n enum\n\n {\n\n arity = sizeof...(Args)\n\n };\n\n\n\n using result_type = ReturnType;\n\n using signature = ReturnType(Args...);\n\n\n\n template <size_t i>\n\n struct arg\n\n {\n\n using type = typename std::tuple_element<i, std::tuple<Args...>>::type;\n\n };\n\n};\n\n\n\ntemplate <typename ReturnType, typename... Args>\n", "file_path": "src/csapex_util/include/csapex/utility/function_traits.hpp", "rank": 1, "score": 158559.98355435248 }, { "content": "class SessionClient : public Session\n\n{\n\npublic:\n\n SessionClient(const std::string& ip, int port);\n\n ~SessionClient() override;\n\n\n\n std::string getDescription() const override;\n\n\n\n void run() override;\n\n void shutdown() override;\n\n\n\n bool isRunning() const override;\n\n\n\nprivate:\n\n boost::asio::io_service io_service;\n\n boost::asio::ip::tcp::socket socket_impl;\n\n boost::asio::ip::tcp::resolver resolver;\n\n#if (BOOST_VERSION / 100000) >= 1 && (BOOST_VERSION / 100 % 1000) >= 66\n\n boost::asio::ip::tcp::resolver::endpoint_type resolver_iterator;\n\n#else\n", "file_path": "src/csapex_remote/include/csapex/io/session_client.h", "rank": 2, "score": 151769.49311627494 }, { "content": "class Session : public Observer, public std::enable_shared_from_this<Session>\n\n{\n\npublic:\n\n using Socket = boost::asio::ip::tcp::socket;\n\n\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 3, "score": 149982.43646336906 }, { "content": "#ifndef SWITCH_THREAD_H\n\n#define SWITCH_THREAD_H\n\n\n\n/// COMPONENT\n\n#include \"command_impl.hpp\"\n\n#include <csapex/utility/uuid.h>\n\n\n\nnamespace csapex\n\n{\n\nnamespace command\n\n{\n", "file_path": "src/csapex_core/include/csapex/command/switch_thread.h", "rank": 4, "score": 149582.02439049236 }, { "content": "class CSAPEX_COMMAND_EXPORT SwitchThread : public CommandImplementation<SwitchThread>\n\n{\n\n COMMAND_HEADER(SwitchThread);\n\n\n\npublic:\n\n SwitchThread(const AUUID& graph_uuid, const UUID& node, int thread_id);\n\n\n\n std::string getDescription() const override;\n\n\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n\n\nprotected:\n\n bool doExecute() override;\n\n bool doUndo() override;\n\n bool doRedo() override;\n\n\n\nprivate:\n\n UUID uuid;\n\n int old_id;\n\n int id;\n\n std::string name;\n\n};\n\n\n\n} // namespace command\n\n\n\n} // namespace csapex\n\n#endif // SWITCH_THREAD_H\n", "file_path": "src/csapex_core/include/csapex/command/switch_thread.h", "rank": 5, "score": 142166.02256871536 }, { "content": "namespace csapex\n\n{\n\nnamespace mime\n\n{\n\nstatic const std::string node = \"csapex/model/node\";\n\nstatic const std::string snippet = \"csapex/model/snippet\";\n\n\n\nstatic const std::string connection_create = \"csapex/connectable/create_connection\";\n\nstatic const std::string connection_move = \"csapex/connectable/move_connections\";\n\n} // namespace mime\n\n\n", "file_path": "src/csapex_core/include/csapex/csapex_mime.h", "rank": 6, "score": 140254.26629872204 }, { "content": "namespace csapex\n\n{\n\nnamespace model\n\n{\n\nTokenDataConstPtr getTokenData(const TokenPtr& token);\n\n\n\ntemplate <typename M>\n\nstd::shared_ptr<const M> getTokenData(const TokenPtr& token)\n\n{\n\n auto data = getTokenData(token);\n\n return std::dynamic_pointer_cast<const M>(data);\n\n}\n\n\n\n} // namespace model\n", "file_path": "src/csapex_core/include/csapex/model/io.h", "rank": 7, "score": 140053.60680717858 }, { "content": "namespace csapex\n\n{\n\nnamespace connection_types\n\n{\n\nstruct CSAPEX_CORE_EXPORT AnyMessage : public Message\n\n{\n\nprotected:\n\n CLONABLE_IMPLEMENTATION(AnyMessage);\n\n\n\npublic:\n\n typedef std::shared_ptr<AnyMessage> Ptr;\n\n\n\npublic:\n\n AnyMessage();\n\n\n\npublic:\n\n bool canConnectTo(const TokenData* other_side) const override;\n\n bool acceptsConnectionFrom(const TokenData* other_side) const override;\n\n\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n};\n\n\n\ntemplate <>\n\nstruct type<AnyMessage>\n\n{\n\n static std::string name()\n\n {\n\n return \"Anything\";\n\n }\n\n};\n\n\n\n} // namespace connection_types\n\n\n\ntemplate <>\n\ninline std::shared_ptr<connection_types::AnyMessage> makeEmpty<connection_types::AnyMessage>()\n\n{\n\n static std::shared_ptr<connection_types::AnyMessage> instance(new connection_types::AnyMessage);\n\n return instance;\n\n}\n\n\n", "file_path": "src/csapex_core/include/csapex/msg/any_message.h", "rank": 8, "score": 140053.60680717858 }, { "content": "namespace csapex\n\n{\n\nstruct CSAPEX_CORE_EXPORT Point\n\n{\n\n float x;\n\n float y;\n\n\n\n Point(float x, float y) : x(x), y(y)\n\n {\n\n }\n\n\n\n Point() : x(0.f), y(0.f)\n\n {\n\n }\n\n\n\n bool operator==(const Point& rhs) const\n\n {\n\n return x == rhs.x && y == rhs.y;\n\n }\n\n bool operator!=(const Point& rhs) const\n\n {\n\n return x != rhs.x || y != rhs.y;\n\n }\n\n};\n\n\n", "file_path": "src/csapex_core/include/csapex/data/point.h", "rank": 9, "score": 140053.60680717858 }, { "content": "namespace csapex\n\n{\n\nnamespace connection_types\n\n{\n\nstruct CSAPEX_CORE_EXPORT NoMessage : public MarkerMessage\n\n{\n\nprotected:\n\n CLONABLE_IMPLEMENTATION(NoMessage);\n\n\n\npublic:\n\n typedef std::shared_ptr<NoMessage> Ptr;\n\n\n\npublic:\n\n NoMessage();\n\n\n\npublic:\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n};\n\n\n\ntemplate <>\n\nstruct type<NoMessage>\n\n{\n\n static std::string name()\n\n {\n\n return \"Nothing\";\n\n }\n\n};\n\n} // namespace connection_types\n\n\n\ntemplate <>\n\ninline std::shared_ptr<connection_types::NoMessage> makeEmpty<connection_types::NoMessage>()\n\n{\n\n static std::shared_ptr<connection_types::NoMessage> instance(new connection_types::NoMessage);\n\n return instance;\n\n}\n\n\n", "file_path": "src/csapex_core/include/csapex/msg/no_message.h", "rank": 10, "score": 140053.60680717858 }, { "content": "namespace csapex\n\n{\n\nnamespace command\n\n{\n\nstruct CSAPEX_COMMAND_EXPORT Quit : public CommandImplementation<Quit>\n\n{\n\n COMMAND_HEADER_NO_DEFAULT(Quit);\n\n\n\npublic:\n\n typedef std::shared_ptr<Quit> Ptr;\n\n\n\npublic:\n\n Quit();\n\n\n\n std::string getDescription() const override;\n\n\n\n bool isHidden() const override;\n\n bool isUndoable() const override;\n\n\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n\n\nprotected:\n\n bool doExecute() override;\n\n bool doUndo() override;\n\n bool doRedo() override;\n\n\n\nprivate:\n\n AUUID uuid;\n\n\n\n std::any value;\n\n};\n\n\n", "file_path": "src/csapex_core/include/csapex/command/quit.h", "rank": 11, "score": 140053.60680717858 }, { "content": "namespace csapex\n\n{\n\nstruct ProfilerStats\n\n{\n\n double mean;\n\n double stddev;\n\n};\n\n\n\nstruct CSAPEX_PROFILING_EXPORT Profile\n\n{\n\n friend class Profiler;\n\n friend class ProfilerProxy;\n\n\n\npublic:\n\n Profile(const std::string& key, int timer_history_length = 1, bool enabled = true);\n\n\n\n Timer::Ptr getTimer() const;\n\n\n\n std::size_t count() const;\n\n std::size_t size() const;\n\n int getCurrentIndex() const;\n\n\n\n const std::vector<Interval::Ptr>& getIntervals() const;\n\n Interval::Ptr getInterval(const std::size_t index) const;\n\n\n\n ProfilerStats getStats(const std::string& name) const;\n\n void reset();\n\n\n\nprotected:\n\n void addInterval(Interval::Ptr interval);\n\n\n\nprivate:\n\n Timer::Ptr timer;\n\n\n\n std::size_t timer_history_length;\n\n int timer_history_pos_;\n\n\n\n typedef boost::accumulators::stats<boost::accumulators::tag::variance> stats;\n\n typedef boost::accumulators::accumulator_set<double, stats> accumulator;\n\n std::map<std::string, accumulator> steps_acc_;\n\n std::vector<Interval::Ptr> timer_history_;\n\n unsigned int count_;\n\n};\n\n\n", "file_path": "src/csapex_core/include/csapex/profiling/profile.h", "rank": 12, "score": 140053.60680717858 }, { "content": "struct should_use_no_generic_message\n\n{\n\n static constexpr bool value = !should_use_pointer_message<M>::value && !should_use_value_message<M>::value;\n\n};\n\n\n\n} // namespace connection_types\n\n} // namespace csapex\n\n\n\n#endif // token_traits_H\n", "file_path": "src/csapex_core/include/csapex/msg/token_traits.h", "rank": 13, "score": 139178.7077221181 }, { "content": "struct should_use_pointer_message\n\n{\n\n static constexpr bool value = \n\n std::is_class<M>::value \n\n && (\n\n has_ptr_member<M>::value // has nested ptr member type\n\n || sizeof(M) >= getMaxValueMessageSize() // is too large\n\n || !std::is_copy_assignable<M>::value // is not copyable\n\n )\n\n && !std::is_same<std::string, M>::value \n\n && !std::is_base_of<TokenData, M>::value;\n\n};\n\n// clang-format on\n\n\n\ntemplate <typename M>\n", "file_path": "src/csapex_core/include/csapex/msg/token_traits.h", "rank": 14, "score": 139178.7077221181 }, { "content": "struct should_use_value_message\n\n{\n\n static constexpr bool value = !should_use_pointer_message<M>::value && !has_elem_type_member<M>::value && // reject shared_ptr\n\n !std::is_base_of<TokenData, M>::value;\n\n};\n\n\n\ntemplate <typename M>\n", "file_path": "src/csapex_core/include/csapex/msg/token_traits.h", "rank": 15, "score": 139178.7077221181 }, { "content": "namespace csapex\n\n{\n\nnamespace command\n\n{\n\nstruct CSAPEX_COMMAND_EXPORT FlipSides : public CommandImplementation<FlipSides>\n\n{\n\n COMMAND_HEADER(FlipSides);\n\n\n\npublic:\n\n FlipSides(const AUUID& graph_uuid, const UUID& node);\n\n\n\n std::string getDescription() const override;\n\n\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n\n\nprotected:\n\n bool doExecute() override;\n\n bool doUndo() override;\n\n bool doRedo() override;\n\n\n\nprivate:\n\n UUID uuid;\n\n};\n\n\n\n} // namespace command\n\n\n", "file_path": "src/csapex_core/include/csapex/command/flip_sides.h", "rank": 16, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nenum class TracingType\n\n{\n\n PROCESS,\n\n SLOT_CALLBACK,\n\n OTHER\n\n};\n", "file_path": "src/csapex_core/include/csapex/model/tracing_type.h", "rank": 17, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nnamespace serialization\n\n{\n\nenum class Format\n\n{\n\n NATIVE,\n\n APEX_BINARY,\n\n APEX_YAML\n\n};\n\n}\n\n\n", "file_path": "src/csapex_core/include/csapex/msg/serialization_format.h", "rank": 18, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nenum class ExecutionState\n\n{\n\n IDLE,\n\n ENABLED,\n\n FIRED,\n\n PROCESSING,\n\n UNKNOWN\n\n};\n", "file_path": "src/csapex_core/include/csapex/model/execution_state.h", "rank": 19, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nnamespace param\n\n{\n\ntemplate <typename T>\n\nstd::string serializationName();\n\n}\n", "file_path": "src/csapex_core/include/csapex/param/parameter_traits.h", "rank": 20, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nenum class ExecutionMode\n\n{\n\n PIPELINING,\n\n SEQUENTIAL\n\n};\n", "file_path": "src/csapex_core/include/csapex/model/execution_mode.h", "rank": 21, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nenum class ActivityModifier\n\n{\n\n NONE,\n\n ACTIVATE,\n\n DEACTIVATE,\n\n INHIBIT\n\n};\n", "file_path": "src/csapex_core/include/csapex/model/activity_modifier.h", "rank": 22, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\nenum class ExecutionType\n\n{\n\n AUTO = 0,\n\n DIRECT,\n\n SUBPROCESS\n\n};\n", "file_path": "src/csapex_core/include/csapex/model/execution_type.h", "rank": 23, "score": 138007.8501539734 }, { "content": "namespace csapex\n\n{\n\n// base\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const Serializable& s);\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, Serializable& s);\n\n\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const SemanticVersion& s);\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, SemanticVersion& s);\n\n\n\n// UUID\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const UUID& s);\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, UUID& s);\n\n\n\n// std overloads\n\ntemplate <typename S, typename std::enable_if<std::is_base_of<Serializable, S>::value, int>::type = 0>\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const std::vector<S>& s)\n\n{\n\n apex_assert_lt_hard(s.size(), std::numeric_limits<uint8_t>::max());\n\n data << (static_cast<uint8_t>(s.size()));\n\n for (const S& elem : s) {\n\n // disambiguate possible overloads for serializable objects\n\n data << static_cast<const Serializable&>(elem);\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename S, typename std::enable_if<std::is_integral<S>::value && std::is_base_of<Serializable, S>::value, int>::type = 0>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::vector<S>& s)\n\n{\n\n uint8_t len;\n\n data >> len;\n\n s.reserve(len);\n\n s.clear();\n\n for (uint8_t i = 0; i < len; ++i) {\n\n S integral;\n\n data >> integral;\n\n s.push_back(integral);\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename S, typename std::enable_if<!std::is_integral<S>::value && std::is_base_of<Serializable, S>::value && std::is_default_constructible<S>::value, int>::type = 0>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::vector<S>& s)\n\n{\n\n uint8_t len;\n\n data >> len;\n\n s.reserve(len);\n\n s.clear();\n\n for (uint8_t i = 0; i < len; ++i) {\n\n s.emplace_back();\n\n data >> static_cast<Serializable&>(s.back());\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename S, typename std::enable_if<!std::is_integral<S>::value && std::is_base_of<Serializable, S>::value && !std::is_default_constructible<S>::value, int>::type = 0>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::vector<S>& s)\n\n{\n\n uint8_t len;\n\n data >> len;\n\n s.reserve(len);\n\n s.clear();\n\n for (uint8_t i = 0; i < len; ++i) {\n\n std::shared_ptr<S> object = makeEmpty<S>();\n\n data >> static_cast<Serializable&>(*object);\n\n s.push_back(*object);\n", "file_path": "src/csapex_core/include/csapex/serialization/io/csapex_io.h", "rank": 24, "score": 136267.0074951616 }, { "content": "namespace csapex\n\n{\n\nnamespace connection_types\n\n{\n\nstruct CSAPEX_CORE_EXPORT EndOfProgramMessage : public MarkerMessage\n\n{\n\nprotected:\n\n CLONABLE_IMPLEMENTATION(EndOfProgramMessage);\n\n\n\npublic:\n\n typedef std::shared_ptr<EndOfProgramMessage> Ptr;\n\n\n\npublic:\n\n EndOfProgramMessage();\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n};\n\n\n\ntemplate <>\n\nstruct type<EndOfProgramMessage>\n\n{\n\n static std::string name()\n\n {\n\n return \"EndOfProgram\";\n\n }\n\n};\n\n\n\n} // namespace connection_types\n", "file_path": "src/csapex_core/include/csapex/msg/end_of_program_message.h", "rank": 25, "score": 136052.28675331123 }, { "content": "namespace csapex\n\n{\n\nnamespace connection_types\n\n{\n\nstruct CSAPEX_CORE_EXPORT EndOfSequenceMessage : public MarkerMessage\n\n{\n\nprotected:\n\n CLONABLE_IMPLEMENTATION(EndOfSequenceMessage);\n\n\n\npublic:\n\n typedef std::shared_ptr<EndOfSequenceMessage> Ptr;\n\n\n\npublic:\n\n EndOfSequenceMessage();\n\n void serialize(SerializationBuffer& data, SemanticVersion& version) const override;\n\n void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;\n\n\n\nprotected:\n\n EndOfSequenceMessage(const std::string& name);\n\n};\n\n\n\ntemplate <>\n\nstruct type<EndOfSequenceMessage>\n\n{\n\n static std::string name()\n\n {\n\n return \"EndOfSequence\";\n\n }\n\n};\n\n\n\n} // namespace connection_types\n", "file_path": "src/csapex_core/include/csapex/msg/end_of_sequence_message.h", "rank": 26, "score": 136052.28675331123 }, { "content": "namespace csapex\n\n{\n\n// SHARED POINTER (of non-serializable type)\n\ntemplate <typename T>\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const boost::shared_ptr<T>& s)\n\n{\n\n if (s) {\n\n data << true;\n\n data << *s;\n\n } else {\n\n data << false;\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename T>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, boost::shared_ptr<T>& s)\n\n{\n\n bool valid;\n\n data >> valid;\n\n if (!valid) {\n\n return data;\n\n }\n\n\n\n // in case T is const, we need to strip that, otherwise we cannot deserialize\n\n using TT = typename std::remove_const<T>::type;\n\n boost::shared_ptr<TT> res = boost::make_shared<TT>();\n\n data >> *res;\n\n s = res;\n\n return data;\n\n}\n", "file_path": "src/csapex_core/include/csapex/serialization/io/boost_io.h", "rank": 27, "score": 136052.28675331123 }, { "content": "namespace csapex\n\n{\n\n// STRINGS\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const std::string& s);\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::string& s);\n\n\n\n// STRING STREAMS\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const std::stringstream& s);\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::stringstream& s);\n\n\n\n// VECTOR\n\ntemplate <typename S, typename std::enable_if<!std::is_base_of<Serializable, S>::value, int>::type = 0>\n\nSerializationBuffer& operator<<(SerializationBuffer& data, const std::vector<S>& s)\n\n{\n\n apex_assert_lt_hard(s.size(), std::numeric_limits<uint8_t>::max());\n\n data << (static_cast<uint8_t>(s.size()));\n\n for (const S& elem : s) {\n\n data << elem;\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename S, typename std::enable_if<std::is_integral<S>::value && !std::is_base_of<Serializable, S>::value, int>::type = 0>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::vector<S>& s)\n\n{\n\n uint8_t len;\n\n data >> len;\n\n s.reserve(len);\n\n s.clear();\n\n for (uint8_t i = 0; i < len; ++i) {\n\n S integral;\n\n data >> integral;\n\n s.push_back(integral);\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename S, typename std::enable_if<!std::is_integral<S>::value && !std::is_base_of<Serializable, S>::value && std::is_default_constructible<S>::value, int>::type = 0>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::vector<S>& s)\n\n{\n\n uint8_t len;\n\n data >> len;\n\n s.reserve(len);\n\n s.clear();\n\n for (uint8_t i = 0; i < len; ++i) {\n\n s.emplace_back();\n\n data >> s.back();\n\n }\n\n return data;\n\n}\n\n\n\ntemplate <typename S, typename std::enable_if<!std::is_integral<S>::value && !std::is_base_of<Serializable, S>::value && !std::is_default_constructible<S>::value, int>::type = 0>\n\nconst SerializationBuffer& operator>>(const SerializationBuffer& data, std::vector<S>& s)\n\n{\n\n uint8_t len;\n\n data >> len;\n\n s.reserve(len);\n\n s.clear();\n\n for (uint8_t i = 0; i < len; ++i) {\n\n std::shared_ptr<S> object = makeEmpty<S>();\n\n data >> object;\n\n s.push_back(*object);\n", "file_path": "src/csapex_core/include/csapex/serialization/io/std_io.h", "rank": 28, "score": 136052.28675331123 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::GenericState>\n\n{\n\n static Node encode(const csapex::GenericState& rhs);\n\n static bool decode(const Node& node, csapex::GenericState& rhs);\n\n};\n\n} // namespace YAML\n\n\n\n#endif // GENERIC_STATE_H\n", "file_path": "src/csapex_core/include/csapex/model/generic_state.h", "rank": 29, "score": 132542.81329053247 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::NodeState>\n\n{\n\n static Node encode(const csapex::NodeState& rhs);\n\n static bool decode(const Node& node, csapex::NodeState& rhs);\n\n};\n\n} // namespace YAML\n\n\n\n#endif // NODE_STATE_H\n", "file_path": "src/csapex_core/include/csapex/model/node_state.h", "rank": 30, "score": 132542.81329053247 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::connection_types::Message>\n\n{\n\n static Node encode(const csapex::connection_types::Message& rhs, const csapex::SemanticVersion& version = csapex::SemanticVersion(0, 0, 0));\n\n static csapex::SemanticVersion decode(const Node& node, csapex::connection_types::Message& rhs);\n\n};\n\n} // namespace YAML\n\n\n\n#endif // MESSAGE_H\n", "file_path": "src/csapex_core/include/csapex/msg/message.h", "rank": 31, "score": 130372.09472914775 }, { "content": "struct convert<csapex::MultiTokenData>\n\n{\n\n static Node encode(const csapex::MultiTokenData& rhs);\n\n static bool decode(const Node& node, csapex::MultiTokenData& rhs);\n\n};\n\n} // namespace YAML\n\n\n\n#endif // MULTI_CONNECTION_TYPE_H\n", "file_path": "src/csapex_core/include/csapex/model/multi_connection_type.h", "rank": 32, "score": 123654.90072360323 }, { "content": "struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + sizeof(int)>\n\n{\n\n template <class X, class XFuncType, class GenericMemFuncType>\n\n inline static GenericClass* Convert(X* pthis, XFuncType function_to_bind, GenericMemFuncType& bound_func)\n\n {\n\n // We need to use a horrible_cast to do this conversion.\n\n // In MSVC, a multiple inheritance member pointer is internally defined as:\n\n union\n\n {\n\n XFuncType func;\n\n struct\n\n {\n\n GenericMemFuncType funcaddress; // points to the actual member function\n\n int delta; // #BYTES to be added to the 'this' pointer\n\n } s;\n\n } u;\n\n // Check that the horrible_cast will work\n\n typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind) == sizeof(u.s) ? 1 : -1];\n\n u.func = function_to_bind;\n\n bound_func = u.s.funcaddress;\n", "file_path": "src/csapex_util/include/csapex/utility/delegate.h", "rank": 33, "score": 123019.9013859279 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::connection_types::GenericVectorMessage>\n\n{\n\n static Node encode(const csapex::connection_types::GenericVectorMessage& rhs);\n\n static bool decode(const Node& node, csapex::connection_types::GenericVectorMessage& rhs);\n\n};\n\n} // namespace YAML\n\n\n\n#endif // GENERIC_VECTOR_MESSAGE_HPP\n", "file_path": "src/csapex_core/include/csapex/msg/generic_vector_message.hpp", "rank": 34, "score": 122767.59526793004 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::Foo>\n\n{\n\n static Node encode(const csapex::Foo& rhs)\n\n {\n\n Node node;\n\n node[\"value\"] = rhs.value;\n\n return node;\n\n }\n\n static bool decode(const Node& node, csapex::Foo& rhs)\n\n {\n\n rhs.value = node[\"value\"].as<int>();\n\n return true;\n\n }\n\n};\n\n\n\ntemplate <>\n", "file_path": "src/csapex_testing/include/csapex_testing/mockup_msgs.h", "rank": 35, "score": 121505.11694274895 }, { "content": "struct convert<std::shared_ptr<T const> >\n\n{\n\n static Node encode(const std::shared_ptr<T const> rhs)\n\n {\n\n return YAML::convertConstPtr<T>::encode(rhs);\n\n }\n\n\n\n static bool decode(const Node& node, std::shared_ptr<T const>& rhs)\n\n {\n\n return YAML::convertConstPtr<T>::decode(node, rhs);\n\n }\n\n};\n\n\n\ntemplate <>\n", "file_path": "src/csapex_util/include/csapex/utility/yaml_io.hpp", "rank": 36, "score": 120847.28322560329 }, { "content": "struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3 * sizeof(int)>\n\n{\n\n template <class X, class XFuncType, class GenericMemFuncType>\n\n inline static GenericClass* Convert(X* pthis, XFuncType function_to_bind, GenericMemFuncType& bound_func)\n\n {\n\n // The member function pointer is 16 bytes long. We can't use a normal cast, but\n\n // we can use a union to do the conversion.\n\n union\n\n {\n\n XFuncType func;\n\n // In VC++ and ICL, an unknown_inheritance member pointer\n\n // is internally defined as:\n\n struct\n\n {\n\n GenericMemFuncType m_funcaddress; // points to the actual member function\n\n int delta; // #bytes to be added to the 'this' pointer\n\n int vtordisp; // #bytes to add to 'this' to find the vtable\n\n int vtable_index; // or 0 if no virtual inheritance\n\n } s;\n\n } u;\n", "file_path": "src/csapex_util/include/csapex/utility/delegate.h", "rank": 37, "score": 120834.02692100045 }, { "content": "struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 2 * sizeof(int)>\n\n{\n\n template <class X, class XFuncType, class GenericMemFuncType>\n\n inline static GenericClass* Convert(X* pthis, XFuncType function_to_bind, GenericMemFuncType& bound_func)\n\n {\n\n union\n\n {\n\n XFuncType func;\n\n GenericClass* (X::*ProbeFunc)();\n\n MicrosoftVirtualMFP s;\n\n } u;\n\n u.func = function_to_bind;\n\n bound_func = reinterpret_cast<GenericMemFuncType>(u.s.codeptr);\n\n union\n\n {\n\n GenericVirtualClass::ProbePtrType virtfunc;\n\n MicrosoftVirtualMFP s;\n\n } u2;\n\n // Check that the horrible_cast<>s will work\n\n typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind) == sizeof(u.s) && sizeof(function_to_bind) == sizeof(u.ProbeFunc) && sizeof(u2.virtfunc) == sizeof(u2.s) ? 1 : -1];\n", "file_path": "src/csapex_util/include/csapex/utility/delegate.h", "rank": 38, "score": 120834.02692100045 }, { "content": "#ifndef CSAPEX_CORE_H\n\n#define CSAPEX_CORE_H\n\n\n\n/// COMPONENT\n\n#include <csapex/command/dispatcher.h>\n\n#include <csapex/core/settings.h>\n\n#include <csapex_core/csapex_core_export.h>\n\n#include <csapex/model/observer.h>\n\n#include <csapex/plugin/plugin_fwd.h>\n\n#include <csapex/model/notifier.h>\n\n#include <csapex/profiling/profilable.h>\n\n#include <csapex/utility/slim_signal.h>\n\n#include <csapex/utility/utility_fwd.h>\n\n#include <csapex/utility/uuid.h>\n\n#include <csapex/io/io_fwd.h>\n\n\n\n/// SYSTEM\n\n#include <thread>\n\n#include <mutex>\n\n#include <condition_variable>\n\n\n\nnamespace class_loader\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 39, "score": 116432.32779825687 }, { "content": " std::thread main_thread_;\n\n std::mutex running_mutex_;\n\n std::condition_variable running_changed_;\n\n bool running_;\n\n\n\n bool init_;\n\n bool load_needs_reset_;\n\n int return_code_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // CSAPEX_CORE_H\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 40, "score": 116427.71080005969 }, { "content": " slim_signal::Signal<void()> shutdown_requested;\n\n slim_signal::Signal<void()> shutdown_complete;\n\n\n\n // TODO: refactor this to support remote clients\n\n csapex::slim_signal::Signal<void(const GraphFacade&, YAML::Node& e)> save_detail_request;\n\n csapex::slim_signal::Signal<void(GraphFacade&, const YAML::Node& n)> load_detail_request;\n\n\n\nprivate:\n\n CsApexCore(Settings& settings_, ExceptionHandler& handler, PluginLocatorPtr plugin_locator);\n\n CorePluginPtr makeCorePlugin(const std::string& name);\n\n\n\nprivate:\n\n bool is_root_;\n\n\n\n BootstrapPtr bootstrap_;\n\n\n\n Settings& settings_;\n\n PluginLocatorPtr plugin_locator_;\n\n ExceptionHandler& exception_handler_;\n\n\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 41, "score": 116417.8920035208 }, { "content": " NodeFactoryImplementationPtr node_factory_;\n\n SnippetFactoryPtr snippet_factory_;\n\n\n\n std::function<ServerPtr()> server_factory_;\n\n ServerPtr server_;\n\n\n\n ThreadPoolPtr thread_pool_;\n\n\n\n UUIDProviderPtr root_uuid_provider_;\n\n GraphFacadeImplementationPtr root_;\n\n NodeFacadeImplementationPtr root_facade_;\n\n\n\n std::shared_ptr<CommandDispatcher> dispatcher_;\n\n\n\n std::shared_ptr<Profiler> profiler_;\n\n\n\n std::shared_ptr<PluginManager<CorePlugin>> core_plugin_manager;\n\n std::map<std::string, std::shared_ptr<CorePlugin>> core_plugins_;\n\n std::map<std::string, bool> core_plugins_connected_;\n\n\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 42, "score": 116414.24271712752 }, { "content": " bool startServer();\n\n bool stopServer();\n\n\n\n void load(const std::string& file);\n\n void saveAs(const std::string& file, bool quiet = false);\n\n\n\n SnippetPtr serializeNodes(const AUUID& graph_id, const std::vector<UUID>& nodes) const;\n\n\n\n void reset();\n\n\n\n int getReturnCode() const;\n\n\n\n Settings& getSettings() const;\n\n NodeFactoryImplementationPtr getNodeFactory() const;\n\n SnippetFactoryPtr getSnippetFactory() const;\n\n\n\n GraphFacadeImplementationPtr getRoot() const;\n\n NodeFacadeImplementationPtr getRootNode() const;\n\n ThreadPoolPtr getThreadPool() const;\n\n\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 43, "score": 116411.35510974766 }, { "content": "\n\npublic:\n\n slim_signal::Signal<void()> config_changed;\n\n slim_signal::Signal<void(const std::string& msg)> status_changed;\n\n slim_signal::Signal<void()> new_node_type;\n\n slim_signal::Signal<void()> new_snippet_type;\n\n\n\n slim_signal::Signal<void()> reset_requested;\n\n slim_signal::Signal<void()> reset_done;\n\n\n\n slim_signal::Signal<void()> saved;\n\n slim_signal::Signal<void()> loaded;\n\n\n\n slim_signal::Signal<void(bool)> paused;\n\n\n\n slim_signal::Signal<void()> stepping_enabled;\n\n slim_signal::Signal<void()> begin_step;\n\n slim_signal::Signal<void()> end_step;\n\n\n\n slim_signal::Signal<void()> startup_requested;\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 44, "score": 116408.0455862187 }, { "content": " PluginLocatorPtr getPluginLocator() const;\n\n ExceptionHandler& getExceptionHandler() const;\n\n\n\n CommandDispatcherPtr getCommandDispatcher() const;\n\n\n\n std::shared_ptr<Profiler> getProfiler() const;\n\n\n\n bool isPaused() const;\n\n void setPause(bool pause);\n\n\n\n bool isSteppingMode() const;\n\n void setSteppingMode(bool stepping);\n\n void step();\n\n\n\n void drainPipeline();\n\n\n\n void settingsChanged();\n\n void setStatusMessage(const std::string& msg);\n\n\n\n void sendNotification(const std::string& notification, ErrorState::ErrorLevel error_level = ErrorState::ErrorLevel::ERROR);\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 45, "score": 116408.0455862187 }, { "content": "#ifndef CORE_PLUGIN_H\n\n#define CORE_PLUGIN_H\n\n\n\n/// PROJECT\n\n#include <csapex/core/csapex_core.h>\n\n#include <csapex/utility/export_plugin.h>\n\n\n\n/// SYSTEM\n\n#include <memory>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/core_plugin.h", "rank": 46, "score": 115954.8089579161 }, { "content": "#ifndef CORE_FWD_H\n\n#define CORE_FWD_H\n\n\n\n/// shared_ptr\n\n#include <memory>\n\n\n\n#define FWD(name) \\\n", "file_path": "src/csapex_core/include/csapex/core/core_fwd.h", "rank": 47, "score": 115941.26255088687 }, { "content": "class Profiler;\n\n\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 48, "score": 114452.45131168595 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::connection_types::VectorMessage>\n\n{\n\n static Node encode(const csapex::connection_types::VectorMessage& rhs)\n\n {\n\n Node node;\n\n node[\"value\"] = rhs.value;\n\n return node;\n\n }\n\n static bool decode(const Node& node, csapex::connection_types::VectorMessage& rhs)\n\n {\n\n rhs.value = node[\"value\"].as<std::vector<csapex::Foo>>();\n\n return true;\n\n }\n\n};\n\n\n\ntemplate <>\n", "file_path": "src/csapex_testing/include/csapex_testing/mockup_msgs.h", "rank": 49, "score": 114174.80442048934 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::connection_types::BaseMessage>\n\n{\n\n static Node encode(const csapex::connection_types::BaseMessage& rhs)\n\n {\n\n return {};\n\n }\n\n static bool decode(const Node& node, csapex::connection_types::BaseMessage& rhs)\n\n {\n\n return true;\n\n }\n\n};\n\ntemplate <>\n", "file_path": "src/csapex_testing/include/csapex_testing/mockup_msgs.h", "rank": 50, "score": 114174.80442048934 }, { "content": "struct CSAPEX_CORE_EXPORT convert<csapex::connection_types::ChildMessage>\n\n{\n\n static Node encode(const csapex::connection_types::ChildMessage& rhs)\n\n {\n\n return {};\n\n }\n\n static bool decode(const Node& node, csapex::connection_types::ChildMessage& rhs)\n\n {\n\n return true;\n\n }\n\n};\n\n} // namespace YAML\n\n\n\n#endif // MOCKUP_MSGS_H\n", "file_path": "src/csapex_testing/include/csapex_testing/mockup_msgs.h", "rank": 51, "score": 114174.80442048934 }, { "content": "class Settings;\n\n} // namespace csapex\n\n\n\n#undef FWD\n\n\n\n#endif // CORE_FWD_H\n", "file_path": "src/csapex_core/include/csapex/core/core_fwd.h", "rank": 52, "score": 113957.80464720345 }, { "content": "#define FWD(name) \\\n\n class name; \\\n\n typedef std::shared_ptr<name> name##Ptr; \\\n\n typedef std::unique_ptr<name> name##UniquePtr; \\\n\n typedef std::weak_ptr<name> name##WeakPtr; \\\n\n typedef std::shared_ptr<const name> name##ConstPtr;\n\n\n\nnamespace csapex\n\n{\n\nFWD(CsApexCore)\n\nFWD(CorePlugin)\n\nFWD(Bootstrap)\n\nFWD(BootstrapPlugin)\n\nFWD(ExceptionHandler)\n\n\n", "file_path": "src/csapex_core/include/csapex/core/core_fwd.h", "rank": 53, "score": 113957.80464720345 }, { "content": "class CSAPEX_CORE_EXPORT CorePlugin\n\n{\n\npublic:\n\n typedef std::shared_ptr<CorePlugin> Ptr;\n\n\n\npublic:\n\n virtual ~CorePlugin();\n\n virtual void prepare(Settings& settings);\n\n virtual void init(CsApexCore& core);\n\n virtual void setupGraph(SubgraphNode* graph);\n\n virtual void shutdown();\n\n\n\n void setName(const std::string& name);\n\n std::string getName();\n\n\n\nprivate:\n\n std::string name_;\n\n};\n\n} // namespace csapex\n\n\n\n#endif // CORE_PLUGIN_H\n", "file_path": "src/csapex_core/include/csapex/core/core_plugin.h", "rank": 54, "score": 113342.81295294665 }, { "content": "#ifndef BOOTSTRAP_H\n\n#define BOOTSTRAP_H\n\n\n\n/// PROJECT\n\n#include <csapex/plugin/plugin_fwd.h>\n\n#include <csapex/command/dispatcher.h>\n\n#include <csapex_core/csapex_core_export.h>\n\n\n\nnamespace class_loader\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/bootstrap.h", "rank": 55, "score": 112863.71874817704 }, { "content": "#ifndef SETTINGS_H\n\n#define SETTINGS_H\n\n\n\n/// PROJECT\n\n#include <csapex/param/parameter.h>\n\n#include <csapex_core/csapex_core_export.h>\n\n#include <csapex/param/value_parameter.h>\n\n#include <csapex/utility/slim_signal.h>\n\n#include <csapex/model/model_fwd.h>\n\n\n\n/// SYSTEM\n\n#include <string>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 56, "score": 112863.46219625874 }, { "content": "#ifndef GRAPHIO_H\n\n#define GRAPHIO_H\n\n\n\n/// COMPONENT\n\n#include <csapex/model/graph.h>\n\n\n\n/// PROJECT\n\n#include <csapex/factory/factory_fwd.h>\n\n#include <csapex/data/point.h>\n\n#include <csapex/profiling/profilable.h>\n\n#include <csapex/serialization/serialization_fwd.h>\n\n#include <csapex/model/connection_description.h>\n\n#include <csapex/utility/yaml.h>\n\n\n\n/// SYSTEM\n\n#include <unordered_map>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/graphio.h", "rank": 57, "score": 112857.6556853052 }, { "content": " }\n\n\n\n settingsChanged(param.get());\n\n }\n\n\n\nprotected:\n\n void setNotDirty();\n\n void settingsChanged(const param::Parameter* parameter);\n\n\n\n virtual void triggerSettingsChanged();\n\n\n\npublic:\n\n csapex::slim_signal::Signal<void(const std::string&)> setting_changed;\n\n csapex::slim_signal::Signal<void()> settings_changed;\n\n\n\nprotected:\n\n bool dirty_;\n\n bool quiet_;\n\n\n\n std::vector<std::string> changes_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // SETTINGS_H\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 58, "score": 112849.25171763255 }, { "content": "\n\nprotected:\n\n void saveNodes(YAML::Node& yaml, const std::vector<NodeFacadeImplementationPtr>& nodes);\n\n void saveConnections(YAML::Node& yaml, const std::vector<ConnectionDescription>& connections);\n\n\n\n void serializeNode(YAML::Node& doc, NodeFacadeImplementationConstPtr node_handle);\n\n void deserializeNode(const YAML::Node& doc, NodeFacadeImplementationPtr node_handle, SemanticVersion version);\n\n\n\n void loadConnection(ConnectorPtr from, const UUID& to_uuid, const std::string& connection_type, SemanticVersion version);\n\n\n\n UUID readNodeUUID(std::weak_ptr<UUIDProvider> parent, const YAML::Node& doc);\n\n UUID readConnectorUUID(std::weak_ptr<UUIDProvider> parent, const YAML::Node& doc);\n\n\n\nprivate:\n\n GraphFacadeImplementation& graph_;\n\n NodeFactoryImplementation* node_factory_;\n\n\n\n std::unordered_map<UUID, UUID, UUID::Hasher> old_node_uuid_to_new_;\n\n double position_offset_x_;\n\n double position_offset_y_;\n\n\n\n bool ignore_forwarding_connections_;\n\n bool throw_on_error_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // GRAPHIO_H\n", "file_path": "src/csapex_core/include/csapex/core/graphio.h", "rank": 59, "score": 112846.80899544695 }, { "content": "\n\n bool isDirty() const;\n\n\n\n bool isQuiet() const;\n\n void setQuiet(bool quiet);\n\n\n\n virtual bool knows(const std::string& name) const = 0;\n\n\n\n virtual void add(csapex::param::Parameter::Ptr p, bool persistent) = 0;\n\n virtual csapex::param::ParameterPtr get(const std::string& name) const = 0;\n\n virtual csapex::param::ParameterPtr getNoThrow(const std::string& name) const = 0;\n\n\n\n void addTemporary(csapex::param::Parameter::Ptr p);\n\n void addPersistent(csapex::param::Parameter::Ptr p);\n\n\n\n virtual void savePersistent() = 0;\n\n virtual void loadPersistent() = 0;\n\n\n\n virtual void saveTemporary(YAML::Node& node) = 0;\n\n virtual void loadTemporary(YAML::Node& node) = 0;\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 60, "score": 112845.51276098628 }, { "content": " auto param = getNoThrow(name);\n\n if (!param) {\n\n param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));\n\n p->set(def);\n\n addTemporary(p);\n\n return def;\n\n }\n\n\n\n return param->as<T>();\n\n }\n\n\n\n template <typename T>\n\n void set(const std::string& name, const T& val)\n\n {\n\n auto param = getNoThrow(name);\n\n if (!param) {\n\n param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));\n\n p->set(val);\n\n addTemporary(p);\n\n param = p;\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 61, "score": 112844.38108742208 }, { "content": "\n\n std::unordered_map<UUID, UUID, UUID::Hasher> loadIntoGraph(const Snippet& blueprint, const csapex::Point& position, SemanticVersion version={});\n\n\n\npublic:\n\n csapex::slim_signal::Signal<void(const GraphFacade&, YAML::Node& e)> saveViewRequest;\n\n csapex::slim_signal::Signal<void(GraphFacade&, const YAML::Node& n)> loadViewRequest;\n\n\n\nprivate:\n\n void saveNodes(YAML::Node& yaml);\n\n void loadNodes(const YAML::Node& doc, SemanticVersion version);\n\n void loadNode(const YAML::Node& doc, SemanticVersion version);\n\n\n\n void saveConnections(YAML::Node& yaml);\n\n void loadConnections(const YAML::Node& doc, SemanticVersion version);\n\n void loadConnection(const YAML::Node& connection, SemanticVersion version);\n\n\n\n void saveFulcrums(YAML::Node& fulcrum, const ConnectionDescription& connection);\n\n void loadFulcrum(const YAML::Node& fulcrum, SemanticVersion version);\n\n\n\n void sendNotification(const std::string& notification);\n", "file_path": "src/csapex_core/include/csapex/core/graphio.h", "rank": 62, "score": 112844.16581369814 }, { "content": " return param->as<T>();\n\n }\n\n\n\n template <typename T>\n\n T getPersistent(const std::string& name, T def)\n\n {\n\n auto param = getNoThrow(name);\n\n if (!param) {\n\n param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));\n\n p->set(def);\n\n addPersistent(p);\n\n return def;\n\n }\n\n\n\n return param->as<T>();\n\n }\n\n\n\n template <typename T>\n\n T getTemporary(const std::string& name, T def)\n\n {\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 63, "score": 112843.36237629657 }, { "content": "\n\n } else {\n\n param->set<T>(val);\n\n }\n\n\n\n settingsChanged(param.get());\n\n }\n\n\n\n template <typename T>\n\n void setPersistent(const std::string& name, const T& val)\n\n {\n\n auto param = getNoThrow(name);\n\n if (!param) {\n\n param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));\n\n p->set(val);\n\n addPersistent(p);\n\n param = p;\n\n\n\n } else {\n\n param->set<T>(val);\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 64, "score": 112843.33186469729 }, { "content": "\n\n template <typename T>\n\n T get(const std::string& name) const\n\n {\n\n auto param = getNoThrow(name);\n\n if (!param) {\n\n throw std::runtime_error(std::string(\"settings.get: unknown parameter '\") + name + \"'\");\n\n }\n\n\n\n return param->as<T>();\n\n }\n\n\n\n template <typename T>\n\n T get(const std::string& name, const T default_value) const\n\n {\n\n auto param = getNoThrow(name);\n\n if (!param) {\n\n return default_value;\n\n }\n\n\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 65, "score": 112839.48806416547 }, { "content": "class ClassLoader;\n\n}\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 66, "score": 112570.7986406528 }, { "content": "struct convert<csapex::connection_types::GenericPointerMessage<T>>\n\n{\n\n static Node encode(const csapex::connection_types::GenericPointerMessage<T>& rhs)\n\n {\n\n if constexpr (csapex::is_complete_v<YAML::convert<T>>) {\n\n Node node;\n\n node[\"value\"] = *rhs.value;\n\n return node;\n\n\n\n } else {\n\n throw std::runtime_error(\"Object not serializable\");\n\n }\n\n }\n\n\n\n static bool decode(const Node& node, csapex::connection_types::GenericPointerMessage<T>& rhs)\n\n {\n\n if constexpr (csapex::is_complete_v<YAML::convert<T>>) {\n\n if (!node.IsMap()) {\n\n return false;\n\n }\n", "file_path": "src/csapex_core/include/csapex/msg/generic_pointer_message.hpp", "rank": 67, "score": 112225.65512407782 }, { "content": "struct convert<csapex::connection_types::GenericValueMessage<T>>\n\n{\n\n static Node encode(const csapex::connection_types::GenericValueMessage<T>& rhs)\n\n {\n\n if constexpr (csapex::is_complete_v<YAML::convert<T>>) {\n\n Node node;\n\n node[\"value\"] = rhs.value;\n\n return node;\n\n\n\n } else {\n\n throw std::runtime_error(\"Object not serializable\");\n\n }\n\n }\n\n\n\n static bool decode(const Node& node, csapex::connection_types::GenericValueMessage<T>& rhs)\n\n {\n\n if constexpr (csapex::is_complete_v<YAML::convert<T>>) {\n\n if (!node.IsMap()) {\n\n return false;\n\n }\n", "file_path": "src/csapex_core/include/csapex/msg/generic_value_message.hpp", "rank": 68, "score": 112225.65512407782 }, { "content": "class CSAPEX_CORE_EXPORT Bootstrap\n\n{\n\npublic:\n\n Bootstrap();\n\n ~Bootstrap();\n\n\n\n bool bootFrom(const std::string& directory, PluginLocator* plugin_locator, bool require_boot_plugin = true);\n\n\n\nprivate:\n\n bool tryBootFrom(const std::string& directory, PluginLocator* plugin_locator, bool require_boot_plugin);\n\n\n\nprivate:\n\n std::vector<class_loader::ClassLoader*> boot_plugin_loaders_;\n\n std::vector<BootstrapPluginPtr> boot_plugins_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // BOOTSTRAP_H\n", "file_path": "src/csapex_core/include/csapex/core/bootstrap.h", "rank": 69, "score": 110758.53870400351 }, { "content": "class CSAPEX_CORE_EXPORT Settings\n\n{\n\npublic:\n\n static const std::string settings_file;\n\n static const std::string config_extension;\n\n static const std::string template_extension;\n\n static const std::string message_extension;\n\n static const std::string message_extension_compressed;\n\n static const std::string message_extension_binary;\n\n static const std::string default_config;\n\n static const std::string config_selector;\n\n\n\n static const std::string namespace_separator;\n\n\n\n static std::string defaultConfigFile();\n\n static std::string defaultConfigPath();\n\n\n\npublic:\n\n Settings();\n\n virtual ~Settings();\n", "file_path": "src/csapex_core/include/csapex/core/settings.h", "rank": 70, "score": 110758.53870400351 }, { "content": "#ifndef EXCEPTION_HANDLER_H\n\n#define EXCEPTION_HANDLER_H\n\n\n\n/// PROJECT\n\n#include <csapex/utility/exceptions.h>\n\n#include <csapex_core/csapex_core_export.h>\n\n#include <csapex/utility/slim_signal.hpp>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/exception_handler.h", "rank": 71, "score": 110619.55444733432 }, { "content": "#ifndef BOOTSTRAP_PLUGIN_H\n\n#define BOOTSTRAP_PLUGIN_H\n\n\n\n/// PROJECT\n\n#include <csapex/plugin/plugin_fwd.h>\n\n#include <csapex_core/csapex_core_export.h>\n\n#include <csapex/utility/register_apex_plugin.h>\n\n#include <csapex/utility/export_plugin.h>\n\n\n\n#define CSAPEX_REGISTER_BOOT(name) CLASS_LOADER_REGISTER_CLASS_WITH_MESSAGE(name, BootstrapPlugin, \"INSTALLING BOOTSTRAP PLUGIN\")\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/bootstrap_plugin.h", "rank": 72, "score": 110617.96748742109 }, { "content": "#ifndef SETTINGS_IMPL_H\n\n#define SETTINGS_IMPL_H\n\n\n\n/// COMPONENT\n\n#include <csapex/core/settings.h>\n\n#include <csapex/model/observer.h>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/settings/settings_impl.h", "rank": 73, "score": 108466.56943384188 }, { "content": "private:\n\n struct Entry\n\n {\n\n csapex::param::Parameter::Ptr parameter;\n\n bool persistent;\n\n };\n\n\n\n std::map<std::string, Entry> settings_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // SETTINGS_IMPL_H\n", "file_path": "src/csapex_core/include/csapex/core/settings/settings_impl.h", "rank": 74, "score": 108454.74069235289 }, { "content": "class ClassLoader;\n\n}\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_core/include/csapex/core/bootstrap.h", "rank": 75, "score": 108443.64618409397 }, { "content": "class CSAPEX_CORE_EXPORT ExceptionHandler\n\n{\n\npublic:\n\n ExceptionHandler(bool fatal_exceptions);\n\n virtual ~ExceptionHandler();\n\n\n\n virtual bool handleException(std::exception_ptr eptr);\n\n virtual void handleAssertionFailure(const csapex::Failure& assertion);\n\n\n\npublic:\n\n slim_signal::Signal<void()> assertion_failed;\n\n\n\nprotected:\n\n void pause();\n\n\n\nprotected:\n\n bool fatal_exceptions_;\n\n};\n\n} // namespace csapex\n\n\n\n#endif // EXCEPTION_HANDLER_H\n", "file_path": "src/csapex_core/include/csapex/core/exception_handler.h", "rank": 76, "score": 107325.90292373711 }, { "content": "class CSAPEX_CORE_EXPORT BootstrapPlugin\n\n{\n\npublic:\n\n virtual ~BootstrapPlugin();\n\n\n\n virtual void boot(csapex::PluginLocator* locator) = 0;\n\n};\n\n} // namespace csapex\n\n\n\n#endif // BOOTSTRAP_PLUGIN_H\n", "file_path": "src/csapex_core/include/csapex/core/bootstrap_plugin.h", "rank": 77, "score": 107325.90292373711 }, { "content": "#ifndef SESSION_H\n\n#define SESSION_H\n\n\n\n/// PROJECT\n\n#include <csapex/core/core_fwd.h>\n\n#include <csapex/serialization/serialization_fwd.h>\n\n#include <csapex/model/observer.h>\n\n#include <csapex/io/remote_io_fwd.h>\n\n#include <csapex/utility/uuid.h>\n\n#include <csapex/utility/slim_signal.hpp>\n\n\n\n/// SYSTEM\n\n#include <boost/asio.hpp>\n\n#include <deque>\n\n#include <future>\n\n#include <unordered_map>\n\n#include <boost/asio.hpp>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 78, "score": 106217.87410435421 }, { "content": " std::unordered_map<AUUID, io::ChannelPtr, AUUID::Hasher> channels_;\n\n\n\nprivate:\n\n std::string name_;\n\n bool is_valid_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // SESSION_H\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 79, "score": 106204.87639377503 }, { "content": " sendNote(std::make_shared<NoteWrapper>(std::forward<Args>(args)...));\n\n }\n\n\n\n //\n\n // BROADCAST\n\n //\n\n template <typename BroadcastWrapper, typename... Args>\n\n void sendBroadcast(Args&&... args)\n\n {\n\n write(std::make_shared<BroadcastWrapper>(std::forward<Args>(args)...));\n\n }\n\n\n\n //\n\n // CHANNEL\n\n //\n\n io::ChannelPtr openChannel(const AUUID& name);\n\n\n\nprotected:\n\n Session(const std::string& name);\n\n\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 80, "score": 106201.20379099919 }, { "content": " void handleFeedback(const ResponseConstPtr& fb);\n\n\n\npublic:\n\n slim_signal::Signal<void(Session*)> started;\n\n slim_signal::Signal<void(Session*)> stopped;\n\n\n\n slim_signal::Signal<void(const StreamableConstPtr&)> packet_received;\n\n slim_signal::Signal<void(const BroadcastMessageConstPtr&)> broadcast_received;\n\n\n\n slim_signal::Signal<void(const StreamableConstPtr&)>& raw_packet_received(const AUUID& uuid);\n\n\n\nprotected:\n\n void mainLoop();\n\n\n\n void read_async();\n\n\n\n void write_packet(SerializationBuffer& buffer);\n\n\n\nprotected:\n\n std::thread packet_handler_thread_;\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 81, "score": 106200.81392840297 }, { "content": " std::shared_ptr<typename RequestWrapper::ResponseT const> sendRequest(Args&&... args)\n\n {\n\n auto res = sendRequest(std::make_shared<typename RequestWrapper::RequestT>(std::forward<Args>(args)...));\n\n apex_assert_hard(res);\n\n if (auto casted = std::dynamic_pointer_cast<typename RequestWrapper::ResponseT const>(res)) {\n\n return casted;\n\n } else {\n\n handleFeedback(res);\n\n }\n\n return nullptr;\n\n }\n\n\n\n //\n\n // NOTE\n\n //\n\n void sendNote(io::NoteConstPtr note);\n\n\n\n template <typename NoteWrapper, typename... Args>\n\n void sendNote(Args&&... args)\n\n {\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 82, "score": 106200.13908227101 }, { "content": " void stopForced();\n\n\n\n virtual std::string getDescription() const;\n\n\n\n void write(const StreamableConstPtr& packet);\n\n void write(const std::string& message);\n\n\n\n\n\n //\n\n // REQUEST\n\n //\n\n ResponseConstPtr sendRequest(RequestConstPtr request);\n\n\n\n template <typename RequestWrapper>\n\n std::shared_ptr<typename RequestWrapper::ResponseT const> sendRequest(std::shared_ptr<typename RequestWrapper::RequestT const> request)\n\n {\n\n return std::dynamic_pointer_cast<typename RequestWrapper::RequestT const>(sendRequest(request));\n\n }\n\n\n\n template <typename RequestWrapper, typename... Args>\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 83, "score": 106198.77806719577 }, { "content": " std::unique_ptr<Socket> socket_;\n\n\n\n uint8_t next_request_id_;\n\n\n\n std::recursive_mutex packets_mutex_;\n\n std::condition_variable_any packets_available_;\n\n std::deque<StreamableConstPtr> packets_received_;\n\n std::deque<StreamableConstPtr> packets_to_send_;\n\n\n\n std::recursive_mutex open_requests_mutex_;\n\n std::map<uint8_t, std::promise<ResponseConstPtr>*> open_requests_;\n\n\n\n std::recursive_mutex running_mutex_;\n\n std::atomic<bool> running_;\n\n std::atomic<bool> is_live_;\n\n std::atomic<bool> was_live_;\n\n\n\n // TODO: use the more general channel\n\n std::unordered_map<AUUID, std::shared_ptr<slim_signal::Signal<void(const StreamableConstPtr&)>>, AUUID::Hasher> auuid_to_signal_;\n\n\n", "file_path": "src/csapex_remote/include/csapex/io/session.h", "rank": 84, "score": 106198.55156939643 }, { "content": "class CSAPEX_CORE_EXPORT GraphIO : public Profilable\n\n{\n\npublic:\n\n GraphIO(GraphFacadeImplementation& graph, NodeFactoryImplementation* node_factory, bool throw_on_error = false);\n\n\n\npublic:\n\n // options\n\n void setIgnoreForwardingConnections(bool ignore);\n\n\n\n // api\n\n void saveSettings(YAML::Node& yaml);\n\n void loadSettings(const YAML::Node& doc);\n\n\n\n Snippet saveGraph();\n\n void saveGraphTo(YAML::Node& yaml);\n\n\n\n void loadGraph(const Snippet& doc);\n\n void loadGraphFrom(const YAML::Node& doc);\n\n\n\n Snippet saveSelectedGraph(const std::vector<UUID>& nodes);\n", "file_path": "src/csapex_core/include/csapex/core/graphio.h", "rank": 85, "score": 105698.21009600924 }, { "content": "class CSAPEX_CORE_EXPORT Scheduler\n\n{\n\npublic:\n\n virtual ~Scheduler();\n\n\n\n virtual int id() const = 0;\n\n virtual std::string getName() const = 0;\n\n virtual void setName(const std::string& name) = 0;\n\n\n\n virtual void setPause(bool pause) = 0;\n\n\n\n virtual bool canStartStepping() const = 0;\n\n virtual void setSteppingMode(bool stepping) = 0;\n\n virtual bool isStepping() const = 0;\n\n virtual bool isStepDone() const = 0;\n\n virtual void step() = 0;\n\n\n\n virtual void start() = 0;\n\n virtual void stop() = 0;\n\n virtual void clear() = 0;\n", "file_path": "src/csapex_core/include/csapex/scheduling/scheduler.h", "rank": 86, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT Connection\n\n{\n\n friend class GraphIO;\n\n friend class Graph;\n\n friend class Fulcrum;\n\n\n\npublic:\n\n typedef std::shared_ptr<Connection> Ptr;\n\n\n", "file_path": "src/csapex_core/include/csapex/model/connection.h", "rank": 87, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT Task\n\n{\n\npublic:\n\n Task(const std::string& name, std::function<void()> callback, long priority = 0, TaskGenerator* parent = nullptr);\n\n virtual ~Task();\n\n\n\n virtual void execute();\n\n\n\n void setPriority(long priority);\n\n long getPriority() const;\n\n\n\n void setScheduled(bool scheduled);\n\n bool isScheduled() const;\n\n\n\n TaskGenerator* getParent() const;\n\n std::string getName() const;\n\n\n\nprivate:\n\n TaskGenerator* parent_;\n\n std::string name_;\n\n std::function<void()> callback_;\n\n\n\n long priority_;\n\n bool scheduled_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // TASK_H\n", "file_path": "src/csapex_core/include/csapex/scheduling/task.h", "rank": 88, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT Unique\n\n{\n\npublic:\n\n Unique(const UUID& uuid);\n\n virtual ~Unique();\n\n\n\n UUID getUUID() const;\n\n AUUID getAUUID() const;\n\n\n\nprotected:\n\n virtual void setUUID(const UUID& uuid);\n\n\n\nprivate:\n\n UUID uuid_;\n\n};\n\n} // namespace csapex\n\n\n\n#endif // UNIQUE_H\n", "file_path": "src/csapex_core/include/csapex/model/unique.h", "rank": 89, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT Executor\n\n{\n\npublic:\n\n Executor();\n\n virtual ~Executor();\n\n\n\n virtual void add(TaskGenerator*) = 0;\n\n virtual void remove(TaskGenerator*) = 0;\n\n\n\n void addChild(Executor* e);\n\n\n\n bool isPaused() const;\n\n void setPause(bool pause);\n\n\n\n bool isSteppingMode() const;\n\n void setSteppingMode(bool stepping);\n\n void step();\n\n\n\n virtual void start() = 0;\n\n virtual void stop() = 0;\n", "file_path": "src/csapex_core/include/csapex/scheduling/executor.h", "rank": 90, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT Parameterizable\n\n{\n\npublic:\n\n /**\n\n * @brief ChangedParameterList A list of parameters and their callback functions\n\n */\n\n typedef std::vector<std::pair<param::ParameterWeakPtr, std::vector<std::function<void(param::Parameter*)>>>> ChangedParameterList;\n\n\n\npublic:\n\n /**\n\n * @brief parameters_changed is triggered, when one of the object's parameters has a new value.\n\n */\n\n slim_signal::Signal<void()> parameters_changed;\n\n\n\npublic:\n\n /**\n\n * @brief Parameterizable\n\n */\n\n Parameterizable();\n\n\n", "file_path": "src/csapex_core/include/csapex/model/parameterizable.h", "rank": 91, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT Transition\n\n{\n\npublic:\n\n Transition(delegate::Delegate0<> activation_fn);\n\n Transition();\n\n\n\n virtual ~Transition();\n\n\n\n virtual int getPortCount() const = 0;\n\n\n\n void setActivationFunction(delegate::Delegate0<> activation_fn);\n\n\n\n void addConnection(ConnectionPtr connection);\n\n void removeConnection(ConnectionPtr connection);\n\n\n\n bool hasConnection() const;\n\n bool hasConnection(const ConnectionPtr& connection) const;\n\n bool hasConnection(Connection* connection) const;\n\n bool hasActiveConnection() const;\n\n\n", "file_path": "src/csapex_core/include/csapex/msg/transition.h", "rank": 92, "score": 104917.50011342071 }, { "content": "class CSAPEX_CORE_EXPORT CsApexCore : public Observer, public Notifier, public Profilable\n\n{\n\npublic:\n\n CsApexCore(Settings& settings_, ExceptionHandler& handler);\n\n CsApexCore(Settings& settings_, ExceptionHandler& handler, PluginLocatorPtr plugin_locator, NodeFactoryPtr node_factory, SnippetFactoryPtr snippet_factory, bool is_root = false);\n\n\n\n ~CsApexCore() override;\n\n\n\n void init();\n\n void boot();\n\n void startup();\n\n void shutdown();\n\n void abort();\n\n\n\n void startMainLoop();\n\n bool isMainLoopRunning() const;\n\n void joinMainLoop();\n\n\n\n bool isServerActive() const;\n\n void setServerFactory(std::function<ServerPtr()> server);\n", "file_path": "src/csapex_core/include/csapex/core/csapex_core.h", "rank": 93, "score": 104453.82979315611 }, { "content": "class CoreRequests\n\n{\n\npublic:\n", "file_path": "src/csapex_remote/include/csapex/io/protcol/core_requests.h", "rank": 94, "score": 104393.53072166766 }, { "content": "class CsApexCore;\n\n\n", "file_path": "src/csapex_core/include/csapex/scheduling/thread_pool.h", "rank": 95, "score": 104393.53072166766 }, { "content": "#ifndef SESSION_CLIENT_H\n\n#define SESSION_CLIENT_H\n\n\n\n/// PROJECT\n\n#include <csapex/io/session.h>\n\n\n\n/// SYSTEM\n\n#include <boost/asio.hpp>\n\n#include <boost/version.hpp>\n\n\n\nnamespace csapex\n\n{\n", "file_path": "src/csapex_remote/include/csapex/io/session_client.h", "rank": 96, "score": 103586.93205711889 }, { "content": " // deprecated in boost 1.66\n\n boost::asio::ip::tcp::resolver::iterator resolver_iterator;\n\n#endif\n\n\n\n bool io_service_running_;\n\n\n\n std::string ip_;\n\n int port_;\n\n};\n\n\n\n} // namespace csapex\n\n\n\n#endif // SESSION_CLIENT_H\n", "file_path": "src/csapex_remote/include/csapex/io/session_client.h", "rank": 97, "score": 103582.11496664108 }, { "content": "class CsApexCore;\n", "file_path": "src/csapex_qt/include/csapex/view/csapex_view_core.h", "rank": 98, "score": 103022.34142434793 }, { "content": "/// HEADER\n\n#include <csapex/io/channel.h>\n\n\n\n/// COMPONENT\n\n#include <csapex/io/note.h>\n\n\n\n/// SYSTEM\n\n#include <iostream>\n\n\n\nusing namespace csapex;\n\nusing namespace csapex::io;\n\n\n\nChannel::Channel(Session& session, const AUUID& name) : session_(session), name_(name)\n\n{\n\n observe(session_.raw_packet_received(name), raw_packet_received);\n\n}\n\n\n\nvoid Channel::handleNote(const io::NoteConstPtr& note)\n\n{\n\n note_received(note);\n\n}\n\n\n\nSession& Channel::getSession()\n\n{\n\n return session_;\n\n}\n", "file_path": "src/csapex_remote/src/io/channel.cpp", "rank": 99, "score": 36.69865525700723 } ]
C++
src/demo/hellocpp/main.cpp
rochus-keller/nappgui_src
394875dfc11c9c73cd7995d56f77dcd4629d70b5
#include "nappgui.h" class App; class MainWindow : public IListener { public: MainWindow(App *app); ~MainWindow(); void *operator new(size_t size) { return (void*)heap_malloc((uint32_t)size, "MainWindow"); } void operator delete(void *ptr, size_t size) { heap_free((byte_t**)&ptr, (uint32_t)size, "MainWindow"); } private: void i_OnButton(Event *e); Panel *i_panel(void); Window *window; TextView *text; uint32_t clicks; }; class App : public IListener { public: App(); ~App(); void i_OnClose(Event *e); void *operator new(size_t size) { return (void*)heap_malloc((uint32_t)size, "App"); } void operator delete(void *ptr, size_t size) { heap_free((byte_t**)&ptr, (uint32_t)size, "App"); } private: MainWindow *main_window; }; void MainWindow::i_OnButton(Event *e) { String *msg = str_printf("Button click (%d)\n", this->clicks); textview_writef(this->text, tc(msg)); str_destroy(&msg); this->clicks += 1; unref(e); } Panel *MainWindow::i_panel(void) { Panel *panel = panel_create(); Layout *layout = layout_create(1, 3); Label *label = label_create(); Button *button = button_push(); TextView *textv = textview_create(); this->text = textv; label_text(label, "Hello!, I'm a label"); button_text(button, "Click Me!"); button_OnClick(button, IListen(this, MainWindow, i_OnButton)); layout_label(layout, label, 0, 0); layout_button(layout, button, 0, 1); layout_textview(layout, textv, 0, 2); layout_hsize(layout, 0, 250); layout_vsize(layout, 2, 100); layout_margin(layout, 5); layout_vmargin(layout, 0, 5); layout_vmargin(layout, 1, 5); panel_layout(panel, layout); return panel; } void App::i_OnClose(Event *e) { osapp_finish(); unref(e); } MainWindow::MainWindow(App *app) { Panel *panel = i_panel(); this->window = window_create(ekWNSTD); this->clicks = 0; window_panel(this->window, panel); window_title(this->window, "Hello, C++!"); window_origin(this->window, v2df(500, 200)); window_OnClose(this->window, IListen(app, App, i_OnClose)); window_show(this->window); } MainWindow::~MainWindow() { window_destroy(&this->window); } App::App(void) { this->main_window = new MainWindow(this); } App::~App() { delete this->main_window; } static App *i_create(void) { return new App(); } static void i_destroy(App **app) { delete *app; *app = NULL; } #include "osmain.h" osmain(i_create, i_destroy, "", App)
#include "nappgui.h" class App; class MainWindow : public IListener { public: MainWindow(App *app); ~MainWindow(); void *operator new(size_t size) { return (void*)heap_malloc((uint32_t)size, "MainWindow"); } void operator delete(void *ptr, size_t size) { heap_free((byte_t**)&ptr, (uint32_t)size, "MainWindow"); } private: void i_OnButton(Event *e); Panel *i_panel(void); Window *window; TextView *text; uint32_t clicks; }; class App : public IListener { public: App(); ~App(); void i_OnClose(Event *e); void *operator new(size_t size) { return (void*)heap_malloc((uint32_t)size, "App"); } void operator delete(void *ptr, size_t size) { heap_free((byte_t**)&ptr, (uint32_t)size, "App"); } private: MainWindow *main_window; }; void MainWindow::i_OnButton(Event *e) { String *msg = str_printf("Button click (%d)\n", this->clicks); textview_writef(this->text, tc(msg)); str_destroy(&msg); this->clicks += 1; unref(e); } Panel *MainWindow::i_panel(void) { Panel *panel = panel_create(); Layout *layout = layout_create(1, 3); Label *label = label_create(); Button *button = button_push(); TextView *textv = textview_create(); this->text = textv; label_text(label, "Hello!, I'm a label"); button_text(button, "Click Me!"); button_OnClick(button, IListen(this, MainWindow, i_OnButton)); layout_label(layout, label, 0, 0); layout_button(layout, button, 0, 1); layout_textview(layout, textv, 0, 2); layout_hsize(layout, 0, 250); layout_vsize(layout, 2, 100); layout_margin(layout, 5); layout_vmargin(layout, 0, 5); layout_vmargin(layout, 1, 5); panel_layout(panel, layout); return panel; } void App::i_OnClose(Event *e) { osapp_finish(); unref(e); } MainWindow::MainWindow(App *app) { Panel *panel = i_panel(); this->window = window_create(ekWNST
MainWindow::~MainWindow() { window_destroy(&this->window); } App::App(void) { this->main_window = new MainWindow(this); } App::~App() { delete this->main_window; } static App *i_create(void) { return new App(); } static void i_destroy(App **app) { delete *app; *app = NULL; } #include "osmain.h" osmain(i_create, i_destroy, "", App)
D); this->clicks = 0; window_panel(this->window, panel); window_title(this->window, "Hello, C++!"); window_origin(this->window, v2df(500, 200)); window_OnClose(this->window, IListen(app, App, i_OnClose)); window_show(this->window); }
function_block-function_prefixed
[ { "content": " String *text;\n", "file_path": "src/gui/label.c", "rank": 3, "score": 145566.12840869065 }, { "content": " String *text;\n", "file_path": "src/gui/button.c", "rank": 4, "score": 145561.48196416028 }, { "content": " Window *window;\n", "file_path": "src/gui/panel.c", "rank": 5, "score": 145560.16226791413 }, { "content": " S2Df size;\n", "file_path": "src/gui/textview.c", "rank": 6, "score": 145536.7779495735 }, { "content": " S2Df size;\n", "file_path": "src/gui/label.c", "rank": 7, "score": 145517.456395683 }, { "content": " S2Df size;\n", "file_path": "src/gui/button.c", "rank": 8, "score": 145512.80995115265 }, { "content": " Panel *panel;\n", "file_path": "src/gui/layout.c", "rank": 9, "score": 145464.13071774167 }, { "content": " real32_t size;\n", "file_path": "src/gui/layout.c", "rank": 10, "score": 145381.19697255082 }, { "content": "static void i_OnButton(App *app, Event *e)\n\n{\n\n String *msg = str_printf(\"Button click (%d)\\n\", app->clicks);\n\n textview_writef(app->text, tc(msg));\n\n str_destroy(&msg);\n\n app->clicks += 1;\n\n unref(e);\n", "file_path": "src/demo/hello/main.c", "rank": 11, "score": 143227.39991173104 }, { "content": "static Panel *i_panel(App *app)\n\n{\n\n Panel *panel = panel_create();\n\n Layout *layout = layout_create(1, 3);\n\n Label *label = label_create();\n\n Button *button = button_push();\n\n TextView *text = textview_create();\n\n app->text = text;\n\n label_text(label, \"Hello!, I'm a label\");\n\n button_text(button, \"Click Me!\");\n\n button_OnClick(button, listener(app, i_OnButton, App));\n\n layout_label(layout, label, 0, 0);\n\n layout_button(layout, button, 0, 1);\n\n layout_textview(layout, text, 0, 2);\n\n layout_hsize(layout, 0, 250);\n\n layout_vsize(layout, 2, 100);\n\n layout_margin(layout, 5);\n\n layout_vmargin(layout, 0, 5);\n\n layout_vmargin(layout, 1, 5);\n\n panel_layout(panel, layout);\n\n return panel;\n", "file_path": "src/demo/hello/main.c", "rank": 12, "score": 143202.89567772363 }, { "content": " Window *window;\n", "file_path": "src/demo/hello/main.c", "rank": 13, "score": 143193.20479808736 }, { "content": " TextView *text;\n", "file_path": "src/demo/hello/main.c", "rank": 14, "score": 143177.09743399138 }, { "content": "void label_OnClick(Label *label, Listener *listener);\n", "file_path": "src/gui/label.h", "rank": 15, "score": 116069.40869596851 }, { "content": "void label_OnClick(Label *label, Listener *listener)\n\n{\n\n cassert_no_null(label);\n\n listener_update(&label->OnClick, listener);\n\n if (label->OnClick != NULL)\n\n label->component.context->func_label_OnClick(label->component.ositem, obj_listener(label, i_OnClick, Label));\n\n else\n\n label->component.context->func_label_OnClick(label->component.ositem, NULL);\n", "file_path": "src/gui/label.c", "rank": 16, "score": 116069.40869596851 }, { "content": "void button_OnClick(Button *button, Listener *listener)\n\n{\n\n cassert_no_null(button);\n\n listener_update(&button->OnClick, listener);\n", "file_path": "src/gui/button.c", "rank": 17, "score": 116063.6344543927 }, { "content": "void button_OnClick(Button *button, Listener *listener);\n", "file_path": "src/gui/button.h", "rank": 18, "score": 116063.6344543927 }, { "content": "void label_text(Label *label, const char_t *text);\n", "file_path": "src/gui/label.h", "rank": 19, "score": 116005.73311979401 }, { "content": "void label_text(Label *label, const char_t *text)\n\n{\n\n const char_t *ltext;\n\n cassert_no_null(label);\n\n ltext = _gui_respack_text(text, &label->textid);\n\n str_upd(&label->text, ltext);\n\n label->component.context->func_label_set_text(label->component.ositem, ltext);\n", "file_path": "src/gui/label.c", "rank": 20, "score": 116005.73311979401 }, { "content": "void _label_text(Label *label, const char_t *text)\n\n{\n\n cassert_no_null(label);\n\n label->component.context->func_label_set_text(label->component.ositem, text);\n", "file_path": "src/gui/label.c", "rank": 21, "score": 116005.73311979401 }, { "content": "void button_text(Button *button, const char_t *text)\n\n{\n\n const char_t *ltext;\n\n cassert_no_null(button);\n\n ltext = _gui_respack_text(text, &button->textid);\n\n str_upd(&button->text, ltext);\n\n i_update_text(button);\n", "file_path": "src/gui/button.c", "rank": 22, "score": 115999.9588782182 }, { "content": "void button_text(Button *button, const char_t *text);\n", "file_path": "src/gui/button.h", "rank": 23, "score": 115999.9588782182 }, { "content": "void _panel_window(Panel *panel, Window *window)\n\n{\n\n cassert_no_null(panel);\n\n\n\n if (window != NULL)\n\n {\n\n cassert(panel->window == NULL);\n\n panel->window = obj_retain(window, Window);\n\n }\n\n else\n\n {\n\n obj_release(&panel->window, Window);\n\n }\n\n\n\n {\n\n register GuiComponent **child;\n\n register uint32_t i, num_elems;\n\n child = arrpt_all(panel->children, GuiComponent);\n\n num_elems = arrpt_size(panel->children, GuiComponent);\n\n for (i = 0; i < num_elems; ++i, ++child)\n\n {\n\n cassert_no_null(child);\n\n _component_set_parent_window(*child, panel->window);\n\n }\n\n }\n", "file_path": "src/gui/panel.c", "rank": 24, "score": 115995.28719575092 }, { "content": "void window_panel(Window *window, Panel *panel);\n", "file_path": "src/gui/window.h", "rank": 25, "score": 115993.21846357716 }, { "content": "void window_panel(Window *window, Panel *panel)\n\n{\n\n Layout *layout = layout_create(1, 1);\n\n layout_panel(layout, panel, 0, 0);\n\n i_attach_main_layout(window, NULL, &layout);\n", "file_path": "src/gui/window.c", "rank": 26, "score": 115993.21846357716 }, { "content": "void textview_size(TextView *view, const S2Df size);\n", "file_path": "src/gui/textview.h", "rank": 27, "score": 115987.6667340121 }, { "content": "void textview_size(TextView *view, const S2Df size)\n\n{\n\n cassert_no_null(view);\n\n view->size = size;\n", "file_path": "src/gui/textview.c", "rank": 28, "score": 115987.6667340121 }, { "content": "void panel_size(Panel *panel, const S2Df size)\n\n{\n\n cassert_no_null(panel);\n\n panel->control_size = size;\n", "file_path": "src/gui/panel.c", "rank": 29, "score": 115935.70451978158 }, { "content": "void panel_size(Panel *panel, const S2Df size);\n", "file_path": "src/gui/panel.h", "rank": 30, "score": 115935.70451978158 }, { "content": "void window_size(Window *window, const S2Df size);\n", "file_path": "src/gui/window.h", "rank": 31, "score": 115926.041542382 }, { "content": "void window_size(Window *window, const S2Df size)\n\n{\n\n cassert_no_null(window);\n\n cassert(window->flags & ekWNRES);\n\n i_main_layout_compose(window, &size);\n", "file_path": "src/gui/window.c", "rank": 32, "score": 115926.041542382 }, { "content": "void layout_textview(Layout *layout, TextView *view, const uint32_t col, const uint32_t row);\n", "file_path": "src/gui/layout.h", "rank": 33, "score": 115902.33736326905 }, { "content": "void layout_textview(Layout *layout, TextView *view, const uint32_t col, const uint32_t row)\n\n{\n\n Cell *cell;\n\n cassert_no_null(view);\n\n cell = i_set_component(layout, (GuiComponent*)view, col, row, ekJUSTIFY, ekJUSTIFY);\n\n cassert(cell->tabstop == TRUE);\n\n cell->tabstop = FALSE;\n", "file_path": "src/gui/layout.c", "rank": 34, "score": 115902.33736326905 }, { "content": "uint32_t panel_layout(Panel *panel, Layout *layout)\n\n{\n\n uint32_t layout_index;\n\n cassert_no_null(panel);\n\n cassert_no_null(layout);\n\n layout_index = arrpt_size(panel->layouts, Layout);\n\n arrpt_append(panel->layouts, layout, Layout);\n\n _layout_attach_to_panel(layout, panel);\n\n if (layout_index == 0)\n\n {\n\n cassert(panel->active_layout == UINT32_MAX);\n\n panel->active_layout = 0;\n\n }\n\n else\n\n {\n\n cassert(panel->active_layout != UINT32_MAX);\n\n }\n\n\n\n return layout_index;\n", "file_path": "src/gui/panel.c", "rank": 35, "score": 115891.7678715482 }, { "content": "ArrPt(Layout) *_panel_layouts(const Panel *panel)\n\n{\n\n cassert_no_null(panel);\n\n return panel->layouts;\n", "file_path": "src/gui/panel.c", "rank": 36, "score": 115891.7678715482 }, { "content": "uint32_t panel_layout(Panel *panel, Layout *layout);\n", "file_path": "src/gui/panel.h", "rank": 37, "score": 115891.7678715482 }, { "content": "void layout_label(Layout *layout, Label *label, const uint32_t col, const uint32_t row);\n", "file_path": "src/gui/layout.h", "rank": 38, "score": 115883.4665813293 }, { "content": "void layout_label(Layout *layout, Label *label, const uint32_t col, const uint32_t row)\n\n{\n\n Cell *cell;\n\n register align_t align = ekLEFT;\n\n //if (_label_is_multiline(label) == TRUE)\n\n // align = ekJUSTIFY;\n\n cell = i_set_component(layout, (GuiComponent*)label, col, row, align, ekCENTER);\n\n cassert(cell->tabstop == TRUE);\n\n cell->tabstop = FALSE;\n", "file_path": "src/gui/layout.c", "rank": 39, "score": 115883.4665813293 }, { "content": "void layout_button(Layout *layout, Button *button, const uint32_t col, const uint32_t row);\n", "file_path": "src/gui/layout.h", "rank": 40, "score": 115878.92853837353 }, { "content": "void layout_button(Layout *layout, Button *button, const uint32_t col, const uint32_t row)\n\n{\n\n register align_t align = ekJUSTIFY;\n\n button_flag_t flags = _button_flags(button);\n\n if (button_type(flags) != ekBTPUSH/* && button_type(flags) != ekBTHEADER*/)\n\n align = ekLEFT;\n\n i_set_component(layout, (GuiComponent*)button, col, row, align, ekCENTER);\n", "file_path": "src/gui/layout.c", "rank": 41, "score": 115878.92853837353 }, { "content": "Panel *_layout_panel(const Layout *layout)\n\n{\n\n cassert_no_null(layout);\n\n return layout->panel;\n", "file_path": "src/gui/layout.c", "rank": 42, "score": 115861.49966066191 }, { "content": "void layout_panel(Layout *layout, Panel *panel, const uint32_t col, const uint32_t row);\n", "file_path": "src/gui/layout.h", "rank": 43, "score": 115861.49966066191 }, { "content": "void layout_panel(Layout *layout, Panel *panel, const uint32_t col, const uint32_t row)\n\n{\n\n Cell *cell = i_get_cell(layout, col, row);\n\n cassert_no_null(cell);\n\n if (cell->type == i_ekEMPTY)\n\n i_set_component(layout, (GuiComponent*)panel, col, row, ekJUSTIFY, ekJUSTIFY);\n\n else\n\n i_change_component(layout, (GuiComponent*)panel, col, row);\n", "file_path": "src/gui/layout.c", "rank": 44, "score": 115861.49966066191 }, { "content": "void button_text_alt(Button *button, const char_t *text)\n\n{\n\n const char_t *ltext;\n\n cassert_no_null(button);\n\n cassert(button_type(button->flags) == ekBTFLATGLE);\n\n ltext = _gui_respack_text(text, &button->taltid);\n\n str_upd(&button->talt, ltext);\n", "file_path": "src/gui/button.c", "rank": 45, "score": 113886.40300398669 }, { "content": "void button_text_alt(Button *button, const char_t *text);\n", "file_path": "src/gui/button.h", "rank": 46, "score": 113886.40300398669 }, { "content": "Window *_panel_get_window(Panel *panel)\n\n{\n\n cassert_no_null(panel);\n\n return panel->window;\n", "file_path": "src/gui/panel.c", "rank": 47, "score": 113881.65658706421 }, { "content": "S2Df window_get_size(const Window *window);\n", "file_path": "src/gui/window.h", "rank": 48, "score": 113813.91063342123 }, { "content": "S2Df _window_get_size(const Window *window)\n\n{\n\n return window_get_size(window);\n", "file_path": "src/gui/window.c", "rank": 49, "score": 113813.91063342123 }, { "content": "S2Df window_get_size(const Window *window)\n\n{\n\n S2Df size;\n\n cassert_no_null(window);\n\n cassert_no_null(window->context);\n\n cassert_no_nullf(window->context->func_window_get_size);\n\n window->context->func_window_get_size(window->ositem, &size.width, &size.height);\n\n return size;\n", "file_path": "src/gui/window.c", "rank": 50, "score": 113813.91063342123 }, { "content": "void panel_visible_layout(Panel *panel, const uint32_t index)\n\n{\n\n cassert_no_null(panel);\n\n cassert(index < arrpt_size(panel->layouts, Layout));\n\n if (panel->active_layout != index)\n\n panel->active_layout = index;\n", "file_path": "src/gui/panel.c", "rank": 51, "score": 113780.49730932678 }, { "content": "Layout *panel_get_layout(Panel *panel, const uint32_t index)\n\n{\n\n cassert_no_null(panel);\n\n return arrpt_get(panel->layouts, index, Layout);\n", "file_path": "src/gui/panel.c", "rank": 52, "score": 113780.49730932678 }, { "content": "Layout *panel_get_layout(Panel *panel, const uint32_t index);\n", "file_path": "src/gui/panel.h", "rank": 53, "score": 113780.49730932678 }, { "content": "void _panel_invalidate_layout(Panel *panel, Layout *layout)\n\n{\n\n cassert_no_null(panel);\n\n cassert_no_null(panel->component.context);\n\n cassert_no_nullf(panel->component.context->func_panel_set_need_display);\n\n if (panel->visible_layout != UINT32_MAX)\n\n {\n\n Layout *main_layout = arrpt_get(panel->layouts, panel->visible_layout, Layout);\n\n if (_layout_search_layout(main_layout, layout) == TRUE)\n\n panel->visible_layout = UINT32_MAX;\n\n }\n\n\n\n //panel->component.context->func_panel_set_need_display(panel->component.ositem);\n", "file_path": "src/gui/panel.c", "rank": 54, "score": 113780.49730932678 }, { "content": "void panel_visible_layout(Panel *panel, const uint32_t index);\n", "file_path": "src/gui/panel.h", "rank": 55, "score": 113780.49730932678 }, { "content": "void _layout_attach_to_panel(Layout *layout, Panel *panel)\n\n{\n\n cassert_no_null(layout);\n\n cassert(layout->panel == NULL || layout->panel == panel);\n\n layout->panel = panel;\n\n arrst_foreach(cell, layout->cells, Cell)\n\n switch (cell->type)\n\n {\n\n case i_ekCOMPONENT:\n\n _panel_attach_component(panel, cell->content.component);\n\n break;\n\n case i_ekLAYOUT:\n\n _layout_attach_to_panel(cell->content.layout, panel);\n\n break;\n\n case i_ekEMPTY:\n\n break;\n\n cassert_default();\n\n }\n\n arrst_end()\n", "file_path": "src/gui/layout.c", "rank": 56, "score": 113749.76370501373 }, { "content": "void layout_content_size(Layout *layout, const S2Df size);\n", "file_path": "src/gui/layout.h", "rank": 57, "score": 113684.11829164704 }, { "content": "S2Df window_get_client_size(const Window *window);\n", "file_path": "src/gui/window.h", "rank": 58, "score": 111780.97771941983 }, { "content": "S2Df window_get_client_size(const Window *window)\n\n{\n\n Panel *panel = NULL;\n\n GuiComponent *component = NULL;\n\n S2Df size;\n\n cassert_no_null(window);\n\n panel = layout_get_panel(window->main_layout, 0, 0);\n\n component = _panel_get_component(panel);\n\n window->context->func_get_size[ekGUI_COMPONENT_PANEL](component->ositem, &size.width, &size.height);\n\n return size;\n", "file_path": "src/gui/window.c", "rank": 59, "score": 111780.97771941983 }, { "content": "__EXTERN_C\n\n\n", "file_path": "src/gui/button.h", "rank": 60, "score": 106018.02346905207 }, { "content": "Button *button_push(void)\n\n{\n\n return i_create(ekBTPUSH, ekCENTER);\n", "file_path": "src/gui/button.c", "rank": 61, "score": 106018.02346905207 }, { "content": " Listener *OnClick;\n", "file_path": "src/gui/label.c", "rank": 62, "score": 104597.69201452064 }, { "content": "static void i_OnClick(Label *label, Event *event)\n\n{\n\n const EvText *params = NULL;\n\n cassert_no_null(label);\n\n cassert_no_null(label->OnClick);\n\n params = event_params(event, EvText);\n\n cassert(params->text == NULL);\n\n ((EvText*)params)->text = tc(label->text);\n\n listener_pass_event(label->OnClick, event, label, Label);\n", "file_path": "src/gui/label.c", "rank": 63, "score": 104597.69201452064 }, { "content": "static void i_OnClick(Button *button, Event *event)\n\n{\n\n EvButton *params = NULL;\n\n Button *sender = button;\n\n\n\n cassert_no_null(button);\n\n cassert(button->component.ositem == event_sender_imp(event, NULL));\n\n cassert_no_null(event);\n\n cassert(event_type(event) == ekEVBUTTON);\n\n params = event_params(event, EvButton);\n\n cassert_no_null(params);\n\n cassert(params->index == 0);\n\n\n\n i_update_button(button, params->state);\n\n\n\n switch (button_type(button->flags)) {\n\n case ekBTRADIO:\n\n {\n\n Cell* cell = _cell_radio_dbind_cell(button->component.parent);\n\n params->index = _cell_radio_index(button->component.parent);\n\n\n\n if (cell != NULL)\n\n _cell_upd_uint32(cell, params->index);\n\n\n\n if (button->OnClick == NULL)\n\n sender = _cell_radio_listener(button->component.parent);\n\n\n\n break;\n\n }\n\n\n\n case ekBTCHECK2:\n\n case ekBTFLATGLE:\n\n _cell_upd_bool(button->component.parent, params->state == ekOFF ? FALSE : TRUE);\n\n break;\n\n\n\n case ekBTCHECK3:\n\n {\n\n uint32_t v = 0;\n\n switch (params->state) {\n\n case ekOFF:\n\n v = 0;\n\n break;\n\n case ekON:\n\n v = 1;\n\n break;\n\n case ekMIXED:\n\n v = 2;\n\n break;\n\n cassert_default();\n\n }\n\n\n\n _cell_upd_uint32(button->component.parent, v);\n\n break;\n\n }}\n\n\n\n if (sender && sender->OnClick)\n\n {\n\n cassert(params->text == NULL);\n\n if (button_type(button->flags) == ekBTFLATGLE && params->state == ekON && button->talt != NULL)\n\n ((EvButton*)params)->text = tc(button->talt);\n\n else\n\n ((EvButton*)params)->text = tc(button->text);\n\n\n\n listener_pass_event(sender->OnClick, event, sender, Button);\n\n }\n", "file_path": "src/gui/button.c", "rank": 64, "score": 104593.04556999027 }, { "content": " Listener *OnClick;\n", "file_path": "src/gui/button.c", "rank": 65, "score": 104593.04556999027 }, { "content": " ArrPt(Layout) *layouts;\n", "file_path": "src/gui/panel.c", "rank": 66, "score": 104421.93473393968 }, { "content": "struct _app_t\n\n{\n\n Window *window;\n\n TextView *text;\n\n uint32_t clicks;\n", "file_path": "src/demo/hello/main.c", "rank": 67, "score": 102228.96643676661 }, { "content": " uint32_t clicks;\n", "file_path": "src/demo/hello/main.c", "rank": 68, "score": 102207.14000249606 }, { "content": "static void i_update_text(Button *button)\n\n{\n\n switch (button_type(button->flags)) {\n\n case ekBTPUSH:\n\n case ekBTHEADER:\n\n case ekBTCHECK2:\n\n case ekBTCHECK3:\n\n case ekBTRADIO:\n\n button->component.context->func_button_set_text(button->component.ositem, tc(button->text));\n\n break;\n\n case ekBTFLAT:\n\n case ekBTFLATGLE:\n\n button->component.context->func_set_tooltip[ekGUI_COMPONENT_BUTTON](button->component.ositem, tc(button->text));\n\n break;\n\n cassert_default();\n\n }\n", "file_path": "src/gui/button.c", "rank": 69, "score": 102089.21370749826 }, { "content": " S2Df natural_size;\n", "file_path": "src/gui/panel.c", "rank": 70, "score": 102029.70711253285 }, { "content": " S2Df content_size;\n", "file_path": "src/gui/panel.c", "rank": 71, "score": 102029.70711253285 }, { "content": " S2Df control_size;\n", "file_path": "src/gui/panel.c", "rank": 72, "score": 102029.70711253285 }, { "content": " uint32_t active_layout;\n", "file_path": "src/gui/panel.c", "rank": 73, "score": 101985.77046429948 }, { "content": "static void i_activate_layout(\n\n ArrPt(Layout) *layouts, \n\n const uint32_t active_layout,\n\n uint32_t *visible_layout,\n\n ArrPt(GuiComponent) **visible_children)\n\n{\n\n Layout *layout = NULL;\n\n ArrPt(GuiComponent) *layout_components = NULL;\n\n cassert_no_null(visible_layout);\n\n cassert_no_null(visible_children);\n\n cassert(*visible_layout != active_layout);\n\n layout = arrpt_get(layouts, active_layout, Layout);\n\n cassert_no_null(layout);\n\n layout_components = arrpt_create(GuiComponent);\n\n _layout_components(layout, layout_components);\n\n\n\n /*! <Hidden components that's become visible> */\n\n arrpt_foreach(component, layout_components, GuiComponent)\n\n if (arrpt_find(*visible_children, component, GuiComponent) == UINT32_MAX)\n\n _component_visible(component, TRUE);\n\n arrpt_end()\n\n\n\n /*! <Visible components that's become hidden> */\n\n arrpt_foreach(component, *visible_children, GuiComponent)\n\n if (arrpt_find(layout_components, component, GuiComponent) == UINT32_MAX)\n\n _component_visible(component, FALSE);\n\n arrpt_end()\n\n\n\n arrpt_destroy(visible_children, NULL, GuiComponent);\n\n *visible_children = layout_components;\n\n *visible_layout = active_layout;\n", "file_path": "src/gui/panel.c", "rank": 74, "score": 101985.77046429948 }, { "content": " uint32_t visible_layout;\n", "file_path": "src/gui/panel.c", "rank": 75, "score": 101985.77046429948 }, { "content": " Layout *main_layout;\n", "file_path": "src/gui/window.c", "rank": 76, "score": 101978.17621907366 }, { "content": " real32_t forced_size;\n", "file_path": "src/gui/layout.c", "rank": 77, "score": 101918.59354310432 }, { "content": "static real32_t i_dimension_size(const ArrSt(i_LineDim) *dim, const real32_t margin)\n\n{\n\n real32_t size = margin;\n\n arrst_foreach_const(edim, dim, i_LineDim)\n\n size += edim->margin;\n\n size += edim->size;\n\n arrst_end()\n\n return size;\n", "file_path": "src/gui/layout.c", "rank": 78, "score": 101918.59354310432 }, { "content": "static void i_detach_main_panel(Panel *main_panel, void *window_renderable_item, FPtr_set_ptr func_detach_main_panel_from_window)\n\n{\n\n GuiComponent *panel_component;\n\n cassert_no_nullf(func_detach_main_panel_from_window);\n\n panel_component = _panel_get_component(main_panel);\n\n cassert_no_null(panel_component);\n\n func_detach_main_panel_from_window(window_renderable_item, panel_component->ositem);\n\n _panel_detach_components(main_panel);\n\n _panel_window(main_panel, NULL);\n", "file_path": "src/gui/window.c", "rank": 79, "score": 99761.84542616739 }, { "content": "static void i_OnLayoutWidth(Layout *layout, Event *event)\n\n{\n\n const EvButton *p = event_params(event, EvButton);\n\n real32_t width = 0;\n\n switch (p->index) {\n\n case 0:\n\n width = 0;\n\n break;\n\n case 1:\n\n width = 100;\n\n break;\n\n case 2:\n\n width = 200;\n\n break;\n\n case 3:\n\n width = 300;\n\n break;\n\n case 4:\n\n width = 400;\n\n break;\n\n cassert_default();\n\n }\n\n\n\n layout_hsize(layout, 0, width);\n\n layout_update(layout);\n", "file_path": "src/howto/guihello/labels.c", "rank": 80, "score": 99682.15226450002 }, { "content": " uint32_t text_size;\n", "file_path": "src/osgui/win/ostext.c", "rank": 81, "score": 99679.09413431739 }, { "content": "static void i_attach_main_layout(Window *window, const S2Df *content_size, Layout **layout)\n\n{\n\n Panel *main_panel = NULL;\n\n GuiComponent *panel_component = NULL;\n\n cassert_no_null(window);\n\n cassert(window->main_layout == NULL);\n\n cassert_no_null(window->context);\n\n cassert_no_nullf(window->context->func_attach_main_panel_to_window);\n\n cassert_no_null(layout);\n\n window->main_layout = *layout;\n\n main_panel = layout_get_panel(window->main_layout, 0, 0);\n\n _panel_window(main_panel, window);\n\n panel_component = _panel_get_component(main_panel);\n\n cassert_no_null(panel_component);\n\n window->context->func_attach_main_panel_to_window(window->ositem, panel_component->ositem);\n\n i_main_layout_compose(window, content_size);\n\n _component_visible(panel_component, TRUE);\n", "file_path": "src/gui/window.c", "rank": 82, "score": 99653.26503775406 }, { "content": "static void i_main_layout_compose(Window *window, const S2Df *content_required_size)\n\n{\n\n S2Df main_layout_size;\n\n cassert_no_null(window);\n\n cassert_no_null(window->context);\n\n cassert_no_nullf(window->context->func_window_set_taborder);\n\n cassert_no_nullf(window->context->func_window_set_size);\n\n _layout_compose(window->main_layout, content_required_size, &main_layout_size);\n\n window->context->func_window_set_taborder(window->ositem, NULL);\n\n _layout_taborder(window->main_layout, window);\n\n window->context->func_window_set_size(window->ositem, main_layout_size.width, main_layout_size.height);\n\n //_component_set_frame(_panel_get_component(window->main_panel), &kV2D_ZEROf, &main_panel_size);\n\n _layout_locate(window->main_layout);\n", "file_path": "src/gui/window.c", "rank": 83, "score": 99653.26503775406 }, { "content": "void _cell_upd_string(Cell *cell, const char_t *str)\n\n{\n\n cassert_no_null(cell);\n\n if (cell->dbind != NULL)\n\n {\n\n void *obj = NULL;\n\n\t\tLayout *layout_notif = NULL;\n\n Layout *layout = i_cell_obj(cell, &obj, &layout_notif);\n\n\n\n if (layout->objbind != NULL)\n\n gbind_upd_string(layout, cell->dbind, obj, layout_notif, str);\n\n }\n", "file_path": "src/gui/layout.c", "rank": 84, "score": 99616.01149319959 }, { "content": " void *ptr;\n", "file_path": "src/core/heap.c", "rank": 85, "score": 93348.77311877333 }, { "content": "static void i_OnButton(App *app, Event *e)\n\n{\n\n textview_printf(app->text, \"Button click (%d)\\n\", app->clicks);\n\n app->clicks += 1;\n\n unref(e);\n", "file_path": "prj/templates/main.c", "rank": 86, "score": 93327.10386326205 }, { "content": "static Panel *i_panel(App *app)\n\n{\n\n Panel *panel = panel_create();\n\n Layout *layout = layout_create(1, 3);\n\n Label *label = label_create();\n\n Button *button = button_push();\n\n TextView *text = textview_create();\n\n app->text = text;\n\n label_text(label, \"Hello!, I'm a label\");\n\n button_text(button, \"Click Me!\");\n\n button_OnClick(button, listener(app, i_OnButton, App));\n\n layout_label(layout, label, 0, 0);\n\n layout_button(layout, button, 0, 1);\n\n layout_textview(layout, text, 0, 2);\n\n layout_hsize(layout, 0, 250);\n\n layout_vsize(layout, 2, 100);\n\n layout_margin(layout, 5);\n\n layout_vmargin(layout, 0, 5);\n\n layout_vmargin(layout, 1, 5);\n\n panel_layout(panel, layout);\n\n return panel;\n", "file_path": "prj/templates/main.c", "rank": 87, "score": 93302.1833004967 }, { "content": "static Panel *i_panel(const GuiComponent *component)\n\n{\n\n cassert_no_null(component);\n\n if (component->parent != NULL)\n\n {\n\n Layout *layout = _cell_parent(component->parent);\n\n return _layout_panel(layout);\n\n }\n\n\n\n return NULL;\n", "file_path": "src/gui/component.c", "rank": 88, "score": 93302.1833004967 }, { "content": " Window *window;\n", "file_path": "prj/templates/main.c", "rank": 89, "score": 93292.31101487814 }, { "content": " String *text;\n", "file_path": "src/draw2d/btext.c", "rank": 90, "score": 93275.78550465478 }, { "content": " String *text;\n", "file_path": "src/gui/combo.c", "rank": 91, "score": 93275.78550465478 }, { "content": " String *text;\n", "file_path": "src/gui/tableview.c", "rank": 92, "score": 93275.78550465478 }, { "content": " TextView *text;\n", "file_path": "prj/templates/main.c", "rank": 93, "score": 93275.78550465478 }, { "content": " String *text;\n", "file_path": "src/gui/popup.c", "rank": 94, "score": 93275.78550465478 }, { "content": " String *text;\n", "file_path": "src/gui/listbox.c", "rank": 95, "score": 93275.78550465478 }, { "content": " String *text;\n", "file_path": "src/gui/edit.c", "rank": 96, "score": 93275.78550465478 }, { "content": " S2Df size;\n", "file_path": "src/gui/slider.c", "rank": 97, "score": 93227.11349164712 }, { "content": "\n\nstatic void i_OnExit(void *empty, Event *event)\n\n{\n\n unref(empty);\n\n unref(event);\n\n window_stop_modal(i_GUI.assert_window, 2);\n\n}\n\n\n\n/*---------------------------------------------------------------------------*/\n\n\n\nstatic Layout *i_buttons_layout(const ResPack *pack, const icon_t icon, Button **defbutton)\n\n{\n\n Layout *layout = layout_create(3, 1);\n\n Button *button1 = button_push();\n\n Button *button3 = button_push();\n\n button_text(button1, respack_text(pack, DEBUG_TEXT));\n\n button_text(button3, respack_text(pack, EXIT_TEXT));\n\n button_OnClick(button1, listener(NULL, i_OnDebug, void));\n\n button_OnClick(button3, listener(NULL, i_OnExit, void));\n\n layout_button(layout, button1, (uint32_t)(icon != ekICON_CRASH ? 0 : 1), 0);\n", "file_path": "src/gui/gui.cpp", "rank": 99, "score": 24.3427842703858 } ]
C++
src/projects/fea/test_FEA_ancf_cable.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
#include <assert.h> #include <iostream> #include <string> #include <vector> #include "chrono/ChConfig.h" #include "chrono/physics/ChSystemSMC.h" #include "chrono/solver/ChIterativeSolverLS.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_mkl/ChSolverMKL.h" #include "chrono/fea/ChBuilderBeam.h" #include "chrono/fea/ChElementCableANCF.h" #include "chrono/fea/ChLinkDirFrame.h" #include "chrono/fea/ChLinkPointFrame.h" #include "chrono/fea/ChMesh.h" #include "chrono/fea/ChVisualizationFEAmesh.h" #include "chrono_thirdparty/filesystem/path.h" #include "chrono_thirdparty/filesystem/resolver.h" using namespace chrono; using namespace chrono::irrlicht; using std::cout; using std::endl; int main(int argc, char* argv[]) { bool use_MKL = true; bool use_HHT = true; ChSystemSMC mphysicalSystem; mphysicalSystem.Set_G_acc(ChVector<>(0.01, 0.0, 0.0)); auto ground = chrono_types::make_shared<ChBody>(); ground->SetIdentifier(-1); ground->SetBodyFixed(true); mphysicalSystem.Add(ground); auto msection_cable = chrono_types::make_shared<fea::ChBeamSectionCable>(); msection_cable->SetDiameter(0.002); msection_cable->SetYoungModulus(5e3); msection_cable->SetDensity(2000); msection_cable->SetBeamRaleyghDamping(0.2); int N_x = 2; int N_y = 2; int num_elements = 4; double delta = 0.1; auto my_mesh = chrono_types::make_shared<fea::ChMesh>(); fea::ChBuilderCableANCF builder; std::vector<std::shared_ptr<fea::ChNodeFEAxyzD>> base_nodes; std::vector<std::shared_ptr<fea::ChNodeFEAxyzD>> tip_nodes; for (int j = 0; j < N_y; j++) { for (int i = 0; i < N_x; i++) { double loc_x = i * delta; double loc_y = j * delta; builder.BuildBeam( my_mesh, msection_cable, num_elements, ChVector<>(loc_x, loc_y, 0.0), ChVector<>(loc_x, loc_y, 0.1) ); base_nodes.push_back(builder.GetLastBeamNodes().front()); tip_nodes.push_back(builder.GetLastBeamNodes().back()); } } for (auto node : base_nodes) { node->SetFixed(true); } mphysicalSystem.Add(my_mesh); auto mvisualizebeamA = chrono_types::make_shared<fea::ChVisualizationFEAmesh>(*my_mesh); mvisualizebeamA->SetFEMdataType(fea::ChVisualizationFEAmesh::E_PLOT_ANCF_BEAM_BD); mvisualizebeamA->SetColorscaleMinMax(-20, 20); mvisualizebeamA->SetSmoothFaces(true); mvisualizebeamA->SetWireframe(false); my_mesh->AddAsset(mvisualizebeamA); ChIrrApp application(&mphysicalSystem, L"Test ANCF Cables", irr::core::dimension2d<irr::u32>(1600, 1200), false, true); application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(irr::core::vector3df(30.f, -100.f, 30.f), irr::core::vector3df(30.f, -80.f, -30.f)); application.AddTypicalCamera(irr::core::vector3df(0.05f, -0.3f, 0.05f), irr::core::vector3df(0.05f, 0.0f, 0.0f)); application.AssetBindAll(); application.AssetUpdateAll(); if (use_MKL) { auto mkl_solver = chrono_types::make_shared<ChSolverMKL>(); mkl_solver->LockSparsityPattern(true); mphysicalSystem.SetSolver(mkl_solver); } else { auto minres_solver = chrono_types::make_shared<ChSolverMINRES>(); minres_solver->SetMaxIterations(400); minres_solver->SetTolerance(1e-12); minres_solver->EnableWarmStart(true); mphysicalSystem.SetSolver(minres_solver); } if (use_HHT) { mphysicalSystem.SetTimestepperType(ChTimestepper::Type::HHT); auto mystepper = std::dynamic_pointer_cast<ChTimestepperHHT>(mphysicalSystem.GetTimestepper()); mystepper->SetAlpha(-0.1); mystepper->SetMaxiters(100); mystepper->SetAbsTolerances(1e-10, 1e-10); mystepper->SetMode(ChTimestepperHHT::ACCELERATION); mystepper->SetScaling(true); mystepper->SetVerbose(false); } else { mphysicalSystem.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); } std::string out_dir = "../TEST_ancf_cable"; if (filesystem::path(out_dir).exists()) { cout << "Output directory already exists" << endl; } else if (filesystem::create_directory(filesystem::path(out_dir))) { cout << "Create directory = " << filesystem::path(out_dir).make_absolute() << endl; } else { cout << "Error creating output directory" << endl; return 1; } utils::CSV_writer csv(" "); csv.stream().setf(std::ios::scientific | std::ios::showpos); csv.stream().precision(18); int step_number = 0; double dt = 0.01; application.SetTimestep(dt); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); ChIrrTools::drawAllCOGs(mphysicalSystem, application.GetVideoDriver(), 0.05); application.DoStep(); application.EndScene(); step_number++; if (step_number == 1) { for (auto node : my_mesh->GetNodes()) { cout << node->GetIndex() << " " << node->NodeGetOffset_x() << " " << node->NodeGetOffset_w() << endl; } } csv << mphysicalSystem.GetChTime(); for (auto node : tip_nodes) { csv << node->GetPos(); } csv << endl; csv.write_to_file(out_dir + "/results.dat"); } return 0; }
#include <assert.h> #include <iostream> #include <string> #include <vector> #include "chrono/ChConfig.h" #include "chrono/physics/ChSystemSMC.h" #include "chrono/solver/ChIterativeSolverLS.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_mkl/ChSolverMKL.h" #include "chrono/fea/ChBuilderBeam.h" #include "chrono/fea/ChElementCableANCF.h" #include "chrono/fea/ChLinkDirFrame.h" #include "chrono/fea/ChLinkPointFrame.h" #include "chrono/fea/ChMesh.h" #include "chrono/fea/ChVisualizationFEAmesh.h" #include "chrono_thirdparty/filesystem/path.h" #include "chrono_thirdparty/filesystem/resolver.h" using namespace chrono; using namespace chrono::irrlicht; using std::cout; using std::endl;
int main(int argc, char* argv[]) { bool use_MKL = true; bool use_HHT = true; ChSystemSMC mphysicalSystem; mphysicalSystem.Set_G_acc(ChVector<>(0.01, 0.0, 0.0)); auto ground = chrono_types::make_shared<ChBody>(); ground->SetIdentifier(-1); ground->SetBodyFixed(true); mphysicalSystem.Add(ground); auto msection_cable = chrono_types::make_shared<fea::ChBeamSectionCable>(); msection_cable->SetDiameter(0.002); msection_cable->SetYoungModulus(5e3); msection_cable->SetDensity(2000); msection_cable->SetBeamRaleyghDamping(0.2); int N_x = 2; int N_y = 2; int num_elements = 4; double delta = 0.1; auto my_mesh = chrono_types::make_shared<fea::ChMesh>(); fea::ChBuilderCableANCF builder; std::vector<std::shared_ptr<fea::ChNodeFEAxyzD>> base_nodes; std::vector<std::shared_ptr<fea::ChNodeFEAxyzD>> tip_nodes; for (int j = 0; j < N_y; j++) { for (int i = 0; i < N_x; i++) { double loc_x = i * delta; double loc_y = j * delta; builder.BuildBeam( my_mesh, msection_cable, num_elements, ChVector<>(loc_x, loc_y, 0.0), ChVector<>(loc_x, loc_y, 0.1) ); base_nodes.push_back(builder.GetLastBeamNodes().front()); tip_nodes.push_back(builder.GetLastBeamNodes().back()); } } for (auto node : base_nodes) { node->SetFixed(true); } mphysicalSystem.Add(my_mesh); auto mvisualizebeamA = chrono_types::make_shared<fea::ChVisualizationFEAmesh>(*my_mesh); mvisualizebeamA->SetFEMdataType(fea::ChVisualizationFEAmesh::E_PLOT_ANCF_BEAM_BD); mvisualizebeamA->SetColorscaleMinMax(-20, 20); mvisualizebeamA->SetSmoothFaces(true); mvisualizebeamA->SetWireframe(false); my_mesh->AddAsset(mvisualizebeamA); ChIrrApp application(&mphysicalSystem, L"Test ANCF Cables", irr::core::dimension2d<irr::u32>(1600, 1200), false, true); application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(irr::core::vector3df(30.f, -100.f, 30.f), irr::core::vector3df(30.f, -80.f, -30.f)); application.AddTypicalCamera(irr::core::vector3df(0.05f, -0.3f, 0.05f), irr::core::vector3df(0.05f, 0.0f, 0.0f)); application.AssetBindAll(); application.AssetUpdateAll(); if (use_MKL) { auto mkl_solver = chrono_types::make_shared<ChSolverMKL>(); mkl_solver->LockSparsityPattern(true); mphysicalSystem.SetSolver(mkl_solver); } else { auto minres_solver = chrono_types::make_shared<ChSolverMINRES>(); minres_solver->SetMaxIterations(400); minres_solver->SetTolerance(1e-12); minres_solver->EnableWarmStart(true); mphysicalSystem.SetSolver(minres_solver); } if (use_HHT) { mphysicalSystem.SetTimestepperType(ChTimestepper::Type::HHT); auto mystepper = std::dynamic_pointer_cast<ChTimestepperHHT>(mphysicalSystem.GetTimestepper()); mystepper->SetAlpha(-0.1); mystepper->SetMaxiters(100); mystepper->SetAbsTolerances(1e-10, 1e-10); mystepper->SetMode(ChTimestepperHHT::ACCELERATION); mystepper->SetScaling(true); mystepper->SetVerbose(false); } else { mphysicalSystem.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); } std::string out_dir = "../TEST_ancf_cable"; if (filesystem::path(out_dir).exists()) { cout << "Output directory already exists" << endl; } else if (filesystem::create_directory(filesystem::path(out_dir))) { cout << "Create directory = " << filesystem::path(out_dir).make_absolute() << endl; } else { cout << "Error creating output directory" << endl; return 1; } utils::CSV_writer csv(" "); csv.stream().setf(std::ios::scientific | std::ios::showpos); csv.stream().precision(18); int step_number = 0; double dt = 0.01; application.SetTimestep(dt); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); ChIrrTools::drawAllCOGs(mphysicalSystem, application.GetVideoDriver(), 0.05); application.DoStep(); application.EndScene(); step_number++; if (step_number == 1) { for (auto node : my_mesh->GetNodes()) { cout << node->GetIndex() << " " << node->NodeGetOffset_x() << " " << node->NodeGetOffset_w() << endl; } } csv << mphysicalSystem.GetChTime(); for (auto node : tip_nodes) { csv << node->GetPos(); } csv << endl; csv.write_to_file(out_dir + "/results.dat"); } return 0; }
function_block-full_function
[]
C++
Qt/Components/pqDisplayColorWidget.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
#include "pqDisplayColorWidget.h" #include "vtkEventQtSlotConnect.h" #include "vtkPVArrayInformation.h" #include "vtkPVDataSetAttributesInformation.h" #include "vtkPVGeometryInformation.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMPVRepresentationProxy.h" #include "vtkSMStringVectorProperty.h" #include <QComboBox> #include <QHBoxLayout> #include <QIcon> #include <QList> #include <QRegExp> #include <QtDebug> #include <QTimer> #include "pqApplicationCore.h" #include "pqPipelineRepresentation.h" #include "pqUndoStack.h" pqDisplayColorWidget::pqDisplayColorWidget( QWidget *p ) : QWidget( p ), BlockEmission(false) { this->CellDataIcon = new QIcon(":/pqWidgets/Icons/pqCellData16.png"); this->PointDataIcon = new QIcon(":/pqWidgets/Icons/pqPointData16.png"); this->SolidColorIcon = new QIcon(":/pqWidgets/Icons/pqSolidColor16.png"); this->Layout = new QHBoxLayout( this ); this->Layout->setMargin(0); this->Layout->setSpacing(6); this->Variables = new QComboBox( this ); this->Variables->setMaxVisibleItems(60); this->Variables->setObjectName("Variables"); this->Variables->setMinimumSize( QSize( 150, 0 ) ); this->Layout->setMargin( 0 ); this->Layout->setSpacing( 1 ); this->Layout->addWidget(this->Variables); QObject::connect(this->Variables, SIGNAL(currentIndexChanged(int)), SLOT(onVariableActivated(int))); QObject::connect(this, SIGNAL(variableChanged(pqVariableType, const QString&)), this, SLOT(onVariableChanged(pqVariableType, const QString&))); this->VTKConnect = vtkEventQtSlotConnect::New(); pqUndoStack* stack = pqApplicationCore::instance()->getUndoStack(); if (stack) { QObject::connect(this, SIGNAL(begin(const QString&)), stack, SLOT(beginUndoSet(const QString&))); QObject::connect(this, SIGNAL(end()), stack, SLOT(endUndoSet())); } } pqDisplayColorWidget::~pqDisplayColorWidget() { delete this->Layout; delete this->Variables; delete this->CellDataIcon; delete this->PointDataIcon; delete this->SolidColorIcon; this->Layout = 0; this->Variables = 0; this->VTKConnect->Delete(); } QString pqDisplayColorWidget::getCurrentText() const { return this->Variables->currentText(); } void pqDisplayColorWidget::clear() { this->BlockEmission = true; this->Variables->clear(); this->BlockEmission = false; } void pqDisplayColorWidget::addVariable(pqVariableType type, const QString& name) { if(-1 != this->Variables->findData(this->variableData(type, name))) { return; } bool old_value = this->BlockEmission; this->BlockEmission = true; switch(type) { case VARIABLE_TYPE_NONE: this->Variables->addItem(*this->SolidColorIcon, "Solid Color", this->variableData(type, name)); break; case VARIABLE_TYPE_NODE: this->Variables->addItem(*this->PointDataIcon, name, this->variableData(type, name)); break; case VARIABLE_TYPE_CELL: this->Variables->addItem(*this->CellDataIcon, name, this->variableData(type, name)); break; } this->BlockEmission = old_value; } void pqDisplayColorWidget::chooseVariable(pqVariableType type, const QString& name) { const int row = this->Variables->findData(variableData(type, name)); if(row != -1) { this->Variables->setCurrentIndex(row); } } void pqDisplayColorWidget::onVariableActivated(int row) { if(this->BlockEmission) { return; } const QStringList d = this->Variables->itemData(row).toString().split("|"); if(d.size() != 2) return; pqVariableType type = VARIABLE_TYPE_NONE; if(d[1] == "cell") { type = VARIABLE_TYPE_CELL; } else if(d[1] == "point") { type = VARIABLE_TYPE_NODE; } const QString name = d[0]; emit variableChanged(type, name); emit this->modified(); } const QString pqDisplayColorWidget::variableData(pqVariableType type, const QString& name) { switch(type) { case VARIABLE_TYPE_NONE: return name + "|none"; case VARIABLE_TYPE_NODE: return name + "|point"; case VARIABLE_TYPE_CELL: return name + "|cell"; } return QString(); } void pqDisplayColorWidget::onVariableChanged(pqVariableType type, const QString& name) { pqPipelineRepresentation* display = this->getRepresentation(); if (display) { emit this->begin("Color Change"); switch(type) { case VARIABLE_TYPE_NONE: display->colorByArray(NULL, 0); break; case VARIABLE_TYPE_NODE: display->colorByArray(name.toAscii().data(), vtkSMDataRepresentationProxy::POINT_DATA); break; case VARIABLE_TYPE_CELL: display->colorByArray(name.toAscii().data(), vtkSMDataRepresentationProxy::CELL_DATA); break; } emit this->end(); display->renderViewEventually(); } } void pqDisplayColorWidget::updateGUI() { this->BlockEmission = true; pqPipelineRepresentation* display = this->getRepresentation(); if (display) { int index = this->AvailableArrays.indexOf(display->getColorField()); if (index < 0) { index = 0; } this->Variables->setCurrentIndex(index); } this->BlockEmission = false; } void pqDisplayColorWidget::setRepresentation(pqDataRepresentation* display) { if(display == this->Display) { return; } if (this->Display) { QObject::disconnect(this->Display, 0, this, 0); } this->VTKConnect->Disconnect(); this->Display = qobject_cast<pqPipelineRepresentation*>(display); if(this->Display) { vtkSMProxy* repr = this->Display->getProxy(); this->VTKConnect->Connect(repr->GetProperty("ColorAttributeType"), vtkCommand::ModifiedEvent, this, SLOT(reloadGUI()), NULL, 0.0, Qt::QueuedConnection); this->VTKConnect->Connect(repr->GetProperty("ColorArrayName"), vtkCommand::ModifiedEvent, this, SLOT(reloadGUI()), NULL, 0.0, Qt::QueuedConnection); this->VTKConnect->Connect( repr->GetProperty("Representation"), vtkCommand::ModifiedEvent, this, SLOT(reloadGUI()), NULL, 0.0, Qt::QueuedConnection); QObject::connect(this->Display, SIGNAL(updated()), this, SLOT(reloadGUI()), Qt::QueuedConnection); } QTimer::singleShot(0, this, SLOT(reloadGUI())); } pqPipelineRepresentation* pqDisplayColorWidget::getRepresentation() const { return this->Display; } void pqDisplayColorWidget::reloadGUI() { this->BlockEmission = true; this->clear(); pqPipelineRepresentation* display = this->getRepresentation(); if (!display) { this->addVariable(VARIABLE_TYPE_NONE, "Solid Color"); this->BlockEmission = false; this->setEnabled(false); return; } this->setEnabled(true); this->AvailableArrays = display->getColorFields(); QRegExp regExpCell(" \\(cell\\)\\w*$"); QRegExp regExpPoint(" \\(point\\)\\w*$"); foreach(QString arrayName, this->AvailableArrays) { if (arrayName == "Solid Color") { this->addVariable(VARIABLE_TYPE_NONE, arrayName); } else if (regExpCell.indexIn(arrayName) != -1) { arrayName = arrayName.replace(regExpCell, ""); this->addVariable(VARIABLE_TYPE_CELL, arrayName); } else if (regExpPoint.indexIn(arrayName) != -1) { arrayName = arrayName.replace(regExpPoint, ""); this->addVariable(VARIABLE_TYPE_NODE, arrayName); } } this->BlockEmission = false; this->updateGUI(); emit this->modified(); }
#include "pqDisplayColorWidget.h" #include "vtkEventQtSlotConnect.h" #include "vtkPVArrayInformation.h" #include "vtkPVDataSetAttributesInformation.h" #include "vtkPVGeometryInformation.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMPVRepresentationProxy.h" #include "vtkSMStringVectorProperty.h" #include <QComboBox> #include <QHBoxLayout> #include <QIcon> #include <QList> #include <QRegExp> #include <QtDebug> #include <QTimer> #include "pqApplicationCore.h" #include "pqPipelineRepresentation.h" #include "pqUndoStack.h" pqDisplayColorWidget::pqDisplayColorWidget( QWidget *p ) : QWidget( p ), BlockEmission(false) { this->CellDataIcon = new QIcon(":/pqWidgets/Icons/pqCellData16.png"); this->PointDataIcon = new QIcon(":/pqWidgets/Icons/pqPointData16.png"); this->SolidColorIcon = new QIcon(":/pqWidgets/Icons/pqSolidColor16.png"); this->Layout = new QHBoxLayout( this ); this->Layout->setMargin(0); this->Layout->setSpacing(6); this->Variables = new QComboBox( this ); this->Variables->setMaxVisibleItems(60); this->Variables->setObjectName("Variables"); this->Variables->setMinimumSize( QSize( 150, 0 ) ); this->Layout->setMargin( 0 ); this->Layout->setSpacing( 1 ); this->Layout->addWidget(this->Variables); QObject::connect(this->Variables, SIGNAL(currentIndexChanged(int)), SLOT(onVariableActivated(int))); QObject::connect(this, SIGNAL(variableChanged(pqVariableType, const QString&)), this, SLOT(onVariableChanged(pqVariableType, const QString&))); this->VTKConnect = vtkEventQtSlotConnect::New(); pqUndoStack* stack = pqApplicationCore::instance()->getUndoStack(); if (stack) { QObject::connect(this, SIGNAL(begin(const QString&)), stack, SLOT(beginUndoSet(const QString&))); QObject::connect(this, SIGNAL(end()), stack, SLOT(endUndoSet())); } } pqDisplayColorWidget::~pqDisplayColorWidget() { delete this->Layout; delete this->Variables; delete this->CellDataIcon; delete this->PointDataIcon; delete this->SolidColorIcon; this->Layout = 0; this->Variables = 0; this->VTKConnect->Delete(); } QString pqDisplayColorWidget::getCurrentText() const { return this->Variables->currentText(); } void pqDisplayColorWidget::clear() { this->BlockEmission = true; this->Variables->clear(); this->BlockEmission = false; } void pqDisplayColorWidget::addVariable(pqVariableType type, const QString& name) { if(-1 != this->Variables->findData(this->variableData(type, name))) { return; } bool old_value = this->BlockEmission; this->BlockEmission = true; switch(type) { case VARIABLE_TYPE_NONE: this->Variables->addItem(*this->SolidColorIcon, "Solid Color", this->variableData(type, name)); break; case VARIABLE_TYPE_NODE: this->Variables->addItem(*this->PointDataIcon, name, this->variableData(type, name)); break; case VARIABLE_TYPE_CELL: this->Variables->addItem(*this->CellDataIcon, name, this->variableData(type, name)); break; } this->BlockEmission = old_value; } void pqDisplayColorWidget::chooseVariable(pqVariableType type, const QString& name) { const int row = this->Variables->findData(variableData(type, name)); if(row != -1) { this->Variables->setCurrentIndex(row); } } void pqDisplayColorWidget::onVariableActivated(int row) { if(this->BlockEmission) { return; } const QStringList d = this->Variables->itemData(row).toString().split("|"); if(d.size() != 2) return; pqVariableType type = VARIABLE_TYPE_NONE; if(d[1] == "cell") { type = VARIABLE_TYPE_CELL; } else if(d[1] == "point") { type = VARIABLE_TYPE_NODE; } const QString name = d[0]; emit variableChanged(type, name); emit this->modified(); } const QString pqDisplayColorWidget::variableData(pqVariableType type, const QString& name) { switch(type) { case VARIABLE_TYPE_NONE: return name + "|none"; case VARIABLE_TYPE_NODE: return name + "|point"; case VARIABLE_TYPE_CELL: return name + "|cell"; } return QString(); } void pqDisplayColorWidget::onVariableChanged(pqVariableType type, const QString& name) { pqPipelineRepresentation* display = this->getRepresentation(); if (display) { emit this->begin("Color Change"); switch(type) { case VARIABLE_TYPE_NONE: display->colorByArray(NULL, 0); break; case VARIABLE_TYPE_NODE: display->colorByArray(name.toAscii().data(), vtkSMDataRepresentationProxy::POINT_DATA); break; case VARIABLE_TYPE_CELL: display->colorByArray(name.toAscii().data(), vtkSMDataRepresentationProxy::CELL_DATA); break; } emit this->end(); display->renderViewEventually(); } } void pqDisplayColorWidget::updateGUI() { this->BlockEmission = true; pqPipelineRepresentation* display = this->getRepresentation(); if (display) { int index = this->AvailableArrays.indexOf(display->getColorField()); if (index < 0) { index = 0; } this->Variables->setCurrentIndex(index); } this->BlockEmission = false; } void pqDisplayColorWidget::setRepresentation(pqDataRepresentation* display) { if(display == this->Display) { return; } if (this->Display) { QObject::disconnect(this->Display, 0, this, 0); } this->VTKConnect->Disconnect(); this->Display = qobject_cast<pqPipelineRepresentation*>(display); if(this->Display) { vtkSMProxy* repr = this->Display->getProxy(); this->VTKConnect->Connect(repr->GetProperty("ColorAttributeType"), vtkCommand::ModifiedEvent, this, SLOT(reloadGUI()), NULL, 0.0, Qt::QueuedConnection); this->VTKConnect->Connect(repr->GetProperty("ColorArrayName"), vtkCommand::ModifiedEvent, this, SLOT(reloadGUI()), NULL, 0.0, Qt::QueuedConnection);
; QObject::connect(this->Display, SIGNAL(updated()), this, SLOT(reloadGUI()), Qt::QueuedConnection); } QTimer::singleShot(0, this, SLOT(reloadGUI())); } pqPipelineRepresentation* pqDisplayColorWidget::getRepresentation() const { return this->Display; } void pqDisplayColorWidget::reloadGUI() { this->BlockEmission = true; this->clear(); pqPipelineRepresentation* display = this->getRepresentation(); if (!display) { this->addVariable(VARIABLE_TYPE_NONE, "Solid Color"); this->BlockEmission = false; this->setEnabled(false); return; } this->setEnabled(true); this->AvailableArrays = display->getColorFields(); QRegExp regExpCell(" \\(cell\\)\\w*$"); QRegExp regExpPoint(" \\(point\\)\\w*$"); foreach(QString arrayName, this->AvailableArrays) { if (arrayName == "Solid Color") { this->addVariable(VARIABLE_TYPE_NONE, arrayName); } else if (regExpCell.indexIn(arrayName) != -1) { arrayName = arrayName.replace(regExpCell, ""); this->addVariable(VARIABLE_TYPE_CELL, arrayName); } else if (regExpPoint.indexIn(arrayName) != -1) { arrayName = arrayName.replace(regExpPoint, ""); this->addVariable(VARIABLE_TYPE_NODE, arrayName); } } this->BlockEmission = false; this->updateGUI(); emit this->modified(); }
this->VTKConnect->Connect( repr->GetProperty("Representation"), vtkCommand::ModifiedEvent, this, SLOT(reloadGUI()), NULL, 0.0, Qt::QueuedConnection)
call_expression
[ { "content": "extern struct obj_stats* els;\n", "file_path": "VTK/Utilities/vtkexodus2/include/exodusII_int.h", "rank": 0, "score": 239731.76580513327 }, { "content": "class VTK_PARALLEL_EXPORT vtkPCellDataToPointData : public vtkCellDataToPointData\n\n{\n\npublic:\n\n vtkTypeRevisionMacro(vtkPCellDataToPointData,vtkCellDataToPointData);\n\n void PrintSelf(ostream& os, vtkIndent indent);\n\n\n\n // Description:\n\n static vtkPCellDataToPointData *New();\n\n\n\n // Description:\n\n // To get piece invariance, this filter has to request an \n\n // extra ghost level. By default piece invariance is on.\n\n vtkSetMacro(PieceInvariant, int);\n\n vtkGetMacro(PieceInvariant, int);\n\n vtkBooleanMacro(PieceInvariant, int);\n\n\n\nprotected:\n\n vtkPCellDataToPointData();\n\n ~vtkPCellDataToPointData() {};\n\n\n", "file_path": "VTK/Parallel/vtkPCellDataToPointData.h", "rank": 1, "score": 215630.27264489816 }, { "content": " class PQCOMPONENTS_EXPORT Index: public QList<int>\n\n {\n\n public:\n\n QString getString() const;\n\n void setFromString(const QString& string);\n\n };\n\n \n\n pqMultiView(QWidget* parent = NULL);\n\n virtual ~pqMultiView();\n\n\n\n /// Must be called to initialize the first frame.\n\n void init();\n\n\n\n /// \\brief\n\n /// Resets the multi-view to its original state.\n\n /// \\param removed Used to return all the removed widgets.\n\n virtual void reset(QList<QWidget*> &removed);\n\n\n\n /// replace a widget at index with a new widget, returns the old one\n\n virtual QWidget* replaceView(Index index, QWidget* widget);\n", "file_path": "Qt/Components/pqMultiView.h", "rank": 2, "score": 199799.22642181494 }, { "content": "/*=========================================================================\n\n\n\n Program: Visualization Toolkit\n\n Module: $RCSfile: vtkPCellDataToPointData.h,v $\n\n\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n\n All rights reserved.\n\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n\n PURPOSE. See the above copyright notice for more information.\n\n\n\n=========================================================================*/\n\n// .NAME vtkPCellDataToPointData - Compute point arrays from cell arrays.\n\n// .SECTION Description\n\n// Like it super class, this filter averages the cell data around\n\n// a point to get new point data. This subclass requests a layer of\n\n// ghost cells to make the results invariant to pieces. There is a \n\n// \"PieceInvariant\" flag that lets the user change the behavior\n\n// of the filter to that of its superclass.\n\n\n\n#ifndef __vtkPCellDataToPointData_h\n\n#define __vtkPCellDataToPointData_h\n\n\n\n#include \"vtkCellDataToPointData.h\"\n\n\n", "file_path": "VTK/Parallel/vtkPCellDataToPointData.h", "rank": 3, "score": 193051.8067676245 }, { "content": " // Usual data generation method\n\n virtual int RequestData(vtkInformation* request,\n\n vtkInformationVector** inputVector,\n\n vtkInformationVector* outputVector);\n\n virtual int RequestUpdateExtent(vtkInformation*,\n\n vtkInformationVector**,\n\n vtkInformationVector*);\n\n\n\n int PieceInvariant;\n\nprivate:\n\n vtkPCellDataToPointData(const vtkPCellDataToPointData&); // Not implemented.\n\n void operator=(const vtkPCellDataToPointData&); // Not implemented.\n\n};\n\n\n\n#endif\n", "file_path": "VTK/Parallel/vtkPCellDataToPointData.h", "rank": 4, "score": 193049.09186203463 }, { "content": " const char *name; /* Pointer to name to check */\n", "file_path": "Utilities/hdf5/H5P.c", "rank": 5, "score": 189791.17887260776 }, { "content": " char name[255]; // Fieldname / keyword to designate a variable\n", "file_path": "VTK/Utilities/vtkmetaio/metaTypes.h", "rank": 6, "score": 186596.5198220695 }, { "content": "#define XdmfGetIndexValueMacro(var,type) \\\n\ntype Get##var (XdmfInt64 Index) \\\n\n { \\\n\n return ( this->var[ Index ] ); \\\n\n }\n\n\n", "file_path": "Utilities/Xdmf2/libsrc/XdmfObject.h", "rank": 7, "score": 185101.35492503823 }, { "content": " int index;\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/xpath.h", "rank": 8, "score": 183461.54625750106 }, { "content": " const xmlChar *name; /* Current parsed Node */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/parser.h", "rank": 9, "score": 183410.43838154105 }, { "content": " const xmlChar *name; /* the name of the node, or the entity */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/tree.h", "rank": 10, "score": 183402.88467619848 }, { "content": " int type;\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/tree.h", "rank": 11, "score": 183401.16408519397 }, { "content": " char *name;\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/encoding.h", "rank": 12, "score": 183395.53324569273 }, { "content": " const xmlChar *name; /* the axis name */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/xpath.h", "rank": 13, "score": 183395.53324569273 }, { "content": " FT_String* name;\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/ftmm.h", "rank": 14, "score": 183395.53324569273 }, { "content": " const xmlChar *name; /* Entity name */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/entities.h", "rank": 15, "score": 183395.53324569273 }, { "content": " FT_Size_Request_Type type;\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/freetype.h", "rank": 16, "score": 183387.14780050842 }, { "content": " xmlXPathObjectType type;\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/xpath.h", "rank": 17, "score": 183387.14780050842 }, { "content": " BDF_PropertyType type;\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/ftbdf.h", "rank": 18, "score": 183387.14780050842 }, { "content": " xmlElementType type; /* XML_ENTITY_DECL, must be second ! */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/entities.h", "rank": 19, "score": 183387.14780050842 }, { "content": " GLenum type;\n", "file_path": "Utilities/IceT/src/include/state.h", "rank": 20, "score": 183387.14780050842 }, { "content": " FT_EXPORT( FT_TrueTypeEngineType )\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/ftmodapi.h", "rank": 21, "score": 182020.48701134644 }, { "content": " FT_Long stack[T1_MAX_CHARSTRINGS_OPERANDS];\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/internal/psaux.h", "rank": 22, "score": 180622.66552287055 }, { "content": " FT_Int index;\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/internal/ftgloadr.h", "rank": 23, "score": 180612.8183837809 }, { "content": " const xmlChar *name;\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/schemasInternals.h", "rank": 24, "score": 180555.44256676827 }, { "content": " const char *name; /* The entity name */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/HTMLparser.h", "rank": 25, "score": 180547.89472397172 }, { "content": " const char *name;\n", "file_path": "Utilities/IceT/src/include/GL/ice-t.h", "rank": 26, "score": 180547.89472397172 }, { "content": " xmlSchemaTypePtr type;/* the linked type */\n", "file_path": "VTK/Utilities/vtklibxml2/include/libxml/schemasInternals.h", "rank": 27, "score": 180547.16897907894 }, { "content": " T1_FieldType type; /* type of field */\n", "file_path": "VTK/Utilities/vtkfreetype/include/freetype/internal/psaux.h", "rank": 28, "score": 180539.72063704758 }, { "content": " Display *display; /* Display containing window. */\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.5/tkInt.h", "rank": 29, "score": 177372.2672907985 }, { "content": " Display *display; /* Display containing window. */\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.3/tkInt.h", "rank": 30, "score": 177372.2672907985 }, { "content": " Display *display; /* Display containing window. */\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.2/tkInt.h", "rank": 31, "score": 177372.2672907985 }, { "content": " Display *display; /* Display containing window. */\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.4/tkInt.h", "rank": 32, "score": 177372.2672907985 }, { "content": "EXTERN void TkPrintPadAmount _ANSI_ARGS_((Tcl_Interp *interp,\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.4/tkInt.h", "rank": 33, "score": 177322.35033719186 }, { "content": "EXTERN void TkEventInit _ANSI_ARGS_((void));\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.3/tkInt.h", "rank": 34, "score": 177322.35033719186 }, { "content": "EXTERN void TclFinalizeEnvironment _ANSI_ARGS_((void));\n", "file_path": "VTK/Utilities/TclTk/internals/tk8.2/tclInt.h", "rank": 35, "score": 177322.35033719186 }, { "content": " /// Emitted when the opacity of a point has been changed.\n\n /// \\param index The index of the point.\n\n /// \\param opacity The new opacity for the point.\n\n void opacityChanged(int index, const pqChartValue &opacity);\n\n\n\nprivate:\n\n pqColorMapModelInternal *Internal; ///< Stores the points.\n\n ColorSpace Space; ///< Stores the color space.\n\n bool InModify; ///< True if in modify mode.\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Chart/pqColorMapModel.h", "rank": 36, "score": 59.523344409416126 }, { "content": " double *red, double *green, double *blue);\n\n\n\nsignals:\n\n /// Emitted when the color space changes.\n\n void colorSpaceChanged();\n\n\n\n /// Emitted when the table size changes.\n\n void tableSizeChanged();\n\n\n\n /// \\brief\n\n /// Emitted when the color for a point changes.\n\n /// \\param index The point index.\n\n /// \\param color The point's new color.\n\n void colorChanged(int index, const QColor &color);\n\n\n\n /// Emitted when all or many of the points have changed.\n\n void pointsReset();\n\n\n\n /// \\brief\n\n /// Emitted after a point has been added.\n", "file_path": "Qt/Chart/pqColorMapModel.h", "rank": 37, "score": 56.90086771799034 }, { "content": " /// \\brief\n\n /// Emitted when the color for a series has changed.\n\n /// \\param series The index of the series.\n\n /// \\param color The new color for the series.\n\n void colorChanged(int series, const QColor &color);\n\n\n\n /// \\brief\n\n /// Emitted when the style for a series has changed.\n\n /// \\param series The index of the series.\n\n /// \\param style The new line style for the series.\n\n void styleChanged(int series, Qt::PenStyle style);\n\n\n\nprotected:\n\n /// method to set default values for the status property.\n\n void setStatusDefaults(vtkSMProperty* prop);\n\n bool getXArrayDefault(vtkSMProperty* prop, QString &arrayName);\n\n\n\nprivate slots:\n\n void changeSeriesList();\n\n void markPointModified();\n", "file_path": "Qt/Core/pqLineChartRepresentation.h", "rank": 38, "score": 55.05488810420937 }, { "content": " void handleEditorAddOrDelete();\n\n void handleEditorAdd(int index);\n\n void setColors();\n\n void changeCurrentColor();\n\n\n\n void handlePointsChanged();\n\n\n\n void handleEditorCurrentChanged();\n\n void setCurrentPoint(int index);\n\n void setValueFromText();\n\n void setOpacityFromText();\n\n\n\n void setColorSpace(int index);\n\n\n\n void savePreset();\n\n void loadPreset();\n\n\n\n void setComponent(int index);\n\n\n\n void setLogScale(bool on);\n", "file_path": "Qt/Components/pqColorScaleEditor.h", "rank": 39, "score": 51.805995311824546 }, { "content": "private slots:\n\n void moveTimeout();\n\n void updateColorGradient();\n\n void handlePointsReset();\n\n void addPoint(int index);\n\n void startRemovingPoint(int index);\n\n void finishRemovingPoint(int index);\n\n void updatePointValue(int index, const pqChartValue &value);\n\n\n\nprivate:\n\n bool isInScaleRegion(int px, int py);\n\n void layoutPoints();\n\n void generateGradient();\n\n\n\nprivate:\n\n pqColorMapWidgetInternal *Internal; ///< Stores the color map data.\n\n pqColorMapModel *Model; ///< Stores the color map points\n\n QPixmap *DisplayImage; ///< Used for drawing color map.\n\n int TableSize; ///< Stores the table size.\n\n int Margin; ///< Stores the layout margin.\n\n int PointWidth; ///< Stores the size of the points.\n\n bool AddingAllowed; ///< True if points can be added.\n\n bool MovingAllowed; ///< True if points can be moved.\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Chart/pqColorMapWidget.h", "rank": 40, "score": 51.69991435495903 }, { "content": " /// \\param index The index of the new point.\n\n void pointAdded(int index);\n\n\n\n /// \\brief\n\n /// Emitted before a point is removed.\n\n /// \\param index The index of the point to be removed.\n\n void removingPoint(int index);\n\n\n\n /// \\brief\n\n /// Emitted after a point is removed.\n\n /// \\param index The index of the removed point.\n\n void pointRemoved(int index);\n\n\n\n /// \\brief\n\n /// Emitted when the value of a point has been changed.\n\n /// \\param index The index of the point.\n\n /// \\param value The new value for the point.\n\n void valueChanged(int index, const pqChartValue &value);\n\n\n\n /// \\brief\n", "file_path": "Qt/Chart/pqColorMapModel.h", "rank": 41, "score": 51.492975347813285 }, { "content": " /// Called to emit the variableChanged() signal in response to user input \n\n /// or the chooseVariable() method.\n\n void onVariableActivated(int row);\n\n\n\n /// Called when any important property on the display changes.\n\n /// This updates the selected value.\n\n void updateGUI();\n\n\n\nprivate:\n\n /// Converts a variable type and name into a packed string representation \n\n /// that can be used with a combo box.\n\n static const QString variableData(pqVariableType, const QString& name);\n\n \n\n QIcon* CellDataIcon;\n\n QIcon* PointDataIcon;\n\n QIcon* SolidColorIcon;\n\n\n\n QHBoxLayout* Layout;\n\n QComboBox* Variables;\n\n bool BlockEmission;\n\n vtkEventQtSlotConnect* VTKConnect;\n\n QPointer<pqPipelineRepresentation> Display;\n\n QList<QString> AvailableArrays;\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Components/pqDisplayColorWidget.h", "rank": 42, "score": 51.063467988513096 }, { "content": " void finishSeriesUpdate();\n\n void setAttributeType(int attr);\n\n void markAsModified();\n\n\n\nsignals:\n\n /// Emitted when the series list has changed.\n\n void seriesListChanged();\n\n\n\n /// \\brief\n\n /// Emitted when the enabled state for a series has changed.\n\n /// \\param series The index of the series.\n\n /// \\param enabled True if the series is enabled.\n\n void enabledStateChanged(int series, bool enabled);\n\n\n\n /// \\brief\n\n /// Emitted when the legend state for a series has changed.\n\n /// \\param series The index of the series.\n\n /// \\param inLegend True if the series is in the legend.\n\n void legendStateChanged(int series, bool inLegend);\n\n\n", "file_path": "Qt/Core/pqLineChartRepresentation.h", "rank": 43, "score": 50.71035832661731 }, { "content": " // return NULL. This method returns a new vtkSMProxy instance which the \n\n // caller must free after use.\n\n // This implementation converts a prop selection to a selection source.\n\n virtual vtkSMProxy* ConvertSelection(vtkSelection* input);\n\n\n\n // Description:\n\n // Returns true is opactity < 1.0\n\n virtual bool GetOrderedCompositingNeeded();\n\n\n\n // Description:\n\n // Set the scalar coloring mode\n\n void SetColorAttributeType(int type);\n\n\n\n // Description:\n\n // Set the scalar color array name. If array name is 0 or \"\" then scalar\n\n // coloring is disabled.\n\n void SetColorArrayName(const char* name);\n\n\n\n // Description:\n\n // Set the ambient coefficient. This is used only when representation type is\n", "file_path": "Servers/ServerManager/vtkSMSurfaceRepresentationProxy.h", "rank": 44, "score": 47.981080343586896 }, { "content": "\n\n\n\n // Get the internal display proxy.\n\n vtkSMPVRepresentationProxy* getRepresentationProxy() const;\n\n\n\n // Sets the default color mapping for the display.\n\n // The rules are:\n\n // If the source created a NEW point scalar array, use it.\n\n // Else if the source created a NEW cell scalar array, use it.\n\n // Else if the input color by array exists in this source, use it.\n\n // Else color by property.\n\n virtual void setDefaultPropertyValues();\n\n\n\n // Call to select the coloring array. \n\n void colorByArray(const char* arrayname, int fieldtype);\n\n\n\n /// Get the names of the arrays that a part may be colored by.\n\n /// This information may change based on the current reprentation\n\n /// of the display, eg. when showing Outline, only \"Solid Color\" is\n\n /// available; when rendering as Volume, can be colored only by \n", "file_path": "Qt/Core/pqPipelineRepresentation.h", "rank": 45, "score": 47.23004043322233 }, { "content": " // Get the name of the point or cell array with the given index in\n\n // the input.\n\n const char* GetPointArrayName(int index);\n\n const char* GetCellArrayName(int index);\n\n \n\n // Description:\n\n // Get/Set whether the point or cell array with the given name is to\n\n // be read.\n\n int GetPointArrayStatus(const char* name);\n\n int GetCellArrayStatus(const char* name);\n\n void SetPointArrayStatus(const char* name, int status); \n\n void SetCellArrayStatus(const char* name, int status); \n\n \n\n //BTX\n\n enum FileTypes\n\n {\n\n ENSIGHT_6 = 0,\n\n ENSIGHT_6_BINARY = 1,\n\n ENSIGHT_GOLD = 2,\n\n ENSIGHT_GOLD_BINARY = 3,\n", "file_path": "VTK/IO/vtkGenericEnSightReader.h", "rank": 46, "score": 47.131899283621244 }, { "content": "\n\n /// \\brief\n\n /// Emitted when new points have been inserted.\n\n /// \\param sequence The index of the modified sequence.\n\n void pointsInserted(int sequence);\n\n\n\n /// \\brief\n\n /// Emitted when points will be removed.\n\n /// \\param sequence The index of the sequence to be modified.\n\n /// \\param first The first index of the point removal.\n\n /// \\param last The last index of the point removal.\n\n void aboutToRemovePoints(int sequence, int first, int last);\n\n\n\n /// \\brief\n\n /// Emitted when points have been removed.\n\n /// \\param sequence The index of the modified sequence.\n\n void pointsRemoved(int sequence);\n\n\n\n /// \\brief\n\n /// Emitted when changes will be made to multiple sequences\n", "file_path": "Qt/Chart/pqLineChartSeries.h", "rank": 47, "score": 46.05778667547365 }, { "content": " // queried independent of the output mesh. The \\a cellType parameter\n\n // should be one of: LS_POINT, LS_BEAM, LS_SHELL, LS_THICK_SHELL,\n\n // LS_SOLID, LS_RIGID_BODY, or LS_ROAD_SURFACE\n\n int GetNumberOfCellArrays( int cellType );\n\n const char* GetCellArrayName( int cellType, int arr );\n\n virtual void SetCellArrayStatus( int cellType, int arr, int status );\n\n virtual void SetCellArrayStatus( int cellType, const char* arrName, int status );\n\n int GetCellArrayStatus( int cellType, int arr );\n\n int GetCellArrayStatus( int cellType, const char* arrName );\n\n int GetNumberOfComponentsInCellArray( int cellType, int arr );\n\n int GetNumberOfComponentsInCellArray( int cellType, const char* arrName );\n\n\n\n // Description:\n\n // These methods allow you to load only selected subsets of the cell\n\n // variables defined over the mesh.\n\n int GetNumberOfSolidArrays();\n\n const char* GetSolidArrayName(int);\n\n virtual void SetSolidArrayStatus( int arr, int status );\n\n virtual void SetSolidArrayStatus( const char* arrName, int status );\n\n int GetSolidArrayStatus( int arr );\n", "file_path": "VTK/Hybrid/vtkLSDynaReader.h", "rank": 48, "score": 45.90556233057375 }, { "content": " void setRepresentation(int type);\n\n\n\n /// Returns the type of representation currently used i.e.\n\n //SURFACE/POINTS/VOLUME etc.\n\n int getRepresentationType() const;\n\n\n\n /// Returns the opacity.\n\n double getOpacity() const;\n\nsignals:\n\n /// This is fire when any property that affects the color\n\n /// mode for the display changes.\n\n void colorChanged();\n\n\n\npublic slots:\n\n // If lookuptable is set up and is used for coloring,\n\n // then calling this method resets the table ranges to match the current \n\n // range of the selected array.\n\n void resetLookupTableScalarRange();\n\n\n\n /// If color lookuptable is set up and coloring is enabled, the this\n", "file_path": "Qt/Core/pqPipelineRepresentation.h", "rank": 49, "score": 45.90311012508839 }, { "content": " virtual QVariant headerData(int section, Qt::Orientation orient,\n\n int role=Qt::DisplayRole) const;\n\n //@}\n\n\n\n void addBuiltinColorMap(const pqColorMapModel &colorMap,\n\n const QString &name);\n\n void addColorMap(const pqColorMapModel &colorMap, const QString &name);\n\n void normalizeColorMap(int index);\n\n void removeColorMap(int index);\n\n const pqColorMapModel *getColorMap(int index) const;\n\n bool isModified() const {return this->Modified;}\n\n void setModified(bool modified) {this->Modified = modified;}\n\n\n\nprivate:\n\n pqColorPresetModelInternal *Internal;\n\n bool Modified;\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Components/pqColorPresetModel.h", "rank": 50, "score": 45.33707890551942 }, { "content": "\n\n // Description:\n\n // Return the name of the specified query field.\n\n const char* GetFieldName(int i);\n\n\n\n // Description:\n\n // Return the type of the field, using the constants defined in vtkType.h.\n\n int GetFieldType(int i);\n\n\n\n // Description:\n\n // Advance row, return false if past end.\n\n bool NextRow();\n\n\n\n // Description:\n\n // Return true if there is an error on the current query.\n\n bool HasError();\n\n\n\n // Description:\n\n // Begin, abort (roll back), or commit a transaction.\n\n bool BeginTransaction();\n", "file_path": "VTK/IO/vtkSQLiteQuery.h", "rank": 51, "score": 45.136435590328155 }, { "content": " // Specify a group of cell types.\n\n void SetCellTypes(int ncells, vtkUnsignedCharArray *cellTypes, vtkIntArray *cellLocations);\n\n\n\n // Description:\n\n // Return the location of the cell in the associated vtkCellArray.\n\n int GetCellLocation(int cellId) { return this->LocationArray->GetValue(cellId);};\n\n\n\n // Description:\n\n // Delete cell by setting to NULL cell type.\n\n void DeleteCell(int cellId) { this->TypeArray->SetValue(cellId, VTK_EMPTY_CELL);};\n\n\n\n // Description:\n\n // Return the number of types in the list.\n\n int GetNumberOfTypes() { return (this->MaxId + 1);};\n\n\n\n // Description:\n\n // Return 1 if type specified is contained in list; 0 otherwise.\n\n int IsType(unsigned char type);\n\n\n\n // Description:\n", "file_path": "VTK/Filtering/vtkCellTypes.h", "rank": 52, "score": 44.95352410529424 }, { "content": "\n\n // Description:\n\n // Return the name of the specified query field.\n\n virtual const char* GetFieldName(int i) = 0;\n\n\n\n // Description:\n\n // Return the type of the field, using the constants defined in vtkType.h.\n\n virtual int GetFieldType(int i) = 0;\n\n\n\n // Description:\n\n // Return the index of the specified query field.\n\n // Uses GetNumberOfFields() and GetFieldName()\n\n // to match field name.\n\n int GetFieldIndex(char* name);\n\n\n\n // Description:\n\n // Advance row, return false if past end.\n\n virtual bool NextRow() = 0;\n\n\n\n // Description:\n", "file_path": "VTK/IO/vtkSQLQuery.h", "rank": 53, "score": 44.85761936891325 }, { "content": " int getAttributeType() const;\n\n\n\n int getNumberOfSeries() const;\n\n\n\n int getSeriesIndex(const QString &name) const;\n\n\n\n bool isSeriesEnabled(int series) const;\n\n void setSeriesEnabled(int series, bool enabled);\n\n\n\n void getSeriesName(int series, QString &name) const;\n\n void setSeriesName(int series, const QString &name);\n\n\n\n bool isSeriesInLegend(int series) const;\n\n void setSeriesInLegend(int series, bool inLegend);\n\n\n\n void getSeriesLabel(int series, QString &label) const;\n\n void setSeriesLabel(int series, const QString &label);\n\n\n\n void getSeriesColor(int series, QColor &color) const;\n\n void setSeriesColor(int series, const QColor &color);\n", "file_path": "Qt/Core/pqLineChartRepresentation.h", "rank": 54, "score": 44.83976127425002 }, { "content": "\n\n vtkIdType *PointMap;\n\n vtkIdType GetOutputPointId(vtkIdType inPtId, vtkDataSet *input, \n\n vtkPoints *outPts, vtkPointData *outPD);\n\n \n\n vtkIdType NumberOfNewCells;\n\n \n\n // Better memory allocation for faces (hash)\n\n void InitFastGeomQuadAllocation(int numberOfCells);\n\n vtkFastGeomQuad* NewFastGeomQuad();\n\n void DeleteAllFastGeomQuads();\n\n // -----\n\n int FastGeomQuadArrayLength;\n\n int NumberOfFastGeomQuadArrays;\n\n vtkFastGeomQuad** FastGeomQuadArrays;\n\n // These indexes allow us to find the next available face.\n\n int NextArrayIndex;\n\n int NextQuadIndex;\n\n\n\n int PieceInvariant;\n", "file_path": "VTK/Graphics/vtkDataSetSurfaceFilter.h", "rank": 55, "score": 44.809136004251286 }, { "content": " const char* GetCellArrayName(int index);\n\n int GetPointArrayStatus(const char* name);\n\n int GetCellArrayStatus(const char* name);\n\n void SetPointArrayStatus(const char* name, int status); \n\n void SetCellArrayStatus(const char* name, int status);\n\n\n\n void DisableAllCellArrays();\n\n void EnableAllCellArrays();\n\n void DisableAllPointArrays();\n\n void EnableAllPointArrays();\n\n\n\n // get min and max value for the index-th value of a cell component\n\n // index varies from 0 to (veclen - 1)\n\n void GetCellDataRange(int cellComp, int index, float *min, float *max);\n\n\n\n // get min and max value for the index-th value of a node component\n\n // index varies from 0 to (veclen - 1)\n\n void GetNodeDataRange(int nodeComp, int index, float *min, float *max);\n\n\n\nprotected:\n", "file_path": "VTK/IO/vtkAVSucdReader.h", "rank": 56, "score": 44.795999069108234 }, { "content": "\n\n int PassThroughCellIds;\n\n void RecordOrigCellId(vtkIdType newIndex, vtkIdType origId);\n\n vtkIdTypeArray *OriginalCellIds;\n\n\n\n int PassThroughPointIds;\n\n void RecordOrigPointId(vtkIdType newIndex, vtkIdType origId);\n\n vtkIdTypeArray *OriginalPointIds;\n\n\n\nprivate:\n\n vtkDataSetSurfaceFilter(const vtkDataSetSurfaceFilter&); // Not implemented.\n\n void operator=(const vtkDataSetSurfaceFilter&); // Not implemented.\n\n};\n\n\n\n#endif\n", "file_path": "VTK/Graphics/vtkDataSetSurfaceFilter.h", "rank": 57, "score": 44.68671122551152 }, { "content": " QStyleOptionViewItem getViewOptions() const;\n\n\n\nprivate slots:\n\n /// \\name Header Signal Handlers\n\n //@{\n\n void handleSectionResized(int index, int oldSize, int newSize);\n\n void handleSectionMoved(int index, int oldVisual, int newVisual);\n\n //@}\n\n\n\n /// \\name Selection Signal Handlers\n\n //@{\n\n void changeCurrent(const QModelIndex &current, const QModelIndex &previous);\n\n void changeCurrentRow(const QModelIndex &current,\n\n const QModelIndex &previous);\n\n void changeCurrentColumn(const QModelIndex &current,\n\n const QModelIndex &previous);\n\n void changeSelection(const QItemSelection &selected,\n\n const QItemSelection &deselected);\n\n //@}\n\n\n", "file_path": "Qt/Widgets/pqFlatTreeView.h", "rank": 58, "score": 44.33920015785353 }, { "content": " int RequestInformation(vtkInformation *, \n\n vtkInformationVector **, vtkInformationVector *);\n\n int RequestData(vtkInformation *, vtkInformationVector **, \n\n vtkInformationVector *);\n\n vtkDataArraySelection* CellDataArraySelection;\n\n char * FileName;\n\n int NumberOfCells;\n\n int NumberOfCellArrays;\n\n bool OpenCaseFile(const char *filename);\n\n bool OpenDataFile(const char *filename);\n\n int GetCaseChunk ();\n\n void GetNumberOfCellZones();\n\n int GetCaseIndex();\n\n void LoadVariableNames();\n\n int GetDataIndex();\n\n int GetDataChunk();\n\n\n\n void ParseCaseFile();\n\n int GetDimension();\n\n void GetLittleEndianFlag();\n", "file_path": "VTK/IO/vtkFLUENTReader.h", "rank": 59, "score": 44.29067313678401 }, { "content": " bool _readElements=true,\n\n void * _buffer=NULL);\n\n\n\n virtual bool Write(const char *_headName=NULL,\n\n const char *_dataName=NULL,\n\n bool _writeElements=true,\n\n const void * _constElementData=NULL,\n\n bool _append=false);\n\n\n\n virtual bool WriteStream(METAIO_STREAM::ofstream * _stream,\n\n bool _writeElements=true,\n\n const void * _constElementData=NULL);\n\n\n\n virtual bool Append(const char *_headName=NULL);\n\n\n\n ////\n\n //\n\n // PROTECTED\n\n //\n\n ////\n", "file_path": "VTK/Utilities/vtkmetaio/metaImage.h", "rank": 60, "score": 44.193947377104244 }, { "content": " /// Emitted when the text for an entry has changed.\n\n /// \\param index The index of the entry that changed.\n\n void textChanged(int index);\n\n\n\nprivate:\n\n pqChartLegendModelInternal *Internal; ///< Stores the legend items.\n\n bool InModify; ///< True when blocking signals.\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Chart/pqChartLegendModel.h", "rank": 61, "score": 43.96330641428952 }, { "content": " // Description: \n\n // Get the number of point or cell arrays available in the input.\n\n int GetNumberOfPointArrays();\n\n int GetNumberOfCellArrays();\n\n \n\n // Description:\n\n // Get the name of the point or cell array with the given index in\n\n // the input.\n\n const char* GetPointArrayName(int index);\n\n const char* GetCellArrayName(int index);\n\n\n\n // Description:\n\n // Get/Set whether the point or cell array with the given name is to\n\n // be read.\n\n int GetPointArrayStatus(const char* name);\n\n int GetCellArrayStatus(const char* name);\n\n void SetPointArrayStatus(const char* name, int status); \n\n void SetCellArrayStatus(const char* name, int status); \n\n\n\n // Description:\n", "file_path": "Utilities/Xdmf2/vtk/vtkXdmfReader.h", "rank": 62, "score": 43.88610343247406 }, { "content": "\n\n int getColorSpaceAsInt() const;\n\n void setColorSpaceFromInt(int space);\n\n\n\n int getNumberOfPoints() const;\n\n void addPoint(const pqChartValue &value, const QColor &color);\n\n void addPoint(const pqChartValue &value, const QColor &color,\n\n const pqChartValue &opacity);\n\n void removePoint(int index);\n\n void removeAllPoints();\n\n void startModifyingData();\n\n bool isDataBeingModified() const {return this->InModify;}\n\n void finishModifyingData();\n\n\n\n void getPointValue(int index, pqChartValue &value) const;\n\n void setPointValue(int index, const pqChartValue &value);\n\n void getPointColor(int index, QColor &color) const;\n\n void setPointColor(int index, const QColor &color);\n\n void getPointOpacity(int index, pqChartValue &opacity) const;\n\n void setPointOpacity(int index, const pqChartValue &opacity);\n", "file_path": "Qt/Chart/pqColorMapModel.h", "rank": 63, "score": 43.870384540273285 }, { "content": " // operator is (typically) used when links from points to cells have not been \n\n // built (i.e., BuildLinks() has not been executed). Use the operator \n\n // ReplaceLinkedCell() to replace a cell when cell structure has been built.\n\n void ReplaceCell(vtkIdType cellId, int npts, vtkIdType *pts);\n\n\n\n // Description:\n\n // Replace a point in the cell connectivity list with a different point.\n\n void ReplaceCellPoint(vtkIdType cellId, vtkIdType oldPtId,\n\n vtkIdType newPtId);\n\n \n\n // Description:\n\n // Reverse the order of point ids defining the cell.\n\n void ReverseCell(vtkIdType cellId);\n\n\n\n // Description:\n\n // Mark a point/cell as deleted from this vtkPolyData.\n\n void DeletePoint(vtkIdType ptId);\n\n void DeleteCell(vtkIdType cellId);\n\n\n\n // Description:\n", "file_path": "VTK/Filtering/vtkPolyData.h", "rank": 64, "score": 43.78202672363577 }, { "content": " //\n\n //\n\n void ClearUserFields();\n\n\n\n void * GetUserField(const char* _name);\n\n\n\n bool AddUserField(const char* _fieldName,\n\n MET_ValueEnumType _type,\n\n int _length=0,\n\n bool _required=true,\n\n int _dependsOn=-1);\n\n\n\n template <class TType>\n\n bool AddUserField(const char* _fieldName,\n\n MET_ValueEnumType _type,\n\n int _length,\n\n TType *_v,\n\n bool _required=true,\n\n int _dependsOn=-1 )\n\n {\n", "file_path": "VTK/Utilities/vtkmetaio/metaForm.h", "rank": 65, "score": 43.094808236604116 }, { "content": " /// Emitted when the data for a series has changed drastically.\n\n /// \\param series The modified series.\n\n void seriesReset(const pqLineChartSeries *series);\n\n\n\n /// \\brief\n\n /// Emitted when new points will be inserted in a series.\n\n /// \\param series The series to be modified.\n\n /// \\param sequence The index of the sequence to be modified.\n\n /// \\param first The first index of the point insertion.\n\n /// \\param last The last index of the point insertion.\n\n void aboutToInsertPoints(const pqLineChartSeries *series, int sequence,\n\n int first, int last);\n\n\n\n /// \\brief\n\n /// Emitted when new points have been inserted in a series.\n\n /// \\param series The modified series.\n\n /// \\param sequence The index of the modified sequence.\n\n void pointsInserted(const pqLineChartSeries *series, int sequence);\n\n\n\n /// \\brief\n", "file_path": "Qt/Chart/pqLineChartModel.h", "rank": 66, "score": 42.93224631061538 }, { "content": " // Set whether the all point or cell arrays are to\n\n // be read.\n\n void EnableAllArrays();\n\n void DisableAllArrays();\n\n\n\n // PARAMETERS ///////////////////////////////////////////////////////////////\n\n \n\n // Description:\n\n // Get the number of Parameters\n\n int GetNumberOfParameters();\n\n\n\n // Description:\n\n // Get Parameter Type\n\n int GetParameterType(int index);\n\n int GetParameterType(const char *Name);\n\n const char *GetParameterTypeAsString(int index);\n\n const char *GetParameterTypeAsString(const char *Name);\n\n\n\n // Description:\n\n // Get start, stride, count\n", "file_path": "Utilities/Xdmf2/vtk/vtkXdmfReader.h", "rank": 67, "score": 42.8821298122567 }, { "content": "\n\nprivate slots:\n\n void pickTitleFont();\n\n void convertLegendLocation(int index);\n\n void convertLegendFlow(int index);\n\n void setAxisShowing(bool axisShowing);\n\n void setAxisGridShowing(bool gridShowing);\n\n void setGridColorType(int index);\n\n void setAxisColor(const QColor &color);\n\n void setGridColor(const QColor &color);\n\n void setAxisLabelsShowing(bool labelsShowing);\n\n void pickAxisLabelFont();\n\n void setLabelColor(const QColor &color);\n\n void setLabelNotation(int index);\n\n void setLabelPrecision(int precision);\n\n void setUsingLogScale(bool usingLogScale);\n\n void changeLayoutPage(bool checked);\n\n void setAxisMinimum(const QString &text);\n\n void setAxisMaximum(const QString &text);\n\n void addAxisLabel();\n", "file_path": "Qt/Components/pqChartOptionsEditor.h", "rank": 68, "score": 42.75275369880397 }, { "content": " /// \\param pen The pen to draw the line with.\n\n /// \\param marker The point marker to use.\n\n /// \\param pointPen The pen to draw the point with.\n\n /// \\return\n\n /// An icon for a line chart series.\n\n static QPixmap generateLineIcon(const QPen &pen, pqPointMarker *marker=0,\n\n const QPen *pointPen=0);\n\n\n\n /// \\brief\n\n /// Generates an icon for a solid color.\n\n /// \\param color The color to use.\n\n /// \\return\n\n /// An icon for a solid color.\n\n static QPixmap generateColorIcon(const QColor &color);\n\n\n\nsignals:\n\n /// \\brief\n\n /// Emitted when a new entry is added.\n\n /// \\param index Where the entry was added.\n\n void entryInserted(int index);\n", "file_path": "Qt/Chart/pqChartLegendModel.h", "rank": 69, "score": 42.57150720059087 }, { "content": " /// point data.\n\n QList<QString> getColorFields();\n\n\n\n /// get the data range for a particular component. if component == -1,\n\n /// range for the vector magnitude is returned.\n\n QPair<double, double> getColorFieldRange(const QString& array, int component);\n\n\n\n /// Returns the range for the currently selected color field i.e.\n\n /// the range for the array component (or magnitude) of the array by which\n\n /// this display is being colored, if at all.\n\n QPair<double, double> getColorFieldRange();\n\n\n\n /// set the array to color the part by\n\n void setColorField(const QString& field);\n\n\n\n /// get the array the part is colored by\n\n /// if raw is true, it will not add (point) or (cell) but simply\n\n /// return the array name\n\n QString getColorField(bool raw=false);\n\n\n", "file_path": "Qt/Core/pqPipelineRepresentation.h", "rank": 70, "score": 42.27863535341157 }, { "content": "\n\n /// \\name Drawing Options\n\n //@{\n\n int getIconSize() const;\n\n void setIconSize(int iconSize);\n\n //@}\n\n\n\n /// \\name Index Location Methods\n\n //@{\n\n bool isIndexHidden(const QModelIndex &index) const;\n\n QModelIndex getIndexVisibleAt(const QPoint &point) const;\n\n QModelIndex getIndexCellAt(const QPoint &point) const;\n\n void getSelectionIn(const QRect &rect, QItemSelection &items) const;\n\n //@}\n\n\n\n /// \\name Index Navigation Methods\n\n //@{\n\n bool isIndexExpanded(const QModelIndex &index) const;\n\n QModelIndex getNextVisibleIndex(const QModelIndex &index,\n\n const QModelIndex &root=QModelIndex()) const;\n", "file_path": "Qt/Widgets/pqFlatTreeView.h", "rank": 71, "score": 42.116321756880126 }, { "content": " /// Updates the color for the given series index.\n\n /// \\param index The index of the line series.\n\n /// \\param color The new series color.\n\n void updateItemColor(int index, const QColor &color);\n\n\n\n /// \\brief\n\n /// Updates the style for the given series index.\n\n /// \\param index The index of the line series.\n\n /// \\param lineStyle The new series style.\n\n void updateItemStyle(int index, Qt::PenStyle lineStyle);\n\n\n\nprivate:\n\n pqXYPlotDisplayProxyEditor(const pqXYPlotDisplayProxyEditor&); // Not implemented.\n\n void operator=(const pqXYPlotDisplayProxyEditor&); // Not implemented.\n\n\n\n /// Set the display whose properties this editor is editing.\n\n /// This call will raise an error is the display is not\n\n /// a XYPlotDisplay2 proxy.\n\n void setDisplay(pqRepresentation* display);\n\n\n\n void switchXAxisProperties();\n\n void reloadXComponentList(const QString &arrayName);\n\n\n\n Qt::CheckState getEnabledState() const;\n\n\n", "file_path": "Qt/Components/pqXYPlotDisplayProxyEditor.h", "rank": 72, "score": 42.044923523403256 }, { "content": " void M_SetupReadFields(void);\n\n\n\n void M_SetupWriteFields(void);\n\n\n\n bool M_Read(void);\n\n\n\n bool M_Write(void);\n\n\n\n int m_ParentPoint; // \"ParentPoint = \" -1\n\n\n\n bool m_Root; // \"Root = \" false\n\n\n\n bool m_Artery; // \"Artery = \" true\n\n\n\n int m_NPoints; // \"NPoints = \" 0\n\n\n\n char m_PointDim[255]; // \"PointDim = \" \"x y z r\"\n\n\n\n PointListType m_PointList;\n\n MET_ValueEnumType m_ElementType;\n\n };\n\n\n\n#if (METAIO_USE_NAMESPACE)\n\n};\n\n#endif\n\n\n\n#endif\n", "file_path": "VTK/Utilities/vtkmetaio/metaVesselTube.h", "rank": 73, "score": 41.77464333910277 }, { "content": " \n\n \n\n // Descriptions:\n\n // By default arrays are not loaded. These methods allow the user to select\n\n // which arrays they want to load. You can get information about the arrays\n\n // by first caling UpdateInformation, and using GetPointArrayName ...\n\n // (Developer Note) This meta data is all accessed through vtkExodusMetadata\n\n int GetNumberOfPointArrays();\n\n const char *GetPointArrayName(int index);\n\n int GetPointArrayID( const char *name );\n\n int GetPointArrayNumberOfComponents(int index);\n\n void SetPointArrayStatus(int index, int flag);\n\n void SetPointArrayStatus(const char*, int flag);\n\n int GetPointArrayStatus(int index);\n\n int GetPointArrayStatus(const char*);\n\n\n\n int GetNumberOfCellArrays();\n\n const char *GetCellArrayName(int index);\n\n int GetCellArrayID( const char *name );\n\n int GetCellArrayNumberOfComponents(int index);\n", "file_path": "VTK/Hybrid/vtkExodusReader.h", "rank": 74, "score": 41.55839068387549 }, { "content": " ~vtkExodusReader();\n\n\n\n void NewExodusModel();\n\n\n\n void ReadGeometry(int exoid, vtkUnstructuredGrid* output);\n\n void ReadCells(int exoid, vtkUnstructuredGrid* output);\n\n void ReadPoints(int exoid, vtkUnstructuredGrid* output);\n\n void ReadArrays(int exoid, vtkUnstructuredGrid* output);\n\n void ReadNodeAndSideSets(int exoid, vtkUnstructuredGrid* output);\n\n vtkDataArray *ReadPointArray(int exoid, int varIndex);\n\n vtkDataArray *ReadPointVector(int handle, int varIndex, int dim);\n\n vtkDataArray *ReadCellArray(int exoid, int varIndex);\n\n vtkDataArray *ReadCellVector(int handle, int varIndex, int dim);\n\n void ReadNodeSetMetadata();\n\n void ReadSideSetMetadata();\n\n\n\n // helper for finding IDs\n\n static int GetIDHelper ( const char *arrayName, vtkDataSet *data, int localID,\n\n int searchType );\n\n static int GetGlobalID( const char *arrayName, vtkDataSet *data, int localID, \n", "file_path": "VTK/Hybrid/vtkExodusReader.h", "rank": 75, "score": 41.52908396678139 }, { "content": "}\n\n\n\ninline int vtkLSDynaReader::GetNumberOfComponentsInPointArray( const char* arrName )\n\n{\n\n for ( int a=0; a<this->GetNumberOfPointArrays(); ++a )\n\n {\n\n if ( strcmp( arrName, this->GetPointArrayName( a ) ) == 0 )\n\n {\n\n return this->GetNumberOfComponentsInPointArray( a );\n\n }\n\n }\n\n //vtkWarningMacro( \"Point array \\\"\" << arrName << \"\\\" does not exist\" );\n\n return 0;\n\n}\n\n\n\ninline void vtkLSDynaReader::SetCellArrayStatus( int cellType, const char* arrName, int status )\n\n{\n\n for ( int a=0; a<this->GetNumberOfCellArrays( cellType ); ++a )\n\n {\n\n if ( strcmp( arrName, this->GetCellArrayName( cellType, a ) ) == 0 )\n", "file_path": "VTK/Hybrid/vtkLSDynaReader.h", "rank": 76, "score": 41.5218172138343 }, { "content": "\n\ninline int vtkLSDynaReader::GetNumberOfComponentsInCellArray( int cellType, const char* arrName )\n\n{\n\n for ( int a=0; a<this->GetNumberOfCellArrays( cellType ); ++a )\n\n {\n\n if ( strcmp( arrName, this->GetCellArrayName( cellType, a ) ) == 0 )\n\n {\n\n return this->GetNumberOfComponentsInCellArray( cellType, a );\n\n }\n\n }\n\n //vtkWarningMacro( \"Cell array \\\"\" << arrName << \"\\\" does not exist\" );\n\n return 0;\n\n}\n\n\n\ninline void vtkLSDynaReader::SetSolidArrayStatus( const char* arrName, int status )\n\n{\n\n for ( int a=0; a<this->GetNumberOfSolidArrays(); ++a )\n\n {\n\n if ( strcmp( arrName, this->GetSolidArrayName(a) ) == 0 )\n\n {\n", "file_path": "VTK/Hybrid/vtkLSDynaReader.h", "rank": 77, "score": 41.52053143384539 }, { "content": " static vtkInformation *SetActiveAttribute(vtkInformation *info,\n\n int fieldAssociation, const char *attributeName, int attributeType);\n\n\n\n // Description:\n\n // Set the name, array type, number of components, and number of tuples\n\n // within the passed information object for the active attribute of type\n\n // attributeType (in specified association, FIELD_ASSOCIATION_POINTS or\n\n // FIELD_ASSOCIATION_CELLS). If there is not an active attribute of the\n\n // specified type, an entry in the information object is created. If\n\n // arrayType, numComponents, or numTuples equal to -1, or name=NULL the \n\n // value is not changed.\n\n static void SetActiveAttributeInfo(vtkInformation *info, \n\n int fieldAssociation, int attributeType, const char *name, int arrayType,\n\n int numComponents, int numTuples);\n\n\n\n // Description:\n\n // Convenience version of previous method for use (primarily) by the Imaging\n\n // filters. If arrayType or numComponents == -1, the value is not changed.\n\n static void SetPointDataActiveScalarInfo(vtkInformation *info,\n\n int arrayType, int numComponents);\n", "file_path": "VTK/Filtering/vtkDataObject.h", "rank": 78, "score": 41.47164088027655 }, { "content": " ///\n\n /// \\param index The model index.\n\n /// \\return\n\n /// The flags for the given model index.\n\n virtual Qt::ItemFlags flags(const QModelIndex &index) const;\n\n //@}\n\n\n\n int getTableSize() const {return this->rowCount();}\n\n void setTableSize(int tableSize);\n\n\n\n void getColor(int index, QColor &color) const;\n\n void getColor(const QModelIndex &index, QColor &color) const;\n\n void setColor(int index, const QColor &color);\n\n void setColor(const QModelIndex &index, const QColor &color);\n\n\n\n void buildGradient(const QModelIndex &first, const QModelIndex &last);\n\n\n\nsignals:\n\n void colorChanged(int index, const QColor &color);\n\n void colorRangeChanged(int first, int last);\n\n\n\nprivate:\n\n pqColorTableModelInternal *Internal; ///< Stores the list of colors.\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Widgets/pqColorTableModel.h", "rank": 79, "score": 41.43755723040076 }, { "content": " int **RegionList; // indexed by process ID\n\n\n\n vtkIdType **CellCountList; // indexed by region ID\n\n\n\n double *CellDataMin; // global range for data arrays\n\n double *CellDataMax;\n\n double *PointDataMin;\n\n double *PointDataMax;\n\n char **CellDataName;\n\n char **PointDataName;\n\n int NumCellArrays;\n\n int NumPointArrays; \n\n\n\n // distribution of indices for select operation\n\n\n\n int BuildGlobalIndexLists(vtkIdType ncells);\n\n\n\n vtkIdType *StartVal;\n\n vtkIdType *EndVal;\n\n vtkIdType *NumCells;\n", "file_path": "VTK/Parallel/vtkPKdTree.h", "rank": 80, "score": 41.24179908464714 }, { "content": " bool m_ElementByteOrderMSB;\n\n void M_Destroy(void);\n\n void M_SetupReadFields(void);\n\n void M_SetupWriteFields(void);\n\n bool M_Read(void);\n\n bool M_Write(void);\n\n\n\n int m_NControlPoints;\n\n int m_NInterpolatedPoints;\n\n char m_ControlPointDim[255];\n\n char m_InterpolatedPointDim[255];\n\n bool m_Closed;\n\n MET_InterpolationEnumType m_InterpolationType;\n\n ControlPointListType m_ControlPointsList;\n\n InterpolatedPointListType m_InterpolatedPointsList;\n\n\n\n int m_DisplayOrientation;\n\n long m_AttachedToSlice;\n\n\n\n};\n\n\n\n#if (METAIO_USE_NAMESPACE)\n\n};\n\n#endif\n\n\n\n\n\n#endif\n", "file_path": "VTK/Utilities/vtkmetaio/metaContour.h", "rank": 81, "score": 41.077118562271906 }, { "content": " void *_elementData=NULL,\n\n bool _allocateElementData=false,\n\n bool _autoFreeElementData=true);\n\n\n\n bool AllocateElementData(bool _autoFreeElementData=true);\n\n\n\n int Length(void) const;\n\n void Length(int _length);\n\n\n\n int NDims(void) const;\n\n void NDims(int _length);\n\n\n\n MET_ValueEnumType ElementType(void) const;\n\n void ElementType(MET_ValueEnumType _elementType);\n\n\n\n int ElementNumberOfChannels(void) const;\n\n void ElementNumberOfChannels(int _elementNumberOfChannels);\n\n\n\n //\n\n //\n", "file_path": "VTK/Utilities/vtkmetaio/metaArray.h", "rank": 82, "score": 41.05917711289768 }, { "content": " // data. These methods are similar to those for defining points, except\n\n // that no normalization of the data is possible. Basically, you need to\n\n // define an array of cell types (an integer value per cell), and another\n\n // array consisting (for each cell) of a number of points per cell, and\n\n // then the cell connectivity. (This is the vtk file format described in \n\n // in the textbook or User's Guide.)\n\n void SetCellTypeComponent(char *arrayName, int arrayComp,\n\n int min, int max);\n\n void SetCellTypeComponent(char *arrayName, int arrayComp)\n\n {this->SetCellTypeComponent(arrayName, arrayComp, -1, -1);};\n\n const char *GetCellTypeComponentArrayName();\n\n int GetCellTypeComponentArrayComponent();\n\n int GetCellTypeComponentMinRange();\n\n int GetCellTypeComponentMaxRange();\n\n void SetCellConnectivityComponent(char *arrayName, int arrayComp,\n\n int min, int max);\n\n void SetCellConnectivityComponent(char *arrayName, int arrayComp)\n\n {this->SetCellConnectivityComponent(arrayName, arrayComp, -1, -1);};\n\n const char *GetCellConnectivityComponentArrayName();\n\n int GetCellConnectivityComponentArrayComponent();\n", "file_path": "VTK/Graphics/vtkDataObjectToDataSetFilter.h", "rank": 83, "score": 41.023097509741255 }, { "content": "static int\n\nnsPush(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URL)\n\n{\n\n if (ctxt->options & XML_PARSE_NSCLEAN) {\n\n int i;\n\n for (i = 0;i < ctxt->nsNr;i += 2) {\n\n if (ctxt->nsTab[i] == prefix) {\n\n /* in scope */\n\n if (ctxt->nsTab[i + 1] == URL)\n\n return(-2);\n\n /* out of scope keep it */\n\n break;\n\n }\n\n }\n\n }\n\n if ((ctxt->nsMax == 0) || (ctxt->nsTab == NULL)) {\n\n ctxt->nsMax = 10;\n\n ctxt->nsNr = 0;\n\n ctxt->nsTab = (const xmlChar **)\n\n xmlMalloc(ctxt->nsMax * sizeof(xmlChar *));\n\n if (ctxt->nsTab == NULL) {\n\n xmlErrMemory(ctxt, NULL);\n\n ctxt->nsMax = 0;\n\n return (-1);\n\n }\n\n } else if (ctxt->nsNr >= ctxt->nsMax) {\n\n ctxt->nsMax *= 2;\n\n ctxt->nsTab = (const xmlChar **)\n\n xmlRealloc((char *) ctxt->nsTab,\n\n ctxt->nsMax * sizeof(ctxt->nsTab[0]));\n\n if (ctxt->nsTab == NULL) {\n\n xmlErrMemory(ctxt, NULL);\n\n ctxt->nsMax /= 2;\n\n return (-1);\n\n }\n\n }\n\n ctxt->nsTab[ctxt->nsNr++] = prefix;\n\n ctxt->nsTab[ctxt->nsNr++] = URL;\n\n return (ctxt->nsNr);\n", "file_path": "VTK/Utilities/vtklibxml2/parser.c", "rank": 84, "score": 40.917438931288316 }, { "content": " bool _readElements=true,\n\n void * _elementDataBuffer=NULL,\n\n bool _autoFreeElementData=false);\n\n\n\n virtual bool CanReadStream(METAIO_STREAM::ifstream * _stream) const;\n\n\n\n virtual bool ReadStream(METAIO_STREAM::ifstream * _stream,\n\n bool _readElements=true,\n\n void * _elementDataBuffer=NULL,\n\n bool _autoFreeElementData=false);\n\n\n\n virtual bool Write(const char *_headName=NULL,\n\n const char *_dataName=NULL,\n\n bool _writeElements=true, \n\n const void * _constElementData=NULL);\n\n\n\n virtual bool WriteStream(METAIO_STREAM::ofstream * _stream,\n\n bool _writeElements=true, \n\n const void * _constElementData=NULL);\n\n\n", "file_path": "VTK/Utilities/vtkmetaio/metaArray.h", "rank": 85, "score": 40.85605205075358 }, { "content": " /// \\param first The first index of the modified points.\n\n /// \\param last The last index of the modified points.\n\n void errorBoundsChanged(int sequence, int first, int last);\n\n\n\n /// \\brief\n\n /// Emitted when the error bar width for a sequence has changed.\n\n /// \\param sequence The index of the modified sequence.\n\n void errorWidthChanged(int sequence);\n\n\n\nprotected:\n\n /// Emits the series reset signal.\n\n void resetSeries();\n\n\n\n /// \\brief\n\n /// Called to begin the point insertion process.\n\n ///\n\n /// This method must be called before inserting the points into the\n\n /// sequence. After the points have been inserted, the\n\n /// \\c endInsertPoints method must be called. Each begin must have\n\n /// a matching end called.\n", "file_path": "Qt/Chart/pqLineChartSeries.h", "rank": 86, "score": 40.794097370121506 }, { "content": " //@}\n\n\n\n /// \\name Axis Label Changes\n\n //@{\n\n void showAxisLabelsChanged(pqChartAxis::AxisLocation location,\n\n bool labelsShowing);\n\n void axisLabelFontChanged(pqChartAxis::AxisLocation location,\n\n const QFont &newFont);\n\n void axisLabelColorChanged(pqChartAxis::AxisLocation location,\n\n const QColor &color);\n\n void axisLabelNotationChanged(pqChartAxis::AxisLocation location,\n\n pqChartValue::NotationType notation);\n\n void axisLabelPrecisionChanged(pqChartAxis::AxisLocation location,\n\n int precision);\n\n //@}\n\n\n\n /// \\name Axis Layout Changes\n\n //@{\n\n void axisScaleChanged(pqChartAxis::AxisLocation location, bool useLogScale);\n\n void axisBehaviorChanged(pqChartAxis::AxisLocation location,\n", "file_path": "Qt/Components/pqChartOptionsEditor.h", "rank": 87, "score": 40.77532265046583 }, { "content": " void finishSeriesRemoval(int first, int last);\n\n\n\n /// \\brief\n\n /// Changes the series painting order.\n\n /// \\param current The current index of the moving series.\n\n /// \\param index The index to move the series to.\n\n void handleSeriesMoved(int current, int index);\n\n\n\n /// \\brief\n\n /// Updates the series layout after a major change.\n\n /// \\param series The series that changed.\n\n void handleSeriesReset(const pqLineChartSeries *series);\n\n\n\n /// \\brief\n\n /// Prepares the chart for a series point insertion.\n\n /// \\param series The affected series.\n\n /// \\param sequence The index of the point sequence.\n\n /// \\param first The first index of the new points.\n\n /// \\param last The last index of the new points.\n\n void startPointInsertion(const pqLineChartSeries *series, int sequence,\n", "file_path": "Qt/Chart/pqLineChart.h", "rank": 88, "score": 40.65659204616836 }, { "content": " /// \\param series The modified series.\n\n /// \\param sequence The index of the modified sequence.\n\n void errorWidthChanged(const pqLineChartSeries *series, int sequence);\n\n\n\n /// Emitted when the line chart range in x and/or y changes.\n\n void chartRangeChanged();\n\n\n\nprivate slots:\n\n /// \\name Series Modification Handlers\n\n //@{\n\n /// Handles a series reset signal from a line chart series.\n\n void handleSeriesReset();\n\n\n\n /// \\brief\n\n /// Handles a series begin insertion notification.\n\n /// \\param sequence The index of the sequence to be modified.\n\n /// \\param first The first index of the point insertion.\n\n /// \\param last The last index of the point insertion.\n\n void handleSeriesBeginInsert(int sequence, int first, int last);\n\n\n", "file_path": "Qt/Chart/pqLineChartModel.h", "rank": 89, "score": 40.332874013825574 }, { "content": " static int FindCellType(int blockId, int *blockIdList, unsigned char *cellTypeList, \n\n int nCells);\n\n\n\n int CreateNewExodusFile();\n\n int OpenExodusFile();\n\n void CloseExodusFile();\n\n\n\n void InitializeVariableArrayNames();\n\n void ClearVariableArrayNames();\n\n void SetNewNodeVariableNames(vtkDataArray *da, char **nm);\n\n void SetNewElementVariableNames(vtkDataArray *da, char **nm);\n\n\n\n void InitializeBlockLists();\n\n void ClearBlockLists();\n\n int WriteBlockVariables();\n\n//BTX\n\n vtkstd::map<int, int> *BuildBlockElementSearchStructure(int block);\n\n//ETX\n\n\n\n int WriteInitializationParameters();\n", "file_path": "VTK/Parallel/vtkExodusIIWriter.h", "rank": 90, "score": 40.00549942309758 }, { "content": "int\n\nnamePush(xmlParserCtxtPtr ctxt, const xmlChar * value)\n\n{\n\n if (ctxt == NULL) return (-1);\n\n\n\n if (ctxt->nameNr >= ctxt->nameMax) {\n\n const xmlChar * *tmp;\n\n ctxt->nameMax *= 2;\n\n tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab,\n\n ctxt->nameMax *\n\n sizeof(ctxt->nameTab[0]));\n\n if (tmp == NULL) {\n\n ctxt->nameMax /= 2;\n\n goto mem_error;\n\n }\n\n ctxt->nameTab = tmp;\n\n }\n\n ctxt->nameTab[ctxt->nameNr] = value;\n\n ctxt->name = value;\n\n return (ctxt->nameNr++);\n\nmem_error:\n\n xmlErrMemory(ctxt, NULL);\n\n return (-1);\n", "file_path": "VTK/Utilities/vtklibxml2/parser.c", "rank": 91, "score": 39.96756581313657 }, { "content": " static void AddConstantUnsignedCharPointArray(vtkUnstructuredGrid *grid, \n\n const char *arrayName, unsigned char val);\n\n static void AddConstantUnsignedCharCellArray(vtkUnstructuredGrid *grid, \n\n const char *arrayName, unsigned char val);\n\n\n\n // Description:\n\n // ?\n\n static void RemoveRemoteCellsFromList(vtkIdList *cellList, \n\n vtkIdType *gidCells, \n\n vtkIdType *remoteCells, \n\n vtkIdType nRemoteCells);\n\n\n\n // Description:\n\n // ?\n\n static vtkUnstructuredGrid *MergeGrids(vtkDataSet **sets, int nsets,\n\n int deleteDataSets,\n\n int useGlobalNodeIds, float pointMergeTolerance,\n\n int useGlobalCellIds);\n\n\n\n // Description:\n", "file_path": "VTK/Parallel/vtkDistributedDataFilter.h", "rank": 92, "score": 39.947789329021234 }, { "content": " // has 4 DOF: 1 face and 3 edges. An hexahedron has 19 DOF:\n\n // 1 region, 6 faces, and 12 edges.\n\n //\n\n // The number of vertices is not included in the\n\n // count because vertices are a special case: a vertex will have\n\n // at most a single field value associated with it; DOF nodes may have\n\n // an arbitrary number of field values associated with them.\n\n // \\post valid_result: result==GetNumberOfBoundaries(-1)+1\n\n virtual int GetNumberOfDOFNodes()=0;\n\n \n\n // Description:\n\n // Return the points of cell into `it'.\n\n // \\pre it_exists: it!=0\n\n virtual void GetPointIterator(vtkGenericPointIterator *it)=0;\n\n \n\n // Description:\n\n // Create an empty cell iterator. The user is responsible for deleting it.\n\n // \\post result_exists: result!=0\n\n virtual vtkGenericCellIterator *NewCellIterator()=0;\n\n \n", "file_path": "VTK/Filtering/vtkGenericAdaptorCell.h", "rank": 93, "score": 39.89480389249882 }, { "content": " // Description:\n\n // Overloaded to break the reference loop caused by the \n\n // internal domain iterator.\n\n virtual void UnRegister(vtkObjectBase* obj);\n\n\n\n // Description:\n\n // Creates, initializes and returns a new domain iterator. The user \n\n // has to delete the iterator.\n\n vtkSMDomainIterator* NewDomainIterator();\n\n\n\n // Description:\n\n // Returns a domain give a name. \n\n vtkSMDomain* GetDomain(const char* name);\n\n\n\n // Description:\n\n // Returns the number of domains this property has. This can be \n\n // used to specify a valid index for GetDomain(index).\n\n unsigned int GetNumberOfDomains();\n\n\n\n // Description:\n", "file_path": "Servers/ServerManager/vtkSMProperty.h", "rank": 94, "score": 39.86551034979155 }, { "content": " exposedField SFNode texCoord NULL \\n\\\n\n field SFBool ccw TRUE \\n\\\n\n field MFInt32 colorIndex [] \\n\\\n\n field SFBool colorPerVertex TRUE \\n\\\n\n field SFBool convex TRUE \\n\\\n\n field MFInt32 coordIndex [] \\n\\\n\n field SFFloat creaseAngle 0 \\n\\\n\n field MFInt32 normalIndex [] \\n\\\n\n field SFBool normalPerVertex TRUE \\n\\\n\n field SFBool solid TRUE \\n\\\n\n field MFInt32 texCoordIndex [] \\n\\\n\n] { } \\n\\\n\n \\n\\\n\nPROTO IndexedLineSet [ \\n\\\n\n eventIn MFInt32 set_colorIndex \\n\\\n\n eventIn MFInt32 set_coordIndex \\n\\\n\n exposedField SFNode color NULL \\n\\\n\n exposedField SFNode coord NULL \\n\\\n\n field MFInt32 colorIndex [] \\n\\\n\n field SFBool colorPerVertex TRUE \\n\\\n", "file_path": "VTK/Hybrid/vtkVRML.h", "rank": 95, "score": 39.699576961785326 }, { "content": "private:\n\n void resetRoot();\n\n void resetPreferredSizes();\n\n\n\n /// \\name Layout Methods\n\n //@{\n\n void layoutEditor();\n\n void layoutItems();\n\n void layoutItem(pqFlatTreeViewItem *item, int &point,\n\n const QFontMetrics &fm);\n\n int getDataWidth(const QModelIndex &index, const QFontMetrics &fm) const;\n\n int getWidthSum(pqFlatTreeViewItem *item, int column) const;\n\n bool updateContentsWidth();\n\n void updateScrollBars();\n\n void addChildItems(pqFlatTreeViewItem *item, int parentChildCount);\n\n //@}\n\n\n\n /// \\name Tree Navigation Methods\n\n //@{\n\n bool getIndexRowList(const QModelIndex &index,\n", "file_path": "Qt/Widgets/pqFlatTreeView.h", "rank": 96, "score": 39.60246651585799 }, { "content": " void labelInserted(int index);\n\n\n\n /// \\brief\n\n /// Emitted before a label is removed.\n\n /// \\param index The index being removed.\n\n void removingLabel(int index);\n\n\n\n /// \\brief\n\n /// Emitted after a label is removed.\n\n /// \\param index The index being removed.\n\n void labelRemoved(int index);\n\n\n\n /// Emitted when the axis labels are reset.\n\n void labelsReset();\n\n\n\nprivate:\n\n pqChartAxisModelInternal *Internal; ///< Stores the list of labels.\n\n bool InModify; ///< True when blocking signals.\n\n};\n\n\n\n#endif\n", "file_path": "Qt/Chart/pqChartAxisModel.h", "rank": 97, "score": 39.5809195687478 }, { "content": " /// This signal is fired only when the change is triggered by the wiget\n\n /// i.e. if the ServerManager property changes, this signal won't be fired,\n\n /// use \\c modified() instead.\n\n void variableChanged(pqVariableType type, const QString& name);\n\n\n\n /// Fired when ever the color mode on the display changes\n\n /// either thorough this widget itself, of when the underlying SMObject\n\n /// changes.\n\n void modified();\n\n\n\n /// Fired just before the color is changed on the underlying proxy.\n\n /// This must be hooked to an undo stack to record the\n\n /// changes in a undo set.\n\n void begin(const QString&);\n\n\n\n /// Fired just after the color is changed on the underlying proxy.\n\n /// This must be hooked to an undo stack to record the\n\n /// changes in a undo set.\n\n void end();\n\nprivate slots:\n", "file_path": "Qt/Components/pqDisplayColorWidget.h", "rank": 98, "score": 39.56674094210211 }, { "content": "herr_t\n\nH5P_register(H5P_genclass_t *pclass, const char *name, size_t size,\n\n void *def_value, H5P_prp_create_func_t prp_create, H5P_prp_set_func_t prp_set,\n\n H5P_prp_get_func_t prp_get, H5P_prp_delete_func_t prp_delete,\n\n H5P_prp_copy_func_t prp_copy, H5P_prp_compare_func_t prp_cmp,\n\n H5P_prp_close_func_t prp_close)\n\n{\n\n H5P_genclass_t *new_class; /* New class pointer */\n\n H5P_genprop_t *new_prop=NULL; /* Temporary property pointer */\n\n H5P_genprop_t *pcopy; /* Property copy */\n\n herr_t ret_value=SUCCEED; /* Return value */\n\n\n\n FUNC_ENTER_NOAPI(H5P_register, FAIL);\n\n\n\n assert(pclass);\n\n assert(name);\n\n assert((size>0 && def_value!=NULL) || (size==0));\n\n\n\n /* Check for duplicate named properties */\n\n if(H5SL_search(pclass->props,name)!=NULL)\n\n HGOTO_ERROR(H5E_PLIST, H5E_EXISTS, FAIL, \"property already exists\");\n\n\n\n /* Check if class needs to be split because property lists or classes have\n\n * been created since the last modification was made to the class.\n\n */\n\n if(pclass->plists>0 || pclass->classes>0) {\n\n if((new_class=H5P_create_class(pclass->parent,pclass->name,\n\n pclass->internal,pclass->create_func,pclass->create_data,\n\n pclass->copy_func,pclass->copy_data,\n\n pclass->close_func,pclass->close_data))==NULL)\n\n HGOTO_ERROR(H5E_PLIST, H5E_CANTCOPY, FAIL, \"can't copy class\");\n\n\n\n /* Walk through the skip list of the old class and copy properties */\n\n if(pclass->nprops>0) {\n\n H5SL_node_t *curr_node; /* Current node in skip list */\n\n\n\n /* Walk through the properties in the old class */\n\n curr_node=H5SL_first(pclass->props);\n\n while(curr_node!=NULL) {\n\n /* Make a copy of the class's property */\n\n if((pcopy=H5P_dup_prop(H5SL_item(curr_node),H5P_PROP_WITHIN_CLASS))==NULL)\n\n HGOTO_ERROR (H5E_PLIST, H5E_CANTCOPY, FAIL,\"Can't copy property\");\n\n\n\n /* Insert the initialized property into the property list */\n\n if(H5P_add_prop(new_class->props,pcopy)<0)\n\n HGOTO_ERROR (H5E_PLIST, H5E_CANTINSERT, FAIL,\"Can't insert property into class\");\n\n\n\n /* Increment property count for class */\n\n new_class->nprops++;\n\n\n\n /* Get the next property node in the skip list */\n\n curr_node=H5SL_next(curr_node);\n\n } /* end while */\n\n } /* end if */\n\n\n\n /* Use the new class instead of the old one */\n\n pclass=new_class;\n\n } /* end if */\n\n\n\n /* Create property object from parameters */\n\n if((new_prop=H5P_create_prop(name,size,H5P_PROP_WITHIN_CLASS,def_value,prp_create,prp_set,prp_get,prp_delete,prp_copy,prp_cmp,prp_close))==NULL)\n\n HGOTO_ERROR (H5E_PLIST, H5E_CANTCREATE, FAIL,\"Can't create property\");\n\n\n\n /* Insert property into property list class */\n\n if(H5P_add_prop(pclass->props,new_prop)<0)\n\n HGOTO_ERROR (H5E_PLIST, H5E_CANTINSERT, FAIL,\"Can't insert property into class\");\n\n\n\n /* Increment property count for class */\n\n pclass->nprops++;\n\n\n\n /* Update the revision for the class */\n\n pclass->revision = H5P_GET_NEXT_REV;\n\n\n\ndone:\n\n if(ret_value==FAIL) {\n\n if(new_prop!=NULL) {\n\n if(new_prop->name!=NULL)\n\n H5MM_xfree(new_prop->name);\n\n if(new_prop->value!=NULL)\n\n H5MM_xfree(new_prop->value);\n\n H5FL_FREE(H5P_genprop_t,new_prop);\n\n } /* end if */\n\n } /* end if */\n\n FUNC_LEAVE_NOAPI(ret_value);\n", "file_path": "Utilities/hdf5/H5P.c", "rank": 99, "score": 39.42278391140824 } ]
C++
src/ellipse.cpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
#include "ellipse.hpp" #include <cmath> #include <iostream> #include <memory> #include "program.hpp" #include "shader.hpp" #include "time_point.hpp" #include "utilities.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> namespace { nzl::Program create_program() { const std::string vertex_shader_source = nzl::slurp(nzl::get_env_var("SHADERS_PATH") + "/simple_shader.vert"); const std::string fragment_shader_source = nzl::slurp(nzl::get_env_var("SHADERS_PATH") + "/simple_shader.frag"); nzl::Shader vert_shader(nzl::Shader::Stage::Vertex, vertex_shader_source); vert_shader.compile(); nzl::Shader frag_shader(nzl::Shader::Stage::Fragment, fragment_shader_source); frag_shader.compile(); std::vector<nzl::Shader> vec; vec.push_back(vert_shader); vec.push_back(frag_shader); nzl::Program program{vec}; program.compile(); return program; } std::vector<glm::vec3> gen_points(float rX, float rY, float number_of_points) { float step_size = 2.0f * 3.14159265358979f / number_of_points; std::vector<glm::vec3> points; for (int i = 0; i < number_of_points; i++) { float x = rX * cos(i * step_size); float y = rY * sin(i * step_size); points.emplace_back(x, y, 0.0f); } return points; } } namespace nzl { struct Ellipse::IDContainer { glm::vec3 m_color; unsigned int m_vao_id; unsigned int m_vbo_id; int m_number_of_points{0}; nzl::Program m_program; IDContainer(glm::vec3 color, float rX, float rY, float number_of_points) : m_color{color}, m_program{create_program()} { glGenVertexArrays(1, &m_vao_id); glBindVertexArray(m_vao_id); glGenBuffers(1, &m_vbo_id); glBindBuffer(GL_ARRAY_BUFFER, m_vbo_id); std::vector<glm::vec3> points{gen_points(rX, rY, number_of_points)}; points.push_back(points.front()); m_number_of_points = points.size(); glBufferData(GL_ARRAY_BUFFER, points.size() * 3 * sizeof(float), points.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } ~IDContainer() { glDeleteVertexArrays(1, &m_vao_id); glDeleteBuffers(1, &m_vbo_id); } }; Ellipse::Ellipse(float rX, float rY, int number_of_points, glm::vec3 color) noexcept : m_id_container{ std::make_shared<IDContainer>(color, rX, rY, number_of_points)} {} glm::vec3 Ellipse::color() const noexcept { return m_id_container->m_color; } void Ellipse::set_color(glm::vec3 color) noexcept { m_id_container->m_color = color; } nzl::Program Ellipse::get_program() const noexcept { return m_id_container->m_program; } void Ellipse::do_render(TimePoint t [[maybe_unused]]) { m_id_container->m_program.use(); m_id_container->m_program.set("color", m_id_container->m_color); glBindVertexArray(m_id_container->m_vao_id); glEnableVertexAttribArray(0); glDrawArrays(GL_LINE_STRIP, 0, m_id_container->m_number_of_points); glDisableVertexAttribArray(0); glBindVertexArray(0); } }
#include "ellipse.hpp" #include <cmath> #include <iostream> #include <memory> #include "program.hpp" #include "shader.hpp" #include "time_point.hpp" #include "utilities.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> namespace { nzl::Program create_program() { const std::string vertex_shader_source = nzl::slurp(nzl::get_env_var("SHADERS_PATH") + "/simple_shader.vert"); const std::string fragment_shader_source = nzl::slurp(nzl::get_env_var("SHADERS_PATH") + "/simple_shader.frag"); nzl::Shader vert_shader(nzl::Shader::Stage::Vertex, vertex_shader_source); vert_shader.compile(); nzl::Shader frag_shader(nzl::Shader::Stage::Fragment, fragment_shader_source); frag_shader.compile(); std::vector<nzl::Shader> vec; vec.push_back(vert_shader); vec.push_back(frag_shader); nzl::Program program{vec}; program.compile(); return program; } std::vector<glm::vec3> gen_points(float rX, float rY, float number_of_points) { float step_size = 2.0f * 3.14159265358979f / number_of_points; std::vector<glm::vec3> points; for (int i = 0;
} namespace nzl { struct Ellipse::IDContainer { glm::vec3 m_color; unsigned int m_vao_id; unsigned int m_vbo_id; int m_number_of_points{0}; nzl::Program m_program; IDContainer(glm::vec3 color, float rX, float rY, float number_of_points) : m_color{color}, m_program{create_program()} { glGenVertexArrays(1, &m_vao_id); glBindVertexArray(m_vao_id); glGenBuffers(1, &m_vbo_id); glBindBuffer(GL_ARRAY_BUFFER, m_vbo_id); std::vector<glm::vec3> points{gen_points(rX, rY, number_of_points)}; points.push_back(points.front()); m_number_of_points = points.size(); glBufferData(GL_ARRAY_BUFFER, points.size() * 3 * sizeof(float), points.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } ~IDContainer() { glDeleteVertexArrays(1, &m_vao_id); glDeleteBuffers(1, &m_vbo_id); } }; Ellipse::Ellipse(float rX, float rY, int number_of_points, glm::vec3 color) noexcept : m_id_container{ std::make_shared<IDContainer>(color, rX, rY, number_of_points)} {} glm::vec3 Ellipse::color() const noexcept { return m_id_container->m_color; } void Ellipse::set_color(glm::vec3 color) noexcept { m_id_container->m_color = color; } nzl::Program Ellipse::get_program() const noexcept { return m_id_container->m_program; } void Ellipse::do_render(TimePoint t [[maybe_unused]]) { m_id_container->m_program.use(); m_id_container->m_program.set("color", m_id_container->m_color); glBindVertexArray(m_id_container->m_vao_id); glEnableVertexAttribArray(0); glDrawArrays(GL_LINE_STRIP, 0, m_id_container->m_number_of_points); glDisableVertexAttribArray(0); glBindVertexArray(0); } }
i < number_of_points; i++) { float x = rX * cos(i * step_size); float y = rY * sin(i * step_size); points.emplace_back(x, y, 0.0f); } return points; }
function_block-function_prefixed
[ { "content": "class Program {\n\n public:\n\n /// @brief Create a Program from the given @link Shader Shaders@endlink.\n\n /// @param shaders Shaders to be used to create this Program.\n\n Program(std::vector<nzl::Shader> shaders);\n\n\n\n /// @brief Creates a Program with an empty @link Shader@endlink vector.\n\n Program();\n\n\n\n /// @brief Links and compiles this Program.\n\n /// @throws std::runtime_error on compilation failure.\n\n /// @note If a shader in the vector is not compiled, the Program compiles it.\n\n void compile();\n\n\n\n /// @brief Return an identifier associated with this Program.\n\n unsigned int id() const noexcept;\n\n\n\n /// @brief Calls glUseProgram() with this program's id\n\n void use() const noexcept;\n\n\n", "file_path": "src/program.hpp", "rank": 0, "score": 53374.32739758113 }, { "content": "struct Program::IDContainer {\n\n const unsigned int m_id;\n\n\n\n IDContainer(unsigned int id) noexcept : m_id{id} {}\n\n\n\n ~IDContainer() noexcept { glDeleteProgram(m_id); }\n\n\n\n int find_uniform_location(const std::string& name) {\n\n auto loc = m_u.find(name);\n\n\n\n if (loc != m_u.end()) {\n\n return loc->second;\n\n }\n\n\n\n m_u.insert(std::make_pair(name, create_uniform(name)));\n\n return m_u.find(name)->second;\n\n }\n\n\n\n private:\n\n std::map<std::string, int> m_u;\n", "file_path": "src/program.cpp", "rank": 1, "score": 49336.856265337425 }, { "content": "/// @brief A Barycentric Dynamical Time.\n\nclass TimePoint {\n\n public:\n\n /// @brief Build a TimePoint from a count of Julian days.\n\n /// @param days Number of Julian days as a double value.\n\n static TimePoint Julian(double days);\n\n\n\n /// @return A TimePoint situated before any other TimePoint, so that no point\n\n /// in time t exists, where t < Distant past.\n\n static TimePoint DistantPast() noexcept;\n\n\n\n /// @return A TimePoint situated after any other TimePoint, so that no other\n\n /// point in time t exists, where t > Distant future.\n\n static TimePoint DistantFuture() noexcept;\n\n\n\n /// @brief Build a TimePoint from a Duration.\n\n /// @param duration Elapsed time from the J2000 epoch (default is zero).\n\n /// @return New TimePoint object.\n\n TimePoint(Duration duration = Duration()) noexcept;\n\n\n\n /// @brief Return the Duration elapsed from the J2000 epoch.\n", "file_path": "src/time_point.hpp", "rank": 2, "score": 36180.64855509434 }, { "content": "// mxd Library\n\n#include \"mxd.hpp\"\n\n\n\n// Third party libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n#include <glm/glm.hpp>\n\n\n\nnamespace { // anonymous namespace\n\n\n\nauto check_compilation_errors(unsigned int program_id) {\n\n static const int buffer_size = 1024;\n\n int success{0};\n\n char buffer[buffer_size];\n\n if (glGetProgramiv(program_id, GL_LINK_STATUS, &success);\n\n success == GL_FALSE) {\n\n int info_length{0};\n\n glGetProgramInfoLog(program_id, buffer_size, &info_length, buffer);\n\n std::ostringstream oss;\n\n oss << \"Error compiling shader program \" << program_id << \": \"\n", "file_path": "src/program.cpp", "rank": 3, "score": 31042.88658617935 }, { "content": "#include <gtest/gtest.h>\n\n\n\n// Third Party Libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n#include <glm/glm.hpp>\n\n\n\nnamespace { // anonymous namespace\n\nnzl::Program create_uniform_test_program() {\n\n std::string vSource =\n\n \"#version 330\\n\"\n\n \"layout (location = 0) in vec3 aPos;\\n\"\n\n \"out vec4 vertexColor;\\n\"\n\n \"uniform float testFloat;\\n\"\n\n \"uniform vec2 testVec2;\\n\"\n\n \"uniform vec3 testVec3;\\n\"\n\n \"uniform vec4 testVec4;\\n\"\n\n \"uniform mat2 testMat2;\\n\"\n\n \"uniform mat3 testMat3;\\n\"\n\n \"uniform mat4 testMat4;\\n\"\n", "file_path": "src/program.t.cpp", "rank": 4, "score": 31041.76654438115 }, { "content": "\n\n glm::mat2 value(123.312f, 7567.4f, 1565.2f, 823.3f);\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, value););\n\n\n\n glm::mat2 ret;\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 2 * 2 * sizeof(float), &ret[0][0]);\n\n\n\n for (int i = 0; i < 2; i++) {\n\n for (int z = 0; z < 2; z++) {\n\n EXPECT_FLOAT_EQ(ret[i][z], value[i][z]);\n\n }\n\n }\n\n\n\n EXPECT_FLOAT_EQ(ret[0][0], 123.312f);\n\n\n", "file_path": "src/program.t.cpp", "rank": 5, "score": 31039.821235985135 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file program.hpp\n\n/// @brief Fully processed executable code for one or more Shader stages.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date November 27, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"shader.hpp\"\n\n\n\n// Third party forward declaration only headers\n\n#include <glm/fwd.hpp>\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/program.hpp", "rank": 6, "score": 31039.744125995752 }, { "content": "\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 3 * 3 * sizeof(float), &ret[0][0]);\n\n\n\n for (int i = 0; i < 3; i++) {\n\n for (int z = 0; z < 3; z++) {\n\n EXPECT_FLOAT_EQ(ret[i][z], value[i][z]);\n\n }\n\n }\n\n\n\n EXPECT_FLOAT_EQ(ret[0][0], 123.312f);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, Mat4Uniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n", "file_path": "src/program.t.cpp", "rank": 7, "score": 31039.576035906008 }, { "content": " glUniform1i(m_id_container->find_uniform_location(name), (int)value);\n\n}\n\n\n\nvoid Program::set(const std::string& name, int value) const {\n\n glUniform1i(m_id_container->find_uniform_location(name), value);\n\n}\n\n\n\nvoid Program::set(const std::string& name, float value) const {\n\n glUniform1f(m_id_container->find_uniform_location(name), value);\n\n}\n\n\n\nvoid Program::set(const std::string& name, float x, float y) const {\n\n glUniform2f(m_id_container->find_uniform_location(name), x, y);\n\n}\n\n\n\nvoid Program::set(const std::string& name, float x, float y, float z) const {\n\n glUniform3f(m_id_container->find_uniform_location(name), x, y, z);\n\n}\n\n\n\nvoid Program::set(const std::string& name, float x, float y, float z,\n", "file_path": "src/program.cpp", "rank": 8, "score": 31039.44839021821 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file program.cpp\n\n/// @brief Implementation of program.hpp.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date November 27, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"program.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <exception>\n\n#include <map>\n\n#include <memory>\n\n#include <ostream>\n\n#include <sstream>\n\n#include <stdexcept>\n\n#include <string>\n\n\n", "file_path": "src/program.cpp", "rank": 9, "score": 31039.061512061387 }, { "content": " win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testMat4\";\n\n\n\n glm::mat4 value(123.312f, 7567.4f, 1565.2f, 823.3f, 643.3f, 795.6f, 98.6f,\n\n 342.5f, 396.8f, 231.7f, 95343.3f, 1231234.2f, 329.1f, 1239.3f,\n\n 823.31f, 902.3f);\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, value););\n\n\n\n glm::mat4 ret;\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 4 * 4 * sizeof(float), &ret[0][0]);\n\n\n\n for (int i = 0; i < 4; i++) {\n", "file_path": "src/program.t.cpp", "rank": 10, "score": 31038.04107729777 }, { "content": "\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, 687););\n\n\n\n int value = -1000;\n\n\n\n glGetUniformiv(program.id(), glGetUniformLocation(program.id(), name.c_str()),\n\n &value);\n\n\n\n EXPECT_EQ(value, 687);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, FloatUniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n", "file_path": "src/program.t.cpp", "rank": 11, "score": 31037.953682923602 }, { "content": " /// @brief Adds a @link Shader@endlink to the program\n\n /// @param shader Shader to be added\n\n void add_shader(nzl::Shader& shader);\n\n\n\n /// @brief Sets a boolean uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Boolean value to be set\n\n void set(const std::string& name, bool value) const;\n\n\n\n /// @brief Sets a int uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Integer value to be set\n\n void set(const std::string& name, int value) const;\n\n\n\n /// @brief Sets a float uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Float value to be set\n", "file_path": "src/program.hpp", "rank": 12, "score": 31037.82063653627 }, { "content": "\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testVec4\";\n\n\n\n float val1 = 523.1234f;\n\n float val2 = 773.4321f;\n\n float val3 = 123.65656f;\n\n float val4 = 931.44912f;\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, val1, val2, val3, val4););\n\n\n\n float ret[4];\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 4 * sizeof(float), &ret[0]);\n\n\n\n EXPECT_FLOAT_EQ(ret[0], val1);\n", "file_path": "src/program.t.cpp", "rank": 13, "score": 31036.96720609425 }, { "content": " win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testVec2\";\n\n\n\n float val1 = 523.1234f;\n\n float val2 = 773.4321f;\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, val1, val2););\n\n\n\n float ret[2];\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 2 * sizeof(float), &ret[0]);\n\n\n\n EXPECT_FLOAT_EQ(ret[0], val1);\n", "file_path": "src/program.t.cpp", "rank": 14, "score": 31036.800500833313 }, { "content": " EXPECT_FLOAT_EQ(ret[1], val2);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, 3FloatUniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testVec3\";\n\n\n\n float val1 = 523.1234f;\n\n float val2 = 773.4321f;\n\n float val3 = 123.65656f;\n\n\n\n program.use();\n", "file_path": "src/program.t.cpp", "rank": 15, "score": 31036.780263289857 }, { "content": " nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testFloat\";\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, 687.34f););\n\n\n\n float value = -1000.0f;\n\n\n\n glGetUniformfv(program.id(), glGetUniformLocation(program.id(), name.c_str()),\n\n &value);\n\n\n\n EXPECT_FLOAT_EQ(value, 687.34f);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, 2FloatUniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n", "file_path": "src/program.t.cpp", "rank": 16, "score": 31036.707460346155 }, { "content": " nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testVec3\";\n\n\n\n glm::vec3 value(123.312f, 7567.4f, 1565.2f);\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, value););\n\n\n\n glm::vec3 ret;\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 4 * sizeof(float), &ret[0]);\n\n\n\n EXPECT_FLOAT_EQ(ret.x, value.x);\n\n EXPECT_FLOAT_EQ(ret.y, value.y);\n\n EXPECT_FLOAT_EQ(ret.z, value.z);\n\n\n\n nzl::terminate();\n", "file_path": "src/program.t.cpp", "rank": 17, "score": 31036.536464514273 }, { "content": "\n\n int value = -1000;\n\n\n\n glGetUniformiv(program.id(), glGetUniformLocation(program.id(), name.c_str()),\n\n &value);\n\n\n\n EXPECT_EQ(value, static_cast<int>(true));\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, IntUniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testInt\";\n", "file_path": "src/program.t.cpp", "rank": 18, "score": 31036.500361580813 }, { "content": " glGetUniformLocation(program.id(), name.c_str()),\n\n 4 * sizeof(float), &ret[0]);\n\n\n\n EXPECT_FLOAT_EQ(ret.x, value.x);\n\n EXPECT_FLOAT_EQ(ret.y, value.y);\n\n EXPECT_FLOAT_EQ(ret.z, value.z);\n\n EXPECT_FLOAT_EQ(ret.w, value.w);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, Mat2Uniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testMat2\";\n", "file_path": "src/program.t.cpp", "rank": 19, "score": 31036.486234121174 }, { "content": " ASSERT_NO_THROW(program.set(name, val1, val2, val3););\n\n\n\n float ret[3];\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 3 * sizeof(float), &ret[0]);\n\n\n\n EXPECT_FLOAT_EQ(ret[0], val1);\n\n EXPECT_FLOAT_EQ(ret[1], val2);\n\n EXPECT_FLOAT_EQ(ret[2], val3);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, 4FloatUniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n", "file_path": "src/program.t.cpp", "rank": 20, "score": 31036.476279701903 }, { "content": " EXPECT_FLOAT_EQ(ret[1], val2);\n\n EXPECT_FLOAT_EQ(ret[2], val3);\n\n EXPECT_FLOAT_EQ(ret[3], val4);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, Vec2Uniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testVec2\";\n\n\n\n glm::vec2 value(123.312f, 7567.4f);\n\n\n\n program.use();\n", "file_path": "src/program.t.cpp", "rank": 21, "score": 31036.28401175861 }, { "content": " for (int z = 0; z < 4; z++) {\n\n EXPECT_FLOAT_EQ(ret[i][z], value[i][z]);\n\n }\n\n }\n\n\n\n EXPECT_FLOAT_EQ(ret[0][0], 123.312f);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nint main(int argc, char** argv) {\n\n ::testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n\n}\n", "file_path": "src/program.t.cpp", "rank": 22, "score": 31036.21855948315 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file program.t.cpp\n\n/// @brief Unit tests for program.hpp.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date November 27, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"program.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"mxd.hpp\"\n\n#include \"shader.hpp\"\n\n#include \"window.hpp\"\n\n\n\n// Google Test Framework\n", "file_path": "src/program.t.cpp", "rank": 23, "score": 31036.08614611811 }, { "content": " ASSERT_NO_THROW(program.set(name, value););\n\n\n\n glm::vec2 ret;\n\n\n\n glGetnUniformfv(program.id(),\n\n glGetUniformLocation(program.id(), name.c_str()),\n\n 4 * sizeof(float), &ret[0]);\n\n\n\n EXPECT_FLOAT_EQ(ret[0], value.x);\n\n EXPECT_FLOAT_EQ(ret[1], value.y);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, Vec3Uniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n", "file_path": "src/program.t.cpp", "rank": 24, "score": 31036.075526144836 }, { "content": "\n\n int create_uniform(const std::string& name) {\n\n int uniformLocation = glGetUniformLocation(m_id, name.c_str());\n\n if (uniformLocation < 0) {\n\n std::ostringstream oss;\n\n\n\n oss << \"Program \" << m_id << \" error, unable to find uniform: \" << name;\n\n\n\n throw new std::runtime_error(oss.str());\n\n }\n\n return uniformLocation;\n\n }\n\n};\n\n\n\nProgram::Program(std::vector<nzl::Shader> shaders)\n\n : m_id_container{std::make_shared<IDContainer>(create_program())},\n\n m_shaders{shaders} {}\n\n\n\nProgram::Program()\n\n : m_id_container{std::make_shared<IDContainer>(create_program())} {}\n", "file_path": "src/program.cpp", "rank": 25, "score": 31035.733398542605 }, { "content": " void set(const std::string& name, float value) const;\n\n\n\n /// @brief Sets a vec2 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param x First value of the vec2 to be set\n\n /// @param y Second value of the vec2 to be set\n\n void set(const std::string& name, float x, float y) const;\n\n\n\n /// @brief Sets a vec3 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param x First value of the vec3 to be set\n\n /// @param y Second value of the vec3 to be set\n\n /// @param z Third value of the vec3 to be set\n\n void set(const std::string& name, float x, float y, float z) const;\n\n\n\n /// @brief Sets a vec4 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n", "file_path": "src/program.hpp", "rank": 26, "score": 31035.683054296132 }, { "content": " << std::string_view(buffer, info_length);\n\n throw std::runtime_error(oss.str());\n\n }\n\n}\n\n\n\nauto create_program() {\n\n nzl::requires_current_context();\n\n\n\n if (auto id = glCreateProgram(); id == 0) {\n\n /// @TODO: Add a more extensive error message.\n\n std::ostringstream oss;\n\n oss << \"Error creating Program object\";\n\n throw std::runtime_error(oss.str());\n\n } else {\n\n return id;\n\n }\n\n}\n\n\n\n} // anonymous namespace\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/program.cpp", "rank": 27, "score": 31035.50312739066 }, { "content": " /// @param x First value of the vec4 to be set\n\n /// @param y Second value of the vec4 to be set\n\n /// @param z Third value of the vec4 to be set\n\n /// @param w Fourth value of the vec4 to be set\n\n void set(const std::string& name, float x, float y, float z, float w) const;\n\n\n\n /// @brief Sets a vec2 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Vec2 to be set\n\n void set(const std::string& name, const glm::vec2& value) const;\n\n\n\n /// @brief Sets a vec3 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Vec3 to be set\n\n void set(const std::string& name, const glm::vec3& value) const;\n\n\n\n /// @brief Sets a vec4 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n", "file_path": "src/program.hpp", "rank": 28, "score": 31035.3067251052 }, { "content": " nzl::Program program3(shaders);\n\n EXPECT_NE(program1.id(), program3.id());\n\n program3 = program1;\n\n EXPECT_EQ(program3.id(), program1.id());\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, BoolUniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testInt\";\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, true););\n", "file_path": "src/program.t.cpp", "rank": 29, "score": 31035.09912403141 }, { "content": "\n\nvoid Program::compile() {\n\n for (auto&& s : m_shaders) {\n\n if (!s.is_compiled()) {\n\n s.compile();\n\n }\n\n glAttachShader(m_id_container->m_id, s.id());\n\n }\n\n\n\n glLinkProgram(m_id_container->m_id);\n\n check_compilation_errors(m_id_container->m_id);\n\n}\n\n\n\nunsigned int Program::id() const noexcept { return m_id_container->m_id; }\n\n\n\nvoid Program::use() const noexcept { glUseProgram(m_id_container->m_id); }\n\n\n\nvoid Program::add_shader(nzl::Shader& shader) { m_shaders.push_back(shader); }\n\n\n\nvoid Program::set(const std::string& name, bool value) const {\n", "file_path": "src/program.cpp", "rank": 30, "score": 31034.935090295996 }, { "content": " nzl::Shader shader1(nzl::Shader::Stage::Vertex, vSource);\n\n shaders.push_back(shader1);\n\n shaders.back().compile();\n\n nzl::Shader shader2(nzl::Shader::Stage::Fragment, fSource);\n\n shaders.push_back(shader2);\n\n shaders.back().compile();\n\n\n\n nzl::Program program(shaders);\n\n\n\n program.compile();\n\n\n\n return program;\n\n}\n\n} // anonymous namespace\n\n\n\nTEST(Program, ParameterAccessAndCompilation) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n", "file_path": "src/program.t.cpp", "rank": 31, "score": 31034.87526561264 }, { "content": " \"void main() {\\n\"\n\n \"vec3 pos = aPos;\\n\"\n\n \"pos*=testVec3*testMat3;\\n\"\n\n \"pos.xy+=testVec2*testMat2;\\n\"\n\n \"gl_Position = vec4(pos, 1.0*testFloat)*testMat4;\\n\"\n\n \"vertexColor = vec4(0.5,0.0,0.0,1.0)*testVec4;\\n}\";\n\n\n\n std::string fSource =\n\n \"#version 330\\n\"\n\n \"out vec4 FragColor;\\n\"\n\n \"\"\n\n \"in vec4 vertexColor;\\n\"\n\n \"\"\n\n \"uniform int testInt;\\n\"\n\n \"\"\n\n \"void main(){\\n\"\n\n \"FragColor = vertexColor*testInt;}\";\n\n\n\n std::vector<nzl::Shader> shaders;\n\n\n", "file_path": "src/program.t.cpp", "rank": 32, "score": 31034.59175830402 }, { "content": "\n\nvoid Program::set(const std::string& name, const glm::mat3& value) const {\n\n glUniformMatrix3fv(m_id_container->find_uniform_location(name), 1, GL_FALSE,\n\n &value[0][0]);\n\n}\n\n\n\nvoid Program::set(const std::string& name, const glm::mat4& value) const {\n\n glUniformMatrix4fv(m_id_container->find_uniform_location(name), 1, GL_FALSE,\n\n &value[0][0]);\n\n}\n\n\n\n} // namespace nzl\n", "file_path": "src/program.cpp", "rank": 33, "score": 31034.423669880616 }, { "content": " float w) const {\n\n glUniform4f(m_id_container->find_uniform_location(name), x, y, z, w);\n\n}\n\n\n\nvoid Program::set(const std::string& name, const glm::vec2& value) const {\n\n glUniform2fv(m_id_container->find_uniform_location(name), 1, &value[0]);\n\n}\n\n\n\nvoid Program::set(const std::string& name, const glm::vec3& value) const {\n\n glUniform3fv(m_id_container->find_uniform_location(name), 1, &value[0]);\n\n}\n\n\n\nvoid Program::set(const std::string& name, const glm::vec4& value) const {\n\n glUniform4fv(m_id_container->find_uniform_location(name), 1, &value[0]);\n\n}\n\n\n\nvoid Program::set(const std::string& name, const glm::mat2& value) const {\n\n glUniformMatrix2fv(m_id_container->find_uniform_location(name), 1, GL_FALSE,\n\n &value[0][0]);\n\n}\n", "file_path": "src/program.cpp", "rank": 34, "score": 31034.168702425977 }, { "content": "}\n\n\n\nTEST(Program, Vec4Uniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testVec4\";\n\n\n\n glm::vec4 value(123.312f, 7567.4f, 1565.2f, 823.3f);\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, value););\n\n\n\n glm::vec4 ret;\n\n\n\n glGetnUniformfv(program.id(),\n", "file_path": "src/program.t.cpp", "rank": 35, "score": 31032.641390461955 }, { "content": " nzl::terminate();\n\n}\n\n\n\nTEST(Program, Mat3Uniform) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Program program{create_uniform_test_program()};\n\n\n\n std::string name = \"testMat3\";\n\n\n\n glm::mat3 value(123.312f, 7567.4f, 1565.2f, 823.3f, 643.3f, 795.6f, 98.6f,\n\n 342.5f, 396.8f);\n\n\n\n program.use();\n\n ASSERT_NO_THROW(program.set(name, value););\n\n\n\n glm::mat3 ret;\n", "file_path": "src/program.t.cpp", "rank": 36, "score": 31032.58814049076 }, { "content": " nzl::Shader shader1(nzl::Shader::Stage::Vertex, vSource);\n\n shaders.push_back(shader1);\n\n shaders.back().compile();\n\n nzl::Shader shader2(nzl::Shader::Stage::Fragment, fSource);\n\n shaders.push_back(shader2);\n\n shaders.back().compile();\n\n\n\n ASSERT_NO_THROW(nzl::Program program(shaders); program.compile(););\n\n\n\n nzl::Program program(shaders);\n\n EXPECT_NE(program.id(), 0u);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, CopyConstructor) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n", "file_path": "src/program.t.cpp", "rank": 37, "score": 31032.535831630095 }, { "content": "\n\n std::vector<nzl::Shader> shaders;\n\n\n\n nzl::Program program1(shaders);\n\n nzl::Program program2 = program1;\n\n EXPECT_EQ(program1.id(), program2.id());\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Program, CopyOperator) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Invisible Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n std::vector<nzl::Shader> shaders;\n\n\n\n nzl::Program program1(shaders);\n\n\n", "file_path": "src/program.t.cpp", "rank": 38, "score": 31032.33343477846 }, { "content": " /// @param name Name of the uniform\n\n /// @param value Vec4 to be set\n\n void set(const std::string& name, const glm::vec4& value) const;\n\n\n\n /// @brief Sets a mat2 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Mat2 to be set\n\n void set(const std::string& name, const glm::mat2& value) const;\n\n\n\n /// @brief Sets a mat3 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Mat3 to be set\n\n void set(const std::string& name, const glm::mat3& value) const;\n\n\n\n /// @brief Sets a mat4 uniform within the Program.\n\n /// @throws std::runtime_error when uniform not found\n\n /// @param name Name of the uniform\n\n /// @param value Mat4 to be set\n", "file_path": "src/program.hpp", "rank": 39, "score": 31031.674323610565 }, { "content": " void set(const std::string& name, const glm::mat4& value) const;\n\n\n\n private:\n\n struct IDContainer;\n\n std::shared_ptr<IDContainer> m_id_container{nullptr};\n\n std::vector<nzl::Shader> m_shaders;\n\n};\n\n\n\n} // namespace nzl\n", "file_path": "src/program.hpp", "rank": 40, "score": 31031.374667083648 }, { "content": "\n\n std::string vSource =\n\n \"#version 330\\n\"\n\n \"layout (location = 0) in vec3 aPos;\\n\"\n\n \"out vec4 vertexColor;\\n\"\n\n \"void main() {\\n\"\n\n \"gl_Position = vec4(aPos, 1.0);\\n\"\n\n \"vertexColor = vec4(0.5,0.0,0.0,1.0);\\n}\";\n\n\n\n std::string fSource =\n\n \"#version 330\\n\"\n\n \"out vec4 FragColor;\\n\"\n\n \"\"\n\n \"in vec4 vertexColor;\\n\"\n\n \"\"\n\n \"void main(){\\n\"\n\n \"FragColor = vertexColor;}\";\n\n\n\n std::vector<nzl::Shader> shaders;\n\n\n", "file_path": "src/program.t.cpp", "rank": 41, "score": 31028.348989540587 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file time_point.cpp\n\n/// @brief Implementation of time_point.hpp.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 28, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"time_point.hpp\"\n\n\n\n// C++ Standard Library\n\n\n\n// mxd Library\n\n#include <limits>\n\n#include \"duration.hpp\"\n\n\n\nnamespace nzl {\n\n\n\nTimePoint TimePoint::Julian(double days) {\n", "file_path": "src/time_point.cpp", "rank": 42, "score": 30496.951364723165 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file time_point.hpp\n\n/// @brief A point in time.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 28, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// mxd Library\n\n#include \"duration.hpp\"\n\n\n\nnamespace nzl {\n\n\n\n/// @brief A Barycentric Dynamical Time.\n", "file_path": "src/time_point.hpp", "rank": 43, "score": 30495.695412237666 }, { "content": "/// @return true if lhs > rhs, false otherwise.\n\nbool operator>(const TimePoint& lhs, const TimePoint& rhs);\n\n\n\n/// @brief Less than or equal operator to compare two TimePoints.\n\n/// @param lhs and rhs TimePoint objects to be compared.\n\n/// @return true if lhs <= rhs, false otherwise.\n\nbool operator<=(const TimePoint& lhs, const TimePoint& rhs);\n\n\n\n/// @brief Greater than or equal operator to compare two TimePoints.\n\n/// @param lhs and rhs TimePoint objects to be compared.\n\n/// @return true if lhs < rhs, false otherwise.\n\nbool operator>=(const TimePoint& lhs, const TimePoint& rhs);\n\n\n\n/// @brief Not equal operator to compare two TimePoints.\n\n/// @param lhs and rhs TimePoint objects to be compared.\n\n/// @return true if lhs != rhs, false otherwise.\n\nbool operator!=(const TimePoint& lhs, const TimePoint& rhs);\n\n\n\n/// @brief Return a TimePoint as a Julian date.\n\n/// @param tp TimePoint from which to extract the Julian date.\n\ndouble julian_date(const TimePoint& tp);\n\n} // namespace nzl\n", "file_path": "src/time_point.hpp", "rank": 44, "score": 30494.9736559019 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file time_point.t.cpp\n\n/// @brief Unit tests for time_point.hpp.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 28, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"time_point.hpp\"\n\n\n\n// C++ Standard Library\n\n\n\n// mxd Library\n\n\n\n// Google Test Framework\n\n#include <gtest/gtest.h>\n\n\n\n/// @note included std limits for DistantPast & DistantFuture tests.\n\n#include <limits>\n", "file_path": "src/time_point.t.cpp", "rank": 45, "score": 30494.263385018745 }, { "content": " EXPECT_FALSE(big_time_point <= almost_big_time_point);\n\n EXPECT_TRUE(big_time_point <= big_time_point);\n\n}\n\n\n\nTEST(TimePoint, GreaterThanOrEqualOperator) {\n\n nzl::TimePoint big_time_point{nzl::TimePoint::Julian(1000)};\n\n nzl::TimePoint small_time_point{nzl::TimePoint::Julian(10)};\n\n nzl::TimePoint almost_big_time_point{nzl::TimePoint::Julian(999.9999)};\n\n\n\n EXPECT_TRUE(big_time_point >= small_time_point);\n\n EXPECT_FALSE(small_time_point >= big_time_point);\n\n EXPECT_FALSE(almost_big_time_point >= big_time_point);\n\n EXPECT_TRUE(big_time_point >= big_time_point);\n\n}\n\n\n\nint main(int argc, char** argv) {\n\n ::testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n\n}\n", "file_path": "src/time_point.t.cpp", "rank": 46, "score": 30494.11528212139 }, { "content": "bool operator!=(const TimePoint& lhs, const TimePoint& rhs) {\n\n return lhs.elapsed() != rhs.elapsed();\n\n}\n\n\n\ndouble julian_date(const TimePoint& tp) {\n\n const auto J2000 = 2451545.0;\n\n return tp.elapsed().days() + J2000;\n\n}\n\n\n\n} // namespace nzl\n", "file_path": "src/time_point.cpp", "rank": 47, "score": 30493.80709220235 }, { "content": " (1000.0 - 2 * 24 * 60));\n\n}\n\n\n\nTEST(TimePoint, NotEqualOperatorWorks) {\n\n nzl::TimePoint time_point = nzl::TimePoint::Julian(1000);\n\n nzl::TimePoint different_time_point = nzl::TimePoint::Julian(999);\n\n\n\n EXPECT_TRUE(time_point != different_time_point);\n\n EXPECT_FALSE(time_point != time_point);\n\n}\n\n\n\nTEST(TimePoint, LessThanOperator) {\n\n nzl::TimePoint big_time_point{nzl::TimePoint::Julian(1000)};\n\n nzl::TimePoint small_time_point{nzl::TimePoint::Julian(10)};\n\n nzl::TimePoint almost_big_time_point{nzl::TimePoint::Julian(999.9999)};\n\n\n\n EXPECT_TRUE(small_time_point < big_time_point);\n\n EXPECT_FALSE(big_time_point < small_time_point);\n\n EXPECT_FALSE(big_time_point < almost_big_time_point);\n\n EXPECT_FALSE(big_time_point < big_time_point);\n", "file_path": "src/time_point.t.cpp", "rank": 48, "score": 30491.367398851544 }, { "content": "}\n\n\n\nTEST(TimePoint, GreaterThanOperator) {\n\n nzl::TimePoint big_time_point{nzl::TimePoint::Julian(1000)};\n\n nzl::TimePoint small_time_point{nzl::TimePoint::Julian(10)};\n\n nzl::TimePoint almost_big_time_point{nzl::TimePoint::Julian(999.9999)};\n\n\n\n EXPECT_TRUE(big_time_point > small_time_point);\n\n EXPECT_FALSE(small_time_point > big_time_point);\n\n EXPECT_FALSE(almost_big_time_point > big_time_point);\n\n EXPECT_FALSE(big_time_point > big_time_point);\n\n}\n\n\n\nTEST(TimePoint, LessThanOrEqualOperator) {\n\n nzl::TimePoint big_time_point{nzl::TimePoint::Julian(1000)};\n\n nzl::TimePoint small_time_point{nzl::TimePoint::Julian(10)};\n\n nzl::TimePoint almost_big_time_point{nzl::TimePoint::Julian(999.9999)};\n\n\n\n EXPECT_TRUE(small_time_point <= big_time_point);\n\n EXPECT_FALSE(big_time_point <= small_time_point);\n", "file_path": "src/time_point.t.cpp", "rank": 49, "score": 30491.365404993405 }, { "content": "TimePoint operator+(const TimePoint& lhs, const Duration& rhs);\n\n\n\n/// @brief Subtract a Duration to a timepoint.\n\n/// @param lhs TimePoint object, rhs Duration object.\n\n/// @return New TimePoint with resulting Duration.\n\nTimePoint operator-(const TimePoint& lhs, const Duration& rhs);\n\n\n\n/// @brief Difference between two TimePoints.\n\n/// @param lhs and rhs, both TimePoint object\n\n/// @return New Duration object with a Duration that equals the difference\n\n/// between lhs and rhs.\n\nDuration operator-(const TimePoint& lhs, const TimePoint& rhs);\n\n\n\n/// @brief Less than operator to compare two TimePoints.\n\n/// @param lhs and rhs TimePoint objects to be compared.\n\n/// @return true if lhs < rhs, false otherwise.\n\nbool operator<(const TimePoint& lhs, const TimePoint& rhs);\n\n\n\n/// @brief Greater than operator to compare two TimePoints.\n\n/// @param lhs and rhs TimePoint objects to be compared.\n", "file_path": "src/time_point.hpp", "rank": 50, "score": 30491.221656749607 }, { "content": " // The implementation of TimePoint tracks the number of seconds from the J2000\n\n // epoch (01/Jan/2000 12:00:00.00), which has Julian Date 2451545.0.\n\n const auto J2000 = 2451545.0;\n\n return TimePoint{Duration::Days(days - J2000)};\n\n}\n\n\n\nTimePoint TimePoint::DistantPast() noexcept {\n\n return TimePoint(Duration::Seconds(-std::numeric_limits<double>::infinity()));\n\n}\n\n\n\nTimePoint TimePoint::DistantFuture() noexcept {\n\n return TimePoint(Duration::Seconds(std::numeric_limits<double>::infinity()));\n\n}\n\n\n\nTimePoint::TimePoint(Duration duration) noexcept : m_duration{duration} {}\n\n\n\nconst Duration& TimePoint::elapsed() const noexcept { return m_duration; }\n\n\n\nTimePoint& TimePoint::operator+=(const Duration& duration) {\n\n m_duration += duration;\n", "file_path": "src/time_point.cpp", "rank": 51, "score": 30491.2119828152 }, { "content": "Duration operator-(const TimePoint& lhs, const TimePoint& rhs) {\n\n return (lhs - rhs.elapsed()).elapsed();\n\n}\n\n\n\nbool operator<(const TimePoint& lhs, const TimePoint& rhs) {\n\n return lhs.elapsed() < rhs.elapsed();\n\n}\n\n\n\nbool operator>(const TimePoint& lhs, const TimePoint& rhs) {\n\n return lhs.elapsed() > rhs.elapsed();\n\n}\n\n\n\nbool operator<=(const TimePoint& lhs, const TimePoint& rhs) {\n\n return lhs.elapsed() <= rhs.elapsed();\n\n}\n\n\n\nbool operator>=(const TimePoint& lhs, const TimePoint& rhs) {\n\n return lhs.elapsed() >= rhs.elapsed();\n\n}\n\n\n", "file_path": "src/time_point.cpp", "rank": 52, "score": 30491.173235755134 }, { "content": " const Duration& elapsed() const noexcept;\n\n\n\n /// @brief Add a Duration to this TimePoint.\n\n /// @param duration Duration to be added to TimePoint.\n\n /// @return Reference to TimePoint.\n\n TimePoint& operator+=(const Duration& duration);\n\n\n\n /// @brief Subtract a Duration to this TimePoint.\n\n /// @param duration Duration to be subtracted from TimePoint.\n\n /// @return Reference to Timepoint.\n\n TimePoint& operator-=(const Duration& duration);\n\n\n\n private:\n\n /// @note The implementation tracks TDB seconds from the J2000 epoch.\n\n Duration m_duration{};\n\n};\n\n\n\n/// @brief Add a Duration to a timepoint.\n\n/// @param lhs TimePoint object, rhs Duration object.\n\n/// @return New TimePoint with resulting Duration.\n", "file_path": "src/time_point.hpp", "rank": 53, "score": 30491.109222923602 }, { "content": " return *this;\n\n}\n\n\n\nTimePoint& TimePoint::operator-=(const Duration& duration) {\n\n m_duration -= duration;\n\n return *this;\n\n}\n\n\n\nTimePoint operator+(const TimePoint& lhs, const Duration& rhs) {\n\n auto copy = lhs;\n\n copy += rhs;\n\n return copy;\n\n}\n\n\n\nTimePoint operator-(const TimePoint& lhs, const Duration& rhs) {\n\n auto copy = lhs;\n\n copy -= rhs;\n\n return copy;\n\n}\n\n\n", "file_path": "src/time_point.cpp", "rank": 54, "score": 30491.087225718828 }, { "content": "\n\n auto tp1 = nzl::TimePoint();\n\n EXPECT_EQ(nzl::julian_date(tp1), J2000);\n\n}\n\n\n\nTEST(TimePoint, ConstructorValueIsCorrect) {\n\n EXPECT_DOUBLE_EQ(\n\n nzl::TimePoint(nzl::Duration::Minutes(100)).elapsed().minutes(), 100);\n\n}\n\n\n\nTEST(TimePoint, NoValueLessThanDistantPast) {\n\n nzl::TimePoint infinite_past = nzl::TimePoint::DistantPast();\n\n double min_value = std::numeric_limits<double>::min();\n\n\n\n EXPECT_TRUE(infinite_past.elapsed().seconds() < min_value);\n\n}\n\n\n\nTEST(TimePoint, NoValueGreaterThanDistantFuture) {\n\n nzl::TimePoint infinite_future = nzl::TimePoint::DistantFuture();\n\n double max_value = std::numeric_limits<double>::max();\n", "file_path": "src/time_point.t.cpp", "rank": 55, "score": 30490.99689863984 }, { "content": "\n\n EXPECT_TRUE(infinite_future.elapsed().seconds() > max_value);\n\n}\n\n\n\nTEST(TimePoint, PlusEqualOperatorWorks) {\n\n nzl::TimePoint j200_epoch = nzl::TimePoint();\n\n nzl::Duration ten_seconds = nzl::Duration::Seconds(10);\n\n EXPECT_DOUBLE_EQ((j200_epoch += ten_seconds).elapsed().seconds(), 10.0);\n\n}\n\n\n\nTEST(TimePoint, MinusEqualOperatorWorks) {\n\n nzl::TimePoint j200_epoch = nzl::TimePoint();\n\n nzl::Duration ten_seconds = nzl::Duration::Seconds(10);\n\n EXPECT_DOUBLE_EQ((j200_epoch -= ten_seconds).elapsed().seconds(), -10.0);\n\n}\n\n\n\nTEST(TimePoint, PlusOperatorWorks) {\n\n nzl::TimePoint j200_epoch = nzl::TimePoint();\n\n nzl::Duration ten_seconds = nzl::Duration::Seconds(10);\n\n\n", "file_path": "src/time_point.t.cpp", "rank": 56, "score": 30490.977955667007 }, { "content": " EXPECT_DOUBLE_EQ((j200_epoch + ten_seconds).elapsed().seconds(), 10.0);\n\n}\n\n\n\nTEST(TimePoint, MinusOperatorWorks) {\n\n nzl::TimePoint j200_epoch = nzl::TimePoint();\n\n nzl::Duration ten_seconds = nzl::Duration::Seconds(10);\n\n\n\n EXPECT_DOUBLE_EQ((j200_epoch - ten_seconds).elapsed().seconds(), -10.0);\n\n}\n\n\n\nTEST(TimePoint, TimePointDifferenceOperatorWorks) {\n\n nzl::TimePoint two_days_after_j200 = nzl::TimePoint(nzl::Duration::Days(2));\n\n nzl::TimePoint thousand_minutes_after_j200 =\n\n nzl::TimePoint(nzl::Duration::Minutes(1000));\n\n\n\n EXPECT_DOUBLE_EQ(\n\n (two_days_after_j200 - thousand_minutes_after_j200).minutes(),\n\n (2 * 24 * 60 - 1000.0));\n\n EXPECT_DOUBLE_EQ(\n\n (thousand_minutes_after_j200 - two_days_after_j200).minutes(),\n", "file_path": "src/time_point.t.cpp", "rank": 57, "score": 30490.977955667007 }, { "content": "\n\nTEST(TimePoint, ConstructorDefaultIsZero) {\n\n EXPECT_EQ(nzl::TimePoint().elapsed().seconds(), 0.0);\n\n}\n\n\n\nTEST(TimePoint, CreationFromJulianDate) {\n\n // 2451545.0 is the Julian date of the Epoch of J2000.\n\n auto tp0 = nzl::TimePoint::Julian(2451545.0);\n\n EXPECT_EQ(tp0.elapsed().seconds(), 0);\n\n\n\n // one day after the epoch\n\n auto tp1 = nzl::TimePoint::Julian(2451546.0);\n\n EXPECT_EQ(tp1.elapsed().days(), 1);\n\n}\n\n\n\nTEST(TimePoint, ConvertJulianDate) {\n\n const auto J2000 = 2451545.0;\n\n auto tp0 = nzl::TimePoint::Julian(J2000);\n\n\n\n EXPECT_EQ(nzl::julian_date(tp0), J2000);\n", "file_path": "src/time_point.t.cpp", "rank": 58, "score": 30490.948104538737 }, { "content": " /// @param points Points to be loaded into the VBO.\n\n /// @param size Size of the array.\n\n /// @note Affects all copies of this object.\n\n void load_points(glm::vec3 points[], int size) noexcept;\n\n\n\n /// @brief Returns the line's color.\n\n glm::vec3 color() const noexcept;\n\n\n\n /// @brief Sets the line's color.\n\n /// @param color Color to be set.\n\n /// @note Affects all copies of this object.\n\n void set_color(glm::vec3 color) noexcept;\n\n\n\n /// @brief the program used by the line.\n\n const nzl::Program& get_program() const noexcept;\n\n\n\n private:\n\n struct LineImp;\n\n std::shared_ptr<LineImp> m_pimpl;\n\n\n\n void do_render(TimePoint t) override;\n\n};\n\n\n\n} // namespace nzl\n", "file_path": "src/line.hpp", "rank": 61, "score": 14.409718856125826 }, { "content": "/// @file kepler.hpp\n\n/// @brief Example solution of Kepler's equation.\n\n/// @date November 06, 2018\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <cassert>\n\n#include <cmath>\n\n#include <limits>\n\n#include <sstream>\n\n\n\nnamespace mxd {\n\n\n\n/// @brief Solve Kepler's equation with a naive algorithm.\n\n/// @tparam T Floating-point type.\n\n/// @param ecc Orbital eccentricity.\n\n/// @param man Mean anomaly, rad.\n\n/// @param max_iter Maximum number of iterations.\n\n/// @param tolerance Desired numerical tolerance.\n", "file_path": "docs/cpp/kepler.hpp", "rank": 62, "score": 14.174760081400658 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file line.hpp\n\n/// @brief A a series of points that can be drawn as a line\n\n/// @author F. Ayala <[email protected]>\n\n/// @date December 11, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"geometry.hpp\"\n\n#include \"program.hpp\"\n\n#include \"time_point.hpp\"\n\n\n\n/// @TODO What benefit did you gain from acquiring a\n\n/// full dependency? Did you use any of the features of glm to make it\n\n/// worthwhile to acquire a full dependency?\n\n#include <glm/fwd.hpp>\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/line.hpp", "rank": 63, "score": 14.14786309407873 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file ellipse.hpp\n\n/// @brief An ellipse shape that can be drawn to the screen.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date December 12, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"geometry.hpp\"\n\n#include \"program.hpp\"\n\n#include \"time_point.hpp\"\n\n\n\n// Third party forward declaration headers\n\n#include <glm/fwd.hpp>\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/ellipse.hpp", "rank": 64, "score": 13.808856387359072 }, { "content": "/// @file kepler.cpp\n\n/// @brief Run example solutions of Kepler's equation.\n\n/// @date November 06, 2018\n\n\n\n// C++ Standard Library\n\n#include <cmath>\n\n#include <iomanip>\n\n#include <iostream>\n\n\n\n// mxd Library\n\n#include \"kepler.hpp\"\n\n\n\nint main() {\n\n double ecc;\n\n double man;\n\n\n\n std::cout << std::scientific << std::setprecision(16);\n\n\n\n while (true) {\n\n std::cout << \"enter eccentricity and mean anomaly: \" << std::flush;\n", "file_path": "docs/cpp/kepler.cpp", "rank": 66, "score": 12.2691971502797 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file line.cpp\n\n/// @brief Implementation of line.hpp.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date December 11, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"line.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <string>\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"program.hpp\"\n\n#include \"shader.hpp\"\n\n#include \"time_point.hpp\"\n", "file_path": "src/line.cpp", "rank": 67, "score": 11.812273725313498 }, { "content": "TEST(linspace, TypePromotionIntToFloat) {\n\n const auto points = nzl::linspace(1, 10, 10);\n\n using T = typename decltype(points)::value_type;\n\n static_assert(std::is_same<T, float>::value, \"Promoted type should be float\");\n\n}\n\n\n\nTEST(linspace, EqualBoundsLeadToVectorOfEqualValues) {\n\n for (auto&& point : nzl::linspace(1, 1, 10)) {\n\n EXPECT_EQ(point, 1.0f);\n\n }\n\n}\n\n\n\nint main(int argc, char** argv) {\n\n ::testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n\n}\n", "file_path": "src/linspace.t.cpp", "rank": 68, "score": 11.435749099147607 }, { "content": "#include \"utilities.hpp\"\n\n\n\n// Third party libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n#include <glm/glm.hpp>\n\n\n\nnamespace { // anonymous namespace\n\n\n\nconst std::string vertex_shader_source =\n\n nzl::slurp(nzl::get_env_var(\"SHADERS_PATH\") + \"/simple_shader.vert\");\n\n\n\nconst std::string fragment_shader_source =\n\n nzl::slurp(nzl::get_env_var(\"SHADERS_PATH\") + \"/simple_shader.frag\");\n\n\n\n/// @TODO This is too ugly. Program needs a full refactoring.\n\nauto make_program() {\n\n /// @TODO The Shader/Program interface feels very awkward. For instance: why\n\n /// do I need to pass a vector of shaders? Why do I need to compile the\n\n /// shaders and then compile the program? Shouldn't the program compile the\n", "file_path": "src/line.cpp", "rank": 69, "score": 10.62049322003252 }, { "content": "#include <gtest/gtest.h>\n\n\n\n// Third party libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n#include <glm/glm.hpp>\n\n\n\nTEST(Ellipse, ConstructorAndParameterAccess) {\n\n nzl::initialize();\n\n nzl::Window win(600, 600, \"Test Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Ellipse ellipse(0.1f, 0.9f, 40, glm::vec3(1.0f, 0.0f, 0.0f));\n\n\n\n EXPECT_FLOAT_EQ(ellipse.color().x, 1.0f);\n\n EXPECT_FLOAT_EQ(ellipse.color().y, 0.0f);\n\n EXPECT_FLOAT_EQ(ellipse.color().z, 0.0f);\n\n\n\n EXPECT_NE(ellipse.get_program().id(), 0);\n", "file_path": "src/ellipse.t.cpp", "rank": 70, "score": 10.070924597999912 }, { "content": "#include <gtest/gtest.h>\n\n\n\n// Third party libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n#include <glm/glm.hpp>\n\n\n\nTEST(Line, ConstructorAndParameterAccess) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Test Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n nzl::Line line(glm::vec3(0.4f, 0.5f, 0.3f));\n\n\n\n EXPECT_FLOAT_EQ(line.color().x, 0.4f);\n\n EXPECT_FLOAT_EQ(line.color().y, 0.5f);\n\n EXPECT_FLOAT_EQ(line.color().z, 0.3f);\n\n\n\n EXPECT_NE(line.get_program().id(), 0);\n", "file_path": "src/line.t.cpp", "rank": 71, "score": 10.070924597999912 }, { "content": "\n\nnamespace nzl {\n\n\n\n/// @brief Prototype for the key callback required by GLFW.\n\n/// @note At this point, we provide the same callback for all Windows. In the\n\n/// future, there will likely be more than one key_callback, depending on the\n\n/// type of interaction desired.\n\nvoid key_callback(GLFWwindow* handle, int key, int scancode, int action,\n\n int mods);\n\n\n", "file_path": "src/window.cpp", "rank": 72, "score": 9.748372169273058 }, { "content": " m_pimpl->load_points(points, size);\n\n}\n\n\n\nglm::vec3 Line::color() const noexcept { return m_pimpl->color; }\n\n\n\nvoid Line::set_color(glm::vec3 color) noexcept { m_pimpl->color = color; }\n\n\n\nconst nzl::Program& Line::get_program() const noexcept {\n\n return m_pimpl->program;\n\n}\n\n\n\n/// @TODO Mark unused variables! Compilation must be 100% clean with no\n\n/// warnings.\n\nvoid Line::do_render(TimePoint t [[maybe_unused]]) {\n\n auto&& program = m_pimpl->program;\n\n program.use();\n\n program.set(\"color\", m_pimpl->color);\n\n\n\n /// @TODO Add error checking!\n\n glBindVertexArray(m_pimpl->vao_id);\n\n glEnableVertexAttribArray(0);\n\n glDrawArrays(GL_LINE_STRIP, 0, m_pimpl->number_of_points);\n\n glDisableVertexAttribArray(0);\n\n glBindVertexArray(0);\n\n}\n\n\n\n} // namespace nzl\n", "file_path": "src/line.cpp", "rank": 73, "score": 9.62960974702095 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file shader.hpp\n\n/// @brief Graphics shader.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 12, 2018\n\n/// @copyright (c) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <string>\n\n\n\nnamespace nzl {\n\n\n\n/// @brief A graphics shader.\n", "file_path": "src/shader.hpp", "rank": 76, "score": 9.110678756509309 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file window.hpp\n\n/// @brief A Window to display @link Geometries Geometry@endlink.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 12, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <string>\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/window.hpp", "rank": 77, "score": 9.00860613706915 }, { "content": " /// @brief Return an identifier associated with this Shader.\n\n unsigned int id() const noexcept;\n\n\n\n /// @brief Compile this Shader.\n\n /// @throws std::runtime_error on compilation failure.\n\n void compile();\n\n\n\n /// @brief Returns whether the Shader has been compiled.\n\n bool is_compiled() const noexcept;\n\n\n\n private:\n\n struct IDContainer;\n\n std::shared_ptr<IDContainer> m_id_container{nullptr};\n\n Stage m_stage;\n\n std::string m_source;\n\n};\n\n\n\n} // namespace nzl\n", "file_path": "src/shader.hpp", "rank": 78, "score": 8.990011650152265 }, { "content": " glEnableVertexAttribArray(0);\n\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);\n\n glDisableVertexAttribArray(0);\n\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n\n glBindVertexArray(0);\n\n}\n\n\n\nnzl::Line::LineImp::~LineImp() noexcept {\n\n /// @TODO: Add error checking!\n\n glDeleteVertexArrays(1, &vao_id);\n\n glDeleteBuffers(1, &vbo_id);\n\n}\n\n\n\nvoid nzl::Line::LineImp::load_points(glm::vec3 points[], int size) {\n\n number_of_points = size;\n\n glBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\n glBufferData(GL_ARRAY_BUFFER, size * 3 * sizeof(float), points,\n\n GL_STATIC_DRAW);\n\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n\n}\n", "file_path": "src/line.cpp", "rank": 79, "score": 8.984253134545202 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file geometry.cpp\n\n/// @brief Implementation of geometry.hpp.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 12, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"geometry.hpp\"\n\n\n\nnamespace nzl {\n\n\n\nvoid Geometry::render(TimePoint t) { return this->do_render(t); }\n\n\n\n} // namespace nzl\n", "file_path": "src/geometry.cpp", "rank": 80, "score": 8.720201726613718 }, { "content": "// Third Party Libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n\n\nnamespace { // anonymous namespace\n\n\n\nstd::string error_string(GLenum error_code) {\n\n switch (error_code) {\n\n case GL_INVALID_ENUM:\n\n return \"[GL_INVALID_ENUM] An unacceptable value is specified for an \"\n\n \"enumerated argument.\";\n\n case GL_INVALID_VALUE:\n\n return \"[GL_INVALID_VALUE] A numeric argument is out of range.\";\n\n case GL_INVALID_OPERATION:\n\n return \"[GL_INVALID_OPERATION] The specified operation is not allowed in \"\n\n \"the current state.\";\n\n case GL_INVALID_FRAMEBUFFER_OPERATION:\n\n return \"[GL_INVALID_FRAMEBUFFER_OPERATION] The framebuffer object is not \"\n\n \"complete.\";\n\n case GL_OUT_OF_MEMORY:\n", "file_path": "src/utilities.cpp", "rank": 81, "score": 8.571706651843725 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file geometry.hpp\n\n/// @brief A Geometry is anything that can be drawn.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 12, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// mxd Library\n\n#include \"time_point.hpp\"\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/geometry.hpp", "rank": 82, "score": 8.266819678964172 }, { "content": "// Third party libraries\n\n// Any third-party libraries go here.\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n\n\nnamespace { // anonymous namespace\n\n\n\n/// @brief Return the native identity that corresponds to an nzl::Stage.\n\n/// @note In practice, this translates between nzl::Shader::Stage and GLenums.\n\nauto native_identity(nzl::Shader::Stage stage) noexcept {\n\n switch (stage) {\n\n case nzl::Shader::Stage::Compute:\n\n return GL_COMPUTE_SHADER;\n\n case nzl::Shader::Stage::Fragment:\n\n return GL_FRAGMENT_SHADER;\n\n case nzl::Shader::Stage::Geometry:\n\n return GL_GEOMETRY_SHADER;\n\n case nzl::Shader::Stage::TessellationControl:\n\n return GL_TESS_CONTROL_SHADER;\n\n case nzl::Shader::Stage::TessellationEvaluation:\n", "file_path": "src/shader.cpp", "rank": 83, "score": 8.242592162708684 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file utilities.hpp\n\n/// @brief General programming support utilities.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 13, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n#pragma once\n\n\n\n// C++ Standard Library\n\n#include <cstdlib>\n\n#include <string>\n\n\n\nnamespace nzl {\n\n\n\n/// @brief Slurps a file into a string.\n\n/// @param path Path to the file.\n\n/// @return The contents of the file in a string.\n\n/// @throws std::system_error if the file contents cannot be read.\n", "file_path": "src/utilities.hpp", "rank": 84, "score": 8.17123374318837 }, { "content": " /// shaders if it needs to? What happens if I forget to compile the shader?\n\n std::vector<nzl::Shader> shaders;\n\n shaders.emplace_back(nzl::Shader::Stage::Vertex, vertex_shader_source);\n\n shaders.emplace_back(nzl::Shader::Stage::Fragment, fragment_shader_source);\n\n for (auto& shader : shaders) {\n\n shader.compile();\n\n }\n\n\n\n nzl::Program program(shaders);\n\n program.compile();\n\n\n\n return program;\n\n}\n\n} // anonymous namespace\n\n\n\nnamespace nzl {\n\n\n\n/// Put all you need in the Implementation.\n", "file_path": "src/line.cpp", "rank": 86, "score": 7.277769107272206 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file shader.cpp\n\n/// @brief Graphics shader.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 12, 2018\n\n/// @copyright (c) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"shader.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <sstream>\n\n#include <stdexcept>\n\n#include <string>\n\n\n\n// mxd Library\n\n#include \"mxd.hpp\"\n\n\n", "file_path": "src/shader.cpp", "rank": 87, "score": 6.949650488482945 }, { "content": "\n\n EXPECT_EQ(points.size(), 10u);\n\n EXPECT_EQ(points.front(), 1);\n\n EXPECT_EQ(points.back(), -1);\n\n}\n\n\n\nTEST(linspace, BasicLine) {\n\n const auto points = nzl::linspace(1, 10, 10);\n\n for (auto k = 1u; k < points.size(); ++k) {\n\n EXPECT_EQ(points[k - 1], k);\n\n }\n\n}\n\n\n\nTEST(linspace, TypePromotionIntToDouble) {\n\n const auto points = nzl::linspace(1.0, 10, 10);\n\n using T = typename decltype(points)::value_type;\n\n static_assert(std::is_same<T, double>::value,\n\n \"Promoted type should be double\");\n\n}\n\n\n", "file_path": "src/linspace.t.cpp", "rank": 88, "score": 6.926942641416447 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file window.cpp\n\n/// @brief Implementation of window.hpp.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 12, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"window.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <memory>\n\n#include <sstream>\n\n#include <stdexcept>\n\n#include <string>\n\n\n\n// GLEW and GLFW Library\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n", "file_path": "src/window.cpp", "rank": 89, "score": 6.891980527414272 }, { "content": "/// @tparam Q Type fo the final bound\n\n/// @param begin Initial bound\n\n/// @param end Final bound\n\n/// @param n Number of points (n >= 2).\n\n/// @return std::vector<T>, where @p T is the promoted type, containing @p n\n\n/// equally-spaced points [begin, ..., end].\n\n/// @throws std::runtime_error if n < 2.\n\n/// @note To derive the promoted type, we first promote independently @p P and\n\n/// @p Q to at least @p float (or leave unchanged if already float or higher\n\n/// precision). We then find the common type of the promoted @p P and promoted\n\n/// @p Q to derive the @p T.\n\n/// @note Other classes provide linspace specializations (e.g., TimePoint).\n\ntemplate <typename P, typename Q>\n\nauto linspace(P begin, Q end, std::size_t n = 100) {\n\n using PromotedP = typename std::common_type<P, float>::type;\n\n using PromotedQ = typename std::common_type<Q, float>::type;\n\n using T = typename std::common_type<PromotedP, PromotedQ>::type;\n\n T b = begin;\n\n T e = end;\n\n if (n < 2) {\n", "file_path": "src/linspace.hpp", "rank": 90, "score": 6.833013884943504 }, { "content": " nzl::Line line3(glm::vec3(1.0f, 0.5f, 0.2f), points);\n\n EXPECT_EQ(glGetError(), 0);\n\n\n\n nzl::terminate();\n\n}\n\n\n\nTEST(Line, DrawAndReplacePoints) {\n\n nzl::initialize();\n\n nzl::Window win(800, 600, \"Test Window\");\n\n win.hide();\n\n win.make_current();\n\n\n\n std::vector<glm::vec3> points;\n\n points.emplace_back(-1.0f, 1.0f, 0.0f);\n\n points.emplace_back(1.0f, -1.0f, 0.0f);\n\n\n\n nzl::Line line(glm::vec3(1.0f, 1.0f, 0.0f), points);\n\n\n\n for (int i = 0; i < 3; i++) {\n\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n", "file_path": "src/line.t.cpp", "rank": 91, "score": 6.809105860634394 }, { "content": " throw std::runtime_error(oss.str());\n\n } else {\n\n return id;\n\n }\n\n}\n\n\n\nauto check_compilation_errors(unsigned int shader_id) {\n\n static const int buffer_size = 1024;\n\n int success{0};\n\n char buffer[buffer_size];\n\n if (glGetShaderiv(shader_id, GL_COMPILE_STATUS, &success);\n\n success == GL_FALSE) {\n\n int info_length{0};\n\n glGetShaderInfoLog(shader_id, buffer_size, &info_length, buffer);\n\n std::ostringstream oss;\n\n oss << \"Error compiling shader \" << shader_id << \": \"\n\n << std::string_view(buffer, info_length);\n\n throw std::runtime_error(oss.str());\n\n }\n\n}\n\n\n\n} // anonymous namespace\n\n\n\nnamespace nzl {\n\n\n", "file_path": "src/shader.cpp", "rank": 92, "score": 6.805707358162169 }, { "content": "\n\n// -----------------------------------------------------------------------------\n\n// The section below forwards API calls to the implementation\n\n// -----------------------------------------------------------------------------\n\n\n\nLine::Line(glm::vec3 color) : m_pimpl{std::make_shared<Line::LineImp>()} {\n\n m_pimpl->color = color;\n\n}\n\n\n\nLine::Line() : Line(glm::vec3(1.0f, 1.0f, 1.0f)) {}\n\n\n\nLine::Line(glm::vec3 color, std::vector<glm::vec3>& points) : Line(color) {\n\n load_points(points);\n\n}\n\n\n\nvoid Line::load_points(std::vector<glm::vec3>& points) noexcept {\n\n m_pimpl->load_points(points.data(), points.size());\n\n}\n\n\n\nvoid Line::load_points(glm::vec3 points[], int size) noexcept {\n", "file_path": "src/line.cpp", "rank": 93, "score": 6.728931370502631 }, { "content": " glClear(GL_COLOR_BUFFER_BIT);\n\n\n\n line.render(nzl::TimePoint());\n\n\n\n win.swap_buffers();\n\n }\n\n EXPECT_EQ(glGetError(), 0);\n\n\n\n std::vector<glm::vec3> points2;\n\n points.emplace_back(-1.0f, -1.0f, 0.0f);\n\n points.emplace_back(1.0f, 1.0f, 0.0f);\n\n\n\n line.load_points(points2);\n\n\n\n for (int i = 0; i < 3; i++) {\n\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n\n glClear(GL_COLOR_BUFFER_BIT);\n\n\n\n line.render(nzl::TimePoint());\n\n\n", "file_path": "src/line.t.cpp", "rank": 94, "score": 6.7280692309360575 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file mxd.cpp\n\n/// @brief Implementation of mxd.hpp.\n\n/// @author J. Arrieta <[email protected]>\n\n/// @date November 13, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"mxd.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <sstream>\n\n#include <stdexcept>\n\n\n\n// OpenGL Libraries\n\n#include <GL/glew.h>\n\n#include <GLFW/glfw3.h>\n\n\n\nnamespace nzl {\n", "file_path": "src/mxd.cpp", "rank": 95, "score": 6.606218670564291 }, { "content": " return \"[GL_OUT_OF_MEMORY] There is not enough memory left to execute \"\n\n \"the command.\";\n\n case GL_STACK_UNDERFLOW:\n\n return \"[GL_STACK_UNDERFLOW] An attempt has been made to perform an \"\n\n \"operation that would cause an internal stack to underflow.\";\n\n case GL_STACK_OVERFLOW:\n\n return \"[GL_STACK_OVERFLOW] An attempt has been made to perform an \"\n\n \"operation that would cause an internal stack to overflow.\";\n\n case GL_NO_ERROR:\n\n return \"[GL_NO_ERROR] No error detected.\";\n\n default:\n\n return \"[???] Unwnown error code received in error_string.\";\n\n }\n\n}\n\n\n\n} // anonymous namespace\n\n\n\nnamespace nzl {\n\n\n\nstd::string slurp(const std::string& path) {\n", "file_path": "src/utilities.cpp", "rank": 96, "score": 6.576742557840545 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file line.t.cpp\n\n/// @brief Unit tests for line.hpp.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date December 11, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"line.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"mxd.hpp\"\n\n#include \"time_point.hpp\"\n\n#include \"window.hpp\"\n\n\n\n// Google Test Framework\n", "file_path": "src/line.t.cpp", "rank": 97, "score": 6.549704999826222 }, { "content": "// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*-\n\n\n\n/// @file ellipse.t.cpp\n\n/// @brief Unit tests for ellipse.hpp.\n\n/// @author F. Ayala <[email protected]>\n\n/// @date December 12, 2018\n\n/// @copyright (C) 2018 Nabla Zero Labs\n\n\n\n// Related mxd header\n\n#include \"ellipse.hpp\"\n\n\n\n// C++ Standard Library\n\n#include <vector>\n\n\n\n// mxd Library\n\n#include \"mxd.hpp\"\n\n#include \"time_point.hpp\"\n\n#include \"window.hpp\"\n\n\n\n// Google Test Framework\n", "file_path": "src/ellipse.t.cpp", "rank": 98, "score": 6.549704999826222 }, { "content": "# `mxd` &mdash; Space Mission Design Support Tools\n\n\n\n## Dependencies needed to build `mxd`.\n\n\n\n* A C++ compiler supporting the C++17 Standard.\n\n* [CMake](https://cmake.org/) 3.10.0 or greater.\n\n* [GLFW](https://www.glfw.org/) 3.2.1 or greater.\n\n* [GLEW](http://glew.sourceforge.net/) 2.1.0 or greater.\n\n* [GLM](https://glm.g-truc.net/0.9.9/index.html) version 0.9.9.3 or greater.\n\n* [Google Test Framework](https://github.com/google/googletest) version 1.8.1 or greater.\n\n\n\n## Developer Guidelines\n\n\n\n`mxd` is built of components. A component is a triplet (`name.hpp`, `name.cpp`,\n\n`name.t.cpp`) with the following characteristics:\n\n\n\n* `name.hpp` declares the interface for the component.\n\n* `name.cpp` defines the implementation of the component.\n\n* `name.t.cpp` provides unit tests for the component.\n\n\n\nAll components live under `src` in a flat arrangement (no sub-folders). In the\n\nfuture, when we understand `mxd` better, we may sub-divide `src` into\n\nsub-directories, but not right now.\n\n\n\nSome hard rules:\n\n\n\n* `name.hpp` cannot `#include` any third-party library (only C++ Standard\n\n Library and possibly other headers from the `mxd` library).\n\n\n\n* `name.cpp` will `#include \"name.hpp\"` as the first line of source code.\n\n\n\n* `name.t.cpp` will `#include \"name.hpp\"` as the first line of source code.\n\n\n\n* All tests are written using Google Test Framework and are named after the\n\n `(Component, Feature)` tested. Additionally, they will be stand-alone (will have\n\n a `int main()`). For example:\n\n\n\n```c++\n\nTEST(Name, FeatureWithinName) {\n\n// ... some assertion.\n\n}\n\n\n\nTEST(Name, AnotherFeatureWithinName) {\n\n// ... some assertion.\n\n}\n\n\n\nTEST(Name, YetAnotherFeatureWithinName) {\n\n// ... some assertion.\n\n}\n\n\n\nint main(int argc, char** argv) {\n\n ::testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n\n}\n\n```\n\n\n\nSome guidelines:\n\n\n\n* We use UNIX newlines: `\\n` (as opposed to Windows newlines `\\r\\n`). Please\n\n configure your Git client to clean the newlines before storing the commit\n\n (google how to do it).\n\n\n", "file_path": "README.md", "rank": 99, "score": 6.419556976948031 } ]
C++
Ai.cpp
NicoSchumann/TicTacToe
df7349ebd82dfbc2561b4dc1b4627917d4067845
#include "Ai.hpp" #include <ctime> #include <climits> Ai::Ai(Mark aiPlayer) : m_aiPlayer(aiPlayer) , m_pointsAtLost(-1) , m_pointsAtWin(1) , m_pointsAtDraw(0) {} Ai::Ai() : Ai(Mark::empty) {} RandomAi::RandomAi(const Mark aiPlayer) : Ai::Ai(aiPlayer) , m_randomRounds(100) { std::srand(std::time(0)); } RandomAi::RandomAi() : RandomAi(Mark::empty) {} void RandomAi::playRandomField(Board & board, Mark currPlayer) { int emptyFields = 0; for (int i = 0; i < 9; ++i) { if (board.getMark(i) == Mark::empty) { ++ emptyFields; } } int r = rand() % emptyFields; for (int i = 0; i < 9; ++i ) { if (board.getMark(i) != Mark::empty) { continue; } if (r == 0) { board.setMark(currPlayer, i); break; } --r; } } int RandomAi::getSuggestedField(const Board & board, const Mark currPlayer) { if (board.evaluate() != State::inProgress) { return -1; } std::array<int, 9> fieldVals; for (int i = 0; i < 9; ++i) { if (board.getMark(i) == Mark::empty) { fieldVals[i] = 0; } else { fieldVals[i] = (m_randomRounds * m_pointsAtLost) - 1; } } for (int i = 0; i < 9; ++i) { if (board.getMark(i) != Mark::empty) { continue; } Board * bo = new Board(board); bo->setMark(currPlayer, i); if (bo->evaluate() != State::inProgress) { return i; } for (int k = 0; k < m_randomRounds; ++k) { Mark cp = (currPlayer == Mark::cross ? Mark::ring : Mark::cross); Board * b = new Board(*bo); State state = State::inProgress; do { playRandomField( *b, cp); cp = (cp == Mark::cross ? Mark::ring : Mark::cross); state = b->evaluate(); } while (state == State::inProgress); delete b; if (state == State::draw) { fieldVals[i] += m_pointsAtDraw; } else if ((state == State::cross && currPlayer == Mark::cross) ||(state == State::ring && currPlayer == Mark::ring)) { fieldVals[i] += m_pointsAtWin; } else { fieldVals[i] += m_pointsAtLost; } } delete bo; } int suggestedField = -1; int maxFieldVal = m_randomRounds * m_pointsAtLost -1; for (int i = 0; i < 9; ++i) { if (fieldVals[i] > maxFieldVal) { maxFieldVal = fieldVals[i]; suggestedField = i; } } for (int i = 0; i < fieldVals.size(); ++i) { std::cerr << "fieldVals["<<i<<"]:"<<fieldVals[i]<<"\n"; } return suggestedField; } MinimaxAi::MinimaxAi(const Mark aiPlayer) : Ai::Ai(aiPlayer) {} MinimaxAi::MinimaxAi() : MinimaxAi(Mark::empty) {} int MinimaxAi::getSuggestedField(const Board & board, const Mark currPlayer) { if (board.evaluate() != State::inProgress) { return -1; } int fieldNo = -1; int fieldVal; if(currPlayer == Mark::cross) { fieldVal = INT_MIN; } else if (currPlayer == Mark::ring) { fieldVal = INT_MAX; } Mark changedPlayer = (currPlayer == Mark::cross ? Mark::ring : Mark::cross); for (int i = 0; i < 9; ++i) { if (board.getMark(i) != Mark::empty) { continue; } Board * b = new Board(board); b->setMark(currPlayer, i); int val = minimax(*b, changedPlayer ); delete b; if (currPlayer == Mark::cross && val > fieldVal) { fieldVal = val; fieldNo = i; } else if (currPlayer == Mark::ring && val < fieldVal) { fieldVal = val; fieldNo = i; } } return fieldNo; } int MinimaxAi::minimax(const Board & board, const Mark currPlayer) { State state = board.evaluate(); if (state == State::cross) return m_pointsAtWin; if (state == State::ring) return m_pointsAtLost; if (state == State::draw) return m_pointsAtDraw; int bestVal; if (currPlayer == Mark::cross) bestVal = INT_MIN; else if (currPlayer == Mark::ring) bestVal = INT_MAX; Mark changedPlayer = (currPlayer == Mark::cross ? Mark::ring : Mark::cross); for (int i = 0; i < 9; ++i) { if (board.getMark(i) != Mark::empty) { continue; } Board * b = new Board(board); b->setMark(currPlayer,i); int val = minimax(*b,changedPlayer); delete b; if (currPlayer == Mark::cross && val > bestVal) { bestVal = std::max(val,bestVal); } else if (currPlayer == Mark::ring && val < bestVal) { bestVal = std::min(val,bestVal); } } return bestVal; }
#include "Ai.hpp" #include <ctime> #include <climits> Ai::Ai(Mark aiPlayer) : m_aiPlayer(aiPlayer) , m_pointsAtLost(-1) , m_pointsAtWin(1) , m_pointsAtDraw(0) {} Ai::Ai() : Ai(Mark::empty) {} RandomAi::RandomAi(const Mark aiPlayer) : Ai::Ai(aiPlayer) , m_randomRounds(100) { std::srand(std::time(0)); } RandomAi::RandomAi() : RandomAi(Mark::empty) {} void RandomAi::playRandomField(Board & board, Mark currPlayer) { int emptyFields = 0; for (int i = 0; i < 9; ++i) { if (board.getMark(i) == Mark::empty) { ++ emptyFields; } } int r = rand() % emptyFields; for (int i = 0; i < 9; ++i ) { if (board.getMark(i) != Mark::empty) { continue; } if (r == 0) { board.setMark(currPlayer, i); break; } --r; } } int RandomAi::getSuggestedField(const Board & board, const Mark currPlayer) { if (board.evaluate() != State::inProgress) { return -1; } std::array<int, 9> fieldVals; for (int i = 0; i < 9; ++i) { if (board.getMark(i) == Mark::empty) { fieldVals[i] = 0; } else { fieldVals[i] = (m_randomRounds * m_pointsAtLost) - 1; } } for (int i = 0; i < 9; ++i) { if (board.getMark(i) != Mark::empty) { continue; } Board * bo = new Board(board); bo->setMark(currPlayer, i); if (bo->evaluate() != State::inProgress) { return i; } for (int k = 0; k < m_randomRounds; ++k) { Mark cp = (currPlayer == Mark::cross ? Mark::ring : Mark::cross); Board * b = new Board(*bo); State state = State::inProgress; do { playRandomField( *b, cp); cp = (cp == Mark::cross ? Mark::ring : Mark::cross); state = b->evaluate(); } while (state == State::inProgress); delete b; if (state == State::draw) { fieldVals[i] += m_pointsAtDraw; } else if ((state == State::cross && currPlayer == Mark::cross) ||(state == State::ring && currPlayer == Mark::ring)) { fieldVals[i] += m_pointsAtWin; } else { fieldVals[i] += m_pointsAtLost; } } delete bo; } int suggestedField = -1; int maxFieldVal = m_randomRounds * m_pointsAtLost -1; for (int i = 0; i < 9; ++i) { if (fieldVals[i] > maxFieldVal) { maxFieldVal = fieldVals[i]; suggestedField = i; } } for (int i = 0; i < fieldVals.size(); ++i) { std::cerr << "fieldVals["<<i<<"]:"<<fieldVals[i]<<"\n"; } return suggestedF
No = -1; int fieldVal; if(currPlayer == Mark::cross) { fieldVal = INT_MIN; } else if (currPlayer == Mark::ring) { fieldVal = INT_MAX; } Mark changedPlayer = (currPlayer == Mark::cross ? Mark::ring : Mark::cross); for (int i = 0; i < 9; ++i) { if (board.getMark(i) != Mark::empty) { continue; } Board * b = new Board(board); b->setMark(currPlayer, i); int val = minimax(*b, changedPlayer ); delete b; if (currPlayer == Mark::cross && val > fieldVal) { fieldVal = val; fieldNo = i; } else if (currPlayer == Mark::ring && val < fieldVal) { fieldVal = val; fieldNo = i; } } return fieldNo; } int MinimaxAi::minimax(const Board & board, const Mark currPlayer) { State state = board.evaluate(); if (state == State::cross) return m_pointsAtWin; if (state == State::ring) return m_pointsAtLost; if (state == State::draw) return m_pointsAtDraw; int bestVal; if (currPlayer == Mark::cross) bestVal = INT_MIN; else if (currPlayer == Mark::ring) bestVal = INT_MAX; Mark changedPlayer = (currPlayer == Mark::cross ? Mark::ring : Mark::cross); for (int i = 0; i < 9; ++i) { if (board.getMark(i) != Mark::empty) { continue; } Board * b = new Board(board); b->setMark(currPlayer,i); int val = minimax(*b,changedPlayer); delete b; if (currPlayer == Mark::cross && val > bestVal) { bestVal = std::max(val,bestVal); } else if (currPlayer == Mark::ring && val < bestVal) { bestVal = std::min(val,bestVal); } } return bestVal; }
ield; } MinimaxAi::MinimaxAi(const Mark aiPlayer) : Ai::Ai(aiPlayer) {} MinimaxAi::MinimaxAi() : MinimaxAi(Mark::empty) {} int MinimaxAi::getSuggestedField(const Board & board, const Mark currPlayer) { if (board.evaluate() != State::inProgress) { return -1; } int field
random
[ { "content": "class Board\n\n{\n\npublic:\n\n Board();\n\n Board(const Board &);\n\n\n\n /** Sets all fields of Board to Mark::empty */\n\n void reset();\n\n\n\n /** Sets a field of the Board class */\n\n void setMark( Mark mark, std::size_t field);\n\n\n\n /** Returns a Board's field value */\n\n Mark getMark(const int position) const;\n\n\n\n /** Evaluates Board's state. */\n\n State evaluate() const;\n\n\n\nprivate:\n\n std::array<Mark,9> m_fields;\n\n};\n\n\n\n#endif // BOARD_GUARD\n", "file_path": "Board.hpp", "rank": 0, "score": 37146.7060780411 }, { "content": "enum class Mark { empty, cross, ring };\n", "file_path": "Board.hpp", "rank": 1, "score": 36161.39283479654 }, { "content": "enum class State { inProgress, cross, ring, draw };\n\n\n\n/** Overloads the << operator, so that the enums could be printed to console. */\n\nstd::ostream& operator<<(std::ostream &, const Mark);\n\nstd::ostream & operator<<( std::ostream &, const State);\n\n\n", "file_path": "Board.hpp", "rank": 2, "score": 33745.40837164745 }, { "content": "class Board; // forward declaration\n\n\n\n/** For printing a Board object to console */\n\nstd::ostream & operator<<(std::ostream &, const Board&);\n\n\n\n\n", "file_path": "Board.hpp", "rank": 3, "score": 31865.905594217787 }, { "content": " m_fields = b.m_fields;\n\n}\n\n\n\nvoid\n\nBoard::reset()\n\n{\n\n for (auto & field : m_fields) field = Mark::empty;\n\n}\n\nvoid\n\nBoard::setMark(Mark mark, std::size_t position)\n\n{\n\n m_fields[position] = mark;\n\n}\n\nMark\n\nBoard::getMark(const int position) const\n\n{\n\n return m_fields[position];\n\n}\n\nState\n\nBoard::evaluate() const\n", "file_path": "Board.cpp", "rank": 4, "score": 19951.76231654706 }, { "content": "#include \"Board.hpp\"\n\n\n\n/*-------- helping functions ----------*/\n\n\n\n/** Overloads the << operator, so that enums could be printed to console. */\n\nstd::ostream& operator<<(std::ostream& o, const Mark m)\n\n{\n\n switch (m)\n\n {\n\n case Mark::empty:\n\n o << \"Mark::empty\";\n\n break;\n\n case Mark::cross:\n\n o << \"Mark::cross\";\n\n break;\n\n case Mark::ring:\n\n o << \"Mark::ring\";\n\n }\n\n return o;\n\n}\n", "file_path": "Board.cpp", "rank": 5, "score": 19949.82243205387 }, { "content": "std::ostream & operator<<(std::ostream & ostr, const Board& board)\n\n{\n\n for (int i = 0; i < 9; ++i)\n\n {\n\n Mark mark = board.getMark(i);\n\n if (mark == Mark::cross) { ostr << 'x'; }\n\n else if (mark == Mark::ring) { ostr << 'o'; }\n\n else { ostr << '-'; }\n\n if (i == 2 || i == 5 || i == 8) { ostr << '\\n'; }\n\n }\n\n return ostr;\n\n}\n\n\n\n/*------- class Board ------*/\n\nBoard::Board()\n\n{\n\n reset();\n\n}\n\nBoard::Board(const Board & b)\n\n{\n", "file_path": "Board.cpp", "rank": 6, "score": 19948.81966444815 }, { "content": "\n\nstd::ostream & operator<<( std::ostream & o, const State s)\n\n{\n\n switch (s)\n\n {\n\n case State::cross:\n\n o << \"State::cross\";\n\n break;\n\n case State::draw:\n\n o << \"State::draw\";\n\n break;\n\n case State::inProgress:\n\n o << \"State::inProgress\";\n\n break;\n\n case State::ring:\n\n o << \"State::ring\";\n\n }\n\n return o;\n\n}\n\n\n", "file_path": "Board.cpp", "rank": 7, "score": 19948.00849816679 }, { "content": "#ifndef BOARD_GUARD\n\n#define BOARD_GUARD\n\n\n\n#include <iostream>\n\n#include <array>\n\n\n", "file_path": "Board.hpp", "rank": 8, "score": 19947.56017587672 }, { "content": "{\n\n auto & f = m_fields;\n\n\n\n if ( // Check for a win of player cross.\n\n // horizontal\n\n (f[0] == Mark::cross && f[0] == f[1] && f[1] == f[2])\n\n || (f[3] == Mark::cross && f[3] == f[4] && f[4] == f[5])\n\n || (f[6] == Mark::cross && f[6] == f[7] && f[7] == f[8])\n\n // vertical\n\n || (f[0] == Mark::cross && f[0] == f[3] && f[3] == f[6])\n\n || (f[1] == Mark::cross && f[1] == f[4] && f[4] == f[7])\n\n || (f[2] == Mark::cross && f[2] == f[5] && f[5] == f[8])\n\n // diagonal\n\n || (f[0] == Mark::cross && f[0] == f[4] && f[4] == f[8])\n\n || (f[2] == Mark::cross && f[2] == f[4] && f[4] == f[6])\n\n )\n\n {\n\n //std::cerr << \"Cross wins.\\n\"; // debug\n\n return State::cross;\n\n }\n", "file_path": "Board.cpp", "rank": 9, "score": 19946.349936782477 }, { "content": " else if ( // Check for a win of player ring.\n\n // horizontal\n\n (f[0] == Mark::ring && f[0] == f[1] && f[1] == f[2])\n\n || (f[3] == Mark::ring && f[3] == f[4] && f[4] == f[5])\n\n || (f[6] == Mark::ring && f[6] == f[7] && f[7] == f[8])\n\n // vertical\n\n || (f[0] == Mark::ring && f[0] == f[3] && f[3] == f[6])\n\n || (f[1] == Mark::ring && f[1] == f[4] && f[4] == f[7])\n\n || (f[2] == Mark::ring && f[2] == f[5] && f[5] == f[8])\n\n // diagonal\n\n || (f[0] == Mark::ring && f[0] == f[4] && f[4] == f[8])\n\n || (f[2] == Mark::ring && f[2] == f[4] && f[4] == f[6])\n\n )\n\n {\n\n //std::cerr << \"Ring wins.\\n\"; // debug\n\n return State::ring;\n\n }\n\n\n\n // Check if game is still in progress.\n\n // That's if any field is empty.\n", "file_path": "Board.cpp", "rank": 10, "score": 19946.24092533821 }, { "content": " for (auto & field : m_fields)\n\n {\n\n if (field == Mark::empty)\n\n {\n\n // std::cerr << \"Game is in progess.\\n\"; // debug\n\n return State::inProgress;\n\n }\n\n }\n\n\n\n // No winner, not in progress, so it st be a draw.\n\n //std::cerr << \"Game ends with a draw.\\n\"; // debug\n\n return State::draw;\n\n}\n\n\n", "file_path": "Board.cpp", "rank": 11, "score": 19946.021332337958 }, { "content": " }\n\n for (auto & sprite : m_sprite)\n\n {\n\n m_window->draw(sprite);\n\n }\n\n m_window->display();\n\n}\n\n\n\nvoid\n\nCanvas::update(const Board & board)\n\n{\n\n for (int i = 0; i < 9; ++i)\n\n {\n\n Mark mark = board.getMark(i);\n\n switch (mark)\n\n {\n\n case Mark::cross:\n\n m_sprite[i].setTextureRect(sf::Rect<int>(0,0,32,32));\n\n break;\n\n case Mark::ring:\n", "file_path": "GUI.cpp", "rank": 17, "score": 9.0088588098333 }, { "content": " /** Sets one player to this */\n\n void setRandomAI();\n\n void setMinimaxAI();\n\n void setNoAI();\n\n\n\n /** Here you could set one player at A.I. */\n\n void setAIPlayer(const Mark aiPlayer);\n\n\n\nprivate:\n\n\n\n /** Resizes the button area. */\n\n void resize();\n\n\n\n sf::RenderWindow * m_window;\n\n Canvas m_canvas;\n\n Board m_board;\n\n std::array<sf::Rect<int>, 9> m_button;\n\n Mark m_currPlayer;\n\n State m_state; // State of Game\n\n int m_currButtonNo; //\n\n bool m_done;\n\n Mark m_aiPlayer;\n\n Ai * m_ai;\n\n\n\n};\n\n\n\n#endif // GUI_GUARD\n", "file_path": "GUI.hpp", "rank": 18, "score": 8.618198958007252 }, { "content": "void\n\nGame::setRandomAI()\n\n{\n\n if (m_ai != nullptr) delete m_ai;\n\n m_ai = new RandomAi;\n\n}\n\nvoid\n\nGame::setMinimaxAI()\n\n{\n\n if (m_ai != nullptr) delete m_ai;\n\n m_ai = new MinimaxAi;\n\n}\n\nvoid\n\nGame::setNoAI()\n\n{\n\n if (m_ai != nullptr) delete m_ai;\n\n m_ai = nullptr;\n\n m_aiPlayer = Mark::empty;\n\n}\n\nvoid\n\nGame::setAIPlayer(const Mark aiPlayer)\n\n{\n\n m_aiPlayer = aiPlayer;\n\n}\n\n\n", "file_path": "GUI.cpp", "rank": 19, "score": 7.697705135354216 }, { "content": " m_sprite[i].setTextureRect(sf::Rect<int>(32,0,32,32));\n\n break;\n\n default:\n\n m_sprite[i].setTextureRect(sf::Rect<int>(64,0,32,32));\n\n }\n\n }\n\n}\n\n\n\n\n\n/*--------- class Game -------*/\n\n\n\nGame::Game(sf::RenderWindow * window)\n\n: m_window(window)\n\n, m_canvas(window)\n\n, m_currPlayer(Mark::cross)\n\n, m_state(State::inProgress)\n\n, m_currButtonNo(-1)\n\n, m_done(false)\n\n, m_aiPlayer(Mark::ring)\n\n, m_ai(new MinimaxAi(m_aiPlayer))\n", "file_path": "GUI.cpp", "rank": 22, "score": 7.316498529264285 }, { "content": " {\n\n m_board.setMark(Mark::ring, m_currButtonNo);\n\n }\n\n\n\n toggleCurrPlayer();\n\n\n\n m_currButtonNo = -1;\n\n m_canvas.update(m_board);\n\n std::cerr << m_board << '\\n'; // debug\n\n m_state = m_board.evaluate();\n\n\n\n}\n\nbool\n\nGame::isDone() const\n\n{\n\n return m_done;\n\n}\n\n\n\nvoid\n\nGame::reset()\n", "file_path": "GUI.cpp", "rank": 23, "score": 7.016860850792848 }, { "content": "{\n\n resize();\n\n}\n\nGame::Game()\n\n: Game(new sf::RenderWindow(sf::VideoMode(300,300),\"TicTacToe\"))\n\n{}\n\nGame::~Game()\n\n{\n\n delete m_window;\n\n if (m_ai != nullptr) { delete m_ai; }\n\n}\n\n\n\nvoid\n\nGame::handleInput()\n\n{\n\n // checks if AI is at draw and set AI's suggestion\n\n if (m_state == State::inProgress\n\n && m_currPlayer == m_aiPlayer\n\n && m_ai != nullptr\n\n )\n", "file_path": "GUI.cpp", "rank": 28, "score": 6.4849069859381965 }, { "content": " if (m_currButtonNo == -1)\n\n {\n\n return;\n\n }\n\n if (m_state != State::inProgress)\n\n {\n\n return;\n\n }\n\n if (m_board.getMark(m_currButtonNo) != Mark::empty)\n\n {\n\n std::cerr << \"Game::update: board(m_currButtonNo is not empty!\\n\";\n\n return;\n\n }\n\n\n\n\n\n if (m_currPlayer == Mark::cross)\n\n {\n\n m_board.setMark(Mark::cross, m_currButtonNo);\n\n }\n\n else if (m_currPlayer == Mark::ring)\n", "file_path": "GUI.cpp", "rank": 30, "score": 6.217102699623897 }, { "content": " bool isDone() const;\n\n\n\n /** Resets the game */\n\n void reset();\n\n\n\n /**\n\n * Checks for intersection of mouse click position with\n\n * a TicTacToe draw field.\n\n *\n\n * @return The field from mouse position at mouse click.\n\n * If the mouse is not over a field, returns -1.\n\n */\n\n int getButtonNo(const int posX, const int posY) const;\n\n\n\n /** Returns which player is currently on move. */\n\n Mark getCurrPlayer() const;\n\n\n\n /** Toggles the current player. */\n\n void toggleCurrPlayer();\n\n\n", "file_path": "GUI.hpp", "rank": 31, "score": 6.035584725476099 }, { "content": "}\n\nMark\n\nGame::getCurrPlayer() const\n\n{\n\n return m_currPlayer;\n\n}\n\nvoid\n\nGame::toggleCurrPlayer()\n\n{\n\n m_currPlayer = (m_currPlayer == Mark::ring? Mark::cross : Mark::ring);\n\n}\n\nvoid\n\nGame::update()\n\n{\n\n if (m_done)\n\n {\n\n m_window->close();\n\n delete m_window;\n\n return;\n\n }\n", "file_path": "GUI.cpp", "rank": 32, "score": 5.826877983230375 }, { "content": " {\n\n reset();\n\n std::cerr << \"hello\"; // debug\n\n }\n\n else if (m_state == State::inProgress\n\n && event.mouseButton.button == sf::Mouse::Left\n\n ) {\n\n m_currButtonNo = getButtonNo(event.mouseButton.x, event.mouseButton.y);\n\n }\n\n }\n\n }\n\n}\n\nvoid\n\nGame::resize()\n\n{\n\n sf::Vector2<unsigned int> wSize = m_window->getSize();\n\n int bWidth = wSize.x/3;\n\n int bHeight = wSize.y/3;\n\n\n\n m_button[0] = sf::Rect<int>( 0, 0, bWidth, bHeight);\n", "file_path": "GUI.cpp", "rank": 33, "score": 5.036125064789129 }, { "content": "{\n\n m_board.reset();\n\n m_canvas.update(m_board);\n\n render();\n\n}\n\n\n\nvoid\n\nGame::render()\n\n{\n\n if (m_done) { return; }\n\n\n\n m_canvas.render();\n\n}\n\n\n\nvoid\n\nGame::intro()\n\n{\n\n // not yet implemented\n\n}\n\n\n", "file_path": "GUI.cpp", "rank": 34, "score": 4.511738226053718 }, { "content": "#ifndef GUI_GUARD\n\n#define GUI_GUARD\n\n\n\n#include <SFML/Graphics.hpp>\n\n#include \"Board.hpp\"\n\n#include \"Ai.hpp\"\n\n\n\n\n", "file_path": "GUI.hpp", "rank": 36, "score": 4.484945784253037 }, { "content": "#ifndef AI_GUARD\n\n#define AI_GUARD\n\n\n\n#include \"Board.hpp\"\n\n\n", "file_path": "Ai.hpp", "rank": 37, "score": 4.149491768807172 }, { "content": "#include \"GUI.hpp\"\n\n\n\n//\n\n// Reset the board with right mouse click!\n\n//\n\n\n\nint main()\n\n{\n\n Game game;\n\n\n\n game.setMinimaxAI(); // chose your A.I.\n\n //game.setRandomAI();\n\n // game.setNoAI()\n\n\n\n game.intro(); // not yet implemented\n\n while(!game.isDone())\n\n {\n\n game.render();\n\n game.handleInput();\n\n game.update();\n\n }\n\n return EXIT_SUCCESS;\n\n}\n", "file_path": "main.cpp", "rank": 38, "score": 3.763397921656969 }, { "content": "#include \"GUI.hpp\"\n\n\n\n/*--------------- class Canvas ------------------*/\n\n\n\nCanvas::Canvas(sf::RenderWindow * window)\n\n: m_window(window)\n\n{\n\n if (!m_texture.loadFromFile(\"images/64x32_tictactoe.png\"))\n\n {\n\n std::cerr << \"Texture file couldn't loaded!\";\n\n }\n\n for (auto & sprite : m_sprite)\n\n {\n\n sprite = sf::Sprite(m_texture, sf::Rect<int>(64,0,32,32));\n\n sprite.setOrigin(16,16);\n\n }\n\n resize();\n\n\n\n}\n\n\n", "file_path": "GUI.cpp", "rank": 40, "score": 2.6093628672192786 }, { "content": " m_button[1] = sf::Rect<int>( bWidth, 0, bWidth, bHeight);\n\n m_button[2] = sf::Rect<int>(2*bWidth, 0, bWidth, bHeight);\n\n m_button[3] = sf::Rect<int>( 0, bHeight, bWidth, bHeight);\n\n m_button[4] = sf::Rect<int>( bWidth, bHeight, bWidth, bHeight);\n\n m_button[5] = sf::Rect<int>(2*bWidth, bHeight, bWidth, bHeight);\n\n m_button[6] = sf::Rect<int>( 0, 2*bHeight, bWidth, bHeight);\n\n m_button[7] = sf::Rect<int>( bWidth, 2*bHeight, bWidth, bHeight);\n\n m_button[8] = sf::Rect<int>(2*bWidth, 2*bHeight, bWidth, bHeight);\n\n}\n\nint\n\nGame::getButtonNo(const int x, const int y) const\n\n{\n\n for(std::size_t i = 0; i < m_button.size(); ++i)\n\n {\n\n if (m_button[i].contains(x,y))\n\n {\n\n return i;\n\n }\n\n }\n\n return -1; // if something goes wrong\n", "file_path": "GUI.cpp", "rank": 41, "score": 2.501218116474399 }, { "content": " // Adjust the marks:\n\n m_sprite[0].setPosition(wSize.x / 6.0f * 1, wSize.y / 6.0f * 1);\n\n m_sprite[1].setPosition(wSize.x / 6.0f * 3, wSize.y / 6.0f * 1);\n\n m_sprite[2].setPosition(wSize.x / 6.0f * 5, wSize.y / 6.0f * 1);\n\n m_sprite[3].setPosition(wSize.x / 6.0f * 1, wSize.y / 6.0f * 3);\n\n m_sprite[4].setPosition(wSize.x / 6.0f * 3, wSize.y / 6.0f * 3);\n\n m_sprite[5].setPosition(wSize.x / 6.0f * 5, wSize.y / 6.0f * 3);\n\n m_sprite[6].setPosition(wSize.x / 6.0f * 1, wSize.y / 6.0f * 5);\n\n m_sprite[7].setPosition(wSize.x / 6.0f * 3, wSize.y / 6.0f * 5);\n\n m_sprite[8].setPosition(wSize.x / 6.0f * 5, wSize.y / 6.0f * 5);\n\n}\n\n\n\nvoid\n\nCanvas::render()\n\n{\n\n m_window->clear(sf::Color::Black);\n\n\n\n for (auto bar : m_bar)\n\n {\n\n m_window->draw(bar);\n", "file_path": "GUI.cpp", "rank": 42, "score": 1.8932502577025656 }, { "content": "Canvas::~Canvas()\n\n{}\n\n\n\nvoid\n\nCanvas::resize()\n\n{\n\n sf::Vector2u wSize = m_window->getSize();\n\n\n\n // Adjust the bars:\n\n for (std::size_t i = 0; i < m_bar.size(); ++i)\n\n {\n\n m_bar[i].setFillColor(sf::Color(0xaa, 0xbb, 0xcc));\n\n\n\n if (i % 2 == 0) // 0, 2; horizontal bars\n\n {\n\n m_bar[i].setOrigin(0, 2);\n\n m_bar[i].setSize(sf::Vector2<float>(wSize.x, 5));\n\n if (i == 0)\n\n {\n\n m_bar[i].setPosition(0, wSize.y / 3);\n", "file_path": "GUI.cpp", "rank": 43, "score": 1.2857135716471157 }, { "content": "# TicTacToe\n\nA simple TicTacToe game with A.I. player by using the SFML-framework.\n\n\n\nAt this game I want test two manners of A.I.\n\nAt the one hand I implement the Minimax algorithm,\n\nand on the other hand I implement an A.I. by evaluating\n\na bunch of randomly played games.\n\n\n\nAt a first step I coded the GUI.\n\n\n\nAnd now the randomly playing A.I. works.\n\nHere the pseudo code for the random A.I.:\n\n\n\nFor each empty field of the board:\n\n Play the empty field.\n\n Do several times:\n\n Play the game randomly till end.\n\n Evaluate the board's field.\n\n Sum the evaluation to the fields score.\n\nReturn the highest valuated field number.\n\n\n\nThe implementation of the Minimax algorithm is also finished now.\n\n\n\nHow to compile:\n\nrun 'make' at the base directory.\n\n\n\n\n\ndeutsch:\n\nEin einfaches TicTacToe-Spiel mit KI-Spieler mit Hilfe des SFML-Frameworks.\n\n\n\nBei diesem Spiel will ich zwe verschiedene KI-implementierungen testen.\n\nZum einen eine Implementierung des Minimax-Algorithmus, und\n\nzum Anderen durch Auswertung von Zufällig zu Ende gespielten Runden.\n\n\n\nAls erstes habe ich die grafische Benutzerschnittstelle programmiert.\n\n\n\nUnd jetzt funktioniert auch die KI auf Zufallsbasis.\n\nHier der Pseudo-Code der Zufalls-KI:\n\n\n\nFür jedes freie Feld auf dem Bord:\n\n Spiele dieses Feld.\n\n Tu einige Male:\n\n Spiele das Bord bis zum Ende.\n\n Werte den Bordzustand aus und bewerte das ursprüngliche Feld.\n\n Summiere den Wert zu den Bewertungspunkten des Feldes.\n\nGib das am höchsten bewertete Feld zurück.\n\n\n\nJetzt funktioniert auch die Implementation des Minimax-Algorithmus.\n\n\n\nKompilieren:\n\nEinfach 'make' im obersten Verzeichnis des Repositorys aufrufen.\n\n(dort, wo die 'Makefile'-Datei liegt).\n", "file_path": "README.md", "rank": 44, "score": 1.1129165282144422 }, { "content": " {\n\n m_currButtonNo = m_ai->getSuggestedField(m_board, m_currPlayer);\n\n return;\n\n }\n\n\n\n sf::Event event;\n\n m_window->waitEvent(event);\n\n {\n\n if (event.type == sf::Event::Closed)\n\n {\n\n m_done = true;\n\n }\n\n else if (event.type == sf::Event::Resized)\n\n {\n\n resize();\n\n // m_canvas.resize();\n\n }\n\n else if (event.type == sf::Event::MouseButtonPressed)\n\n {\n\n if (event.mouseButton.button == sf::Mouse::Right)\n", "file_path": "GUI.cpp", "rank": 45, "score": 1.1113449207097759 } ]
C++
hxalignmicrotubules/mtalign/matchingGreedy.cpp
zibamira/microtubulestitching
8322b71701e33fde0400715cd5b4e855779e4eda
#include <hxalignmicrotubules/mtalign/matchingGreedy.h> #include <mclib/internal/McComparators.h> #include <mclib/McDArray.h> #include <mclib/McMath.h> #include <mclib/McPlane.h> #include <mclib/internal/McSorter.h> #include <mclib/McVec3.h> #include <hxalignmicrotubules/mtalign/NullPointRepresentation.h> #include <hxalignmicrotubules/mtalign/data.h> #include <hxalignmicrotubules/mtalign/PGMPairWeights.h> #include <pointmatching/GreedyPointMatchingAlgorithm.h> #include <pointmatching/PointMatchingScoringFunction.h> #include <pointmatching/Transformation.h> #include <pointmatching/PointMatchingDataStruct.h> class CacheObject; namespace ma = mtalign; namespace { class Cache { public: void setCoordsAndDirections(const McDArray<McVec3f>& coordinates, const McDArray<McVec3f>& directions, const McMat4f& transform) { assert(coordinates.size() == directions.size()); mCoords.resize(coordinates.size()); mDirections.resize(directions.size()); for (int i = 0; i < coordinates.size(); i++) { McVec3f dir = coordinates[i] + directions[i]; McVec3f newDir; transform.multVecMatrix(dir, newDir); transform.multVecMatrix(coordinates[i], mCoords[i]); newDir = newDir - mCoords[i]; newDir.normalize(); mDirections[i] = newDir; } } const McDArray<McVec3f>& getCoords() const { return mCoords; } const McDArray<McVec3f>& getDirections() const { return mDirections; } void computeDistancesAndSort(ma::PGMPairWeights weightComputation) { pointSet1IsMatched.resize(weightComputation.mCoords1.size()); pointSet1IsMatched.unsetAll(); pointSet2IsMatched.resize(weightComputation.mCoords2.size()); pointSet2IsMatched.unsetAll(); currListIndex = 0; pointCorrespondence.clear(); pointDist2.clear(); double dist2; for (int i = 0; i < weightComputation.mCoords1.size(); ++i) { for (int j = 0; j < weightComputation.mCoords2.size(); ++j) { if (weightComputation.canPointsBeAPair(i, j)) { dist2 = 1.0 - weightComputation.getWeight(i, j); pointCorrespondence.append(McVec2i(i, j)); pointDist2.append(dist2); } } } sortedDist2List.resize(pointCorrespondence.size()); for (int i = 0; i < sortedDist2List.size(); ++i) { sortedDist2List[i] = i; } if (pointDist2.size() > 0) { McIndexByValueComparator<double> comparator(&pointDist2[0]); sort(&(sortedDist2List[0]), sortedDist2List.size(), comparator); } } bool getNextMatchingPair(int& set1PointIx, int& set2PointIx, double& dist2) { if (currListIndex < sortedDist2List.size()) { int ix1, ix2; do { ix1 = pointCorrespondence[sortedDist2List[currListIndex]][0]; if (pointSet1IsMatched[ix1]) { currListIndex++; } else { ix2 = pointCorrespondence[sortedDist2List[currListIndex]][1]; if (pointSet2IsMatched[ix2]) { currListIndex++; } else { set1PointIx = ix1; set2PointIx = ix2; dist2 = pointDist2[sortedDist2List[currListIndex]]; pointSet1IsMatched.set(ix1); pointSet2IsMatched.set(ix2); return true; } } } while (currListIndex < sortedDist2List.size()); } return false; } protected: McDArray<McVec3f> mCoords; McDArray<McVec3f> mDirections; private: McDArray<McVec2i> pointCorrespondence; McDArray<double> pointDist2; McDArray<int> sortedDist2List; McBitfield pointSet1IsMatched; McBitfield pointSet2IsMatched; int currListIndex; }; class RefRepr : public ma::NullPointRepresentation { public: RefRepr(const ma::FacingPointSets& pts, const McMat4f& startTransformation, ma::PGMPairWeights weightComputation) : mNRef(pts.ref.positions.size()), mNTrans(pts.trans.positions.size()) { mCache.setCoordsAndDirections(pts.trans.positions, pts.trans.directions, startTransformation); ma::PGMPairWeights newComp( weightComputation.mCoords1, mCache.getCoords(), weightComputation.mDirections1, mCache.getDirections(), weightComputation.mConfig); mCache.computeDistancesAndSort(newComp); } virtual int getNumPoints() const { return mNRef; } private: virtual void setScoreDivisor(const PointRepresentation* pointSet2, PointMatchingScoringFunction* scoringFunction) const { scoringFunction->setScoreDivisor(mNRef, mNTrans); } virtual CacheObject* startGreedyPointMatching( const PointRepresentation* pointSet2, const Transformation* pointSet2StartTransform) const { return 0; } virtual bool getNextMatchingPair(CacheObject* cacheObject, int& refPointIx, int& queryPointIx, double& dist2) const { return mCache.getNextMatchingPair(refPointIx, queryPointIx, dist2); } virtual void finishGreedyPointMatching() const {} private: int mNRef; int mNTrans; mutable Cache mCache; }; class TransRepr : public ma::NullPointRepresentation { public: TransRepr(int n) : mN(n) {} private: virtual int getNumPoints() const { return mN; } int mN; }; } ma::Matching ma::matchingGreedy(const ma::FacingPointSets& pts, McMat4f startTransformation, const ma::PGMPairWeightsParams& weightConfig) { McHandle<PointMatchingScoringFunction> scoringFunction = new PointMatchingScoringFunction(); scoringFunction->setRMSDScaleFactor(1.e-15); GreedyPointMatchingAlgorithm pmAlg; pmAlg.setMinPointMatchingSize(3); pmAlg.setScoringFunction(scoringFunction.ptr()); Transformation st; st.setTransformation3d(startTransformation); const ma::PGMPairWeights weightComputation( pts.ref.positions, pts.trans.positions, pts.ref.directions, pts.trans.directions, weightConfig); const RefRepr refRepresentation(pts, startTransformation, weightComputation); const TransRepr transRepresentation(pts.trans.positions.size()); PointMatchingDataStruct pointMatching; pmAlg.computePointMatching(&refRepresentation, &transRepresentation, &st, &pointMatching); Matching matching; matching.matchedRefPointIds = pointMatching.getRefPoints(); matching.matchedTransPointIds = pointMatching.getQueryPoints(); return matching; }
#include <hxalignmicrotubules/mtalign/matchingGreedy.h> #include <mclib/internal/McComparators.h> #include <mclib/McDArray.h> #include <mclib/McMath.h> #include <mclib/McPlane.h> #include <mclib/internal/McSorter.h> #include <mclib/McVec3.h> #include <hxalignmicrotubules/mtalign/NullPointRepresentation.h> #include <hxalignmicrotubules/mtalign/data.h> #include <hxalignmicrotubules/mtalign/PGMPairWeights.h> #include <pointmatching/GreedyPointMatchingAlgorithm.h> #include <pointmatching/PointMatchingScoringFunction.h> #include <pointmatching/Transformation.h> #include <pointmatching/PointMatchingDataStruct.h> class CacheObject; namespace ma = mtalign; namespace { class Cache { public: void setCoordsAndDirections(const McDArray<McVec3f>& coordinates, const McDArray<McVec3f>& directions, const McMat4f& transform) { assert(coordinates.size() == directions.size()); mCoords.resize(coordinates.size()); mDirections.resize(directions.size()); for (int i = 0; i < coordinates.size(); i++) { McVec3f dir = coordinates[i] + directions[i]; McVec3f newDir; transform.multVecMatrix(dir, newDir); transform.multVecMatrix(coordinates[i], mCoords[i]); newDir = newDir - mCoords[i]; newDir.normalize(); mDirections[i] = newDir; } } const McDArray<McVec3f>& getCoords() const { return mCoords; } const McDArray<McVec3f>& getDirections() const { return mDirections; } void computeDistancesAndSort(ma::PGMPairWeights weightComputation) { pointSet1IsMatched.resize(weightComputation.mCoords1.size()); pointSet1IsMatched.unsetAll(); pointSet2IsMatched.resize(weightComputation.mCoords2.size()); pointSet2IsMatched.unsetAll(); currListIndex = 0; pointCorrespondence.clear(); pointDist2.clear(); double dist2; for (int i = 0; i < weightComputation.mCoords1.size(); ++i) { for (int j = 0; j < weightComputation.mCoords2.size(); ++j) { if (weightComputation.canPointsBeAPair(i, j)) { dist2 = 1.0 - weightComputation.getWeight(i, j); pointCorrespondence.append(McVec2i(i, j)); pointDist2.append(dist2); } } } sortedDist2List.resize(pointCorrespondence.size()); for (int i = 0; i < sortedDist2List.size(); ++i) { sortedDist2List[i] = i; }
} bool getNextMatchingPair(int& set1PointIx, int& set2PointIx, double& dist2) { if (currListIndex < sortedDist2List.size()) { int ix1, ix2; do { ix1 = pointCorrespondence[sortedDist2List[currListIndex]][0]; if (pointSet1IsMatched[ix1]) { currListIndex++; } else { ix2 = pointCorrespondence[sortedDist2List[currListIndex]][1]; if (pointSet2IsMatched[ix2]) { currListIndex++; } else { set1PointIx = ix1; set2PointIx = ix2; dist2 = pointDist2[sortedDist2List[currListIndex]]; pointSet1IsMatched.set(ix1); pointSet2IsMatched.set(ix2); return true; } } } while (currListIndex < sortedDist2List.size()); } return false; } protected: McDArray<McVec3f> mCoords; McDArray<McVec3f> mDirections; private: McDArray<McVec2i> pointCorrespondence; McDArray<double> pointDist2; McDArray<int> sortedDist2List; McBitfield pointSet1IsMatched; McBitfield pointSet2IsMatched; int currListIndex; }; class RefRepr : public ma::NullPointRepresentation { public: RefRepr(const ma::FacingPointSets& pts, const McMat4f& startTransformation, ma::PGMPairWeights weightComputation) : mNRef(pts.ref.positions.size()), mNTrans(pts.trans.positions.size()) { mCache.setCoordsAndDirections(pts.trans.positions, pts.trans.directions, startTransformation); ma::PGMPairWeights newComp( weightComputation.mCoords1, mCache.getCoords(), weightComputation.mDirections1, mCache.getDirections(), weightComputation.mConfig); mCache.computeDistancesAndSort(newComp); } virtual int getNumPoints() const { return mNRef; } private: virtual void setScoreDivisor(const PointRepresentation* pointSet2, PointMatchingScoringFunction* scoringFunction) const { scoringFunction->setScoreDivisor(mNRef, mNTrans); } virtual CacheObject* startGreedyPointMatching( const PointRepresentation* pointSet2, const Transformation* pointSet2StartTransform) const { return 0; } virtual bool getNextMatchingPair(CacheObject* cacheObject, int& refPointIx, int& queryPointIx, double& dist2) const { return mCache.getNextMatchingPair(refPointIx, queryPointIx, dist2); } virtual void finishGreedyPointMatching() const {} private: int mNRef; int mNTrans; mutable Cache mCache; }; class TransRepr : public ma::NullPointRepresentation { public: TransRepr(int n) : mN(n) {} private: virtual int getNumPoints() const { return mN; } int mN; }; } ma::Matching ma::matchingGreedy(const ma::FacingPointSets& pts, McMat4f startTransformation, const ma::PGMPairWeightsParams& weightConfig) { McHandle<PointMatchingScoringFunction> scoringFunction = new PointMatchingScoringFunction(); scoringFunction->setRMSDScaleFactor(1.e-15); GreedyPointMatchingAlgorithm pmAlg; pmAlg.setMinPointMatchingSize(3); pmAlg.setScoringFunction(scoringFunction.ptr()); Transformation st; st.setTransformation3d(startTransformation); const ma::PGMPairWeights weightComputation( pts.ref.positions, pts.trans.positions, pts.ref.directions, pts.trans.directions, weightConfig); const RefRepr refRepresentation(pts, startTransformation, weightComputation); const TransRepr transRepresentation(pts.trans.positions.size()); PointMatchingDataStruct pointMatching; pmAlg.computePointMatching(&refRepresentation, &transRepresentation, &st, &pointMatching); Matching matching; matching.matchedRefPointIds = pointMatching.getRefPoints(); matching.matchedTransPointIds = pointMatching.getQueryPoints(); return matching; }
if (pointDist2.size() > 0) { McIndexByValueComparator<double> comparator(&pointDist2[0]); sort(&(sortedDist2List[0]), sortedDist2List.size(), comparator); }
if_condition
[ { "content": "/// Approximate inference algorithm \"Tree Expectation Propagation\" [\\ref MiQ04]\n\nclass TreeEP : public JTree {\n\n private:\n\n /// Maximum difference encountered so far\n\n Real _maxdiff;\n\n /// Number of iterations needed\n\n size_t _iters;\n\n\n\n public:\n\n /// Parameters for TreeEP\n\n struct Properties {\n\n /// Enumeration of possible choices for the tree\n\n /** The two possibilities are:\n\n * - \\c ORG: take the maximum spanning tree where the weights are crude\n\n * estimates of the mutual information between the nodes;\n\n * - \\c ALT: take the maximum spanning tree where the weights are upper\n\n * bounds on the effective interaction strengths between pairs of nodes.\n\n */\n\n DAI_ENUM(TypeType,ORG,ALT);\n\n\n\n /// Verbosity (amount of output sent to stderr)\n", "file_path": "dai/upstream/include/dai/treeep.h", "rank": 0, "score": 221126.79828286552 }, { "content": "class JTree : public DAIAlgRG {\n\n private:\n\n /// Stores the messages\n\n std::vector<std::vector<Factor> > _mes;\n\n\n\n /// Stores the logarithm of the partition sum\n\n Real _logZ;\n\n\n\n public:\n\n /// The junction tree (stored as a rooted tree)\n\n RootedTree RTree;\n\n\n\n /// Outer region beliefs\n\n std::vector<Factor> Qa;\n\n\n\n /// Inner region beliefs\n\n std::vector<Factor> Qb;\n\n\n\n /// Parameters for JTree\n\n struct Properties {\n", "file_path": "dai/upstream/include/dai/jtree.h", "rank": 1, "score": 216972.47002692136 }, { "content": "class IPOPTForCPDLinearAligner : public mtalign::IPOPTForCPD {\n\n public:\n\n /** default constructor */\n\n IPOPTForCPDLinearAligner();\n\n\n\n /** default destructor */\n\n virtual ~IPOPTForCPDLinearAligner();\n\n\n\n /**@name Overloaded from TNLP */\n\n //@{\n\n /** Method to return some info about the nlp */\n\n virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,\n\n Index& nnz_h_lag, IndexStyleEnum& index_style);\n\n\n\n /** Method to return the bounds for my problem */\n\n virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, Index m,\n\n Number* g_l, Number* g_u);\n\n\n\n /** Method to return the starting point for the algorithm */\n\n virtual bool get_starting_point(Index n, bool init_x, Number* x,\n", "file_path": "hxalignmicrotubules/mtalign/IPOPTForCPDLinearAligner.cpp", "rank": 3, "score": 191067.9208286116 }, { "content": "// `CPDElasticAlignerTesting` is used to run tests that access protected\n\n// members.\n\nclass CPDElasticAlignerTesting : public mtalign::CPDElasticAligner {\n\n public:\n\n void givenPoints_runCDPNLFMAndCheckResult_E3MS() {\n\n CPDElasticAlignerTesting& cpd = *this;\n\n cpd.params.beta = 1;\n\n cpd.params.lambda = 1;\n\n cpd.params.w = 0.1;\n\n McDMatrix<double> W;\n\n McDMatrix<double> G;\n\n McDMatrix<double> P;\n\n\n\n cpd.align(G, W);\n\n McDMatrix<double> shifted;\n\n cpd.shiftYs(cpd.ys, G, W, shifted);\n\n checkSameCoord(cpd.xs.getRowVector(0), shifted.getRowVector(0));\n\n checkSameCoord(cpd.xs.getRowVector(1), shifted.getRowVector(1));\n\n checkSameCoord(cpd.xs.getRowVector(2), shifted.getRowVector(2));\n\n }\n\n\n\n void givenAssymPoints43_checkRuns_E3MS() {\n", "file_path": "hxalignmicrotubules/mtalign/CPDElasticAlignerTest.cpp", "rank": 4, "score": 188676.64779884162 }, { "content": "class DAIAlg : public InfAlg, public GRM {\n\n public:\n\n /// \\name Constructors/destructors\n\n //@{\n\n /// Default constructor\n\n DAIAlg() : InfAlg(), GRM() {}\n\n\n\n /// Construct from GRM\n\n DAIAlg( const GRM &grm ) : InfAlg(), GRM(grm) {}\n\n //@}\n\n\n\n /// \\name Queries\n\n //@{\n\n /// Returns reference to underlying FactorGraph.\n\n FactorGraph &fg() { return (FactorGraph &)(*this); }\n\n\n\n /// Returns constant reference to underlying FactorGraph.\n\n const FactorGraph &fg() const { return (const FactorGraph &)(*this); }\n\n //@}\n\n\n", "file_path": "dai/upstream/include/dai/daialg.h", "rank": 5, "score": 183952.43156752124 }, { "content": "class TRWBP : public BP {\n\n protected:\n\n /// \"Edge weights\" (indexed by factor ID)\n\n /** In [\\ref WJW03], only unary or pairwise factors are considered.\n\n * Here we are more general by having a weight for each factor in the\n\n * factor graph. If unary factors have weight 1, and higher-order factors\n\n * are absent, then we have the special case considered in [\\ref WJW03].\n\n */\n\n std::vector<Real> _weight;\n\n\n\n public:\n\n /// Size of sample of trees used to set the weights\n\n /** \\todo See if there is a way to wrap TRWBP::nrtrees in a props struct\n\n * together with the other properties currently in TRWBP::props\n\n * (without copying al lot of BP code literally)\n\n */\n\n size_t nrtrees;\n\n\n\n public:\n\n /// \\name Constructors/destructors\n", "file_path": "dai/upstream/include/dai/trwbp.h", "rank": 6, "score": 182822.1280401429 }, { "content": "class FBP : public BP {\n\n protected:\n\n /// Factor weights (indexed by factor ID)\n\n std::vector<Real> _weight;\n\n\n\n public:\n\n /// \\name Constructors/destructors\n\n //@{\n\n /// Default constructor\n\n FBP() : BP(), _weight() {}\n\n\n\n /// Construct from FactorGraph \\a fg and PropertySet \\a opts\n\n /** \\param fg Factor graph.\n\n * \\param opts Parameters @see BP::Properties\n\n */\n\n FBP( const FactorGraph &fg, const PropertySet &opts ) : BP(fg, opts), _weight() {\n\n setProperties( opts );\n\n construct();\n\n }\n\n //@}\n", "file_path": "dai/upstream/include/dai/fbp.h", "rank": 7, "score": 182822.1280401429 }, { "content": "/// Transforms a selection containing only edges and vertices by a\n\n/// transformation\n\nclass HXALIGNMICROTUBULES_API MicrotubuleTransformOperation : public Operation {\n\n public:\n\n MicrotubuleTransformOperation(HxSpatialGraph* sg,\n\n const SpatialGraphSelection& selectedElements,\n\n const SpatialGraphSelection& visibleElements,\n\n const SbMatrix mat);\n\n\n\n virtual ~MicrotubuleTransformOperation();\n\n virtual void exec();\n\n virtual void undo();\n\n virtual SpatialGraphSelection getVisibleSelectionAfterOperation() const;\n\n virtual SpatialGraphSelection getHighlightSelectionAfterOperation() const;\n\n\n\n void\n\n setTransformParameterList(const McDArray<HxParameter*> transformParameters);\n\n\n\n protected:\n\n SbMatrix mMat;\n\n McDArray<HxParameter*> mTransParams;\n\n void appendTransform(HxParameter* p, const SbMatrix& mat);\n\n};\n", "file_path": "hxalignmicrotubules/MicrotubuleTransformOperation.h", "rank": 8, "score": 182283.80543936076 }, { "content": "class IPOPTForCPDLinearAlignerWithoutScale : public mtalign::IPOPTForCPD {\n\n public:\n\n /** default constructor */\n\n IPOPTForCPDLinearAlignerWithoutScale();\n\n\n\n /** default destructor */\n\n virtual ~IPOPTForCPDLinearAlignerWithoutScale();\n\n\n\n /**@name Overloaded from TNLP */\n\n //@{\n\n /** Method to return some info about the nlp */\n\n virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,\n\n Index& nnz_h_lag, IndexStyleEnum& index_style);\n\n\n\n /** Method to return the bounds for my problem */\n\n virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, Index m,\n\n Number* g_l, Number* g_u);\n\n\n\n /** Method to return the starting point for the algorithm */\n\n virtual bool get_starting_point(Index n, bool init_x, Number* x,\n", "file_path": "hxalignmicrotubules/mtalign/IPOPTForCPDLinearAlignerWithoutScale.cpp", "rank": 9, "score": 182011.8605765255 }, { "content": "/// A Region is a set of variables with a counting number\n\nclass Region : public VarSet {\n\n private:\n\n /// Counting number\n\n Real _c;\n\n\n\n public:\n\n /// Default constructor\n\n Region() : VarSet(), _c(1.0) {}\n\n\n\n /// Construct from a set of variables and a counting number\n\n Region( const VarSet& x, Real c ) : VarSet(x), _c(c) {}\n\n\n\n /// Returns constant reference to counting number\n\n const Real& c() const { return _c; }\n\n\n\n /// Returns reference to counting number\n\n Real& c() { return _c; }\n\n};\n\n\n\n\n", "file_path": "dai/upstream/include/dai/regiongraph.h", "rank": 10, "score": 179400.34050730226 }, { "content": "/// An FRegion is a factor with a counting number\n\nclass FRegion : public Factor {\n\n private:\n\n /// Counting number\n\n Real _c;\n\n\n\n public:\n\n /// Default constructor\n\n FRegion() : Factor(), _c(1.0) {}\n\n\n\n /// Constructs from a factor and a counting number\n\n FRegion( const Factor& x, Real c ) : Factor(x), _c(c) {}\n\n\n\n /// Returns constant reference to counting number\n\n const Real& c() const { return _c; }\n\n\n\n /// Returns reference to counting number\n\n Real& c() { return _c; }\n\n};\n\n\n\n\n", "file_path": "dai/upstream/include/dai/regiongraph.h", "rank": 11, "score": 179400.34050730226 }, { "content": "/// Approximate inference algorithm: implementation of single-loop (\"Generalized Belief Propagation\") and double-loop algorithms by Heskes, Albers and Kappen [\\ref HAK03]\n\nclass HAK : public DAIAlgRG {\n\n private:\n\n /// Outer region beliefs\n\n std::vector<Factor> _Qa;\n\n /// Inner region beliefs\n\n std::vector<Factor> _Qb;\n\n /// Messages from outer to inner regions\n\n std::vector<std::vector<Factor> > _muab;\n\n /// Messages from inner to outer regions\n\n std::vector<std::vector<Factor> > _muba;\n\n /// Maximum difference encountered so far\n\n Real _maxdiff;\n\n /// Number of iterations needed\n\n size_t _iters;\n\n\n\n public:\n\n /// Parameters for HAK\n\n struct Properties {\n\n /// Enumeration of possible cluster choices\n\n /** The following cluster choices are defined:\n", "file_path": "dai/upstream/include/dai/hak.h", "rank": 12, "score": 176147.01799655135 }, { "content": "/// Approximate inference algorithm \"Loop Corrected Belief Propagation\" [\\ref MoK07]\n\nclass LC : public DAIAlgFG {\n\n private:\n\n /// Stores for each variable the approximate cavity distribution multiplied with the omitted factors\n\n std::vector<Factor> _pancakes;\n\n /// Stores for each variable the approximate cavity distribution\n\n std::vector<Factor> _cavitydists;\n\n /// _phis[i][_I] corresponds to \\f$ \\phi^{\\setminus i}_I(x_{I \\setminus i}) \\f$ in the paper\n\n std::vector<std::vector<Factor> > _phis;\n\n /// Single variable beliefs\n\n std::vector<Factor> _beliefs;\n\n /// Maximum difference encountered so far\n\n Real _maxdiff;\n\n /// Number of iterations needed\n\n size_t _iters;\n\n\n\n public:\n\n /// Parameters for LC\n\n struct Properties {\n\n /// Enumeration of possible ways to initialize the cavities\n\n /** The following initialization methods are defined:\n", "file_path": "dai/upstream/include/dai/lc.h", "rank": 13, "score": 176141.6975647723 }, { "content": "class MF : public DAIAlgFG {\n\n private:\n\n /// Current approximations of single variable marginals\n\n std::vector<Factor> _beliefs;\n\n /// Maximum difference encountered so far\n\n Real _maxdiff;\n\n /// Number of iterations needed\n\n size_t _iters;\n\n\n\n public:\n\n /// Parameters for MF\n\n struct Properties {\n\n /// Enumeration of possible message initializations\n\n DAI_ENUM(InitType,UNIFORM,RANDOM);\n\n\n\n /// Enumeration of possible update types\n\n DAI_ENUM(UpdateType,NAIVE,HARDSPIN);\n\n\n\n /// Verbosity (amount of output sent to stderr)\n\n size_t verbose;\n", "file_path": "dai/upstream/include/dai/mf.h", "rank": 14, "score": 176141.6975647723 }, { "content": "class CBP : public DAIAlgFG {\n\n private:\n\n /// Variable beliefs\n\n std::vector<Factor> _beliefsV;\n\n /// Factor beliefs\n\n std::vector<Factor> _beliefsF;\n\n /// Logarithm of partition sum\n\n Real _logZ;\n\n\n\n /// Numer of iterations needed\n\n size_t _iters;\n\n /// Maximum difference encountered so far\n\n Real _maxdiff;\n\n\n\n /// Number of clampings at each leaf node\n\n Real _sum_level;\n\n /// Number of leaves of recursion tree\n\n size_t _num_leaves;\n\n\n\n /// Output stream where information about the clampings is written\n", "file_path": "dai/upstream/include/dai/cbp.h", "rank": 15, "score": 176141.6975647723 }, { "content": "class MR : public DAIAlgFG {\n\n private:\n\n /// Is the underlying factor graph supported?\n\n bool supported;\n\n\n\n /// The interaction graph (Markov graph)\n\n GraphAL G;\n\n\n\n /// tJ[i][_j] is the hyperbolic tangent of the interaction between spin \\a i and its neighbour G.nb(i,_j)\n\n std::vector<std::vector<Real> > tJ;\n\n /// theta[i] is the local field on spin \\a i\n\n std::vector<Real> theta;\n\n\n\n /// M[i][_j] is \\f$ M^{(i)}_j \\f$\n\n std::vector<std::vector<Real> > M;\n\n /// Cavity correlations\n\n std::vector<std::vector<std::vector<Real> > > cors;\n\n\n\n /// Type used for managing a subset of neighbors\n\n typedef boost::dynamic_bitset<> sub_nb;\n", "file_path": "dai/upstream/include/dai/mr.h", "rank": 16, "score": 176141.6975647723 }, { "content": "class Gibbs : public DAIAlgFG {\n\n private:\n\n /// Type used to store the counts of various states\n\n typedef std::vector<size_t> _count_t;\n\n /// Type used to store the joint state of all variables\n\n typedef std::vector<size_t> _state_t;\n\n /// Number of samples counted so far (excluding burn-in periods)\n\n size_t _sample_count;\n\n /// State counts for each variable\n\n std::vector<_count_t> _var_counts;\n\n /// State counts for each factor\n\n std::vector<_count_t> _factor_counts;\n\n /// Number of iterations done (including burn-in periods)\n\n size_t _iters;\n\n /// Current joint state of all variables\n\n _state_t _state;\n\n /// Joint state with maximum probability seen so far\n\n _state_t _max_state;\n\n /// Highest score so far\n\n Real _max_score;\n", "file_path": "dai/upstream/include/dai/gibbs.h", "rank": 17, "score": 176141.6975647723 }, { "content": "class GLC : public DAIAlgCG {\n\n private:\n\n /// Stores for each variable the approximate cavity distribution\n\n std::vector<Cobweb> _CWs;\n\n\n\n /// Gives the starting global index for the factors of outgoing messages of each region\n\n std::vector<int> _outOffset; \n\n\n\n /// Cavity distributions\n\n /** For each region it contains:\n\n * - Nothing if using UniCAV\n\n * - One Factor if using FullCAV\n\n * - All pairwise caivity factors if using PairCAV or Pair2CAV\n\n */\n\n std::vector<std::vector<Factor> > _cavitydists;\n\n\n\n /// Single variable beliefs\n\n std::vector<Factor> _beliefs;\n\n\n\n /// Beliefs over factors\n", "file_path": "dai/upstream/include/dai/glc.h", "rank": 18, "score": 176141.6975647723 }, { "content": "class RegionGraph : public FactorGraph {\n\n protected:\n\n /// Stores the neighborhood structure\n\n BipartiteGraph _G;\n\n\n\n /// The outer regions (corresponding to nodes of type 1)\n\n std::vector<FRegion> _ORs;\n\n\n\n /// The inner regions (corresponding to nodes of type 2)\n\n std::vector<Region> _IRs;\n\n\n\n /// Stores for each factor index the index of the outer region it belongs to\n\n std::vector<size_t> _fac2OR;\n\n\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor\n\n RegionGraph() : FactorGraph(), _G(), _ORs(), _IRs(), _fac2OR() {}\n", "file_path": "dai/upstream/include/dai/regiongraph.h", "rank": 19, "score": 176141.6975647723 }, { "content": "class CobwebGraph : public FactorGraph {\n\n protected:\n\n /// Vector of variable indices internal to each region (r)\n\n std::vector<SmallSet<size_t> > _INRs;\n\n /// Vector of variable indices on the boundary of each region (\\ominus r)\n\n std::vector<SmallSet<size_t> > _EXRs;\n\n /// Index of factors in each region\n\n std::vector<SmallSet<size_t> > _Rfs;\n\n /// Index of factors internal to each region, i.e., all its variables are internal to the region\n\n std::vector<SmallSet<size_t> > _Rifs;\n\n /// Index of factors that bridge each region, i.e., not all its variables are internal to the region\n\n std::vector<SmallSet<size_t> > _Rxfs;\n\n /// The vector of domain of messages leaving each region (\\ominus r_{p,q})\n\n std::vector<std::vector<VarSet> > _outM;\n\n\n\n /// The information in connection between two regions\n\n struct Connection {\n\n /// Index of the first region (p)\n\n size_t my;\n\n /// Index of the second region (q)\n", "file_path": "dai/upstream/include/dai/cobwebgraph.h", "rank": 20, "score": 176141.6975647723 }, { "content": "/// `IPOPTForCPD` is the base class to implement derivatives objects for Ipopt.\n\n/// It is used internally by `CPDLinearAligner`.\n\nclass IPOPTForCPD : public Ipopt::TNLP {\n\n public:\n\n double s;\n\n double rho;\n\n double kappa;\n\n double sigmaSquare;\n\n CPDLinearAlignerDerivatives gradAndHessAndFunc;\n\n McDVector<double> resultValues;\n\n};\n\n\n\n} // namespace mtalign\n", "file_path": "hxalignmicrotubules/mtalign/IPOPTForCPD.h", "rank": 21, "score": 174853.40658586973 }, { "content": "class DecMAP : public DAIAlgFG {\n\n private:\n\n /// Stores the final MAP state\n\n std::vector<size_t> _state;\n\n /// Stores the log probability of the MAP state\n\n Real _logp;\n\n /// Maximum difference encountered so far\n\n Real _maxdiff;\n\n /// Number of iterations needed\n\n size_t _iters;\n\n\n\n public:\n\n /// Parameters for DecMAP\n\n struct Properties {\n\n /// Verbosity (amount of output sent to stderr)\n\n size_t verbose;\n\n\n\n /// Complete or partial reinitialization of clamped subgraphs?\n\n bool reinit;\n\n\n", "file_path": "dai/upstream/include/dai/decmap.h", "rank": 23, "score": 173034.803227561 }, { "content": "/// `NullPointRepresentation` is used internally by the `matching*()`\n\n/// functions.\n\nclass NullPointRepresentation : public PointRepresentation {\n\n protected:\n\n virtual ~NullPointRepresentation();\n\n\n\n private:\n\n virtual int getNumPoints() const;\n\n\n\n virtual void\n\n computeTransformation(const PointRepresentation* pointRep2,\n\n const PointMatchingDataStruct* pointMatching,\n\n Transformation* pointRep2Transform) const;\n\n\n\n virtual void\n\n setScoreDivisor(const PointRepresentation* pointRep2,\n\n PointMatchingScoringFunction* scoringFunction) const;\n\n\n\n virtual CacheObject* startGreedyPointMatching(\n\n const PointRepresentation* pointRep2,\n\n const Transformation* pointRep2StartTransform) const;\n\n\n", "file_path": "hxalignmicrotubules/mtalign/NullPointRepresentation.h", "rank": 24, "score": 172877.12442859582 }, { "content": "// Derive from CPDLinearAligner to access protected members\n\n// in tests. `this->` is used below to make the access explicit.\n\nclass mtalign__CPDLinearAlignerTest : public ::testing::Test,\n\n public ma::CPDLinearAligner {\n\n\n\n protected:\n\n void initCPDdata1NoDir() {\n\n\n\n this->params.withScaling = true;\n\n this->params.usePositions = true;\n\n this->params.useDirections = false;\n\n // create data\n\n\n\n McDArray<McVec3f> xc, xd, yc, yd;\n\n McDArray<McVec3f> tempD;\n\n McDArray<double> xz, yz;\n\n xc.append(McVec3f(0, 0, 0));\n\n xc.append(McVec3f(0, 1, 0));\n\n xc.append(McVec3f(1, 0, 0));\n\n tempD.append(McVec3f(0, 0, 0));\n\n tempD.append(McVec3f(0, 0, 0));\n\n tempD.append(McVec3f(0, 0, 0));\n", "file_path": "hxalignmicrotubules/mtalign/CPDLinearAlignerTest.cpp", "rank": 25, "score": 170177.27358537156 }, { "content": "class VarSet : public SmallSet<Var> {\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor (constructs an empty set)\n\n VarSet() : SmallSet<Var>() {}\n\n\n\n /// Construct from \\link SmallSet \\endlink<\\link Var \\endlink> \\a x\n\n VarSet( const SmallSet<Var> &x ) : SmallSet<Var>(x) {}\n\n\n\n /// Construct a VarSet with one element, \\a v\n\n VarSet( const Var &v ) : SmallSet<Var>(v) {}\n\n\n\n /// Construct a VarSet with two elements, \\a v1 and \\a v2\n\n VarSet( const Var &v1, const Var &v2 ) : SmallSet<Var>(v1,v2) {}\n\n\n\n /// Construct a VarSet from the range between \\a begin and \\a end.\n\n /** \\tparam VarIterator Iterates over instances of type Var.\n\n * \\param begin Points to first Var to be added.\n\n * \\param end Points just beyond last Var to be added.\n", "file_path": "dai/upstream/include/dai/varset.h", "rank": 26, "score": 168647.77756097063 }, { "content": "class Repr : public ma::NullPointRepresentation {\n\n public:\n\n Repr(const McDArray<McVec3f>& positions,\n\n const McDArray<McVec3f>& directions, const double cliqueDistThreshold,\n\n const double maxAngleDistForInitMatching)\n\n : mCoords(positions), mDirections(directions) {\n\n mCliqueDistThreshold = cliqueDistThreshold;\n\n mMaxAngleDistForInitMatching = maxAngleDistForInitMatching;\n\n distMatrix = computeDistMatrix(positions);\n\n }\n\n\n\n private:\n\n virtual int getNumPoints() const;\n\n\n\n const McDArray<McVec3f>& getDirections() const;\n\n\n\n virtual const McDArray<McVec3f>& getCoords() const;\n\n\n\n virtual void\n\n computeCorrespondenceGraphVertices(const PointRepresentation* pointSet2,\n", "file_path": "hxalignmicrotubules/mtalign/matchingClique.cpp", "rank": 27, "score": 168490.09876200545 }, { "content": "/// Predefined cost functions that can be used with BBP\n\nclass BBPCostFunction : public BBPCostFunctionBase {\n\n public:\n\n /// Default constructor\n\n BBPCostFunction() : BBPCostFunctionBase() {}\n\n\n\n /// Construct from BBPCostFunctionBase \\a x\n\n BBPCostFunction( const BBPCostFunctionBase &x ) : BBPCostFunctionBase(x) {}\n\n\n\n /// Returns whether this cost function depends on having a Gibbs state\n\n bool needGibbsState() const;\n\n\n\n /// Evaluates cost function in state \\a stateP using the information in inference algorithm \\a ia\n\n Real evaluate( const InfAlg &ia, const std::vector<size_t> *stateP ) const;\n\n\n\n /// Assignment operator\n\n BBPCostFunction& operator=( const BBPCostFunctionBase &x ) {\n\n BBPCostFunctionBase::operator=( x );\n\n return *this;\n\n }\n\n};\n\n\n\n\n\n/// Implements BBP (Back-Belief-Propagation) [\\ref EaG09]\n\n/** \\author Frederik Eaton\n\n */\n", "file_path": "dai/upstream/include/dai/bbp.h", "rank": 28, "score": 167235.74718069402 }, { "content": "class DAI_API BP : public DAIAlgFG {\n\n protected:\n\n /// Type used for index cache\n\n typedef std::vector<size_t> ind_t;\n\n /// Type used for storing edge properties\n\n struct EdgeProp {\n\n /// Index cached for this edge\n\n ind_t index;\n\n /// Old message living on this edge\n\n Prob message;\n\n /// New message living on this edge\n\n Prob newMessage;\n\n /// Residual for this edge\n\n Real residual;\n\n };\n\n /// Stores all edge properties\n\n std::vector<std::vector<EdgeProp> > _edges;\n\n /// Type of lookup table (only used for maximum-residual BP)\n\n typedef std::multimap<Real, std::pair<std::size_t, std::size_t> > LutType;\n\n /// Lookup table (only used for maximum-residual BP)\n", "file_path": "dai/upstream/include/dai/bp.h", "rank": 29, "score": 165682.27307058778 }, { "content": "class RefRepr : public ma::NullPointRepresentation {\n\n public:\n\n RefRepr(int nRef, int nTrans, const ma::PGMPairWeights& weightComputation)\n\n : mNRef(nRef), mNTrans(nTrans), mWeightComputation(weightComputation) {}\n\n\n\n private:\n\n virtual int getNumPoints() const { return mNRef; }\n\n\n\n virtual void\n\n setScoreDivisor(const PointRepresentation* pointSet2,\n\n PointMatchingScoringFunction* scoringFunction) const {\n\n scoringFunction->setScoreDivisor(mNRef, mNTrans);\n\n }\n\n\n\n virtual CacheObject*\n\n startExactPointMatching(const PointRepresentation* pointRep2,\n\n const Transformation* pointRep2Transform) const {\n\n return 0;\n\n }\n\n\n", "file_path": "hxalignmicrotubules/mtalign/matchingExact.cpp", "rank": 31, "score": 165528.1821279856 }, { "content": "class TransRepr : public ma::NullPointRepresentation {\n\n public:\n\n TransRepr(int n) : mN(n) {}\n\n\n\n private:\n\n virtual int getNumPoints() const { return mN; }\n\n\n\n int mN;\n\n};\n\n\n\n} // namespace\n\n\n\nstatic McDArray<McDArray<double> >\n\nmakeEdgeWeight(const ma::FacingPointSets& pts,\n\n const ma::PGMPairWeights& weightComputer) {\n\n McDArray<McDArray<double> > edgeWeights;\n\n for (int i = 0; i < pts.ref.positions.size(); i++) {\n\n McDArray<double> weights;\n\n for (int j = 0; j < pts.trans.positions.size(); j++) {\n\n weights.append(1.0 - weightComputer.getWeight(i, j));\n", "file_path": "hxalignmicrotubules/mtalign/matchingExact.cpp", "rank": 33, "score": 165528.1821279856 }, { "content": "class DAI_API ExactInf : public DAIAlgFG {\n\n public:\n\n /// Parameters for ExactInf\n\n struct Properties {\n\n /// Verbosity (amount of output sent to stderr)\n\n size_t verbose;\n\n } props;\n\n\n\n private:\n\n /// All single variable marginals\n\n std::vector<Factor> _beliefsV;\n\n /// All factor variable marginals\n\n std::vector<Factor> _beliefsF;\n\n /// Logarithm of partition sum\n\n Real _logZ;\n\n\n\n public:\n\n /// \\name Constructors/destructors\n\n //@{\n\n /// Default constructor\n", "file_path": "dai/upstream/include/dai/exactinf.h", "rank": 34, "score": 162848.72151410364 }, { "content": "class RootedTree : public std::vector<DEdge> {\n\n public:\n\n /// Default constructor\n\n RootedTree() {}\n\n\n\n /// Constructs a rooted tree from a tree and a root\n\n /** \\pre T has no cycles and contains node \\a Root\n\n */\n\n RootedTree( const GraphEL &T, size_t Root );\n\n};\n\n\n\n\n\n/// Constructs a minimum spanning tree from the (non-negatively) weighted graph \\a G.\n\n/** \\param G Weighted graph that should have non-negative weights.\n\n * \\param usePrim If true, use Prim's algorithm (complexity O(E log(V))), otherwise, use Kruskal's algorithm (complexity O(E log(E))).\n\n * \\note Uses implementation from Boost Graph Library.\n\n * \\note The vertices of \\a G must be in the range [0,N) where N is the number of vertices of \\a G.\n\n */\n\ntemplate<typename T> RootedTree MinSpanningTree( const WeightedGraph<T> &G, bool usePrim ) {\n\n RootedTree result;\n", "file_path": "dai/upstream/include/dai/weightedgraph.h", "rank": 35, "score": 162112.58952990803 }, { "content": "class DAI_API Exception : public std::runtime_error {\n\n public:\n\n /// Enumeration of exceptions used in libDAI\n\n enum Code {NOT_IMPLEMENTED,\n\n ASSERTION_FAILED,\n\n IMPOSSIBLE_TYPECAST,\n\n OBJECT_NOT_FOUND,\n\n BELIEF_NOT_AVAILABLE,\n\n UNKNOWN_ENUM_VALUE,\n\n UNKNOWN_DAI_ALGORITHM,\n\n UNKNOWN_PARAMETER_ESTIMATION_METHOD,\n\n UNKNOWN_PROPERTY_TYPE,\n\n UNKNOWN_PROPERTY,\n\n MALFORMED_PROPERTY,\n\n NOT_ALL_PROPERTIES_SPECIFIED,\n\n INVALID_ALIAS,\n\n CANNOT_READ_FILE,\n\n CANNOT_WRITE_FILE,\n\n INVALID_FACTORGRAPH_FILE,\n\n INVALID_EVIDENCE_FILE,\n", "file_path": "dai/upstream/include/dai/exceptions.h", "rank": 36, "score": 162112.58952990803 }, { "content": "/// Represents an undirected graph, implemented as a std::set of undirected edges\n\nclass GraphEL : public std::set<UEdge> {\n\n public:\n\n /// Default constructor\n\n GraphEL() {}\n\n\n\n /// Construct from range of objects that can be cast to UEdge\n\n template <class InputIterator>\n\n GraphEL( InputIterator begin, InputIterator end ) {\n\n insert( begin, end );\n\n }\n\n\n\n /// Construct from GraphAL\n\n GraphEL( const GraphAL& G ) {\n\n for( size_t n1 = 0; n1 < G.nrNodes(); n1++ )\n\n bforeach( const Neighbor n2, G.nb(n1) )\n\n if( n1 < n2 )\n\n insert( UEdge( n1, n2 ) );\n\n }\n\n};\n\n\n\n\n\n/// Represents an undirected weighted graph, with weights of type \\a T, implemented as a std::map mapping undirected edges to weights\n\ntemplate<class T> class WeightedGraph : public std::map<UEdge, T> {};\n\n\n\n\n\n/// Represents a rooted tree, implemented as a vector of directed edges\n\n/** By convention, the edges are stored such that they point away from \n\n * the root and such that edges nearer to the root come before edges\n\n * farther away from the root.\n\n */\n", "file_path": "dai/upstream/include/dai/weightedgraph.h", "rank": 37, "score": 162112.58952990803 }, { "content": " class hash_map : public std::tr1::unordered_map<T,U,H> {};\n\n\n\n\n\n/// Returns wall clock time in seconds\n\ndouble toc();\n\n\n\n\n\n/// Returns absolute value of \\a t\n\ntemplate<class T>\n\ninline T abs( const T &t ) {\n\n return (t < 0) ? (-t) : t;\n\n}\n\n\n\n\n\n/// Sets the random seed\n\nvoid rnd_seed( size_t seed );\n\n\n\n/// Returns a real number, distributed uniformly on [0,1)\n\nReal rnd_uniform();\n\n\n", "file_path": "dai/upstream/include/dai/util.h", "rank": 38, "score": 146383.81035295257 }, { "content": "namespace mtalign {\n\n\n\nstruct FacingPointSets;\n\nstruct Matching;\n\n\n\n/// `fitTransform()` fits an transform as specified by `TransformType` that\n\n/// transforms the second `trans` set onto the first `ref` set of\n\n/// `FacingPointSets` assuming the correspondences in `Matching`.\n\nMcMat4f fitTransform(const FacingPointSets& pts, const Matching& matching,\n\n TransformType tfType);\n\n\n\n/// `fitTransformRigid()` fits a transform that is either completely rigid or\n\n/// rigid + iso-scale as specified by `TransformType`.\n\nMcMat4f fitTransformRigid(const FacingPointSets& pts, const Matching& matching,\n\n TransformType tfType);\n\n\n\n/// `fitTransformAffine()` fits an affine transform.\n\nMcMat4f fitTransformAffine(const FacingPointSets& pts,\n\n const Matching& matching);\n\n\n", "file_path": "hxalignmicrotubules/mtalign/fitTransform.h", "rank": 39, "score": 140198.87346856957 }, { "content": "/// `WriteMatchingProperties2` might be useful to understand the factor values\n\n/// for matching microtubule endpoints as implemented by\n\n/// `mtalign::PGMPairWeights`\n\n/// Use it for example on `data/spatialgraph/small3SlicesWithWarp.am`.\n\nclass WriteMatchingProperties2 : public HxCompModule {\n\n\n\n HX_HEADER(WriteMatchingProperties2);\n\n\n\n public:\n\n\n\n HxPortFloatTextN portDistanceThreshold;\n\n HxPortFloatTextN portProjectedDistanceThreshold;\n\n HxPortFloatTextN portAngleThreshold;\n\n HxPortDoIt portAction;\n\n\n\n virtual void compute();\n\n\n\n private:\n\n mtalign::SliceSelector* mSelectionHelper;\n\n\n\n int getMatchedVertex(const int vertex);\n\n\n\n SpreadSheetWrapper* getResultSpreadSheet(const std::string& outputName);\n\n\n", "file_path": "hxalignmicrotubules/attic/WriteMatchingProperties2.h", "rank": 40, "score": 128186.62736836182 }, { "content": "class MicrotubuleSpatialGraphAligner : public McHandable {\n\n struct AlignmentResults {\n\n float duration_s;\n\n float score;\n\n McDArray<int> matchedRefPointIds;\n\n McDArray<int> matchedTransPointIds;\n\n SpatialGraphSelection refVertexSelection;\n\n SpatialGraphSelection transVertexSelection;\n\n };\n\n\n\n public:\n\n MicrotubuleSpatialGraphAligner(HxSpatialGraph* graph);\n\n ~MicrotubuleSpatialGraphAligner();\n\n\n\n /// Return a list of attribute names which can be used for alignment.\n\n McDArray<McString> getPossibleAlignmentAttributeNames() const;\n\n\n\n /// Return a list of projection types which can be used for alignment.\n\n static McDArray<McString> getPossiblePointMatchingAlgorithms();\n\n\n", "file_path": "hxalignmicrotubules/MicrotubuleSpatialGraphAligner.h", "rank": 41, "score": 128181.5534192048 }, { "content": "class mtalign__projectTestWithTestingData\n\n : public ::testing::TestWithParam<Expectation> {};\n\n\n\n} // namespace\n\n\n\nstatic void expectSha1(const McDArray<McVec3f>& arr, const char* sha1) {\n\n int dims[3];\n\n dims[0] = 3; // 3 floats per element.\n\n dims[1] = arr.size();\n\n dims[2] = 1;\n\n EXPECT_THAT(&arr[0][0], ht::EqArray3Sha1<float>(dims, sha1));\n\n}\n\n\n\nTEST_P(mtalign__projectTestWithTestingData, computesBaseline_E6MS) {\n\n TestingDevNullRedirect silentout(stdout);\n\n TestingDevNullRedirect silenterr(stderr);\n\n Expectation e = GetParam();\n\n\n\n TestingObjectPoolCleaner cleaner;\n\n TestingData sgdat(e.filename);\n", "file_path": "hxalignmicrotubules/mtalign/projectTest.cpp", "rank": 42, "score": 126427.20348743426 }, { "content": "class QString;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/Context.h", "rank": 43, "score": 126324.26440409268 }, { "content": "class Permute {\n\n private:\n\n /// Stores the number of possible values of all indices\n\n std::vector<size_t> _ranges;\n\n /// Stores the permutation\n\n std::vector<size_t> _sigma;\n\n\n\n public:\n\n /// Default constructor\n\n Permute() : _ranges(), _sigma() {}\n\n\n\n /// Construct from vector of index ranges and permutation\n\n Permute( const std::vector<size_t> &rs, const std::vector<size_t> &sigma ) : _ranges(rs), _sigma(sigma) {\n\n DAI_ASSERT( _ranges.size() == _sigma.size() );\n\n }\n\n\n\n /// Construct from vector of variables.\n\n /** The implied permutation maps the index of each variable in \\a vars according to the canonical ordering \n\n * (i.e., sorted ascendingly according to their label) to the index it has in \\a vars.\n\n * If \\a reverse == \\c true, reverses the indexing in \\a vars first.\n", "file_path": "dai/upstream/include/dai/index.h", "rank": 44, "score": 123858.46098991299 }, { "content": "class State {\n\n private:\n\n /// Type for representing a joint state of some variables as a map, which maps each variable to its state\n\n typedef std::map<Var, size_t> states_type;\n\n\n\n /// Current state (represented linearly)\n\n BigInt state;\n\n\n\n /// Current state (represented as a map)\n\n states_type states;\n\n\n\n public:\n\n /// Default constructor\n\n State() : state(0), states() {}\n\n\n\n /// Construct from VarSet \\a vs and corresponding linear state \\a linearState\n\n State( const VarSet &vs, BigInt linearState=0 ) : state(linearState), states() {\n\n if( linearState == 0 )\n\n for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ )\n\n states[*v] = 0;\n", "file_path": "dai/upstream/include/dai/index.h", "rank": 45, "score": 123858.46098991299 }, { "content": "class DAG {\n\n private:\n\n /// Contains for each node a vector of its parent nodes\n\n std::vector<Neighbors> _pa;\n\n \n\n /// Contains for each node a vector of its children nodes\n\n std::vector<Neighbors> _ch;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor (creates an empty DAG).\n\n DAG() : _pa(), _ch() {}\n\n\n\n /// Constructs DAG with \\a nr nodes and no edges.\n\n DAG( size_t nr ) : _pa( nr ), _ch( nr ) {}\n\n\n\n /// Constructs DAG from a range of edges.\n\n /** \\tparam EdgeInputIterator Iterator that iterates over instances of Edge.\n\n * \\param nr The number of nodes.\n", "file_path": "dai/upstream/include/dai/dag.h", "rank": 46, "score": 123858.46098991299 }, { "content": "class BBP {\n\n private:\n\n /// \\name Input variables\n\n //@{\n\n /// Stores a BP_dual helper object\n\n BP_dual _bp_dual;\n\n /// Pointer to the factor graph\n\n const FactorGraph *_fg;\n\n /// Pointer to the approximate inference algorithm (currently, only BP objects are supported)\n\n const InfAlg *_ia;\n\n //@}\n\n\n\n /// \\name Output variables\n\n //@{\n\n /// Variable factor adjoints\n\n std::vector<Prob> _adj_psi_V;\n\n /// Factor adjoints\n\n std::vector<Prob> _adj_psi_F;\n\n /// Variable->factor message adjoints (indexed [i][_I])\n\n std::vector<std::vector<Prob> > _adj_n;\n", "file_path": "dai/upstream/include/dai/bbp.h", "rank": 47, "score": 123858.46098991299 }, { "content": "class multifor {\n\n private:\n\n /// Stores the number of possible values of all indices\n\n std::vector<size_t> _ranges;\n\n /// Stores the current values of all indices\n\n std::vector<size_t> _indices;\n\n /// Stores the current linear index\n\n long _linear_index;\n\n\n\n public:\n\n /// Default constructor\n\n multifor() : _ranges(), _indices(), _linear_index(0) {}\n\n\n\n /// Initialize from vector of index ranges\n\n multifor( const std::vector<size_t> &d ) : _ranges(d), _indices(d.size(),0), _linear_index(0) {}\n\n\n\n /// Returns linear index (i.e., the index in the Cartesian product space)\n\n operator size_t() const {\n\n DAI_DEBASSERT( valid() );\n\n return( _linear_index );\n", "file_path": "dai/upstream/include/dai/index.h", "rank": 48, "score": 123858.46098991299 }, { "content": "class Var {\n\n private:\n\n /// Label of the variable (its unique ID)\n\n size_t _label;\n\n\n\n /// Number of possible values\n\n size_t _states;\n\n\n\n public:\n\n /// Default constructor (creates a variable with label 0 and 0 states)\n\n Var() : _label(0), _states(0) {}\n\n /// Constructs a variable with a given label and number of states\n\n Var( size_t label, size_t states ) : _label(label), _states(states) {}\n\n\n\n /// Returns the label\n\n size_t label() const { return _label; }\n\n /// Returns reference to label\n\n size_t& label() { return _label; }\n\n\n\n /// Returns the number of states\n", "file_path": "dai/upstream/include/dai/var.h", "rank": 49, "score": 123858.46098991299 }, { "content": "class Evidence {\n\n public:\n\n /// Stores joint state of a set of variables\n\n typedef std::map<Var, size_t> Observation;\n\n\n\n private:\n\n /// Each sample is an observed joint state of some variables\n\n std::vector<Observation> _samples;\n\n\n\n public:\n\n /// Default constructor\n\n Evidence() : _samples() {}\n\n\n\n /// Construct from \\a samples\n\n Evidence( std::vector<Observation> &samples ) : _samples(samples) {}\n\n\n\n /// Read in tabular data from a stream and add the read samples to \\c *this.\n\n /** \\param is Input stream in .tab file format, describing joint observations of variables in \\a fg\n\n * \\param fg Factor graph describing the corresponding variables\n\n * \\see \\ref fileformats-evidence\n", "file_path": "dai/upstream/include/dai/evidence.h", "rank": 50, "score": 123858.46098991299 }, { "content": "class IndexFor {\n\n private:\n\n /// The current linear index corresponding to the state of indexVars\n\n long _index;\n\n\n\n /// For each variable in forVars, the amount of change in _index\n\n std::vector<long> _sum;\n\n\n\n /// For each variable in forVars, the current state\n\n std::vector<size_t> _state;\n\n\n\n /// For each variable in forVars, its number of possible values\n\n std::vector<size_t> _ranges;\n\n\n\n public:\n\n /// Default constructor\n\n IndexFor() : _index(-1) {}\n\n\n\n /// Construct IndexFor object from \\a indexVars and \\a forVars\n\n IndexFor( const VarSet& indexVars, const VarSet& forVars ) : _state( forVars.size(), 0 ) {\n", "file_path": "dai/upstream/include/dai/index.h", "rank": 51, "score": 123858.46098991299 }, { "content": "class Cobweb {\n\n public:\n\n /// Pointer to the approximate inference algorithm and factor graph over region R (provided in parameters of GLC)\n\n DAIAlgFG *cav;\n\n\n\n /// Global to local factor index conversion.\n\n /** Factor(I) in original graph corresponds to cav->factor(_g2l[I]) in this region\n\n * the j'th incoming message to this region M(R,j) corresponds to cav->factor(_g2l[-j-1])\n\n * the j'th cavity factor (for pairwise case),_cavitydists[R][j] corresponds to cav->factor(_g2l[-m-j-1])\n\n * when m = M(R).size()\n\n * note that for full cavity the _cavitydists[R] has a single factor and for uniform cavity it is empty\n\n * the j'th outgoing message from this region outM(R,j) corresponds to cav->factor(_g2l[-c-m-j-1])\n\n * when m = M(R).size() and c = _cavitydists[R].size()\n\n */\n\n std::map<int, size_t> _g2l;\n\n\n\n /// Default constructor\n\n Cobweb(){}\n\n\n\n /// Construct from global-to-local factor index conversion structure\n", "file_path": "dai/upstream/include/dai/glc.h", "rank": 52, "score": 123858.46098991299 }, { "content": "/// `SliceSelector` partitions a spatial graph into slices based on an\n\n/// attribute and provides functions to compute properties of the slices.\n\n///\n\n/// The attribute is expected to fulfill `isOrderedAttribute()`, that is nodes\n\n/// are grouped by attribute value if visited in index order. Slices indexes\n\n/// start at 0. Slices consist of vertices and complete edges. `getSlice()`\n\n/// will never select individual points.\n\nclass SliceSelector {\n\n public:\n\n /// `SliceSelector()` initializes an invalid object.\n\n SliceSelector();\n\n\n\n /// `SliceSelector()` computes the two-way mapping from attribute values to\n\n /// slice indices. The `graph` must remain valid as long as the\n\n /// `SliceSelector` instance is used.\n\n SliceSelector(const HxSpatialGraph* graph, std::string sliceAttributeName);\n\n\n\n /// `isOrderedAttribute()` tests whether values of the node int attribute\n\n /// are grouped when nodes are visited in index order. The attribute\n\n /// `TransformInfo` on a spatial graph stack fulfills this property.\n\n static bool isOrderedAttribute(const HxSpatialGraph* sg,\n\n const char* attrName);\n\n\n\n /// `getNumSlices()` does what it suggests.\n\n int getNumSlices() const;\n\n\n\n /// `getSliceAttributeValueFromIndex()` returns the attribute value that\n", "file_path": "hxalignmicrotubules/mtalign/SliceSelector.h", "rank": 53, "score": 123680.00650305302 }, { "content": "class HxSpatialGraph;\n", "file_path": "hxalignmicrotubules/mtalign/project.h", "rank": 54, "score": 123680.00650305302 }, { "content": "/// `PGMMatcher` is used internally by `matchingPGM()` to implement PGM\n\n/// inference using libdai.\n\nclass PGMMatcher {\n\n public:\n\n PGMMatcher(const McDArray<McVec3f>& coords1,\n\n const McDArray<McVec3f>& coords2,\n\n const McDArray<McVec3f>& directions1,\n\n const McDArray<McVec3f>& directions2,\n\n const McDArray<McVec2i>& evidence,\n\n PGMPairWeights& weightComputationFunction,\n\n double shiftProbParam);\n\n\n\n /// `setContext()` configures the run-time environment.\n\n void setContext(Context* ctx);\n\n\n\n void createConnectionFactors(const McDMatrix<int>& adjMat,\n\n const McDArray<int> connectedComps,\n\n std::vector<dai::Factor>& pairFactorList);\n\n void createSingletonFactors(const McDArray<int>& connectedComp,\n\n std::vector<dai::Factor>& singletonFactorList);\n\n\n\n static void\n", "file_path": "hxalignmicrotubules/mtalign/PGMMatcher.h", "rank": 55, "score": 123680.00650305302 }, { "content": "class McVec2i;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/matchingPGM.h", "rank": 56, "score": 123680.00650305302 }, { "content": "class SpatialGraphSelection;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/project.h", "rank": 57, "score": 123680.00650305302 }, { "content": "class HxCPDAlignerExample : public HxCompModule {\n\n HX_HEADER(HxCPDAlignerExample);\n\n public:\n\n\n\n HxPortDoIt portAction;\n\n\n\n void compute();\n\n};\n\n\n\nHX_INIT_CLASS(HxCPDAlignerExample, HxCompModule);\n\n\n\nHxCPDAlignerExample::HxCPDAlignerExample()\n\n : HxCompModule(HxSpatialGraph::getClassTypeId()),\n\n portAction(this, \"action\", tr(\"Action\"), 1) {}\n\n\n\n// `printMsg` prints to stdout and to the Amira console.\n\nstatic void printMsg(QString msg) {\n\n printf(\"%s\\n\", qPrintable(msg));\n\n theMsg->printf(msg);\n\n theApp->handlePendingEvents();\n", "file_path": "hxalignmicrotubules/examples/HxCPDAlignerExample.cpp", "rank": 58, "score": 122719.68229640178 }, { "content": "class HXALIGNMICROTUBULES_API SpreadSheetWrapper : public HxSpreadSheet {\n\n\n\n HX_HEADER(SpreadSheetWrapper);\n\n\n\n public:\n", "file_path": "hxalignmicrotubules/SpreadSheetWrapper.h", "rank": 59, "score": 121892.89366700777 }, { "content": "/// Represents a directed edge\n\nclass DEdge {\n\n public:\n\n /// First node index (source of edge)\n\n size_t first;\n\n\n\n /// Second node index (target of edge)\n\n size_t second;\n\n\n\n /// Default constructor\n\n DEdge() : first(0), second(0) {}\n\n\n\n /// Constructs a directed edge pointing from \\a m1 to \\a m2\n\n DEdge( size_t m1, size_t m2 ) : first(m1), second(m2) {}\n\n\n\n /// Tests for equality\n\n bool operator==( const DEdge &x ) const { return ((first == x.first) && (second == x.second)); }\n\n\n\n /// Smaller-than operator (performs lexicographical comparison)\n\n bool operator<( const DEdge &x ) const {\n\n return( (first < x.first) || ((first == x.first) && (second < x.second)) );\n\n }\n\n\n\n /// Writes a directed edge to an output stream\n\n friend std::ostream & operator << (std::ostream & os, const DEdge & e) {\n\n os << \"(\" << e.first << \"->\" << e.second << \")\";\n\n return os;\n\n }\n\n};\n\n\n\n\n", "file_path": "dai/upstream/include/dai/weightedgraph.h", "rank": 60, "score": 121351.26738272737 }, { "content": "// Predefine for definitions of calcLinearState() and calcState()\n\nclass VarSet;\n\n\n\n\n\n/// Calculates the linear index in the Cartesian product of the variables in \\a vs that corresponds to a particular joint assignment of the variables, specified by \\a state.\n\n/** \\param vs Set of variables for which the linear state should be calculated;\n\n * \\param state Specifies the states of some variables.\n\n * \\return The linear index in the Cartesian product of the variables in \\a vs\n\n * corresponding with the joint assignment specified by \\a state, where variables\n\n * for which no state is specified are assumed to be in state 0.\n\n *\n\n * The linear index is calculated as follows. The variables in \\a vs are\n\n * ordered according to their label (in ascending order); say \\a vs corresponds with\n\n * the set \\f$\\{x_{l(0)},x_{l(1)},\\dots,x_{l(n-1)}\\}\\f$ with \\f$l(0) < l(1) < \\dots < l(n-1)\\f$,\n\n * where variable \\f$x_l\\f$ has label \\a l. Denote by \\f$S_l\\f$ the number of possible values\n\n * (\"states\") of variable \\f$x_l\\f$. The argument \\a state corresponds\n\n * with a mapping \\a s that assigns to each variable \\f$x_l\\f$ a state \\f$s(x_l) \\in \\{0,1,\\dots,S_l-1\\}\\f$,\n\n * where \\f$s(x_l)=0\\f$ if \\f$x_l\\f$ is not specified in \\a state. The linear index \\f$S\\f$ corresponding\n\n * with \\a state is now calculated by:\n\n * \\f{eqnarray*}\n\n * S &:=& \\sum_{i=0}^{n-1} s(x_{l(i)}) \\prod_{j=0}^{i-1} S_{l(j)} \\\\\n", "file_path": "dai/upstream/include/dai/varset.h", "rank": 61, "score": 121345.40553166803 }, { "content": "class ParameterEstimation {\n\n public:\n\n /// Type of pointer to factory function.\n\n typedef ParameterEstimation* (*ParamEstFactory)( const PropertySet& );\n\n\n\n /// Virtual destructor for deleting pointers to derived classes.\n\n virtual ~ParameterEstimation() {}\n\n\n\n /// Virtual copy constructor.\n\n virtual ParameterEstimation* clone() const = 0;\n\n\n\n /// General factory method that constructs the desired ParameterEstimation subclass\n\n /** \\param method Name of the subclass that should be constructed;\n\n * \\param p Parameters passed to constructor of subclass.\n\n * \\note \\a method should either be in the default registry or should be registered first using registerMethod().\n\n * \\throw UNKNOWN_PARAMETER_ESTIMATION_METHOD if the requested \\a method is not registered.\n\n */\n\n static ParameterEstimation* construct( const std::string &method, const PropertySet &p );\n\n\n\n /// Register a subclass so that it can be used with construct().\n", "file_path": "dai/upstream/include/dai/emalg.h", "rank": 62, "score": 121345.40553166803 }, { "content": "class SharedParameters {\n\n public:\n\n /// Convenience label for an index of a factor in a FactorGraph.\n\n typedef size_t FactorIndex;\n\n /// Convenience label for a grouping of factor orientations.\n\n typedef std::map<FactorIndex, std::vector<Var> > FactorOrientations;\n\n\n\n private:\n\n /// Maps factor indices to the corresponding VarSets\n\n std::map<FactorIndex, VarSet> _varsets;\n\n /// Maps factor indices to the corresponding Permute objects that permute the canonical ordering into the desired ordering\n\n std::map<FactorIndex, Permute> _perms;\n\n /// Maps factor indices to the corresponding desired variable orderings\n\n FactorOrientations _varorders;\n\n /// Parameter estimation method to be used\n\n ParameterEstimation *_estimation;\n\n /// Indicates whether \\c *this gets ownership of _estimation\n\n bool _ownEstimation;\n\n\n\n /// Calculates the permutation that permutes the canonical ordering into the desired ordering\n", "file_path": "dai/upstream/include/dai/emalg.h", "rank": 63, "score": 121345.40553166803 }, { "content": "class MaximizationStep {\n\n private:\n\n /// Vector of parameter estimation tasks of which this maximization step consists\n\n std::vector<SharedParameters> _params;\n\n\n\n public:\n\n /// Default constructor\n\n MaximizationStep() : _params() {}\n\n\n\n /// Construct MaximizationStep from a vector of parameter estimation tasks\n\n MaximizationStep( std::vector<SharedParameters> &maximizations ) : _params(maximizations) {}\n\n\n\n /// Constructor from an input stream and a corresponding factor graph\n\n /** \\see \\ref fileformats-emalg-maximizationstep\n\n */\n\n MaximizationStep( std::istream &is, const FactorGraph &fg_varlookup );\n\n\n\n /// Collect the beliefs from this InfAlg as expectations for the next Maximization step\n\n void addExpectations( InfAlg &alg );\n\n\n", "file_path": "dai/upstream/include/dai/emalg.h", "rank": 64, "score": 121345.40553166803 }, { "content": "class TFactor {\n\n private:\n\n /// Stores the variables on which the factor depends\n\n VarSet _vs;\n\n /// Stores the factor values\n\n TProb<T> _p;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Constructs factor depending on no variables with value \\a p\n\n TFactor ( T p = 1 ) : _vs(), _p(1,p) {}\n\n\n\n /// Constructs factor depending on the variable \\a v with uniform distribution\n\n TFactor( const Var &v ) : _vs(v), _p(v.states()) {}\n\n\n\n /// Constructs factor depending on variables in \\a vars with uniform distribution\n\n TFactor( const VarSet& vars ) : _vs(vars), _p() {\n\n _p = TProb<T>( BigInt_size_t( _vs.nrStates() ) );\n\n }\n", "file_path": "dai/upstream/include/dai/factor.h", "rank": 65, "score": 121345.40553166803 }, { "content": "/// Represents an undirected edge\n\nclass UEdge {\n\n public:\n\n /// First node index\n\n size_t first;\n\n\n\n /// Second node index\n\n size_t second;\n\n\n\n /// Default constructor\n\n UEdge() : first(0), second(0) {}\n\n\n\n /// Constructs an undirected edge between \\a m1 and \\a m2\n\n UEdge( size_t m1, size_t m2 ) : first(m1), second(m2) {}\n\n\n\n /// Construct from DEdge\n\n UEdge( const DEdge &e ) : first(e.first), second(e.second) {}\n\n\n\n /// Tests for inequality (disregarding the ordering of the nodes)\n\n bool operator==( const UEdge &x ) {\n\n return ((first == x.first) && (second == x.second)) || ((first == x.second) && (second == x.first));\n", "file_path": "dai/upstream/include/dai/weightedgraph.h", "rank": 66, "score": 121345.40553166803 }, { "content": "class EMAlg {\n\n private:\n\n /// All the data samples used during learning\n\n const Evidence &_evidence;\n\n\n\n /// How to do the expectation step\n\n InfAlg &_estep;\n\n\n\n /// The maximization steps to take\n\n std::vector<MaximizationStep> _msteps;\n\n\n\n /// Number of iterations done\n\n size_t _iters;\n\n\n\n /// History of likelihoods\n\n std::vector<Real> _lastLogZ;\n\n\n\n /// Maximum number of iterations\n\n size_t _max_iters;\n\n\n", "file_path": "dai/upstream/include/dai/emalg.h", "rank": 67, "score": 121345.40553166803 }, { "content": " class ClusterGraph {\n\n private:\n\n /// Stores the neighborhood structure\n\n BipartiteGraph _G;\n\n\n\n /// Stores the variables corresponding to the nodes\n\n std::vector<Var> _vars;\n\n\n\n /// Stores the clusters corresponding to the hyperedges\n\n std::vector<VarSet> _clusters;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor\n\n ClusterGraph() : _G(), _vars(), _clusters() {}\n\n\n\n /// Construct from vector of VarSet 's\n\n ClusterGraph( const std::vector<VarSet>& cls );\n\n\n", "file_path": "dai/upstream/include/dai/clustergraph.h", "rank": 68, "score": 121345.40553166803 }, { "content": "class GraphAL {\n\n private:\n\n /// Contains for each node a vector of its neighbors\n\n std::vector<Neighbors> _nb;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor (creates an empty graph).\n\n GraphAL() : _nb() {}\n\n\n\n /// Constructs GraphAL with \\a nr nodes and no edges.\n\n GraphAL( size_t nr ) : _nb( nr ) {}\n\n\n\n /// Constructs GraphAL from a range of edges.\n\n /** \\tparam EdgeInputIterator Iterator that iterates over instances of Edge.\n\n * \\param nr The number of nodes.\n\n * \\param begin Points to the first edge.\n\n * \\param end Points just beyond the last edge.\n\n * \\param check Whether to only add an edge if it does not exist already.\n", "file_path": "dai/upstream/include/dai/graph.h", "rank": 69, "score": 121345.40553166803 }, { "content": "class InfAlg {\n\n public:\n\n /// \\name Constructors/destructors\n\n //@{\n\n /// Virtual destructor (needed because this class contains virtual functions)\n\n virtual ~InfAlg() {}\n\n\n\n /// Returns a pointer to a new, cloned copy of \\c *this (i.e., virtual copy constructor)\n\n virtual InfAlg* clone() const = 0;\n\n\n\n /// Returns a pointer to a newly constructed inference algorithm\n\n /** \\param fg Factor graph on which to perform the inference algorithm;\n\n * \\param opts Parameters passed to constructor of inference algorithm;\n\n */\n\n virtual InfAlg* construct( const FactorGraph &fg, const PropertySet &opts ) const = 0;\n\n //@}\n\n\n\n /// \\name Queries\n\n //@{\n\n /// Returns the name of the algorithm\n", "file_path": "dai/upstream/include/dai/daialg.h", "rank": 70, "score": 121345.40553166803 }, { "content": "class TProb {\n\n public:\n\n /// Type of data structure used for storing the values\n\n typedef std::vector<T> container_type;\n\n\n\n /// Shorthand\n\n typedef TProb<T> this_type;\n\n\n\n private:\n\n /// The data structure that stores the values\n\n container_type _p;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor (constructs empty vector)\n\n TProb() : _p() {}\n\n\n\n /// Construct uniform probability distribution over \\a n outcomes (i.e., a vector of length \\a n with each entry set to \\f$1/n\\f$)\n\n explicit TProb( size_t n ) : _p( n, (T)1 / n ) {}\n", "file_path": "dai/upstream/include/dai/prob.h", "rank": 71, "score": 121345.40553166803 }, { "content": "class SmallSet {\n\n private:\n\n /// The elements in this set\n\n std::vector<T> _elements;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor (constructs an empty set)\n\n SmallSet() : _elements() {}\n\n\n\n /// Construct a set consisting of one element\n\n SmallSet( const T &t ) : _elements() {\n\n _elements.push_back( t );\n\n }\n\n\n\n /// Construct a set consisting of two elements\n\n SmallSet( const T &t1, const T &t2 ) {\n\n if( t1 < t2 ) {\n\n _elements.push_back( t1 );\n", "file_path": "dai/upstream/include/dai/smallset.h", "rank": 72, "score": 121345.40553166803 }, { "content": "class QString;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/CPDElasticAligner.h", "rank": 73, "score": 121171.53292028066 }, { "content": "class HxSpatialGraph;\n", "file_path": "hxalignmicrotubules/mtalign/SliceSelector.h", "rank": 74, "score": 121171.53292028066 }, { "content": "class SpatialGraphSelection;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/SliceSelector.h", "rank": 75, "score": 121171.53292028066 }, { "content": "class mtalign__SliceSelector_withSpatialGraphThreeStackedSections\n\n : public ::testing::Test {\n\n protected:\n\n virtual void SetUp() {\n\n mSpatialGraph = ht::makeSpatialGraphThreeStackedSections();\n\n mSliceSelector = ma::SliceSelector(mSpatialGraph, \"section\");\n\n }\n\n\n\n McHandle<HxSpatialGraph> mSpatialGraph;\n\n ma::SliceSelector mSliceSelector;\n\n};\n\n\n\n} // namespace.\n\n\n\nTEST_F(mtalign__SliceSelector_withSpatialGraphThreeStackedSections,\n\n shouldDistinguishOrderedAndUnorderedAttributes) {\n\n EXPECT_TRUE(\n\n ma::SliceSelector::isOrderedAttribute(mSpatialGraph, \"section\"));\n\n EXPECT_FALSE(\n\n ma::SliceSelector::isOrderedAttribute(mSpatialGraph, \"unordered\"));\n", "file_path": "hxalignmicrotubules/mtalign/SliceSelectorTest.cpp", "rank": 76, "score": 119340.2492008481 }, { "content": "class BP_dual {\n\n protected:\n\n /// Convenience label for storing edge properties\n\n template<class T>\n\n struct _edges_t : public std::vector<std::vector<T> > {};\n\n\n\n /// Groups together the data structures for storing the two types of messages and their normalizers\n\n struct messages {\n\n /// Unnormalized variable->factor messages\n\n _edges_t<Prob> n;\n\n /// Normalizers of variable->factor messages\n\n _edges_t<Real> Zn;\n\n /// Unnormalized Factor->variable messages\n\n _edges_t<Prob> m;\n\n /// Normalizers of factor->variable messages\n\n _edges_t<Real> Zm;\n\n };\n\n /// Stores all messages\n\n messages _msgs;\n\n\n", "file_path": "dai/upstream/include/dai/bp_dual.h", "rank": 77, "score": 118958.16668186839 }, { "content": " class sequentialVariableElimination {\n\n private:\n\n /// The variable elimination sequence\n\n std::vector<Var> seq;\n\n /// Counter\n\n size_t i;\n\n\n\n public:\n\n /// Construct from vector of variables\n\n sequentialVariableElimination( const std::vector<Var> s ) : seq(s), i(0) {}\n\n\n\n /// Returns next variable in sequence\n\n size_t operator()( const ClusterGraph &cl, const std::set<size_t> &/*remainingVars*/ );\n\n };\n\n\n\n\n\n /// Helper object for dai::ClusterGraph::VarElim()\n\n /** Chooses the next variable to eliminate greedily by taking the one that minimizes\n\n * a given heuristic cost function.\n\n */\n", "file_path": "dai/upstream/include/dai/clustergraph.h", "rank": 78, "score": 118958.16668186839 }, { "content": " class greedyVariableElimination {\n\n public:\n\n /// Type of cost functions to be used for greedy variable elimination\n\n typedef size_t (*eliminationCostFunction)(const ClusterGraph &, size_t);\n\n\n\n private:\n\n /// Pointer to the cost function used\n\n eliminationCostFunction heuristic;\n\n\n\n public:\n\n /// Construct from cost function\n\n /** \\note Examples of cost functions are eliminationCost_MinFill() and eliminationCost_WeightedMinFill().\n\n */\n\n greedyVariableElimination( eliminationCostFunction h ) : heuristic(h) {}\n\n\n\n /// Returns the best variable from \\a remainingVars to eliminate in the cluster graph \\a cl by greedily minimizing the cost function.\n\n /** This function calculates the cost for eliminating each variable in \\a remaingVars and returns the variable which has lowest cost.\n\n */\n\n size_t operator()( const ClusterGraph &cl, const std::set<size_t>& remainingVars );\n\n };\n", "file_path": "dai/upstream/include/dai/clustergraph.h", "rank": 79, "score": 118958.16668186839 }, { "content": "/// `CPDElasticAligner` implements 'Algorithm 3: Elastic transformation' of\n\n/// [Weber 2014]. It is used internally to implement `cpd()`. It is also used\n\n/// directly by `HxCPDSpatialGraphWarp`, which is kept for backward\n\n/// compatibility with the supplementary data to [Weber 2014]. Future clients\n\n/// should not use `CPDElasticAligner` but instead call `cpd()`.\n\n///\n\n/// A `Context` can be used to configure the run-time environment used for\n\n/// printing. The default is to print to stdout.\n\nclass CPDElasticAligner {\n\n public:\n\n ///\n\n CPDElasticAligner();\n\n\n\n /// `setContext()` configures the run-time environment.\n\n void setContext(Context* ctx);\n\n\n\n /// `setPoints()` set the point sets that are used in `align()`.\n\n void setPoints(const mtalign::FacingPointSets& points);\n\n\n\n /// `align()` computes the alignment. It returns the shifted positions of\n\n /// the original `points.trans.positions` and stores additional info into\n\n /// the out parameter `info`.\n\n McDArray<McVec3f> align(mtalign::AlignInfo& info);\n\n\n\n /// `params` controls details of the algorithm.\n\n mtalign::AlignParamsElastic params;\n\n\n\n protected: // Members in this block are used by tests.\n", "file_path": "hxalignmicrotubules/mtalign/CPDElasticAligner.h", "rank": 80, "score": 118797.38804031395 }, { "content": "class HxSpatialGraph;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/matchingPGM_sg.h", "rank": 81, "score": 118788.64655347033 }, { "content": "class PointMatchingDataStruct;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/matchingExact.h", "rank": 82, "score": 118788.64655347033 }, { "content": "/// `CPDLinearAligner` implements the linear alignment algorithms from [Weber\n\n/// 2014].\n\n///\n\n/// A `Context` can be used to configure the run-time environment used for\n\n/// printing. The default is to print to stdout.\n\nclass CPDLinearAligner {\n\n public:\n\n ///\n\n CPDLinearAligner();\n\n\n\n /// `setContext()` configures the run-time environment.\n\n void setContext(Context* ctx);\n\n\n\n /// `setPoints()` sets the points with directions to be aligned.\n\n void setPoints(const mtalign::FacingPointSets& points);\n\n\n\n /// `params` control details of the algorithm.\n\n mtalign::AlignParamsLinear params;\n\n\n\n /// `align()` computes the alignment between the `points`. It returns\n\n /// information about convergence and stores the alignment result in the\n\n /// out params `Rc`, `s`, `t`, and `Rd`. The results are valid in a\n\n /// normalized coordinate system, as computed with `normalize()`. Use\n\n /// `getTransformMat4f()` or `warpPoint()` to apply the transformation to\n\n /// the original points.\n", "file_path": "hxalignmicrotubules/mtalign/CPDLinearAligner.h", "rank": 83, "score": 118788.64655347033 }, { "content": "class IPOPTForCPD;\n\n\n\n/// `createIPOPTForCPDLinearAligner()` returns an instance of `IPOPTForCPD`\n\n/// that implements derivatives that include scaling for Ipopt. It is used\n\n/// internally by `CPDLinearAligner`.\n\nIPOPTForCPD* createIPOPTForCPDLinearAligner();\n\n\n\n} // namespace mtalign\n", "file_path": "hxalignmicrotubules/mtalign/IPOPTForCPDLinearAligner.h", "rank": 84, "score": 118788.64655347033 }, { "content": "class SpatialGraphSelection;\n", "file_path": "hxalignmicrotubules/mtalign/matchingPGM_sg.h", "rank": 85, "score": 118788.64655347033 }, { "content": "/// `HxManualMTAlign` is used by the filament editor toolbox\n\n/// `QxMicrotubuleAlignSpatialGraphTool` to implement interactive editing of\n\n/// section transformations.\n\nclass HXALIGNMICROTUBULES_API HxManualMTAlign : public HxCompModule {\n\n HX_HEADER(HxManualMTAlign);\n\n\n\n public:\n\n virtual void compute();\n\n\n\n void startTransform();\n\n SbMatrix stopTransform();\n\n\n\n void showNodes(const bool show);\n\n void showSegments(const bool show);\n\n\n\n void setNodeColorAttribute(const EdgeVertexAttribute* colorAtt);\n\n void setNodeScaleAttribute(const EdgeVertexAttribute* scaleAtt);\n\n void setNodeScaleFactor(const float factor);\n\n void setEdgeColorAttribute(const EdgeVertexAttribute* colorAtt);\n\n void setSegmentWidth(const float width);\n\n\n\n private:\n\n void createSlice();\n", "file_path": "hxalignmicrotubules/HxManualMTAlign.h", "rank": 86, "score": 118337.85229348532 }, { "content": "class HXALIGNMICROTUBULES_API HxTestPointMatching : public HxCompModule {\n\n HX_HEADER(HxTestPointMatching);\n\n\n\n public:\n\n\n\n void compute();\n\n\n\n void update();\n\n\n\n int parse(Tcl_Interp* t, int argc, char** argv);\n\n\n\n HxPortMultiMenu portMatchingAlgorithmType;\n\n HxPortIntTextN portProjectionType;\n\n HxPortFloatTextN portThresholds;\n\n HxPortFloatTextN portParams;\n\n HxPortToggleList portUseParams;\n\n HxPortFloatTextN portPGMPairParam;\n\n HxPortFloatTextN portPGMDummieSignificance;\n\n HxPortFloatTextN portPairDummy;\n\n HxPortDoIt mDoIt;\n\n};\n", "file_path": "hxalignmicrotubules/HxTestPointMatching.h", "rank": 87, "score": 118332.6566298114 }, { "content": "/// `HxComparePointMatchings` is used in the supplementary data package.\n\nclass HXALIGNMICROTUBULES_API HxComparePointMatchings : public HxCompModule {\n\n\n\n HX_HEADER(HxComparePointMatchings);\n\n\n\n public:\n\n\n\n void compute();\n\n\n\n int parse(Tcl_Interp* t, int argc, char** argv);\n\n\n\n void update();\n\n\n\n HxPortMultiMenu portPairLabel;\n\n HxPortIntTextN portFalsePositivePairs;\n\n HxPortIntTextN portFalseNegativePairs;\n\n HxPortIntTextN portDisagreementPairs;\n\n HxPortIntTextN portTruePositivePairs;\n\n HxPortIntTextN portTreeNodes;\n\n HxPortIntTextN portCriticalNodes;\n\n HxPortIntTextN portNumberOfManualPairs;\n", "file_path": "hxalignmicrotubules/HxComparePointMatchings.h", "rank": 88, "score": 118332.6566298114 }, { "content": " class TreeEPSubTree {\n\n private:\n\n /// Outer region pseudomarginals (corresponding with the \\f$\\tilde f_i(x_j,x_k)\\f$ in [\\ref MiQ04])\n\n std::vector<Factor> _Qa;\n\n /// Inner region pseudomarginals (corresponding with the \\f$\\tilde f_i(x_s)\\f$ in [\\ref MiQ04])\n\n std::vector<Factor> _Qb;\n\n /// The junction tree (stored as a rooted tree)\n\n RootedTree _RTree;\n\n /// Index conversion table for outer region indices (_Qa[alpha] corresponds with Qa[_a[alpha]] of the supertree)\n\n std::vector<size_t> _a; \n\n /// Index conversion table for inner region indices (_Qb[beta] corresponds with Qb[_b[beta]] of the supertree)\n\n std::vector<size_t> _b;\n\n /// Pointer to off-tree factor\n\n const Factor * _I;\n\n /// Variables in off-tree factor\n\n VarSet _ns;\n\n /// Variables in off-tree factor which are not in the root of this subtree\n\n VarSet _nsrem;\n\n /// Used for calculating the free energy\n\n Real _logZ;\n", "file_path": "dai/upstream/include/dai/treeep.h", "rank": 89, "score": 116687.52663675965 }, { "content": "/// `CPDLinearAlignerTerms` is used internally. It implements some more\n\n/// complex terms used for linear alignment (see supporting information [Weber\n\n/// 2014]).\n\nclass CPDLinearAlignerTerms {\n\n public:\n\n CPDLinearAlignerTerms(const McDMatrix<double>& XcHat,\n\n const McDMatrix<double>& Xd,\n\n const McDMatrix<double>& YcHat,\n\n const McDMatrix<double>& Yd,\n\n const McDMatrix<double>& P);\n\n\n\n void computeS(const McDMatrix<double>& R, double& s) const;\n\n\n\n void computeRc(McDMatrix<double>& Rc) const;\n\n\n\n void computeRd2d(McDMatrix<double>& Rd) const;\n\n\n\n double computeSigmaSquare(const McDMatrix<double>& Rc, const double s,\n\n const double NP) const;\n\n\n\n bool computeKappa(const McDMatrix<double>& Rd, const double NP,\n\n double& kappa, Context::print_t& print) const;\n\n\n", "file_path": "hxalignmicrotubules/mtalign/CPDLinearAligner.h", "rank": 90, "score": 116522.14640503422 }, { "content": "class PointMatchingDataStruct;\n", "file_path": "hxalignmicrotubules/mtalign/NullPointRepresentation.h", "rank": 91, "score": 116522.14640503422 }, { "content": "class PointMatchingScoringFunction;\n\n\n\nnamespace mtalign {\n\n\n", "file_path": "hxalignmicrotubules/mtalign/NullPointRepresentation.h", "rank": 92, "score": 116522.14640503422 }, { "content": "class HxCPDSpatialGraphWarpTest : public ::testing::Test {\n\n public:\n\n TestingObjectPoolCleaner cleaner;\n\n TestingData sgdat;\n\n HxSpatialGraph* sg;\n\n McHandle<HxCPDSpatialGraphWarp> cpd;\n\n\n\n HxCPDSpatialGraphWarpTest() : sg(0) {}\n\n\n\n virtual void SetUp() {\n\n sgdat = TestingData(\"spatialgraph/fullp0p1.am\");\n\n ASSERT_TRUE(sgdat.dataOk<HxSpatialGraph>());\n\n sg = sgdat.get<HxSpatialGraph>();\n\n cpd = HxCPDSpatialGraphWarp::createInstance();\n\n cpd->portData.connect(sg);\n\n }\n\n\n\n void expectComputesSha1(const char* sha1) {\n\n cpd->portAction.hit();\n\n {\n", "file_path": "hxalignmicrotubules/HxCPDSpatialGraphWarpTest.cpp", "rank": 93, "score": 115063.3604581776 }, { "content": "/// `HxMovingLeastSquaresWarp` applies a moving least squares warp of the input\n\n/// image onto the given second image using `MovingLeastSquares`.\n\n/// `HxMovingLeastSquaresWarp` is neither used in the supplementary data\n\n/// package nor by one of our protocols in the spindle project.\n\nclass HXALIGNMICROTUBULES_API HxMovingLeastSquaresWarp : public HxCompModule {\n\n HX_HEADER(HxMovingLeastSquaresWarp);\n\n\n\n public:\n\n\n\n HxConnection portFromImage;\n\n HxConnection portToImage;\n\n HxPortMultiMenu portMethod;\n\n HxPortFloatSlider portAlpha;\n\n HxPortDoIt portAction;\n\n\n\n virtual void update();\n\n virtual void compute();\n\n\n\n protected:\n\n\n\n HxUniformScalarField3* createOutputDataSet();\n\n HxUniformVectorField3* createOutputVectorDataSet();\n\n\n\n void prepareLandmarks(McDArray<McVec2d>& p1, McDArray<McVec2d>& p2);\n\n};\n", "file_path": "hxalignmicrotubules/HxMovingLeastSquaresWarp.h", "rank": 94, "score": 115063.3604581776 }, { "content": "/// `HxCPDSpatialGraphWarp` is used in the supplementary data package to apply\n\n/// the registration algorithms.\n\nclass HXALIGNMICROTUBULES_API HxCPDSpatialGraphWarp : public HxCompModule {\n\n\n\n HX_HEADER(HxCPDSpatialGraphWarp);\n\n\n\n public:\n\n struct TransformationOrderInfo {\n\n int upperSliceIdx;\n\n int lowerSliceIdx;\n\n std::vector<int> upperTransformSlices;\n\n std::vector<int> lowerTransformSlices;\n\n };\n\n\n\n virtual void update();\n\n\n\n virtual void compute();\n\n\n\n HxPortMultiMenu portMethod;\n\n\n\n HxPortFloatSlider portBeta;\n\n\n", "file_path": "hxalignmicrotubules/HxCPDSpatialGraphWarp.h", "rank": 95, "score": 115063.3604581776 }, { "content": "/// `CPDLinearAlignerDerivatives` implements the Q derivatives (see supporting\n\n/// information [Weber 2014]) and is used internally by `CPDLinearAligner`.\n\nclass CPDLinearAlignerDerivatives {\n\n public:\n\n McDMatrix<double> A, BT, C, DT, E;\n\n double s;\n\n double sigmaSquare;\n\n double rho;\n\n double kappa;\n\n McDMatrix<double> R, RdRho, RdRhodRho;\n\n double Np;\n\n\n\n double trace(const McDMatrix<double>& mat) {\n\n double trace = 0.0;\n\n for (int i = 0; i < mat.nCols(); i++)\n\n trace += mat[i][i];\n\n return trace;\n\n }\n\n\n\n void initCurParams(const McDVector<double>& at) {\n\n s = at[0];\n\n rho = at[1];\n", "file_path": "hxalignmicrotubules/mtalign/CPDLinearAlignerDerivatives.h", "rank": 96, "score": 114363.70885096054 }, { "content": "class IPOPTForCPD;\n\n\n\n/// `createIPOPTForCPDLinearAlignerWithoutScale()` returns an instance of\n\n/// `IPOPTForCPD` that implements derivatives without scaling for Ipopt. It is\n\n/// used internally by `CPDLinearAligner`.\n\nIPOPTForCPD* createIPOPTForCPDLinearAlignerWithoutScale();\n\n\n\n} // namespace mtalign\n", "file_path": "hxalignmicrotubules/mtalign/IPOPTForCPDLinearAlignerWithoutScale.h", "rank": 97, "score": 114363.70885096054 }, { "content": "class DAI_API BipartiteGraph {\n\n private:\n\n /// Contains for each node of type 1 a vector of its neighbors\n\n std::vector<Neighbors> _nb1;\n\n\n\n /// Contains for each node of type 2 a vector of its neighbors\n\n std::vector<Neighbors> _nb2;\n\n\n\n /// Used internally by isTree()\n\n struct levelType {\n\n /// Indices of nodes of type 1\n\n std::vector<size_t> ind1; \n\n /// Indices of nodes of type 2\n\n std::vector<size_t> ind2;\n\n };\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor (creates an empty bipartite graph)\n", "file_path": "dai/upstream/include/dai/bipgraph.h", "rank": 98, "score": 113328.68059075432 }, { "content": "class DAI_API FactorGraph {\n\n private:\n\n /// Stores the neighborhood structure\n\n BipartiteGraph _G;\n\n /// Stores the variables\n\n std::vector<Var> _vars;\n\n /// Stores the factors\n\n std::vector<Factor> _factors;\n\n /// Stores backups of some factors\n\n std::map<size_t,Factor> _backup;\n\n\n\n public:\n\n /// \\name Constructors and destructors\n\n //@{\n\n /// Default constructor\n\n FactorGraph() : _G(), _vars(), _factors(), _backup() {}\n\n\n\n /// Constructs a factor graph from a vector of factors\n\n FactorGraph( const std::vector<Factor>& P );\n\n\n", "file_path": "dai/upstream/include/dai/factorgraph.h", "rank": 99, "score": 113328.68059075432 } ]
C++
net/ias/mmc/nap/machineenumtask.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
#include "Precompiled.h" #include "MachineEnumTask.h" #include "MachineNode.h" CMachineEnumTask::CMachineEnumTask( CMachineNode * pMachineNode ) { TRACE_FUNCTION("CMachineEnumTask::CMachineEnumTask"); _ASSERTE( pMachineNode != NULL ); m_pMachineNode = pMachineNode; } CMachineEnumTask::CMachineEnumTask() { TRACE_FUNCTION("CMachineEnumTask::CMachineEnumTask"); } STDMETHODIMP CMachineEnumTask::Init (IDataObject * pdo, LPOLESTR szTaskGroup) { TRACE_FUNCTION("CMachineEnumTask::Init"); if( !lstrcmp(szTaskGroup, L"CMTP1") ) { m_type = 1; } else { _ASSERTE(FALSE); } return S_OK; } STDMETHODIMP CMachineEnumTask::Next (ULONG celt, MMC_TASK *rgelt, ULONG *pceltFetched) { TRACE_FUNCTION("CMachineEnumTask::Next"); if ((rgelt == NULL) || (pceltFetched == NULL)) { return E_INVALIDARG; } _ASSERTE(!IsBadWritePtr (rgelt, celt*sizeof(MMC_TASK))); _ASSERTE(!IsBadWritePtr (pceltFetched, sizeof(ULONG))); _ASSERTE( m_type == 1 ); _ASSERTE( m_pMachineNode != NULL ); UINT uintTextResourceID; UINT uintHelpTextResourceID; TCHAR lpszTemp[IAS_MAX_STRING]; int nLoadStringResult; OLECHAR szMouseOverBuffer[MAX_PATH*2]; lstrcpy (szMouseOverBuffer, L"res://"); HINSTANCE hInstance = _Module.GetModuleInstance(); ::GetModuleFileName (hInstance, szMouseOverBuffer + lstrlen(szMouseOverBuffer), MAX_PATH); OLECHAR * szMouseOverBufferAfterFileName = szMouseOverBuffer + lstrlen(szMouseOverBuffer); OLECHAR szMouseOffBuffer[MAX_PATH*2]; lstrcpy( szMouseOffBuffer, szMouseOverBuffer ); OLECHAR * szMouseOffBufferAfterFileName = szMouseOffBuffer + lstrlen(szMouseOffBuffer); for (ULONG i=0; i<celt; i++) { MMC_TASK * task = &rgelt[i]; task->eActionType = MMC_ACTION_ID; task->sDisplayObject.eDisplayType = MMC_TASK_DISPLAY_TYPE_BITMAP; switch( m_index ) { case 0: lstrcpy (szMouseOverBufferAfterFileName , L"/img\\TaskDefineNAPMouseOver.gif"); lstrcpy (szMouseOffBufferAfterFileName , L"/img\\TaskDefineNAP.gif"); uintTextResourceID = IDS_TASKPAD_TEXT__DEFINE_NETWORK_ACCCESS_POLICY; uintHelpTextResourceID = IDS_TASKPAD_HELP_TEXT__DEFINE_NETWORK_ACCCESS_POLICY; task->nCommandID = MACHINE_TASK__DEFINE_NETWORK_ACCESS_POLICY; break; default: if (pceltFetched) { *pceltFetched = i; } return S_FALSE; break; } task->sDisplayObject.uBitmap.szMouseOverBitmap = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(szMouseOverBuffer)+1) ); if( task->sDisplayObject.uBitmap.szMouseOverBitmap ) { lstrcpy( task->sDisplayObject.uBitmap.szMouseOverBitmap, szMouseOverBuffer ); task->sDisplayObject.uBitmap.szMouseOffBitmap = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(szMouseOffBuffer)+1) ); if( task->sDisplayObject.uBitmap.szMouseOffBitmap ) { lstrcpy( task->sDisplayObject.uBitmap.szMouseOffBitmap, szMouseOffBuffer); nLoadStringResult = LoadString( _Module.GetResourceInstance(), uintTextResourceID, lpszTemp, IAS_MAX_STRING ); _ASSERT( nLoadStringResult > 0 ); task->szText = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(lpszTemp)+1) ); if (task->szText) { lstrcpy( task->szText, lpszTemp ); nLoadStringResult = LoadString( _Module.GetResourceInstance(), uintHelpTextResourceID, lpszTemp, IAS_MAX_STRING ); _ASSERT( nLoadStringResult > 0 ); task->szHelpString = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(lpszTemp)+1) ); if (task->szHelpString) { lstrcpy( task->szHelpString, lpszTemp ); m_index++; continue; } CoTaskMemFree(task->szText); } CoTaskMemFree(task->sDisplayObject.uBitmap.szMouseOffBitmap); } CoTaskMemFree(task->sDisplayObject.uBitmap.szMouseOverBitmap); } if ( NULL != pceltFetched) { *pceltFetched = i; } return S_FALSE; } if (pceltFetched) *pceltFetched = celt; return S_OK; } STDMETHODIMP CMachineEnumTask::CopyState( CMachineEnumTask * pSourceMachineEnumTask ) { TRACE_FUNCTION("CMachineEnumTask::CopyState"); m_pMachineNode = pSourceMachineEnumTask->m_pMachineNode; m_index = pSourceMachineEnumTask->m_index; m_type = pSourceMachineEnumTask->m_type; return S_OK; }
#include "Precompiled.h" #include "MachineEnumTask.h" #include "MachineNode.h" CMachineEnumTask::CMachineEnumTask( CMachineNode * pMachineNode ) { TRACE_FUNCTION("CMachineEnumTask::CMachineEnumTask"); _ASSERTE( pMachineNode != NULL ); m_pMachineNode = pMachineNode; } CMachineEnumTask::CMachineEnumTask() { TRACE_FUNCTION("CMachineEnumTask::CMachineEnumTask"); } STDMETHODIMP CMachineEnumTask::Init (IDataObject * pdo, LPOLESTR szTaskGroup) { TRACE_FUNCTION("CMachineEnumTask::Init"); if( !lstrcmp(szTaskGroup, L"CMTP1") ) { m_type = 1; } else { _ASSERTE(FALSE); } return S_OK; }
STDMETHODIMP CMachineEnumTask::CopyState( CMachineEnumTask * pSourceMachineEnumTask ) { TRACE_FUNCTION("CMachineEnumTask::CopyState"); m_pMachineNode = pSourceMachineEnumTask->m_pMachineNode; m_index = pSourceMachineEnumTask->m_index; m_type = pSourceMachineEnumTask->m_type; return S_OK; }
STDMETHODIMP CMachineEnumTask::Next (ULONG celt, MMC_TASK *rgelt, ULONG *pceltFetched) { TRACE_FUNCTION("CMachineEnumTask::Next"); if ((rgelt == NULL) || (pceltFetched == NULL)) { return E_INVALIDARG; } _ASSERTE(!IsBadWritePtr (rgelt, celt*sizeof(MMC_TASK))); _ASSERTE(!IsBadWritePtr (pceltFetched, sizeof(ULONG))); _ASSERTE( m_type == 1 ); _ASSERTE( m_pMachineNode != NULL ); UINT uintTextResourceID; UINT uintHelpTextResourceID; TCHAR lpszTemp[IAS_MAX_STRING]; int nLoadStringResult; OLECHAR szMouseOverBuffer[MAX_PATH*2]; lstrcpy (szMouseOverBuffer, L"res://"); HINSTANCE hInstance = _Module.GetModuleInstance(); ::GetModuleFileName (hInstance, szMouseOverBuffer + lstrlen(szMouseOverBuffer), MAX_PATH); OLECHAR * szMouseOverBufferAfterFileName = szMouseOverBuffer + lstrlen(szMouseOverBuffer); OLECHAR szMouseOffBuffer[MAX_PATH*2]; lstrcpy( szMouseOffBuffer, szMouseOverBuffer ); OLECHAR * szMouseOffBufferAfterFileName = szMouseOffBuffer + lstrlen(szMouseOffBuffer); for (ULONG i=0; i<celt; i++) { MMC_TASK * task = &rgelt[i]; task->eActionType = MMC_ACTION_ID; task->sDisplayObject.eDisplayType = MMC_TASK_DISPLAY_TYPE_BITMAP; switch( m_index ) { case 0: lstrcpy (szMouseOverBufferAfterFileName , L"/img\\TaskDefineNAPMouseOver.gif"); lstrcpy (szMouseOffBufferAfterFileName , L"/img\\TaskDefineNAP.gif"); uintTextResourceID = IDS_TASKPAD_TEXT__DEFINE_NETWORK_ACCCESS_POLICY; uintHelpTextResourceID = IDS_TASKPAD_HELP_TEXT__DEFINE_NETWORK_ACCCESS_POLICY; task->nCommandID = MACHINE_TASK__DEFINE_NETWORK_ACCESS_POLICY; break; default: if (pceltFetched) { *pceltFetched = i; } return S_FALSE; break; } task->sDisplayObject.uBitmap.szMouseOverBitmap = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(szMouseOverBuffer)+1) ); if( task->sDisplayObject.uBitmap.szMouseOverBitmap ) { lstrcpy( task->sDisplayObject.uBitmap.szMouseOverBitmap, szMouseOverBuffer ); task->sDisplayObject.uBitmap.szMouseOffBitmap = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(szMouseOffBuffer)+1) ); if( task->sDisplayObject.uBitmap.szMouseOffBitmap ) { lstrcpy( task->sDisplayObject.uBitmap.szMouseOffBitmap, szMouseOffBuffer); nLoadStringResult = LoadString( _Module.GetResourceInstance(), uintTextResourceID, lpszTemp, IAS_MAX_STRING ); _ASSERT( nLoadStringResult > 0 ); task->szText = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(lpszTemp)+1) ); if (task->szText) { lstrcpy( task->szText, lpszTemp ); nLoadStringResult = LoadString( _Module.GetResourceInstance(), uintHelpTextResourceID, lpszTemp, IAS_MAX_STRING ); _ASSERT( nLoadStringResult > 0 ); task->szHelpString = (LPOLESTR) CoTaskMemAlloc( sizeof(OLECHAR)*(lstrlen(lpszTemp)+1) ); if (task->szHelpString) { lstrcpy( task->szHelpString, lpszTemp ); m_index++; continue; } CoTaskMemFree(task->szText); } CoTaskMemFree(task->sDisplayObject.uBitmap.szMouseOffBitmap); } CoTaskMemFree(task->sDisplayObject.uBitmap.szMouseOverBitmap); } if ( NULL != pceltFetched) { *pceltFetched = i; } return S_FALSE; } if (pceltFetched) *pceltFetched = celt; return S_OK; }
function_block-full_function
[]
C++
Analysis/AnalysisOrg/IO/CaptureImageState.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
#include "CaptureImageState.h" #include "IonH5File.h" #include "IonH5Arma.h" #include "ImageTransformer.h" #include "Vecs.h" #include <malloc.h> CaptureImageState::CaptureImageState(std::string _h5File) { h5file = _h5File; } void CaptureImageState::CleanUpOldFile() { if (isFile (h5file.c_str())) remove(h5file.c_str()); } void CaptureImageState::WriteImageGainCorrection(int rows, int cols) { for (int row = 0;row < rows;row++) { for (int col = 0;col < cols;col++) { assert ( !isnan(ImageTransformer::gain_correction[row*cols + col]) ); } } std::string h5_name = h5file + ":/imgGain/gain_corr"; assert(ImageTransformer::gain_correction != NULL); std::vector<float> gain(ImageTransformer::gain_correction, ImageTransformer::gain_correction + rows*cols); printf("[CaptureImageState] Writing Image gain correction to %s\n",h5file.c_str()); H5File::WriteVector (h5_name, gain, false); } void CaptureImageState::LoadImageGainCorrection(int rows, int cols) { std::string h5_name = h5file + ":/imgGain/gain_corr"; std::vector<float> gain; printf("[CaptureImageState] Loading Image gain correction from %s\n",h5file.c_str()); H5File::ReadVector (h5_name, gain); if (ImageTransformer::gain_correction == NULL) { ImageTransformer::gain_correction = (float *)memalign(VEC8F_SIZE_B,sizeof(float)*rows*cols); } std::fill(ImageTransformer::gain_correction, ImageTransformer::gain_correction + rows * cols, 0); std::copy(gain.begin(), gain.end(), ImageTransformer::gain_correction); for (int row = 0;row < rows;row++) { for (int col = 0;col < cols;col++) { if ( isnan(ImageTransformer::gain_correction[row*cols + col]) ) ImageTransformer::gain_correction[row*cols + col] = 1.0f; } } } void CaptureImageState::WriteXTCorrection() { std::string h5_name = h5file + ":/XTalk_corr/"; if ( ImageTransformer::custom_correction_data != NULL ){ ChannelXTCorrectionDescriptor xt_vectors = ImageTransformer::custom_correction_data->GetCorrectionDescriptor(); if ( xt_vectors.xt_vector_ptrs != NULL ){ printf("[CaptureImageState] Writing electrical XeTalk correction to %s\n",h5file.c_str()); float **vects = xt_vectors.xt_vector_ptrs; int nvects = xt_vectors.num_vectors; int *col_offset = xt_vectors.vector_indicies; int vector_len = xt_vectors.vector_len; int num_and_len[] = {nvects, vector_len}; std::vector<int> H5num_and_len(num_and_len, num_and_len+2); H5File::WriteVector (h5_name+"num_and_length", H5num_and_len); std::vector<int> H5col_offset(col_offset, col_offset+nvects-1); H5File::WriteVector (h5_name+"vector_indicies", H5col_offset); arma::Mat<float> H5vectors; H5vectors.set_size (nvects, vector_len); for ( int vndx=0; vndx < nvects; vndx++ ) { for ( int vn=0; vn < vector_len; vn++ ) H5vectors.at (vndx, vn) = vects[vndx][vn]; } H5Arma::WriteMatrix (h5_name+"xt_vectors", H5vectors, false); } } } void CaptureImageState::LoadXTCorrection() { std::string h5_name = h5file + ":/XTalk_corr/"; if (H5File::DatasetExist<std::string> (h5_name+"xt_vectors")){ printf("[CaptureImageState] Loading electrical XeTalk correction from %s\n",h5file.c_str()); std::vector<int> H5num_and_len; H5File::ReadVector (h5_name+"num_and_length", H5num_and_len); int nvects = H5num_and_len[0]; int vector_len = H5num_and_len[1]; std::vector<int> H5col_offset; H5File::ReadVector (h5_name+"vector_indicies",H5col_offset); arma::Mat<float> H5vectors; H5Arma::ReadMatrix (h5_name+"xt_vectors", H5vectors); ChannelXTCorrection *xtptr = new ChannelXTCorrection(); float *pvects = xtptr->AllocateVectorStorage(nvects,vector_len); float **vect_ptrs = xtptr->AllocateVectorPointerStorage(nvects); xtptr->SetVectorIndicies(&H5col_offset[0],vector_len); for ( int vndx=0; vndx < nvects; vndx++ ) { vect_ptrs[vndx] = pvects+vector_len*vndx; for ( int vn=0; vn < vector_len; vn++ ) vect_ptrs[vndx][vn] = H5vectors.at (vndx, vn); } ImageTransformer::custom_correction_data = xtptr; ImageTransformer::selected_chip_xt_vectors = ImageTransformer::custom_correction_data->GetCorrectionDescriptor(); } else{ printf("[CaptureImageState] No electrical XeTalk correction found\n"); } } void CaptureImageState::WriteImageSpec(ImageSpecClass &my_image_spec, int frames) { std::string h5_name = h5file + ":/imgSpec/"; std::vector<int> tstamp(my_image_spec.timestamps, my_image_spec.timestamps + frames); printf("[CaptureImageState] Writing Image Spec to %s\n",h5file.c_str()); H5File::WriteVector (h5_name + "timestamps", tstamp, false); std::vector<int> H5frames(1,frames); H5File::WriteVector (h5_name + "frames", H5frames, false); } void CaptureImageState::LoadImageSpec(ImageSpecClass &my_image_spec) { std::string h5_name = h5file + ":/imgSpec/"; std::vector<int> frames; std::vector<int> tstamp; printf("[CaptureImageState] Loading Image Spec from %s\n",h5file.c_str()); H5File::ReadVector (h5_name + "timestamps", tstamp); H5File::ReadVector (h5_name + "frames", frames); if (my_image_spec.timestamps == NULL) my_image_spec.timestamps = new int[frames[0]]; std::copy(tstamp.begin(), tstamp.end(), my_image_spec.timestamps); }
#include "CaptureImageState.h" #include "IonH5File.h" #include "IonH5Arma.h" #include "ImageTransformer.h" #include "Vecs.h" #include <malloc.h> CaptureImageState::CaptureImageState(std::string _h5File) { h5file = _h5File; } void CaptureImageState::CleanUpOldFile() { if (isFile (h5file.c_str())) remove(h5file.c_str()); } void CaptureImageState::WriteImageGainCorrection(int rows, int cols) { for (int row = 0;row < rows;row++) { for (int col = 0;col < cols;col++) {
void CaptureImageState::LoadImageGainCorrection(int rows, int cols) { std::string h5_name = h5file + ":/imgGain/gain_corr"; std::vector<float> gain; printf("[CaptureImageState] Loading Image gain correction from %s\n",h5file.c_str()); H5File::ReadVector (h5_name, gain); if (ImageTransformer::gain_correction == NULL) { ImageTransformer::gain_correction = (float *)memalign(VEC8F_SIZE_B,sizeof(float)*rows*cols); } std::fill(ImageTransformer::gain_correction, ImageTransformer::gain_correction + rows * cols, 0); std::copy(gain.begin(), gain.end(), ImageTransformer::gain_correction); for (int row = 0;row < rows;row++) { for (int col = 0;col < cols;col++) { if ( isnan(ImageTransformer::gain_correction[row*cols + col]) ) ImageTransformer::gain_correction[row*cols + col] = 1.0f; } } } void CaptureImageState::WriteXTCorrection() { std::string h5_name = h5file + ":/XTalk_corr/"; if ( ImageTransformer::custom_correction_data != NULL ){ ChannelXTCorrectionDescriptor xt_vectors = ImageTransformer::custom_correction_data->GetCorrectionDescriptor(); if ( xt_vectors.xt_vector_ptrs != NULL ){ printf("[CaptureImageState] Writing electrical XeTalk correction to %s\n",h5file.c_str()); float **vects = xt_vectors.xt_vector_ptrs; int nvects = xt_vectors.num_vectors; int *col_offset = xt_vectors.vector_indicies; int vector_len = xt_vectors.vector_len; int num_and_len[] = {nvects, vector_len}; std::vector<int> H5num_and_len(num_and_len, num_and_len+2); H5File::WriteVector (h5_name+"num_and_length", H5num_and_len); std::vector<int> H5col_offset(col_offset, col_offset+nvects-1); H5File::WriteVector (h5_name+"vector_indicies", H5col_offset); arma::Mat<float> H5vectors; H5vectors.set_size (nvects, vector_len); for ( int vndx=0; vndx < nvects; vndx++ ) { for ( int vn=0; vn < vector_len; vn++ ) H5vectors.at (vndx, vn) = vects[vndx][vn]; } H5Arma::WriteMatrix (h5_name+"xt_vectors", H5vectors, false); } } } void CaptureImageState::LoadXTCorrection() { std::string h5_name = h5file + ":/XTalk_corr/"; if (H5File::DatasetExist<std::string> (h5_name+"xt_vectors")){ printf("[CaptureImageState] Loading electrical XeTalk correction from %s\n",h5file.c_str()); std::vector<int> H5num_and_len; H5File::ReadVector (h5_name+"num_and_length", H5num_and_len); int nvects = H5num_and_len[0]; int vector_len = H5num_and_len[1]; std::vector<int> H5col_offset; H5File::ReadVector (h5_name+"vector_indicies",H5col_offset); arma::Mat<float> H5vectors; H5Arma::ReadMatrix (h5_name+"xt_vectors", H5vectors); ChannelXTCorrection *xtptr = new ChannelXTCorrection(); float *pvects = xtptr->AllocateVectorStorage(nvects,vector_len); float **vect_ptrs = xtptr->AllocateVectorPointerStorage(nvects); xtptr->SetVectorIndicies(&H5col_offset[0],vector_len); for ( int vndx=0; vndx < nvects; vndx++ ) { vect_ptrs[vndx] = pvects+vector_len*vndx; for ( int vn=0; vn < vector_len; vn++ ) vect_ptrs[vndx][vn] = H5vectors.at (vndx, vn); } ImageTransformer::custom_correction_data = xtptr; ImageTransformer::selected_chip_xt_vectors = ImageTransformer::custom_correction_data->GetCorrectionDescriptor(); } else{ printf("[CaptureImageState] No electrical XeTalk correction found\n"); } } void CaptureImageState::WriteImageSpec(ImageSpecClass &my_image_spec, int frames) { std::string h5_name = h5file + ":/imgSpec/"; std::vector<int> tstamp(my_image_spec.timestamps, my_image_spec.timestamps + frames); printf("[CaptureImageState] Writing Image Spec to %s\n",h5file.c_str()); H5File::WriteVector (h5_name + "timestamps", tstamp, false); std::vector<int> H5frames(1,frames); H5File::WriteVector (h5_name + "frames", H5frames, false); } void CaptureImageState::LoadImageSpec(ImageSpecClass &my_image_spec) { std::string h5_name = h5file + ":/imgSpec/"; std::vector<int> frames; std::vector<int> tstamp; printf("[CaptureImageState] Loading Image Spec from %s\n",h5file.c_str()); H5File::ReadVector (h5_name + "timestamps", tstamp); H5File::ReadVector (h5_name + "frames", frames); if (my_image_spec.timestamps == NULL) my_image_spec.timestamps = new int[frames[0]]; std::copy(tstamp.begin(), tstamp.end(), my_image_spec.timestamps); }
assert ( !isnan(ImageTransformer::gain_correction[row*cols + col]) ); } } std::string h5_name = h5file + ":/imgGain/gain_corr"; assert(ImageTransformer::gain_correction != NULL); std::vector<float> gain(ImageTransformer::gain_correction, ImageTransformer::gain_correction + rows*cols); printf("[CaptureImageState] Writing Image gain correction to %s\n",h5file.c_str()); H5File::WriteVector (h5_name, gain, false); }
function_block-function_prefix_line
[ { "content": " int row, col; //upper left corner Row and Column\n", "file_path": "Analysis/Region.h", "rank": 0, "score": 125457.39546282355 }, { "content": "__device__\n", "file_path": "Analysis/BkgModel/CUDA/CudaUtils.h", "rank": 1, "score": 119857.84740344397 }, { "content": " int32_t row; /*!< the alphabet size */\n", "file_path": "Analysis/TMAP/src/sw/tmap_fsw.h", "rank": 2, "score": 119844.48531075288 }, { "content": " int32_t row; /*!< the alphabet size */ \n", "file_path": "Analysis/TMAP/src/sw/tmap_sw.h", "rank": 3, "score": 119844.48531075288 }, { "content": "object TreePhaser::queryAllStates( const string& sequence, int maxFlows, int calib_x, int calib_y )\n\n{\n\n return queryStates(dpTreephaser, calibModel, sequence, maxFlows, calib_x, calib_y, true);\n\n}\n\n\n\n\n", "file_path": "torrentPy/src/torrentPy.cpp", "rank": 4, "score": 116745.56166210526 }, { "content": "static void \n\ndat_flow_filter_row_col(dat_frame_t *frame, dat_header_t *header, int32_t min_row, int32_t max_row, int32_t min_col, int32_t max_col)\n\n{\n\n int32_t row, col, ctr1, ctr2;\n\n if(0 < min_row \n\n || max_row < header->rows-1 \n\n || 0 < min_col \n\n || max_col < header->cols-1) {\n\n for(row=min_row,ctr1=0;row<=max_row;row++) {\n\n ctr2 = (row*header->cols) + min_col; // source\n\n for(col=min_col;col<=max_col;col++) {\n\n assert(ctr1 < header->rows*header->cols);\n\n assert(ctr2 < header->rows*header->cols);\n\n frame->data[++ctr1] = frame->data[++ctr2];\n\n }\n\n }\n\n frame->data = ion_realloc(frame->data, (max_row-min_row+1)*(max_col-min_col+1)*sizeof(uint16_t), __func__, \"d->frames[i]->data\");\n\n }\n", "file_path": "Analysis/file-io/dat_flow.c", "rank": 5, "score": 113969.11104132693 }, { "content": "object queryStates( DPTreephaser* dpTreephaser, const LinearCalibrationModel& calibModel, const string& sequence, int maxFlows, int calib_x, int calib_y, bool getStates )\n\n{\n\n BasecallerRead read;\n\n read.sequence = std::vector<char>(sequence.begin(), sequence.end());\n\n if( calibModel.is_enabled() ) {\n\n const vector<vector<vector<float> > > * aPtr = calibModel.getAs(calib_x, calib_y);\n\n const vector<vector<vector<float> > > * bPtr = calibModel.getBs(calib_x, calib_y);\n\n if (aPtr == 0 or bPtr == 0) {\n\n std::cerr<< \"Error finding recalibration model for x: \" << calib_x << \" y: \" << calib_y << std::endl;\n\n }\n\n dpTreephaser->SetAsBs(aPtr, bPtr);\n\n }\n\n if( getStates ){\n\n vector< vector<float> > queryStates;\n\n vector< int > hpLength;\n\n dpTreephaser->QueryAllStates(read, queryStates, hpLength, maxFlows);\n\n vector<float> predictions = read.prediction;\n\n\n\n //packing vector of vectors into a list of numpy\n\n boost::python::list queryStates_list;\n", "file_path": "torrentPy/src/torrentPy.cpp", "rank": 6, "score": 101457.04501469413 }, { "content": "// Creates a new output queue large enough to hold numFrames\n\nstruct FrameOutputQueue *foq_Create(int numFrames)\n\n{\n\n struct frame_info *frames;\n\n struct FrameOutputQueue *q;\n\n\n\n q = (struct FrameOutputQueue *)malloc(sizeof(struct FrameOutputQueue));\n\n\n\n if (q == NULL)\n\n goto err0;\n\n\n\n frames = (struct frame_info *)malloc(sizeof(struct frame_info)*numFrames);\n\n\n\n if (frames == NULL)\n\n goto err1;\n\n\n\n q->frames = frames;\n\n\n\n if (pthread_mutex_init(&q->lock, NULL) != 0)\n\n goto err2;\n\n\n", "file_path": "Analysis/Util/WorkerInfoQueue.h", "rank": 7, "score": 90421.40629994965 }, { "content": "// Creates a new output queue large enough to hold numFrames\n\nstruct FrameOutputQueue *foq_Create(int numFrames);\n\n\n\n// Destroys a FrameOutputQueue and free's the resources used by the control structures\n\nvoid foq_Destroy(struct FrameOutputQueue *q);\n\n\n\n// Puts a new frame into the queue. Blocks if there isn't space for the new frame\n\nvoid foq_PutFrame(struct FrameOutputQueue *q,int frameNum,struct timeval timestamp,UINT32 frame_duration,UINT8 *ptr);\n\n\n\n// Gets the next frame from the queue. Blocks if there aren't any new frames available\n\nint foq_GetFrame(struct FrameOutputQueue *q,struct frame_info *pframe);\n\n\n\n// indicate to readers that the acquisition is complete and no more frames should be\n\n// expected\n\nvoid foq_FinishAcquisition(struct FrameOutputQueue *q);\n\n\n\n// Empty's the queue\n\nvoid foq_Reset(struct FrameOutputQueue *q);\n\n\n\n// Queries number of frames in the queue\n\nint foq_GetNum(struct FrameOutputQueue *q);\n\n\n\n#endif\n\n \n\n \n\n #include \"datacollect_global.h\"\n\n#include \"FrameOutputQueue.h\"\n\n\n", "file_path": "Analysis/Util/WorkerInfoQueue.h", "rank": 8, "score": 90421.40629994965 }, { "content": "// Deal with the inference for a single family\n\nclass EvalFamily : public AbstractMolecularFamily<unsigned int>{\n\npublic:\n\n\tvector<float> family_responsibility;\n\n\tEvalFamily(const string &barcode, int strand, const vector<const Alignment *>* const read_stack)\n\n\t : AbstractMolecularFamily(barcode, strand), read_stack_(read_stack) {};\n\n\t~EvalFamily(){};\n\n\tint CountFamSizeFromValid();\n\n\tint CountFamSizeFromAll();\n\n\tvoid InitializeEvalFamily(unsigned int num_hyp);\n\n\tvoid CleanAllocate(unsigned int num_hyp);\n\n\tvoid InitializeFamilyResponsibility();\n\n\tvoid ComputeFamilyLogLikelihoods(const vector<CrossHypotheses>& my_hypotheses);\n\n\tvoid UpdateFamilyResponsibility(const vector<float > &hyp_prob, float outlier_prob);\n\n\tvoid ComputeFamilyOutlierResponsibility(const vector<CrossHypotheses>& my_hypotheses, unsigned int min_fam_size);\n\n\tfloat ComputeFamilyPosteriorLikelihood(const vector<float>& hyp_prob);\n\n\tfloat ComputeLLDifference(int a_hyp, int b_hyp) const {return my_family_cross_.ComputeLLDifference(a_hyp, b_hyp);};\n\n\tint MostResponsible() const { return my_family_cross_.MostResponsible(); };\n\n\tvector<float> GetFamilyLogLikelihood() const { return my_family_cross_.log_likelihood; };\n\n\tvector<float> GetFamilyScaledLikelihood() const { return my_family_cross_.scaled_likelihood; };\n\n\tvoid FillInFlowDisruptivenessMatrix(const vector<CrossHypotheses> &my_hypotheses);\n", "file_path": "Analysis/VariantCaller/EnsembleEval/CrossHypotheses.h", "rank": 9, "score": 84954.42226121812 }, { "content": "object TreePhaser::Simulate( const string& sequence, int maxFlows )\n\n{\n\n return queryStates(dpTreephaser, calibModel, sequence, maxFlows, 0, 0, false);\n\n}\n\n\n\nvoid makeOutput(const BasecallerRead& read, boost::python::dict& output)\n\n{\n\n output[\"seq\"]=toNumpy(read.sequence);\n\n output[\"predicted\"]=toNumpy(read.prediction);\n\n output[\"norm_additive\"]=toNumpy(read.additive_correction);\n\n output[\"norm_multipl\"]=toNumpy(read.multiplicative_correction);\n\n std::vector<float> res;\n\n res.resize(read.prediction.size());\n\n //res=read.normalized_measurements-read.prediction\n\n std::transform(read.normalized_measurements.begin(), read.normalized_measurements.end(), read.prediction.begin(), res.begin(), std::minus<float>() );\n\n output[\"residual\"]=toNumpy(res);\n\n}\n\n\n\nboost::python::dict TreePhaser::treephaserSolve(boost::python::object _signal, boost::python::object _keyVec)\n\n{\n", "file_path": "torrentPy/src/torrentPy.cpp", "rank": 10, "score": 80004.55631443262 }, { "content": "class RowSumData {\n\npublic:\n\n\tRowSumData();\n\n\tvirtual ~RowSumData();\n\n\n\n\t// read rowsum data from file. The raw data is stored in rowsum private member.\n\n\t// returns 0 if success\n\n\t// returns 1 if error opening file\n\n\t// returns 2 if error reading or closing file\n\n\tint LoadRowSumData(const std::string fileName, const std::vector<unsigned int> startRowList, const std::vector<unsigned int> endRowList);\n\n\n\n\t// return the sensing electrode trace in full resolution\n\n\tstd::vector<float> RowTrace(const unsigned int row);\n\n\n\n\t// return the 4-row averaged sensing electrode trace in full resolution\n\n\tstd::vector<float> RowTrace_avg4(const unsigned int row);\n\n\n\n\t// return the 4-row averaged sensing electrode trace in full resolution with trace offset\n\n\t// adjusted to zero by subtracting the average of the first numOffsetFrames points.\n\n\tstd::vector<float> RowTrace_avg4(\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 11, "score": 78324.00195978172 }, { "content": " uint32_t rows;\t\t\t// number of rows\n", "file_path": "Analysis/Image/RowSumCorrector.h", "rank": 12, "score": 77265.96411964085 }, { "content": "class LSRowImageProcessor\n\n{\n\npublic:\n\n\n\n LSRowImageProcessor(int correction_span = 3)\n\n {\n\n nLen = correction_span*2+1;\n\n indicies = new int[nLen];\n\n\n\n int ndx = 0;\n\n for (int dist=-correction_span*NUM_CHANS;dist <= correction_span*NUM_CHANS;dist+=NUM_CHANS)\n\n indicies[ndx++]=dist;\n\n }\n\n\n\n // generate an electrical cross-talk correction from the lsrow image\n\n // This must be called before any of the other methods (besides the constructor)\n\n // if the file pointed to by lsimg_path does not exist, the method returns false\n\n // and no correction is generated. If lsimg_path does exist, then a correction\n\n // is generated and the method returns true\n\n ChannelXTCorrection *GenerateCorrection(const char *lsimg_path);\n", "file_path": "Analysis/Image/LSRowImageProcessor.h", "rank": 13, "score": 76236.13024286479 }, { "content": "class TraceStoreCol : public TraceStore\n\n {\n\n\n\n public:\n\n\n\n void SetMinRefProbes (int n) { mMinRefProbes = n; }\n\n\n\n TraceStoreCol (Mask &mask, size_t frames, const char *flowOrder,\n\n int numFlowsBuff, int maxFlow, int rowStep, int colStep) {\n\n Init(mask, frames,flowOrder, numFlowsBuff, maxFlow, rowStep, colStep);\n\n }\n\n\n\n TraceStoreCol() { \n\n mUseMeshNeighbors = 0;\n\n mRows = mCols = mFrames = mRowRefStep = mColRefStep = 0;\n\n mFrames = mFrameStride = mMaxDist = mFlowFrameStride = 0;\n\n }\n\n\n\n void Init(Mask &mask, size_t frames, const char *flowOrder,\n\n int numFlowsBuff, int maxFlow, int rowStep, int colStep);\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 14, "score": 75239.70881749017 }, { "content": " uint32_t sumsPerRow;\t// number of sum per row,\n", "file_path": "Analysis/Image/RowSumCorrector.h", "rank": 15, "score": 75233.38741927154 }, { "content": "int WriteRowSumCorrection(char *fname, short int *corr, int rows, int frames);\n", "file_path": "Analysis/Image/RowSumCorrector.h", "rank": 16, "score": 74256.68053147977 }, { "content": "short int *CreateRowSumCorrection(short int *image, int rows, int cols, int frames);\n", "file_path": "Analysis/Image/RowSumCorrector.h", "rank": 17, "score": 74256.68053147977 }, { "content": " \n\n ~TraceStoreCol() { pthread_mutex_destroy (&mLock); }\n\n\n\n void SetSize(int frames) {\n\n mFrames = frames;\n\n mData.resize(mWells * mFrames * mFlowsBuf);\n\n std::fill (mData.begin(), mData.end(), 0);\n\n }\n\n\n\n void SplineLossyCompress(const std::string &strategy, int order, char *bad_wells, float *mad);\n\n void SplineLossyCompress(const std::string &strategy, int order, int flow_ix, char *bad_wells, float *mad);\n\n static void SplineLossyCompress(const std::string &strategy, int order, int flow_ix, char *bad_wells, \n\n float *mad, size_t num_rows, size_t num_cols, size_t num_frames, size_t num_flows,\n\n int use_mesh_neighbors, size_t frame_stride, size_t flow_frame_stride, int16_t *data);\n\n\n\n void PcaLossyCompress(int row_start, int row_end,\n\n int col_start, int col_end,\n\n int flow_ix,\n\n float *ssq, char *filters,\n\n int row_step, int col_step,\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 18, "score": 67820.18257703859 }, { "content": " int num_pca);\n\n static bool PcaLossyCompressChunk(int row_start, int row_end,\n\n int col_start, int col_end,\n\n int num_rows, int num_cols, int num_frames,\n\n int frame_stride,\n\n int flow_ix, int flow_frame_stride,\n\n short *data, bool replace,\n\n float *ssq, char *filters,\n\n int row_step, int col_step,\n\n int num_pca);\n\n\n\n void SetFlowIndex (size_t flowIx, size_t index) {\n\n // no op, we store things in a specific flow order\n\n assert(0);\n\n }\n\n\n\n size_t GetNumFrames() { return mFrames; }\n\n size_t GetNumWells() { return mRows * mCols; }\n\n size_t GetNumRows() { return mRows; }\n\n size_t GetNumCols() { return mCols; }\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 19, "score": 67820.07310219276 }, { "content": "\n\n void IndexToRowCol (size_t index, size_t &rowIx, size_t &colIx) {\n\n rowIx = index / mCols;\n\n colIx = index % mCols;\n\n }\n\n\n\n int PrepareReference(size_t flowIx, std::vector<char> &filteredWells);\n\n\n\n int PrepareReferenceOld (size_t flowIx, std::vector<char> &filteredWells);\n\n\n\n virtual int GetReferenceTrace (size_t wellIx, size_t flowIx,\n\n float *traceBegin) {\n\n size_t row, col;\n\n IndexToRowCol (wellIx, row, col);\n\n mRefReduction[flowIx].GetSmoothEstFrames(row, col, traceBegin);\n\n return TSM_OK;\n\n }\n\n\n\n virtual void SetT0 (std::vector<float> &t0) { mT0 = t0; }\n\n\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 20, "score": 67819.83745907334 }, { "content": " int count = 0;\n\n float totalWells = (colEnd - colStart) * (rowEnd - rowStart);\n\n for (int rowIx = rowStart; rowIx < rowEnd; rowIx++) {\n\n for (int colIx = colStart; colIx < colEnd; colIx++) {\n\n if (filteredWells[rowIx * mCols + colIx] == 0) {\n\n count++;\n\n }\n\n }\n\n }\n\n float percent = count/ totalWells;\n\n return( count >= minWells && percent >= minPercent);\n\n }\n\n\n\n void CalcReference (size_t rowStep, size_t colStep, size_t flowIx,\n\n GridMesh<std::vector<float> > &gridReference,\n\n std::vector<char> &filteredWells) {\n\n gridReference.Init (mRows, mCols, rowStep, colStep);\n\n int numBin = gridReference.GetNumBin();\n\n int rowStart = -1, rowEnd = -1, colStart = -1, colEnd = -1;\n\n for (int binIx = 0; binIx < numBin; binIx++) {\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 21, "score": 67819.74062446834 }, { "content": " std::vector<float> &reference);\n\n\n\n int CalcRegionReference (int rowStart, int rowEnd,\n\n int colStart, int colEnd, size_t flowIx,\n\n std::vector<float> &trace) {\n\n trace.resize (mFrames);\n\n std::fill (trace.begin(), trace.end(), 0.0f);\n\n vector<vector<float> > matrix;\n\n vector<float> traceBuffer (mFrames,0);\n\n matrix.resize (trace.size());\n\n for (int rowIx = rowStart; rowIx < rowEnd; rowIx++)\n\n {\n\n for (int colIx = colStart; colIx < colEnd; colIx++)\n\n {\n\n size_t wellIdx = RowColToIndex (rowIx,colIx);\n\n if (mUseAsReference[wellIdx])\n\n {\n\n GetTrace (wellIdx, flowIx, traceBuffer.begin());\n\n for (size_t frameIx = 0; frameIx < traceBuffer.size(); frameIx++)\n\n {\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 22, "score": 67816.20498018654 }, { "content": " virtual float GetT0 (int idx) { return mT0[idx]; }\n\n\n\n void SetMeshDist (int size) { \n\n mUseMeshNeighbors = size; \n\n mMaxDist = (size+1) * sqrt(mRowRefStep*mRowRefStep + mColRefStep+mColRefStep); \n\n }\n\n\n\n int GetMeshDist() { return mUseMeshNeighbors; }\n\n float GetMaxDist() { return mMaxDist; }\n\n\n\n /** wIx is the well index from mWellIndex, not the usual global one. */\n\n inline size_t ToIdx (size_t wIx, size_t frameIx, size_t flowIx) {\n\n // Organize so flows for same well are near each other.\n\n return (wIx + flowIx * mFrameStride + frameIx * mFlowFrameStride);\n\n }\n\n\n\n int CalcMedianReference (size_t row, size_t col,\n\n GridMesh<std::vector<float> > &regionMed,\n\n std::vector<double> &dist,\n\n std::vector<std::vector<float> *> &values,\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 23, "score": 67814.09305642534 }, { "content": " }\n\n else\n\n {\n\n med = matrix[i][length/2];\n\n }\n\n trace[i] = med;\n\n }\n\n return TraceStore::TS_OK;\n\n }\n\n else\n\n {\n\n trace.resize (0);\n\n }\n\n return TraceStore::TS_BAD_REGION;\n\n }\n\n\n\n int16_t *GetMemPtr() { return &mData[0]; }\n\n\n\n bool RegionOk(int rowStart, int rowEnd, int colStart, int colEnd, std::vector<char> &filteredWells,\n\n int minWells, float minPercent) {\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 24, "score": 67813.3580054554 }, { "content": " gridReference.GetBinCoords (binIx, rowStart, rowEnd, colStart, colEnd);\n\n vector<float> &trace = gridReference.GetItem (binIx);\n\n if (RegionOk(rowStart,rowEnd, colStart,colEnd, filteredWells, MIN_REGION_REF_WELLS, MIN_REGION_REF_PERCENT)) {\n\n CalcRegionReference (rowStart, rowEnd, colStart, colEnd, flowIx, trace);\n\n }\n\n else {\n\n trace.resize(0);\n\n }\n\n }\n\n }\n\n\n\n void WellProj(TraceStoreCol &store,\n\n std::vector<KeySeq> & key_vectors,\n\n vector<char> &filter,\n\n vector<float> &mad);\n\n\n\n size_t mFrames;\n\n size_t mFrameStride;\n\n size_t mFlowFrameStride;\n\n size_t mFlows;\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 25, "score": 67811.75877227011 }, { "content": " *out = (int16_t) (*traceBegin + .5);\n\n traceBegin++;\n\n out += mFlowFrameStride;\n\n }\n\n return TSM_OK;\n\n }\n\n\n\n int SetTrace (size_t wellIx, size_t flowIx,\n\n float * traceBegin, \n\n float * traceEnd) {\n\n int16_t *__restrict out = &mData[0] + flowIx * mFrameStride + wellIx;\n\n while (traceBegin != traceEnd) {\n\n *out = (int16_t) (*traceBegin + .5);\n\n traceBegin++;\n\n out += mFlowFrameStride;\n\n }\n\n return TSM_OK;\n\n }\n\n\n\n size_t RowColToIndex (size_t rowIx, size_t colIx) { return rowIx * mCols + colIx; }\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 26, "score": 67811.05979629162 }, { "content": " if (isfinite (traceBuffer[frameIx]))\n\n {\n\n matrix[frameIx].push_back (traceBuffer[frameIx]);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n size_t length = matrix[0].size();\n\n size_t size = matrix.size();\n\n size_t minRefProbes = max(TSM_MIN_REF_PROBES, (int)floor(1.0 * mMinRefProbes * (1.0 * (rowEnd - rowStart) * (colEnd-colStart) / (mRowRefStep * mColRefStep))));\n\n if (length >= minRefProbes)\n\n {\n\n for (size_t i = 0; i < size; i++)\n\n {\n\n std::sort (matrix[i].begin(), matrix[i].end());\n\n float med = 0;\n\n if (matrix[i].size() % 2 == 0)\n\n {\n\n med = (matrix[i][length / 2] + matrix[i][ (length / 2)-1]) /2.0;\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 27, "score": 67809.97077331207 }, { "content": " size_t mRows;\n\n size_t mCols;\n\n size_t mWells;\n\n size_t mFlowsBuf;\n\n size_t mRowRefStep;\n\n size_t mColRefStep;\n\n size_t mMinRefProbes;\n\n\n\n std::string mFlowOrder;\n\n std::vector<bool> mUseAsReference;\n\n std::vector<char> mRefWells;\n\n std::vector<int16_t> mData;\n\n std::vector<int> mRefGridsValid;\n\n std::vector<GridMesh<std::vector<float> > > mRefGrids;\n\n std::vector<GridMesh<std::vector<float> > > mFineRefGrids;\n\n std::vector<double> mDist;\n\n std::vector<std::vector<float> *> mValues;\n\n std::vector<float> mReference;\n\n std::vector<float> mT0;\n\n std::vector<double> mTime;\n\n std::vector<ChipReduction> mRefReduction;\n\n float mMaxDist;\n\n // Cube<int8_t> mData; // rows = frames, cols = wells,\n\n pthread_mutex_t mLock;\n\n int mUseMeshNeighbors;\n\n };\n\n\n\n#endif // TRACESTORECOL_H\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 28, "score": 67808.9821624242 }, { "content": "\tstd::vector<unsigned int> TimeStamps(bool normalized);\n\n\n\n\n\n\n\n\tunsigned int Row2avg4row(const unsigned int wholeChipRow); // convert row in whole chip coordinate to the corresponding row in senseTrace_avg4\n\n\n\n\tvoid Row2RowsumRows(const unsigned int row, std::vector<unsigned int> & rowsumRows);\n\n\n\n\n\n\tstd::vector<float> CompressFrames(\n\n\t\t\tconst std::vector<float> & rowTrace,\n\n\t\t\tstd::vector<float> & rowTrace_vfc,\n\n\t\t\tconst std::vector<unsigned int> & timeStampOrig,\n\n\t\t\tconst std::vector<unsigned int> & timeStampNew);\n\n\n\n\t// Return if the 4-row-averaged sensing electrode trace is valid. row is whole chip row.\n\n\tbool isValidAvg4(unsigned int row);\n\n\n\n\n\n\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 29, "score": 67807.02332281577 }, { "content": "\n\nprivate:\n\n\n\n\t// compute sensing electrode traces for in (row,frame) format.\n\n\tvoid ComputeSenseTrace();\n\n\n\n\t// filter the trace with median filter.\n\n\tvoid medianFilterTrace(const unsigned int order);\n\n\n\n\t// calculate median\n\n\tfloat median(const float * v1, const unsigned int order);\n\n\n\n\t// compute sense electrode traces, averaged over four rows that are acquired simultaneously.\n\n\tvoid ComputeSenseTrace_avg4();\n\n\n\n\t// adjust the offset of trace to zero by zeroing the first numOffsetFrames frames.\n\n\tvoid ZeroTrace(std::vector<float> & trace, const unsigned int numOffsetFrames);\n\n\n\n\tstd::vector<uint32_t> rowsum; // row sum raw data from file\n\n\tstd::vector<std::vector<float> > senseTrace; // rowsum data averaged by pixelsInSum. (Only the needed rows are populated)\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 30, "score": 67806.50473188127 }, { "content": " size_t GetNumFlows() { return mFlows; }\n\n size_t GetFlowBuff() { return GetNumFlows(); }\n\n const std::string &GetFlowOrder() { return mFlowOrder; }\n\n double GetTime (size_t frame) { return mTime.at (frame); }\n\n void SetTime(double *time, int npts) { mTime.resize(npts); std::copy(time, time+npts, mTime.begin()); }\n\n\n\n bool HaveWell (size_t wellIx) { return true; }\n\n\n\n void SetHaveWellFalse (size_t wellIx) { assert(0); }\n\n\n\n bool HaveFlow (size_t flowIx) { return flowIx < mFlows; }\n\n\n\n void SetReference(size_t wellIx, bool isReference) { mUseAsReference[wellIx] = isReference; }\n\n\n\n bool IsReference (size_t wellIx) { return mUseAsReference[wellIx]; }\n\n\n\n inline int GetTrace (size_t wellIx, size_t flowIx, std::vector<float>::iterator traceBegin) {\n\n int16_t *__restrict start = &mData[0] + flowIx * mFrameStride + wellIx;\n\n int16_t *__restrict end = start + mFlowFrameStride * mFrames;\n\n while (start != end) {\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 31, "score": 67802.76315080785 }, { "content": "\t\t\tconst unsigned int row,\n\n\t\t\tconst unsigned int numOffsetFrames);\n\n\n\n\t// return the 4-row averaged sensing electrode trace in time compressed resolution with trace offset\n\n\t// adjusted to zero by subtracting the average of the first numOffsetFrames points.\n\n\t// the frames are compressed according to the new time stamps, normalized by the rowsum frame interval.\n\n\tstd::vector<float> RowTrace_avg4(\n\n\t\t\tconst unsigned int row,\n\n\t\t\tconst unsigned int numOffsetFrames,\n\n\t\t\tconst std::vector<unsigned int> newTimeStamps);\n\n\n\n\t// returns total number of rows\n\n\tunsigned int NumRows();\n\n\n\n\t// return frame rate in msec\n\n\tfloat FrameRate();\n\n\n\n\t// return time stamp.\n\n\t// normalized = true: returns time stamps normalized by frame intervals.\n\n\t// normalized = false: returns time stamps in msec.\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 32, "score": 67802.10610104837 }, { "content": "/* Copyright (C) 2014 Ion Torrent Systems, Inc. All Rights Reserved */\n\n\n\n/*\n\n * RowSumData.h\n\n *\n\n * Created on: Jan 21, 2014\n\n * Author: awong\n\n */\n\n\n\n#ifndef ROWSUMDATA_H\n\n#define ROWSUMDATA_H\n\n\n\n#include <fstream>\n\n#include<vector>\n\n#include \"../datahdr.h\"\n\n#include <algorithm>\n\n\n\n// rowsum data class for reading and storing sensing electrode data\n\n// rowsum data is always full chip (all rows). Thus row arguments is always in full chip coordinates\n\n\n\n// TODO would there be a condition that different process is trying to read the same rowsum file? any problem?\n\n\n\n\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 33, "score": 67801.58400507487 }, { "content": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#ifndef TRACESTORECOL_H\n\n#define TRACESTORECOL_H\n\n\n\n#include <algorithm>\n\n#include <iostream>\n\n#include \"Mask.h\"\n\n#include \"TraceStore.h\"\n\n#include \"MathOptim.h\"\n\n#include \"GridMesh.h\"\n\n#include \"ChipReduction.h\"\n\n#define TSM_MIN_REF_PROBES 10\n\n#define TSM_OK 1\n\n#define MIN_REGION_REF_WELLS 50\n\n#define MIN_REGION_REF_PERCENT 0.20f\n\n#define REF_REDUCTION_SIZE 10\n\n#define REF_SMOOTH_SIZE 100\n\n#define THUMBNAIL_SIZE 100\n\n/**\n\n * Abstract interface to a repository for getting traces.\n\n */\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 34, "score": 67801.0743332071 }, { "content": "\tstd::vector<std::vector<float> > senseTrace_avg4; // 4 row averaged sensing electrode data\n\n\n\n\tstd::vector< bool > isValid_avg4; // whether the 4-row-averaged sensing electrode data is valid\n\n\n\n\tfloat baseFrameRate; // in msec defined the same rate as in raw struct. (Need to be float. int does not have enough precision when calculating frame numbers.)\n\n\tuint32_t pixelsInSum; // number of pixels summed in each rowsum data\n\n\tuint32_t sumsPerRow; // number of rowsum values per row\n\n\tuint32_t sskey; // The first field in the header of a rowsum file\n\n\tuint32_t version; // version number of rowsum data file\n\n\tuint32_t numRows; // total number of rows of the chip\n\n\tuint32_t numFrames; // number of frames in the rowsum data\n\n\n\n\tstd::vector<unsigned int> startRowList; // first row of isfet data in whole chip coordinate\n\n\tstd::vector<unsigned int> endRowList; // last + 1 row of isfet data in whole chip coordinate\n\n\n\n\tstd::string fileName; // file name of the rowsum file\n\n\tstd::vector<bool> isValid; // indicate if a rowsum trace is valid.\n\n\tstd::vector<bool> isNeeded; // if a row is needed from the data. If isNeeded rows will go through further processing\n\n\n\n\tuint32_t lowPin, highPin; // low and high values for pinned rowsum\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 35, "score": 67799.99165992806 }, { "content": "\tunsigned int numPinnedLow, numPinnedHigh; // number of low and high pin values in the rows needed.\n\n\n\n\tbool DEBUG;\n\n\tbool topHalfOnly;\n\n\n\n};\n\n\n\n\n\n#endif // ROWSUMDATA_H\n", "file_path": "Analysis/Image/RowSumData.h", "rank": 36, "score": 67798.70988215998 }, { "content": " *traceBegin++ = *start;\n\n start += mFlowFrameStride;\n\n }\n\n return TSM_OK;\n\n }\n\n\n\n inline int GetTrace (size_t wellIx, size_t flowIx, float *traceBegin) {\n\n int16_t *__restrict start = &mData[0] + flowIx * mFrameStride + wellIx;\n\n int16_t *__restrict end = start + mFlowFrameStride * mFrames;\n\n while (start != end) {\n\n *traceBegin++ = *start;\n\n start += mFlowFrameStride;\n\n }\n\n return TSM_OK;\n\n }\n\n\n\n inline int SetTrace (size_t wellIx, size_t flowIx,\n\n std::vector<float>::iterator traceBegin, std::vector<float>::iterator traceEnd) {\n\n int16_t *__restrict out = &mData[0] + flowIx * mFrameStride + wellIx;\n\n while (traceBegin != traceEnd) {\n", "file_path": "Analysis/Separator/TraceStoreCol.h", "rank": 37, "score": 67797.9682246845 }, { "content": " }\n\n}\n\n\n\n\n\n\n\n// Compress a block of a data using pca\n\nvoid TraceStoreCol::PcaLossyCompress(int row_start, int row_end,\n\n int col_start, int col_end,\n\n int flow_ix,\n\n float *ssq, char *filters,\n\n int row_step, int col_step,\n\n int num_pca) {\n\n\n\n Eigen::MatrixXf Ysub, Y, S, Basis;\n\n\n\n int loc_num_wells = (col_end - col_start) * (row_end - row_start);\n\n int loc_num_cols = col_end - col_start;\n\n\n\n // Take a sample of the data at rate step, avoiding flagged wells\n\n // Count the good rows\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 38, "score": 66251.13722322386 }, { "content": " \n\n}\n\n\n\nvoid TraceStoreCol::Init(Mask &mask, size_t frames, const char *flowOrder,\n\n int numFlowsBuff, int maxFlow, int rowStep, int colStep) {\n\n\n\n pthread_mutex_init (&mLock, NULL);\n\n mUseMeshNeighbors = 1;\n\n mRowRefStep = rowStep;\n\n mColRefStep = colStep;\n\n mMinRefProbes = floor (mRowRefStep * mColRefStep * .1);\n\n mRows = mask.H();\n\n mCols = mask.W();\n\n mFrames = frames;\n\n mFrameStride = mRows * mCols;\n\n mFlows = mFlowsBuf = maxFlow;\n\n mFlowFrameStride = mFrameStride * maxFlow;\n\n mMaxDist = 2 * sqrt(rowStep*rowStep + colStep+colStep);\n\n mFlowOrder = flowOrder;\n\n \n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 39, "score": 66249.28216777739 }, { "content": " for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n size_t store_offset = row_ix * num_cols + col_start;\n\n float * ssq_start = ssq + store_offset;\n\n float * ssq_end = ssq_start + loc_num_cols;\n\n while (ssq_start != ssq_end) {\n\n *ssq_start /= num_frames;\n\n ssq_start++;\n\n }\n\n }\n\n return true;\n\n}\n\n\n\nvoid TraceStoreCol::SplineLossyCompress(const std::string &strategy, int order, int flow_ix, char *bad_wells, \n\n float *mad, size_t num_rows, size_t num_cols, size_t num_frames, size_t num_flows,\n\n int use_mesh_neighbors, size_t frame_stride, size_t flow_frame_stride, int16_t *data) {\n\n Eigen::MatrixXf Basis;\n\n vector<float> knots;\n\n FillInKnots(strategy, num_frames, knots);\n\n if (!knots.empty()) {\n\n int boundaries[2];\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 40, "score": 66247.59019124214 }, { "content": "}\n\n\n\nbool TraceStoreCol::PcaLossyCompressChunk(int row_start, int row_end,\n\n int col_start, int col_end,\n\n int num_rows, int num_cols, int num_frames,\n\n int frame_stride,\n\n int flow_ix, int flow_frame_stride,\n\n short *data, bool replace,\n\n float *ssq, char *filters,\n\n int row_step, int col_step,\n\n int num_pca) {\n\n\n\n Eigen::MatrixXf Ysub, Y, S, Basis;\n\n\n\n int loc_num_wells = (col_end - col_start) * (row_end - row_start);\n\n int loc_num_cols = col_end - col_start;\n\n\n\n // Take a sample of the data at rate step, avoiding flagged wells\n\n // Count the good rows\n\n int sample_wells = 0;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 41, "score": 66247.51135159288 }, { "content": " int sample_wells = 0;\n\n for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n\n char *filt_start = filters + row_ix * mCols + col_start;\n\n char *filt_end = filt_start + loc_num_cols;\n\n while (filt_start < filt_end) {\n\n if (*filt_start == 0) {\n\n sample_wells++;\n\n }\n\n filt_start += col_step;\n\n }\n\n }\n\n // try backing off to every well rather than just sampled if we didn't get enough\n\n if (sample_wells < MIN_SAMPLE_WELL) {\n\n row_step = 1;\n\n col_step = 1;\n\n int sample_wells = 0;\n\n for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n\n char *filt_start = filters + row_ix * mCols + col_start;\n\n char *filt_end = filt_start + loc_num_cols;\n\n while (filt_start < filt_end) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 42, "score": 66246.07586266546 }, { "content": "/* Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved */\n\n/*\n\n * RowSumCorrector.cpp\n\n *\n\n * Created on: Aug 13, 2015\n\n * Author: ionadmin\n\n */\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <unistd.h>\n\n#include \"RowSumCorrector.h\"\n\n\n\n\n\nvoid RemoveDCOffset(short int *avgs, int rows, int frames)\n\n{\n\n\tfor(int row=0;row<rows;row++){\n\n\t\tfloat avg=0;\n\n\t\tfor(int frame=0;frame<frames;frame++){\n\n\t\t\tavg += avgs[frame*rows+row];\n\n\t\t}\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 43, "score": 66245.86937557661 }, { "content": "\n\n // Copy in all the data into working matrix\n\n Y.resize(loc_num_wells, (int)num_frames);\n\n for (int frame_ix = 0; frame_ix < (int)num_frames; frame_ix++) {\n\n for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n size_t store_offset = row_ix * num_cols + col_start;\n\n int16_t *trace_start = data + (flow_frame_stride * frame_ix) + (flow_ix * frame_stride) + store_offset;\n\n int16_t *trace_end = trace_start + loc_num_cols;\n\n float * y_start = Y.data() + loc_num_wells * frame_ix + (row_ix - row_start) * loc_num_cols;\n\n while( trace_start != trace_end ) {\n\n *y_start++ = *trace_start++;\n\n }\n\n }\n\n }\n\n Eigen::VectorXf col_mean = Y.colwise().sum();\n\n col_mean /= Y.rows();\n\n\n\n for (int i = 0; i < Y.cols(); i++) {\n\n Y.col(i).array() -= col_mean.coeff(i);\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 44, "score": 66245.73139074162 }, { "content": " for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n\n char *filt_start = filters + row_ix * num_cols + col_start;\n\n char *filt_end = filt_start + loc_num_cols;\n\n while (filt_start < filt_end) {\n\n if (*filt_start == 0) {\n\n sample_wells++;\n\n }\n\n filt_start += col_step;\n\n }\n\n }\n\n // try backing off to every well rather than just sampled if we didn't get enough\n\n if (sample_wells < MIN_SAMPLE_WELL) {\n\n row_step = 1;\n\n col_step = 1;\n\n int sample_wells = 0;\n\n for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n\n char *filt_start = filters + row_ix * num_cols + col_start;\n\n char *filt_end = filt_start + loc_num_cols;\n\n while (filt_start < filt_end) {\n\n if (*filt_start == 0) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 45, "score": 66245.42449320384 }, { "content": " if (*filt_start == 0) {\n\n sample_wells++;\n\n }\n\n filt_start += col_step;\n\n }\n\n }\n\n }\n\n\n\n if (sample_wells < MIN_SAMPLE_WELL) {\n\n return; // just give up\n\n }\n\n\n\n // Copy the sampled data in Matrix, frame major\n\n Ysub.resize(sample_wells, mFrames);\n\n for (int frame_ix = 0; frame_ix < (int)mFrames; frame_ix++) {\n\n int sample_offset = 0;\n\n for (int row_ix = row_start; row_ix < row_end; row_ix+=row_step) {\n\n size_t store_offset = row_ix * mCols + col_start;\n\n char *filt_start = filters + store_offset;\n\n char *filt_end = filt_start + loc_num_cols;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 46, "score": 66245.23325098505 }, { "content": "\n\n\n\nint TraceStoreCol::PrepareReferenceOld (size_t flowIx, std::vector<char> &filteredWells) {\n\n int fIdx = flowIx;\n\n CalcReference (mRowRefStep, mColRefStep, flowIx, mRefGrids[fIdx], filteredWells);\n\n mRefGridsValid[fIdx] = 1;\n\n mFineRefGrids.resize (mRefGrids.size());\n\n mFineRefGrids[fIdx].Init (mRows, mCols, mRowRefStep/2, mColRefStep/2);\n\n int numBin = mFineRefGrids[fIdx].GetNumBin();\n\n int rowStart = -1, rowEnd = -1, colStart = -1, colEnd = -1;\n\n for (int binIx = 0; binIx < numBin; binIx++) {\n\n mFineRefGrids[fIdx].GetBinCoords (binIx, rowStart, rowEnd, colStart, colEnd);\n\n vector<float> &trace = mFineRefGrids[fIdx].GetItem (binIx);\n\n CalcMedianReference ( (rowEnd + rowStart) /2, (colEnd + colStart) /2, mRefGrids[fIdx],\n\n mDist, mValues, trace);\n\n }\n\n return TSM_OK;\n\n }\n\n\n\n\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 47, "score": 66245.02298131624 }, { "content": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include <malloc.h>\n\n#include \"Utils.h\"\n\n#include \"TraceStoreCol.h\"\n\n#include \"IonH5Eigen.h\"\n\n//#define EIGEN_USE_MKL_ALL 1\n\n#include <Eigen/Dense>\n\n#include <Eigen/LU>\n\n\n\n#define MIN_SAMPLE_WELL 100\n\n#define SMOOTH_REDUCE_STEP 10\n\n#define SMOOTH_REDUCE_REGION 100\n\n#define INTEGRATION_START 6\n\n#define INTEGRATION_END 12\n\nvoid TraceStoreCol::WellProj(TraceStoreCol &store,\n\n std::vector<KeySeq> & key_vectors,\n\n vector<char> &filter,\n\n vector<float> &mad) {\n\n int useable_flows = 0;\n\n for (size_t i = 0; i < key_vectors.size(); i++) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 48, "score": 66244.95331269052 }, { "content": "}\n\n\n\n/**\n\n * Create the augmented knots vector and fill in matrix Xt with the spline basis vectors\n\n */\n\nvoid basis_splines_endreps_local_v2(float *knots, int n_knots, int order, int *boundaries, int n_boundaries, Eigen::MatrixXf &Xt) {\n\n assert(n_boundaries == 2 && boundaries[0] < boundaries[1]);\n\n int n_rows = boundaries[1] - boundaries[0]; // this is frames so evaluate at each frame we'll need\n\n int n_cols = n_knots + order; // number of basis vectors we'll have at end \n\n Xt.resize(n_cols, n_rows); // swapped to transpose later. This order lets us use it as a scratch space\n\n Xt.fill(0);\n\n int n_std_knots = n_knots + 2 * order;\n\n float std_knots[n_std_knots];\n\n\n\n // Repeat the boundary knots on there to ensure linear out side of knots\n\n for (int i = 0; i < order; i++) {\n\n std_knots[i] = boundaries[0];\n\n }\n\n // Our original boundary knots here\n\n for (int i = 0; i < n_knots; i++) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 49, "score": 66244.81569879211 }, { "content": " for (int i = 0; i < Yhat.cols(); i++) {\n\n Yhat.col(i).array() += col_mean.coeff(i);\n\n Y.col(i).array() += col_mean.coeff(i);\n\n }\n\n \n\n // H5File h5(\"pca_lossy.h5\");\n\n // h5.Open();\n\n // char buff[256];\n\n // snprintf(buff, sizeof(buff), \"/Y_%d_%d_%d\", flow_ix, row_start, col_start);\n\n // H5Eigen::WriteMatrix(h5, buff, Y);\n\n // snprintf(buff, sizeof(buff), \"/Yhat_%d_%d_%d\", flow_ix, row_start, col_start);\n\n // H5Eigen::WriteMatrix(h5, buff, Yhat);\n\n // snprintf(buff, sizeof(buff), \"/Basis_%d_%d_%d\", flow_ix, row_start, col_start);\n\n // H5Eigen::WriteMatrix(h5, buff, Basis);\n\n // h5.Close();\n\n // Copy data out of yhat matrix into original data structure, keeping track of residuals\n\n for (int frame_ix = 0; frame_ix < (int)num_frames; frame_ix++) {\n\n for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n size_t store_offset = row_ix * num_cols + col_start;\n\n int16_t *trace_start = data + flow_frame_stride * frame_ix + flow_ix * frame_stride + store_offset;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 50, "score": 66244.44431726767 }, { "content": " Ysub.resize(sample_wells, num_frames);\n\n for (int frame_ix = 0; frame_ix < (int)num_frames; frame_ix++) {\n\n int sample_offset = 0;\n\n for (int row_ix = row_start; row_ix < row_end; row_ix+=row_step) {\n\n size_t store_offset = row_ix * num_cols + col_start;\n\n char *filt_start = filters + store_offset;\n\n char *filt_end = filt_start + loc_num_cols;\n\n int16_t *trace_start = data + (flow_frame_stride * frame_ix) + (flow_ix * frame_stride) + store_offset;\n\n float *ysub_start = Ysub.data() + sample_wells * frame_ix + sample_offset;\n\n while (filt_start < filt_end) {\n\n if (*filt_start == 0) {\n\n *ysub_start = *trace_start;\n\n ysub_start++;\n\n sample_offset++;\n\n }\n\n trace_start += col_step;\n\n filt_start += col_step;\n\n }\n\n }\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 51, "score": 66244.13629888179 }, { "content": " int16_t *trace_start = &mData[0] + (mFlowFrameStride * frame_ix) + (flow_ix * mFrameStride) + store_offset;\n\n float *ysub_start = Ysub.data() + sample_wells * frame_ix + sample_offset;\n\n while (filt_start < filt_end) {\n\n if (*filt_start == 0) {\n\n *ysub_start = *trace_start;\n\n ysub_start++;\n\n sample_offset++;\n\n }\n\n trace_start += col_step;\n\n filt_start += col_step;\n\n }\n\n }\n\n }\n\n\n\n // Copy in all the data into working matrix\n\n Y.resize(loc_num_wells, (int)mFrames);\n\n for (int frame_ix = 0; frame_ix < (int)mFrames; frame_ix++) {\n\n for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n size_t store_offset = row_ix * mCols + col_start;\n\n int16_t *trace_start = &mData[0] + (mFlowFrameStride * frame_ix) + (flow_ix * mFrameStride) + store_offset;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 52, "score": 66243.45872819766 }, { "content": "\treturn rc;\n\n}\n\n\n\nshort int *CreateRowSumCorrection(short int *image, int rows, int cols, int frames)\n\n{\n\n\t// from Donohues matlab code...\n\n\tint frameStride=rows*cols;\n\n\n\n\tint avgsLen=sizeof(short int)*rows*frames;\n\n\tshort int *avgs = (short int *)malloc(avgsLen);\n\n\tshort int *corr = (short int *)malloc(avgsLen);\n\n\tmemset(corr,0xff,avgsLen);\n\n\tfor(int frame=0;frame<frames;frame++){\n\n\t\tfor(int row=0;row<rows;row++){\n\n\t\t\tfloat avg = 0;\n\n\t\t\tfor(int col=0;col<cols;col++){\n\n\t\t\t\tavg += image[frame*frameStride+row*cols+col];\n\n\t\t\t}\n\n\t\t\tavg /= (float)cols;\n\n\t\t\tavgs[frame*rows+row] = (short int)avg;\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 53, "score": 66242.71255561912 }, { "content": " sample_wells++;\n\n }\n\n filt_start += col_step;\n\n }\n\n }\n\n }\n\n\n\n if (sample_wells < MIN_SAMPLE_WELL) {\n\n return false; // just give up\n\n }\n\n\n\n // Got enough data to work with, zero out the ssq array for accumulation\n\n for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n float *ssq_start = ssq + row_ix * num_cols + col_start;\n\n float *ssq_end = ssq_start + loc_num_cols;\n\n while (ssq_start != ssq_end) {\n\n *ssq_start++ = 0;\n\n }\n\n }\n\n // Copy the sampled data in Matrix, frame major\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 54, "score": 66242.61508460241 }, { "content": " // char buff[256];\n\n // snprintf(buff, sizeof(buff), \"/Y_%d_%d_%d\", flow_ix, row_start, col_start);\n\n // H5Eigen::WriteMatrix(h5, buff, Y);\n\n // snprintf(buff, sizeof(buff), \"/Yhat_%d_%d_%d\", flow_ix, row_start, col_start);\n\n // H5Eigen::WriteMatrix(h5, buff, Yhat);\n\n // snprintf(buff, sizeof(buff), \"/Basis_%d_%d_%d\", flow_ix, row_start, col_start);\n\n // H5Eigen::WriteMatrix(h5, buff, Basis);\n\n // h5.Close();\n\n // Copy data out of yhat matrix into original data structure, keeping track of residuals\n\n for (int frame_ix = 0; frame_ix < (int)mFrames; frame_ix++) {\n\n for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n size_t store_offset = row_ix * mCols + col_start;\n\n int16_t *trace_start = &mData[0] + mFlowFrameStride * frame_ix + flow_ix * mFrameStride + store_offset;\n\n int16_t *trace_end = trace_start + loc_num_cols;\n\n float * ssq_start = ssq + store_offset;\n\n size_t loc_offset = (row_ix - row_start) * loc_num_cols;\n\n float * y_start = Y.data() + loc_num_wells * frame_ix + loc_offset;\n\n float * yhat_start = Yhat.data() + loc_num_wells * frame_ix + loc_offset;\n\n while( trace_start != trace_end ) {\n\n *trace_start = (int16_t)(*yhat_start + .5);\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 55, "score": 66242.42880582008 }, { "content": "\n\n // std::vector<ChipReduction> smoothed_avg(useable_flows);\n\n // int x_clip = mCols;\n\n // int y_clip = mRows;\n\n // if (mUseMeshNeighbors == 0) {\n\n // x_clip = THUMBNAIL_SIZE;\n\n // y_clip = THUMBNAIL_SIZE;\n\n // }\n\n // int last_frame = store.GetNumFrames() - 1;\n\n // for (int flow_ix = 0; flow_ix < useable_flows; flow_ix++) {\n\n // smoothed_avg[flow_ix].Init(mRows, mCols, 1,\n\n // SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n\n // y_clip, x_clip,\n\n // SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n\n // smoothed_avg[flow_ix].ReduceFrame(&mData[0] + flow_ix * mFrameStride + last_frame * mFlowFrameStride, &filter[0], 0);\n\n // smoothed_avg[flow_ix].SmoothBlocks(SMOOTH_REDUCE_REGION, SMOOTH_REDUCE_REGION);\n\n // }\n\n // int x_count = 0;\n\n // for (int flow_ix = 0; flow_ix < useable_flows; flow_ix++) {\n\n // for (size_t row_ix = 0; row_ix < mRows; row_ix++) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 56, "score": 66242.3149659737 }, { "content": "\n\n ~LSRowImageProcessor()\n\n {\n\n delete [] indicies;\n\n }\n\n\n\nprivate:\n\n\n\n bool GenerateGroupCorrection(int group_num,float *vect_output,int rows,int cols,uint16_t *img);\n\n void AccumulateMatrixData(double *lhs,double *rhs,double *amat,double bval);\n\n\n\n int nLen;\n\n int *indicies;\n\n};\n\n\n\n\n\n#endif // LSROWIMAGEPROCESSOR_H \n\n\n\n\n\n\n", "file_path": "Analysis/Image/LSRowImageProcessor.h", "rank": 57, "score": 66242.11235537841 }, { "content": " float val = *y_start - *yhat_start;\n\n *ssq_start += val * val;\n\n y_start++;\n\n yhat_start++;\n\n trace_start++;\n\n ssq_start++;\n\n }\n\n }\n\n }\n\n\n\n // divide ssq data out for per frame avg\n\n for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n\n size_t store_offset = row_ix * mCols + col_start;\n\n float * ssq_start = ssq + store_offset;\n\n float * ssq_end = ssq_start + loc_num_cols;\n\n while (ssq_start != ssq_end) {\n\n *ssq_start /= mFrames;\n\n ssq_start++;\n\n }\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 58, "score": 66241.98654847093 }, { "content": "int TraceStoreCol::CalcMedianReference (size_t row, size_t col,\n\n GridMesh<std::vector<float> > &regionMed,\n\n std::vector<double> &dist,\n\n std::vector<std::vector<float> *> &values,\n\n std::vector<float> &reference) {\n\n int retVal = TraceStore::TS_OK;\n\n reference.resize(mFrames);\n\n std::fill(reference.begin(), reference.end(), 0.0);\n\n regionMed.GetClosestNeighbors (row, col, mUseMeshNeighbors, dist, values);\n\n int num_good = 0;\n\n size_t valSize = values.size();\n\n for (size_t i =0; i < valSize; i++) {\n\n if (values[i]->size() > 0) {\n\n num_good++;\n\n }\n\n }\n\n // try reaching a little farther if no good reference close by\n\n if (num_good == 0) {\n\n regionMed.GetClosestNeighbors (row, col, 2*mUseMeshNeighbors, dist, values);\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 59, "score": 66241.85286401419 }, { "content": "\tif(cor){\n\n\n\n\t\t// correct the acq array\n\n\t\tfor(int frame=0;frame<raw->frames;frame++){\n\n\t\t\tfor(int row=0;row<raw->rows;row++){\n\n\t\t\t\tfor(int col=0;col<raw->cols;col++){\n\n\t\t\t\t\traw->image[frame*frameStride + row*raw->cols + col] -= cor[frame*raw->rows+row];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfree(cor);\n\n\t}\n\n\treturn rc;\n\n}\n\n#endif\n\n\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 60, "score": 66241.84504636034 }, { "content": " float *start = Y.data() + mFrameStride * frame_ix;\n\n float *end = start + mFrameStride;\n\n float *hstart = Yhat.data() + mFrameStride * frame_ix;\n\n for (size_t row = 0; row < mRows; row++) {\n\n for (size_t col = 0; col < mCols; col++) {\n\n float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n\n *start++ += avg;\n\n *hstart++ += avg;\n\n }\n\n }\n\n }\n\n\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n float *yhat_start = Yhat.data() + frame_ix * mFrameStride;\n\n float *yhat_end = yhat_start + mFrameStride;\n\n int16_t *trace_start = &mData[0] + flow_ix * mFrameStride + frame_ix * mFlowFrameStride;\n\n while(yhat_start != yhat_end) {\n\n *trace_start++ = (int)(*yhat_start + .5f);\n\n yhat_start++;\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 61, "score": 66240.93201420527 }, { "content": " int16_t *trace_end = trace_start + loc_num_cols;\n\n float * y_start = Y.data() + loc_num_wells * frame_ix + (row_ix - row_start) * loc_num_cols;\n\n while( trace_start != trace_end ) {\n\n *y_start++ = *trace_start++;\n\n }\n\n }\n\n }\n\n Eigen::VectorXf col_mean = Y.colwise().sum();\n\n col_mean /= Y.rows();\n\n\n\n for (int i = 0; i < Y.cols(); i++) {\n\n Y.col(i).array() -= col_mean.coeff(i);\n\n }\n\n // Create scatter matrix\n\n S = Ysub.transpose() * Ysub;\n\n // Compute the eigenvectors\n\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> es;\n\n es.compute(S);\n\n Eigen::MatrixXf Pca_Basis = es.eigenvectors();\n\n Eigen::VectorXf Pca_Values = es.eigenvalues();\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 62, "score": 66240.77366017329 }, { "content": " mRefWells[i] = 1;\n\n }\n\n }\n\n assert(flowIx < mRefReduction.size());\n\n\n\n int x_clip = mCols;\n\n int y_clip = mRows;\n\n if (mUseMeshNeighbors == 0) {\n\n x_clip = THUMBNAIL_SIZE;\n\n y_clip = THUMBNAIL_SIZE;\n\n }\n\n mRefReduction[flowIx].Init(mRows, mCols, mFrames,\n\n REF_REDUCTION_SIZE, REF_REDUCTION_SIZE, \n\n y_clip, x_clip, 1);\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n mRefReduction[flowIx].ReduceFrame(&mData[0] + flowIx * mFrameStride + frame_ix * mFlowFrameStride, &mRefWells[0], frame_ix);\n\n }\n\n mRefReduction[flowIx].SmoothBlocks(REF_SMOOTH_SIZE, REF_SMOOTH_SIZE);\n\n return TSM_OK;\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 63, "score": 66239.25125819608 }, { "content": " return;\n\n }\n\n\n\n ChipReduction smoothed_avg;\n\n int x_clip = num_cols;\n\n int y_clip = num_rows;\n\n if (use_mesh_neighbors == 0) {\n\n x_clip = THUMBNAIL_SIZE;\n\n y_clip = THUMBNAIL_SIZE;\n\n }\n\n\n\n smoothed_avg.Init(num_rows, num_cols, num_frames,\n\n SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n\n y_clip, x_clip,\n\n SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n\n for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n\n smoothed_avg.ReduceFrame(data + flow_ix * frame_stride + frame_ix * flow_frame_stride, bad_wells, frame_ix);\n\n }\n\n smoothed_avg.SmoothBlocks(SMOOTH_REDUCE_REGION, SMOOTH_REDUCE_REGION);\n\n\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 64, "score": 66239.25125819608 }, { "content": "\t\tavg /= frames;\n\n\t\tfor(int frame=0;frame<frames;frame++){\n\n\t\t\tavgs[frame*rows+row] -= avg;\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid Smooth(short int *avgs, int rows, int frames, int span)\n\n{\n\n\tint bufLen=sizeof(short int)*rows*frames;\n\n\tshort int *tmp = (short int *)malloc(bufLen);\n\n\tfor(int frame=0;frame<frames;frame++){\n\n\t\tfor(int row=0;row<rows;row++){\n\n\t\t\tfloat avg=0;\n\n\t\t\tint start_row = row-span;\n\n\t\t\tint end_row = row+span;\n\n\t\t\tif(start_row<0)\n\n\t\t\t\tstart_row=0;\n\n\t\t\tif(end_row>=rows)\n\n\t\t\t\tend_row=rows-1;\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 65, "score": 66239.13811171894 }, { "content": " }\n\n\n\n\n\n // // subtract them off\n\n // Eigen::VectorXf col_mean = Y.colwise().sum();\n\n // col_mean /= Y.rows();\n\n\n\n // for (int i = 0; i < Y.cols(); i++) {\n\n // Y.col(i).array() -= col_mean.coeff(i);\n\n // }\n\n\n\n // Get coefficients to solve\n\n Eigen::MatrixXf B = Y * SX.transpose();\n\n // Uncompress data into yhat matrix\n\n Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n\n\n\n // add the flow/frame averages back\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 66, "score": 66239.13687856751 }, { "content": " // for (size_t col_ix = 0; col_ix < mCols; col_ix++) {\n\n // float avg = smoothed_avg[flow_ix].GetSmoothEst(row_ix, col_ix, 0);\n\n // norm[x_count] = avg;\n\n // x_count++;\n\n // }\n\n // }\n\n // }\n\n\n\n norm = norm / count;\n\n // start_frame = INTEGRATION_START;\n\n // end_frame = INTEGRATION_END;\n\n start_frame = 5;\n\n end_frame = store.GetNumFrames() - 6;\n\n \n\n for (int frame_ix = start_frame; frame_ix < end_frame; frame_ix++) {\n\n int16_t *__restrict data_start = store.GetMemPtr() + frame_ix * store.mFlowFrameStride;\n\n int16_t *__restrict data_end = data_start + store.mFrameStride * useable_flows;\n\n float *__restrict norm_start = &norm[0];\n\n float *__restrict sum_start = &sum[0];\n\n int well_offset = 0;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 67, "score": 66238.99737174608 }, { "content": " char *bad_start = bad_wells;\n\n char *bad_end = bad_start + mFrameStride;\n\n while(bad_start != bad_end) {\n\n if (*bad_start++ == 0) {\n\n good_wells++;\n\n }\n\n }\n\n \n\n // if nothing good then skip it\n\n if (good_wells < MIN_SAMPLE_WELL) {\n\n return;\n\n }\n\n\n\n ChipReduction smoothed_avg;\n\n int x_clip = mCols;\n\n int y_clip = mRows;\n\n if (mUseMeshNeighbors == 0) {\n\n x_clip = THUMBNAIL_SIZE;\n\n y_clip = THUMBNAIL_SIZE;\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 68, "score": 66238.82796311633 }, { "content": " // if nothing good then skip it\n\n if (good_wells < MIN_SAMPLE_WELL) {\n\n return;\n\n }\n\n\n\n std::vector<ChipReduction> smoothed_avg(mFlows);\n\n int x_clip = mCols;\n\n int y_clip = mRows;\n\n if (mUseMeshNeighbors == 0) {\n\n x_clip = THUMBNAIL_SIZE;\n\n y_clip = THUMBNAIL_SIZE;\n\n }\n\n for (size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n\n smoothed_avg[flow_ix].Init(mRows, mCols, mFrames,\n\n SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n\n y_clip, x_clip,\n\n SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n smoothed_avg[flow_ix].ReduceFrame(&mData[0] + flow_ix * mFrameStride + frame_ix * mFlowFrameStride, bad_wells, frame_ix);\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 69, "score": 66238.76701748619 }, { "content": " // }\n\n // start++;\n\n // bad++;\n\n // }\n\n // *sum /= good_wells;\n\n // }\n\n // }\n\n\n\n // subtract off flow,frame avg\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n\n float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n\n float *end = start + mFrameStride;\n\n for (size_t row = 0; row < mRows; row++) {\n\n for (size_t col = 0; col < mCols; col++) {\n\n float avg = smoothed_avg[flow_ix].GetSmoothEst(row, col, frame_ix);\n\n *start++ -= avg;\n\n }\n\n }\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 70, "score": 66238.52149568987 }, { "content": "\t\t\tfor(int trow=start_row;trow<end_row;trow++){\n\n\t\t\t\tavg += avgs[frame*rows+row];\n\n\t\t\t}\n\n\t\t\tavg /= end_row-start_row;\n\n\t\t\ttmp[frame*rows+row]=avg;\n\n\t\t}\n\n\t}\n\n\tmemcpy(avgs,tmp,bufLen);\n\n\tfree(tmp);\n\n}\n\n\n\nvoid Smooth_simple(short int *avgs, int elems, int span)\n\n{\n\n\tshort int *tmp = (short int *)malloc(sizeof(short int)*elems);\n\n\tfor (int i=0;i<elems;i++){\n\n\t\tif(span > i)\n\n\t\t\tspan = i;\n\n\t\tif((i+span) > elems)\n\n\t\t\tspan = elems-i;\n\n\t\tint start_elem = i-span;\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 71, "score": 66238.49249970105 }, { "content": " mWells = mRows * mCols;\n\n mUseAsReference.resize (mWells, false);\n\n int keep = 0;\n\n int empties = 0;\n\n mRefGridsValid.resize (mFlowsBuf, 0);\n\n mRefGrids.resize (mFlowsBuf);\n\n mData.resize (mWells * mFrames * mFlowsBuf);\n\n std::fill (mData.begin(), mData.end(), 0);\n\n }\n\n\n\n/**\n\n * Create the basis splines for order requested at a particular value of x.\n\n * From \"A Practical Guide To Splines - Revised Edition\" by Carl de Boor p 111\n\n * the algorithm for BSPLVB. The value of the spline coefficients can be calculated\n\n * based on a cool recursion. This is a simplified and numerically stable algorithm\n\n * that seems to be the basis of most bspline implementations including gsl, matlab,etc.\n\n * @param all_knots - Original knots vector augmented with order number of endpoints\n\n * @param n_knots - Total number of knots.\n\n * @param order - Order or order of polynomials, 4 for cubic splines.\n\n * @param i - index of value x in knots such that all_knots[i] <= x && all_knots[i+1] > x\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 72, "score": 66238.25587453345 }, { "content": " // subtract off flow,frame avg\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n float *start = Y.data() + mFrameStride * frame_ix;\n\n float *end = start + mFrameStride;\n\n for (size_t row = 0; row < mRows; row++) {\n\n for (size_t col = 0; col < mCols; col++) {\n\n float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n\n *start++ -= avg;\n\n }\n\n }\n\n }\n\n\n\n // Get coefficients to solve\n\n Eigen::MatrixXf B = Y * SX.transpose();\n\n // Uncompress data into yhat matrix\n\n Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n\n\n\n // add the flow/frame averages back\n\n for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 73, "score": 66238.00208950933 }, { "content": " }\n\n\n\n // Get coefficients to solve\n\n Eigen::MatrixXf B = Y * SX.transpose();\n\n // Uncompress data into yhat matrix\n\n Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n\n\n\n // add the flow/frame averages back\n\n for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n\n float *start = Y.data() + frame_stride * frame_ix;\n\n float *end = start + frame_stride;\n\n float *hstart = Yhat.data() + frame_stride * frame_ix;\n\n for (size_t row = 0; row < num_rows; row++) {\n\n for (size_t col = 0; col < num_cols; col++) {\n\n float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n\n *start++ += avg;\n\n *hstart++ += avg;\n\n }\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 74, "score": 66237.96633232589 }, { "content": "}\n\n\n\n#ifndef BB_DC\n\nint GenerateRowCorrFile(char *srcdir, char *name)\n\n{\n\n\tImage loader;\n\n\tchar fname[2048];\n\n\tint rc=0;\n\n\n\n\t// open the spatial thumbnail.\n\n\t// it is interpolated to 15fps.\n\n\tsprintf(fname,\"%s/%s_spa\",srcdir,name);\n\n if ( loader.LoadRaw ( fname, 0, 1, false, false ) ) {\n\n \tconst RawImage *raw = loader.GetImage();\n\n \tint frameStride=raw->rows*raw->cols;\n\n \t// create the row averages\n\n\n\n \tshort int *corr = CreateRowSumCorrection(raw->image,raw->rows,raw->cols,raw->frames); // turn it into a correction\n\n\n\n \tif(corr){\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 75, "score": 66237.96383922629 }, { "content": " Eigen::MatrixXf flow_mat(store.mFrameStride, useable_flows);\n\n for (int flow_ix = 0; flow_ix < flow_mat.cols(); flow_ix++) {\n\n for (size_t well_ix = 0; well_ix < store.mFrameStride; well_ix++) {\n\n flow_mat(well_ix, flow_ix) = sum(flow_ix * store.mFrameStride + well_ix);\n\n }\n\n }\n\n\n\n Eigen::VectorXf n2;\n\n n2 = flow_mat.rowwise().squaredNorm();\n\n n2 = n2.array().sqrt();\n\n float *n2_start = n2.data();\n\n float *n2_end = n2_start + n2.rows();\n\n while (n2_start != n2_end) {\n\n if (*n2_start == 0.0f) { *n2_start = 1.0f; }\n\n n2_start++;\n\n }\n\n for (int flow_ix = 0; flow_ix < flow_mat.cols(); flow_ix++) {\n\n flow_mat.col(flow_ix).array() = flow_mat.col(flow_ix).array() / n2.array();\n\n }\n\n\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 76, "score": 66237.75249792621 }, { "content": "\n\n for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n\n float *y_start = Y.data() + frame_ix * frame_stride;\n\n float *y_end = y_start + frame_stride;\n\n int16_t *trace_start = data + flow_ix * frame_stride + frame_ix * flow_frame_stride;\n\n while(y_start != y_end) {\n\n *y_start++ = *trace_start++;\n\n }\n\n }\n\n \n\n // subtract off flow,frame avg\n\n for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n\n float *start = Y.data() + frame_stride * frame_ix;\n\n float *end = start + frame_stride;\n\n for (size_t row = 0; row < num_rows; row++) {\n\n for (size_t col = 0; col < num_cols; col++) {\n\n float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n\n *start++ -= avg;\n\n }\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 77, "score": 66237.68637133164 }, { "content": " // *start++ += avg;\n\n // *hstart++ += avg;\n\n // }\n\n // }\n\n // }\n\n\n\n // for (int i = 0; i < Yhat.cols(); i++) {\n\n // Yhat.col(i).array() += col_mean.coeff(i);\n\n // Y.col(i).array() += col_mean.coeff(i);\n\n // }\n\n\n\n float *yhat_start = Yhat.data();\n\n float *yhat_end = Yhat.data() + mData.size();\n\n trace_start = &mData[0];\n\n while(yhat_start != yhat_end) {\n\n *trace_start++ = (int)(*yhat_start + .5);\n\n yhat_start++;\n\n }\n\n\n\n Y = Y - Yhat;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 78, "score": 66237.31970240833 }, { "content": "\t\tclose(fd);\n\n\t}\n\n\telse{\n\n\t\tprintf(\"Failed to opened %s\\n\",fnBuf);\n\n\t}\n\n\treturn rc;\n\n}\n\n\n\nint CorrectRowAverages(char *srcdir, char *name, Image *img)\n\n{\n\n\tint rc = 0;\n\n\tconst RawImage *raw = img->GetImage();\n\n\tint frameStride = raw->rows*raw->cols;\n\n//\t// generate the row averages file\n\n//\trc = GenerateRowAverages(srcdir,name);\n\n\n\n\t// open the row averages file\n\n\timg->SetOffsetFromChipOrigin(srcdir);\n\n\n\n\tshort int *cor = ReadRowCorrection(srcdir,name,img);\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 79, "score": 66237.04425618098 }, { "content": " float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n\n float *end = start + mFrameStride;\n\n float *hstart = Yhat.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n\n for (size_t row = 0; row < mRows; row++) {\n\n for (size_t col = 0; col < mCols; col++) {\n\n float avg = smoothed_avg[flow_ix].GetSmoothEst(row, col, frame_ix);\n\n *start++ += avg;\n\n *hstart++ += avg;\n\n }\n\n }\n\n }\n\n }\n\n\n\n // for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n\n // for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n\n // float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n\n // float *hstart = Yhat.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n\n // float *end = start + mFrameStride;\n\n // float avg = FlowMeans(flow_ix, frame_ix);\n\n // while (start != end) {\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 80, "score": 66236.96846370278 }, { "content": " // Copy top eigen vectors into basis for projection\n\n Basis.resize(mFrames, num_pca);\n\n for (int i = 0; i < Basis.cols(); i++) {\n\n // Basis.col(i) = es.eigenvectors().col(es.eigenvectors().cols() - i -1);\n\n Basis.col(i) = Pca_Basis.col(Pca_Basis.cols() - i - 1);\n\n }\n\n // Create solver matrix, often not a good way of solving things but eigen vectors should be stable and fast\n\n Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n\n // Get coefficients to solve\n\n Eigen::MatrixXf B = Y * SX.transpose();\n\n // Uncompress data into yhat matrix\n\n Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n\n for (int i = 0; i < Yhat.cols(); i++) {\n\n Yhat.col(i).array() += col_mean.coeff(i);\n\n Y.col(i).array() += col_mean.coeff(i);\n\n }\n\n \n\n // H5File h5(\"pca_lossy.h5\");\n\n // h5.Open();\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 81, "score": 66236.52768090529 }, { "content": "}\n\n\n\n\n\nvoid TraceStoreCol::SplineLossyCompress(const std::string &strategy, int order, int flow_ix, char *bad_wells, float *mad) {\n\n Eigen::MatrixXf Basis;\n\n vector<float> knots;\n\n FillInKnots(strategy, mFrames, knots);\n\n // Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> Basis(, compressed.n_frames, compressed.n_basis);\n\n if (!knots.empty()) {\n\n int boundaries[2];\n\n boundaries[0] = 0;\n\n boundaries[1] = mFrames;\n\n basis_splines_endreps_local_v2(&knots[0], knots.size(), order, boundaries, sizeof(boundaries)/sizeof(boundaries[0]), Basis);\n\n }\n\n Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n\n Eigen::MatrixXf Y(mFrameStride, mFrames);\n\n // Eigen::MatrixXf FlowMeans(mFlows, mFrames);\n\n\n\n // FlowMeans.setZero();\n\n int good_wells = 0;\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 82, "score": 66236.36702397799 }, { "content": "\t\t\t// everything went well\n\n\t\t\tComputeSenseTrace(); // calculate sensing electrode trace from rowsum data and mark pinned not valid\n\n\t\t\t//medianFilterTrace(5); // median filter traces\n\n\t\t\tComputeSenseTrace_avg4(); // compute 4-row average sensing electrode trace.\n\n\t\t\treturn 0;\n\n\t\t}\n\n\n\n\n\n\t} else {\n\n\t\t// error opening file\n\n\t\treturn 1;\n\n\t}\n\n\n\n\n\n\n\n\n\n}\n\n\n\n\n\nvoid RowSumData::Row2RowsumRows(const unsigned int row, std::vector<unsigned int> & rowsNeeded){\n", "file_path": "Analysis/Image/RowSumData.cpp", "rank": 83, "score": 66236.22491812088 }, { "content": "\n\n Eigen::VectorXf proj;\n\n Eigen::VectorXf max_abs_proj(flow_mat.rows());\n\n max_abs_proj.setZero();\n\n for (size_t key_ix = 0; key_ix < key_vectors.size(); key_ix++) {\n\n Eigen::VectorXf key(useable_flows);\n\n key.setZero();\n\n for (int f_ix = 0; f_ix < useable_flows; f_ix++) {\n\n key[f_ix] = key_vectors[key_ix].flows[f_ix];\n\n }\n\n proj = flow_mat * key;\n\n proj = proj.array().abs();\n\n for (int i = 0; i < proj.rows(); i++) {\n\n max_abs_proj(i) = max(max_abs_proj(i), proj(i));\n\n }\n\n }\n\n \n\n for (int i = 0; i < max_abs_proj.rows(); i++) {\n\n mad[i] = max_abs_proj(i);\n\n }\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 84, "score": 66235.74089826635 }, { "content": " }\n\n else if (strategy == \"middle\") {\n\n float stride = n_frame / 2.0f;\n\n knots.push_back(stride);\n\n }\n\n else if (strategy.find(\"explicit:\") == 0) {\n\n string spec = strategy.substr(9, strategy.length() - 9);\n\n knots = char2Vec<float>(spec.c_str(), ',');\n\n }\n\n else {\n\n assert(false);\n\n }\n\n }\n\n}\n\n\n\nvoid TraceStoreCol::SplineLossyCompress(const std::string &strategy, int order, char *bad_wells, float *mad) {\n\n Eigen::MatrixXf Basis;\n\n vector<float> knots;\n\n FillInKnots(strategy, mFrames, knots);\n\n // Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> Basis(, compressed.n_frames, compressed.n_basis);\n", "file_path": "Analysis/Separator/TraceStoreCol.cpp", "rank": 85, "score": 66235.3010055526 }, { "content": "\tint out_rows = rows/2;\n\n\tshort int *rc = (short int *)malloc(sizeof(short int)*out_rows*frames);\n\n\tfor(int frame=0;frame<frames;frame++){\n\n\t\tfor(int row=0;row<out_rows;row++){\n\n\t\t\trc[frame*out_rows+row] = (avgs[frame*rows+row] + avgs[frame*rows+(rows-1-row)])/2; // average together top and bottom\n\n\t\t}\n\n\t}\n\n\treturn rc;\n\n}\n\n\n\nshort int *Get_Mean_trace_nodcoffset(short int *avgs, int rows, int frames)\n\n{\n\n\tshort int *rc = (short int *)malloc(sizeof(short int)*frames*rows/2);\n\n\tfor(int frame=0;frame<frames;frame++){\n\n\t\t// get this frame's average\n\n\t\tfloat avg = 0;\n\n\t\tfor(int row=0;row<rows;row++){\n\n\t\t\tavg += avgs[frame*rows+row];\n\n\t\t}\n\n\t\tavg /= (float)rows;\n", "file_path": "Analysis/Image/RowSumCorrector.cpp", "rank": 86, "score": 66235.06721336693 }, { "content": "/* Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved */\n\n\n\n#include <stdlib.h>\n\n#include <malloc.h>\n\n#include <string.h>\n\n#include \"NNAvg.h\"\n\n#include \"Vecs.h\"\n\n\n\nNNAvg::NNAvg(int n_rows, int n_cols, int n_frames) {\n\n InitializeClean();\n\n Alloc(n_rows, n_cols, n_frames);\n\n}\n\n\n\nvoid NNAvg::Alloc(int n_rows, int n_cols, int n_frames) {\n\n Cleanup();\n\n m_num_rows = n_rows;\n\n m_num_cols = n_cols;\n\n m_num_frames = n_frames;\n\n m_cs_col_size = m_num_cols + 1;\n\n m_cs_frame_stride = m_cs_col_size * (m_num_rows + 1);\n", "file_path": "Analysis/Separator/NNAvg.cpp", "rank": 87, "score": 35.53053159276326 }, { "content": "/* Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved */\n\n\n\n#include <stdlib.h>\n\n#include <malloc.h>\n\n#include <string.h>\n\n#include \"ImageNNAvg.h\"\n\n#include \"Vecs.h\"\n\n\n\nImageNNAvg::ImageNNAvg(int n_rows, int n_cols, int n_frames) {\n\n m_gain_min_mult = 1;\n\n InitializeClean();\n\n Alloc(n_rows, n_cols, n_frames);\n\n}\n\n\n\nvoid ImageNNAvg::Alloc(int n_rows, int n_cols, int n_frames) {\n\n Cleanup();\n\n m_num_rows = n_rows;\n\n m_num_cols = n_cols;\n\n m_num_frames = n_frames;\n\n int frame_stride = m_num_cols * m_num_rows;\n", "file_path": "Analysis/Image/ImageNNAvg.cpp", "rank": 88, "score": 35.25372476230191 }, { "content": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include \"Region.h\"\n\n\n\n/* Why is this col major when everything else is row major? */\n\nvoid RegionHelper::SetUpRegions (std::vector<Region>& regions, int rows, int cols, int xinc, int yinc)\n\n{\n\n int i,x,y;\n\n\n\n\n\n for (i = 0, x = 0; x < cols; x += xinc)\n\n {\n\n for (y = 0; y < rows; y += yinc)\n\n {\n\n //for (i = 0,y = 0; y < rows; y += yinc)\n\n //{\n\n //for ( x = 0; x < cols; x += xinc)\n\n // {\n\n regions[i].index = i;\n\n regions[i].col = x;\n\n regions[i].row = y;\n", "file_path": "Analysis/Region.cpp", "rank": 90, "score": 33.30944017690218 }, { "content": "\t\t\tif (mask[i])\n\n\t\t\t\tavg_indicies[num_avg++] = i;\n\n\t\t}\n\n\t\t\n\n\t\tnext = NULL;\n\n\t}\n\n\n\n\tvoid SetRow(int _row)\n\n\t{\n\n\t\trow = _row;\n\n\t}\n\n\n\n\tvoid SetCol(int _col)\n\n\t{\n\n\t\tcol = _col;\n\n\t}\n\n\n\n\tint GetRow(void)\n\n\t{\n\n\t\treturn(row);\n", "file_path": "Analysis/xtalk_sim/SignalAverager.h", "rank": 91, "score": 32.292792597954374 }, { "content": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n\n\n\n#include \"GlobalWriter.h\"\n\n#include <assert.h>\n\n#include \"LinuxCompat.h\"\n\n#include \"RawWells.h\"\n\n#include \"TimeCompression.h\"\n\n#include \"EmphasisVector.h\"\n\n#include \"BkgDataPointers.h\"\n\n#include \"BkgTrace.h\"\n\n#include \"RegionalizedData.h\"\n\n#include \"SlicedChipExtras.h\"\n\n\n\nvoid GlobalWriter::AllocDataCubeResErr(int col, int row, int flow){\n\n int w = col; //= region_data.region->w + region_data.get_region_col();\n\n int h = row; //region_data.region->h + region_data.get_region_row();\n\n printf(\"allocating datacube %d %d %d \\n\", w, h, flow);\n\n mPtrs->mResError->Init(w, h, flow);\n\n mPtrs->mResError->AllocateBuffer();\n\n}\n", "file_path": "Analysis/BkgModel/Writers/GlobalWriter.cpp", "rank": 92, "score": 31.422292329352004 }, { "content": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include \"BkgFitterTracker.h\"\n\n#include \"BkgDataPointers.h\"\n\n#include \"BkgModelHdf5.h\"\n\n#include \"MaskSample.h\"\n\n#include \"GpuMultiFlowFitControl.h\"\n\n#include \"FlowSequence.h\"\n\n\n\n\n\nint BkgFitterTracker::findRegion(int row, int col)\n\n{\n\n int reg = -1;\n\n for(int i=0; i<numFitters; ++i)\n\n {\n\n const Region *rp = sliced_chip[i]->get_region();\n\n int c = rp->col;\n\n int r = rp->row;\n\n int w = rp->w;\n\n int h = rp->h;\n\n if (col>=c && col<c+w && row>=r && row<r+h)\n", "file_path": "Analysis/AnalysisOrg/BkgFitterTracker.cpp", "rank": 93, "score": 30.617563819302124 }, { "content": "\n\n ~SpatialContext();\n\n};\n\n\n\n\n\n//@TODO: actually methods, but why are they passed _rows and _cols?\n\n\n\nvoid SetUpRegionDivisions(SpatialContext &loc_context, int _rows, int _cols);\n\n\n\n\n\nvoid FixCroppedRegions(SpatialContext &loc_context, int _rows, int _cols);\n\n\n\n\n\nvoid SetUpRegionsForAnalysis (int _rows, int _cols, SpatialContext &loc_context);\n\n\n\n#endif // SPATIALCONTEXT_H\n", "file_path": "Analysis/AnalysisOrg/SpatialContext.h", "rank": 94, "score": 30.611916015738473 }, { "content": " void FilterRegionOutliers(Image &bfImg, Mask &mask, float iqrThreshold, \n\n int rowStart, int rowEnd, int colStart, int colEnd);\n\n\n\n void FilterForOutliers(Image &bfImg, Mask &mask, float iqrThreshold, int rowStep, int colStep);\n\n void FilterOutlierSignalWells(int rowStart, int rowEnd, int colStart, int colEnd, int chipWidth,\n\n arma::Mat<float> &data, std::vector<char> &wells);\n\n /**\n\n * Convert row and column to single index. \n\n */\n\n int RowColIdx(int row, int col) const {\n\n return row * GetNumCol() + col;\n\n }\n\n\n\n size_t RowColToIndex(size_t rowIx, size_t colIx) const { \n\n return rowIx * GetNumCol() + colIx; \n\n }\n\n\n\n /**\n\n * Rounding for local work @todo - should be some global functions\n\n */\n", "file_path": "Analysis/Separator/BFReference.h", "rank": 95, "score": 30.59688642155018 }, { "content": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n\n\n\n#include <vector>\n\n\n\n#include \"IonErr.h\"\n\n#include \"MergeAcq.h\"\n\n\n\nvoid MergeAcq::SetSecondImage(Image *img, int rowStart, int colStart) {\n\n mSecond = img;\n\n mSecondRowStart = rowStart;\n\n mSecondColStart = colStart;\n\n}\n\n\n\nvoid MergeAcq::Merge(Image &combo) {\n\n CheckImagesAlign(); \n\n RawImage *raw = new RawImage();\n\n const RawImage *first = mFirst->GetImage();\n\n const RawImage *second = mSecond->GetImage();\n\n /* do either compressed or uncompressed. */\n\n if (first->image != NULL) { \n", "file_path": "Analysis/crop/MergeAcq.cpp", "rank": 96, "score": 30.39299277854126 }, { "content": " if there are no good wells in a region. row_step and col_step\n\n indicate regions within which to calculate average (e.g 100,100\n\n for thumbnail). Column of well is not used in average to avoid \n\n column flicker issues.\n\n\n\n @param row_clip - row modulous within which to calculate average (100 for thumbnail)\n\n @param col_clip - col modulous within which to calculate average (100 for thumbnail)\n\n @param num_row_neighbors - window above and below well to include in average\n\n @param num_col_neighbors - window left and and right of well to use\n\n @param trace_min - array to put the minimum value in for each well (preallocated)\n\n @param trace_min_fram - array to put the minimum frame in for each well (preallocated)\n\n @param image - pointer to the image of data\n\n */\n\n void CalcNNAvg(int row_clip, int col_clip, \n\n int num_row_neighbors, int num_col_neighbors,float default_value=0.0f);\n\n\n\n /** Function for grabbing the cumulative sum for region around well. Useful for rolling variance. */\n\n inline void GetRegionSum(int row_ix, int col_ix, int frame_ix,\n\n int row_step, int col_step,\n\n int row_neighbors, int col_neighbors,\n", "file_path": "Analysis/Separator/NNAvg.h", "rank": 97, "score": 29.99971578379535 }, { "content": " thumbnail=0;\n\n CorrAvg=0;\n\n fmult=1;\n\n initVars();\n\n }\n\n\n\n ~CorrNoiseCorrector() {\n\n }\n\n\n\nprotected:\n\n double CorrectRowNoise_internal(bool verbose, int correctRows);\n\n\n\nprivate:\n\n void NNSubtractComparatorSigs(int row_span, int time_span, int correctRows);\n\n void SumRows();\n\n void SumCols();\n\n void SetMeanToZero();\n\n double ApplyCorrection_rows();\n\n void ApplyCorrection_cols();\n\n void DebugSaveRowNoise(int correctRows);\n", "file_path": "Analysis/Image/CorrNoiseCorrector.h", "rank": 98, "score": 29.902770431892073 }, { "content": " void FillNewImage(const short *first, size_t firstRows, size_t firstCols,\n\n const short *second, size_t secondRows, size_t secondCols,\n\n size_t rowStart, size_t colStart,\n\n size_t rows, size_t cols, size_t frames, short *dest);\n\n\n\n void FillOneImage(const short *first, size_t firstRows, size_t firstCols,\n\n size_t rowStart, size_t colStart,\n\n size_t rows, size_t cols, size_t frames, short *dest);\n\n\n\n /// Some sanity checks for images\n\n void CheckImagesAlign();\n\n void CheckAlignment(int n, int cols, int rows, int &preCols, int &preRows,bool colWise);\n\n void stackMetaData(const RawImage *src, RawImage *dst, int nImages, bool colWise);\n\n\n\n void Init();\n\n\n\n Image *mFirst; ///< memory owned elsewhere\n\n Image *mSecond; ///< memory owned elsewhere\n\n ///< Offsets into new file where second image goes\n\n size_t mSecondRowStart, mSecondColStart;\n\n\n\n};\n\n\n\n#endif // MERGEACQ_H\n", "file_path": "Analysis/crop/MergeAcq.h", "rank": 99, "score": 29.87695743180514 } ]
C++
modules/audio_processing/aec3/aec_state_unittest.cc
imxiangpeng/webrtc
8078c53c2f8ed487b1c6bbdf3d541f7a5884ed70
#include "webrtc/modules/audio_processing/aec3/aec_state.h" #include "webrtc/modules/audio_processing/logging/apm_data_dumper.h" #include "webrtc/test/gtest.h" namespace webrtc { TEST(AecState, NormalUsage) { ApmDataDumper data_dumper(42); AecState state; FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; EchoPathVariability echo_path_variability(false, false); x.fill(0.f); std::vector<std::array<float, kFftLengthBy2Plus1>> converged_filter_frequency_response(10); for (auto& v : converged_filter_frequency_response) { v.fill(0.01f); } std::vector<std::array<float, kFftLengthBy2Plus1>> diverged_filter_frequency_response = converged_filter_frequency_response; converged_filter_frequency_response[2].fill(100.f); state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.ModelBasedAecFeasible()); EXPECT_FALSE(state.UsableLinearEstimate()); state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.ModelBasedAecFeasible()); for (int k = 0; k < 50; ++k) { state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } EXPECT_TRUE(state.ModelBasedAecFeasible()); EXPECT_FALSE(state.UsableLinearEstimate()); for (int k = 0; k < 50; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } EXPECT_TRUE(state.UsableLinearEstimate()); echo_path_variability = EchoPathVariability(true, false); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.UsableLinearEstimate()); x.fill(101.f); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_TRUE(state.ActiveRender()); x.fill(0.f); for (int k = 0; k < 200; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } EXPECT_FALSE(state.ActiveRender()); x.fill(101.f); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_TRUE(state.ActiveRender()); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.EchoLeakageDetected()); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, true); EXPECT_TRUE(state.EchoLeakageDetected()); echo_path_variability = EchoPathVariability(false, false); for (int k = 0; k < 200; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } FftData X; X.re.fill(10000.f); X.im.fill(0.f); for (size_t k = 0; k < X_buffer.Buffer().size(); ++k) { X_buffer.Insert(X); } Y2.fill(10.f * 1000.f * 1000.f); E2_main.fill(100.f * Y2[0]); E2_shadow.fill(100.f * Y2[0]); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); E2_main.fill(0.1f * Y2[0]); E2_shadow.fill(E2_main[0]); for (size_t k = 0; k < Y2.size(); k += 2) { E2_main[k] = Y2[k]; E2_shadow[k] = Y2[k]; } state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); const std::array<bool, kFftLengthBy2Plus1>& reliable_bands = state.BandsWithReliableFilter(); EXPECT_EQ(reliable_bands[0], reliable_bands[1]); for (size_t k = 1; k < kFftLengthBy2 - 5; ++k) { EXPECT_TRUE(reliable_bands[k]); } for (size_t k = kFftLengthBy2 - 5; k < reliable_bands.size(); ++k) { EXPECT_EQ(reliable_bands[kFftLengthBy2 - 6], reliable_bands[k]); } Y2.fill(10.f * X.re[0] * X.re[0]); for (size_t k = 0; k < 100000; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } ASSERT_TRUE(state.UsableLinearEstimate()); const std::array<float, kFftLengthBy2Plus1>& erl = state.Erl(); std::for_each(erl.begin(), erl.end(), [](float a) { EXPECT_NEAR(10.f, a, 0.1); }); E2_main.fill(1.f * X.re[0] * X.re[0]); Y2.fill(10.f * E2_main[0]); for (size_t k = 0; k < 10000; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } ASSERT_TRUE(state.UsableLinearEstimate()); std::for_each(state.Erle().begin(), state.Erle().end(), [](float a) { EXPECT_NEAR(8.f, a, 0.1); }); E2_main.fill(1.f * X.re[0] * X.re[0]); Y2.fill(5.f * E2_main[0]); for (size_t k = 0; k < 10000; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } ASSERT_TRUE(state.UsableLinearEstimate()); std::for_each(state.Erle().begin(), state.Erle().end(), [](float a) { EXPECT_NEAR(5.f, a, 0.1); }); } TEST(AecState, NonSignificantDelay) { AecState state; FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; EchoPathVariability echo_path_variability(false, false); x.fill(0.f); std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(30); for (auto& v : frequency_response) { v.fill(0.01f); } state.Update(frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.FilterDelay()); } TEST(AecState, ConvergedFilterDelay) { constexpr int kFilterLength = 10; AecState state; FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; EchoPathVariability echo_path_variability(false, false); x.fill(0.f); std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response( kFilterLength); for (int k = 0; k < kFilterLength; ++k) { for (auto& v : frequency_response) { v.fill(0.01f); } frequency_response[k].fill(100.f); state.Update(frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_TRUE(k == (kFilterLength - 1) || state.FilterDelay()); if (k != (kFilterLength - 1)) { EXPECT_EQ(k, state.FilterDelay()); } } } TEST(AecState, ExternalDelay) { AecState state; std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; E2_main.fill(0.f); E2_shadow.fill(0.f); Y2.fill(0.f); x.fill(0.f); FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(30); for (auto& v : frequency_response) { v.fill(0.01f); } for (size_t k = 0; k < frequency_response.size() - 1; ++k) { state.Update(frequency_response, rtc::Optional<size_t>(k * kBlockSize + 5), X_buffer, E2_main, E2_shadow, Y2, x, EchoPathVariability(false, false), false); EXPECT_TRUE(state.ExternalDelay()); EXPECT_EQ(k, state.ExternalDelay()); } state.Update(frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, EchoPathVariability(false, false), false); EXPECT_FALSE(state.ExternalDelay()); } }
#include "webrtc/modules/audio_processing/aec3/aec_state.h" #include "webrtc/modules/audio_processing/logging/apm_data_dumper.h" #include "webrtc/test/gtest.h" namespace webrtc { TEST(AecState, NormalUsage) { ApmDataDumper data_dumper(42); AecState state; FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; EchoPathVariability echo_path_variability(false, false); x.fill(0.f); std::vector<std::array<float, kFftLengthBy2Plus1>> converged_filter_frequency_response(10); for (auto& v : converged_filter_frequency_response) { v.fill(0.01f); } std::vector<std::array<float, kFftLengthBy2Plus1>> diverged_filter_frequency_response = converged_filter_frequency_response; converged_filter_frequency_response[2].fill(100.f); state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.ModelBasedAecFeasible()); EXPECT_FALSE(state.UsableLinearEstimate()); state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.ModelBasedAecFeasible()); for (int k = 0; k < 50; ++k) { state.Update(diverged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } EXPECT_TRUE(state.ModelBasedAecFeasible()); EXPECT_FALSE(state.UsableLinearEstimate()); for (int k = 0; k < 50; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } EXPECT_TRUE(state.UsableLinearEstimate()); echo_path_variability = EchoPathVariability(true, false); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.UsableLinearEstimate()); x.fill(101.f); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_TRUE(state.ActiveRender()); x.fill(0.f); for (int k = 0; k < 200; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } EXPECT_FALSE(state.ActiveRender()); x.fill(101.f);
; EXPECT_TRUE(state.ActiveRender()); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.EchoLeakageDetected()); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, true); EXPECT_TRUE(state.EchoLeakageDetected()); echo_path_variability = EchoPathVariability(false, false); for (int k = 0; k < 200; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } FftData X; X.re.fill(10000.f); X.im.fill(0.f); for (size_t k = 0; k < X_buffer.Buffer().size(); ++k) { X_buffer.Insert(X); } Y2.fill(10.f * 1000.f * 1000.f); E2_main.fill(100.f * Y2[0]); E2_shadow.fill(100.f * Y2[0]); state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); E2_main.fill(0.1f * Y2[0]); E2_shadow.fill(E2_main[0]); for (size_t k = 0; k < Y2.size(); k += 2) { E2_main[k] = Y2[k]; E2_shadow[k] = Y2[k]; } state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); const std::array<bool, kFftLengthBy2Plus1>& reliable_bands = state.BandsWithReliableFilter(); EXPECT_EQ(reliable_bands[0], reliable_bands[1]); for (size_t k = 1; k < kFftLengthBy2 - 5; ++k) { EXPECT_TRUE(reliable_bands[k]); } for (size_t k = kFftLengthBy2 - 5; k < reliable_bands.size(); ++k) { EXPECT_EQ(reliable_bands[kFftLengthBy2 - 6], reliable_bands[k]); } Y2.fill(10.f * X.re[0] * X.re[0]); for (size_t k = 0; k < 100000; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } ASSERT_TRUE(state.UsableLinearEstimate()); const std::array<float, kFftLengthBy2Plus1>& erl = state.Erl(); std::for_each(erl.begin(), erl.end(), [](float a) { EXPECT_NEAR(10.f, a, 0.1); }); E2_main.fill(1.f * X.re[0] * X.re[0]); Y2.fill(10.f * E2_main[0]); for (size_t k = 0; k < 10000; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } ASSERT_TRUE(state.UsableLinearEstimate()); std::for_each(state.Erle().begin(), state.Erle().end(), [](float a) { EXPECT_NEAR(8.f, a, 0.1); }); E2_main.fill(1.f * X.re[0] * X.re[0]); Y2.fill(5.f * E2_main[0]); for (size_t k = 0; k < 10000; ++k) { state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); } ASSERT_TRUE(state.UsableLinearEstimate()); std::for_each(state.Erle().begin(), state.Erle().end(), [](float a) { EXPECT_NEAR(5.f, a, 0.1); }); } TEST(AecState, NonSignificantDelay) { AecState state; FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; EchoPathVariability echo_path_variability(false, false); x.fill(0.f); std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(30); for (auto& v : frequency_response) { v.fill(0.01f); } state.Update(frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_FALSE(state.FilterDelay()); } TEST(AecState, ConvergedFilterDelay) { constexpr int kFilterLength = 10; AecState state; FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; EchoPathVariability echo_path_variability(false, false); x.fill(0.f); std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response( kFilterLength); for (int k = 0; k < kFilterLength; ++k) { for (auto& v : frequency_response) { v.fill(0.01f); } frequency_response[k].fill(100.f); state.Update(frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false); EXPECT_TRUE(k == (kFilterLength - 1) || state.FilterDelay()); if (k != (kFilterLength - 1)) { EXPECT_EQ(k, state.FilterDelay()); } } } TEST(AecState, ExternalDelay) { AecState state; std::array<float, kFftLengthBy2Plus1> E2_main; std::array<float, kFftLengthBy2Plus1> E2_shadow; std::array<float, kFftLengthBy2Plus1> Y2; std::array<float, kBlockSize> x; E2_main.fill(0.f); E2_shadow.fill(0.f); Y2.fill(0.f); x.fill(0.f); FftBuffer X_buffer(Aec3Optimization::kNone, 30, std::vector<size_t>(1, 30)); std::vector<std::array<float, kFftLengthBy2Plus1>> frequency_response(30); for (auto& v : frequency_response) { v.fill(0.01f); } for (size_t k = 0; k < frequency_response.size() - 1; ++k) { state.Update(frequency_response, rtc::Optional<size_t>(k * kBlockSize + 5), X_buffer, E2_main, E2_shadow, Y2, x, EchoPathVariability(false, false), false); EXPECT_TRUE(state.ExternalDelay()); EXPECT_EQ(k, state.ExternalDelay()); } state.Update(frequency_response, rtc::Optional<size_t>(), X_buffer, E2_main, E2_shadow, Y2, x, EchoPathVariability(false, false), false); EXPECT_FALSE(state.ExternalDelay()); } }
state.Update(converged_filter_frequency_response, rtc::Optional<size_t>(2), X_buffer, E2_main, E2_shadow, Y2, x, echo_path_variability, false)
call_expression
[ { "content": "namespace webrtc {\n\n\n\n// This function sleeps for the specified number of milliseconds.\n\n// It may return early if the thread is woken by some other event,\n\n// such as the delivery of a signal on Unix.\n\nvoid SleepMs(int msecs);\n\n\n", "file_path": "system_wrappers/include/sleep.h", "rank": 0, "score": 192119.11139271996 }, { "content": "namespace webrtc {\n\nnamespace field_trial {\n\n\n\n// Returns the group name chosen for the named trial, or the empty string\n\n// if the trial does not exists.\n\n//\n\n// Note: To keep things tidy append all the trial names with WebRTC.\n\nstd::string FindFullName(const std::string& name);\n\n\n\n// Convenience method, returns true iff FindFullName(name) return a string that\n\n// starts with \"Enabled\".\n\n// TODO(tommi): Make sure all implementations support this.\n\ninline bool IsEnabled(const char* name) {\n\n return FindFullName(name).find(\"Enabled\") == 0;\n\n}\n\n\n\n} // namespace field_trial\n", "file_path": "system_wrappers/include/field_trial.h", "rank": 1, "score": 188961.89034751803 }, { "content": "namespace webrtc {\n\n\n\nenum CountOperation {\n\n kRelease,\n\n kAddRef,\n\n kAddRefNoCreate\n\n};\n\nenum CreateOperation {\n\n kInstanceExists,\n\n kCreate,\n\n kDestroy\n\n};\n\n\n\ntemplate <class T>\n\n// Construct On First Use idiom. Avoids\n\n// \"static initialization order fiasco\".\n\nstatic T* GetStaticInstance(CountOperation count_operation) {\n\n // TODO (hellner): use atomic wrapper instead.\n\n static volatile long instance_count = 0;\n\n static T* volatile instance = NULL;\n\n CreateOperation state = kInstanceExists;\n\n#ifndef _WIN32\n\n // This memory is staticly allocated once. The application does not try to\n\n // free this memory. This approach is taken to avoid issues with\n\n // destruction order for statically allocated memory. The memory will be\n\n // reclaimed by the OS and memory leak tools will not recognize memory\n\n // reachable from statics leaked so no noise is added by doing this.\n\n static CriticalSectionWrapper* crit_sect(\n\n CriticalSectionWrapper::CreateCriticalSection());\n\n CriticalSectionScoped lock(crit_sect);\n\n\n\n if (count_operation ==\n\n kAddRefNoCreate && instance_count == 0) {\n\n return NULL;\n\n }\n\n if (count_operation ==\n\n kAddRef ||\n\n count_operation == kAddRefNoCreate) {\n\n instance_count++;\n\n if (instance_count == 1) {\n\n state = kCreate;\n\n }\n\n } else {\n\n instance_count--;\n\n if (instance_count == 0) {\n\n state = kDestroy;\n\n }\n\n }\n\n if (state == kCreate) {\n\n instance = T::CreateInstance();\n\n } else if (state == kDestroy) {\n\n T* old_instance = instance;\n\n instance = NULL;\n\n // The state will not change past this point. Release the critical\n\n // section while deleting the object in case it would be blocking on\n\n // access back to this object. (This is the case for the tracing class\n\n // since the thread owned by the tracing class also traces).\n\n // TODO(hellner): this is a bit out of place but here goes, de-couple\n\n // thread implementation with trace implementation.\n\n crit_sect->Leave();\n\n if (old_instance) {\n\n delete old_instance;\n\n }\n\n // Re-acquire the lock since the scoped critical section will release\n\n // it.\n\n crit_sect->Enter();\n\n return NULL;\n\n }\n\n#else // _WIN32\n\n if (count_operation ==\n\n kAddRefNoCreate && instance_count == 0) {\n\n return NULL;\n\n }\n\n if (count_operation == kAddRefNoCreate) {\n\n if (1 == InterlockedIncrement(&instance_count)) {\n\n // The instance has been destroyed by some other thread. Rollback.\n\n InterlockedDecrement(&instance_count);\n\n assert(false);\n\n return NULL;\n\n }\n\n // Sanity to catch corrupt state.\n\n if (instance == NULL) {\n\n assert(false);\n\n InterlockedDecrement(&instance_count);\n\n return NULL;\n\n }\n\n } else if (count_operation == kAddRef) {\n\n if (instance_count == 0) {\n\n state = kCreate;\n\n } else {\n\n if (1 == InterlockedIncrement(&instance_count)) {\n\n // InterlockedDecrement because reference count should not be\n\n // updated just yet (that's done when the instance is created).\n\n InterlockedDecrement(&instance_count);\n\n state = kCreate;\n\n }\n\n }\n\n } else {\n\n int new_value = InterlockedDecrement(&instance_count);\n\n if (new_value == 0) {\n\n state = kDestroy;\n\n }\n\n }\n\n\n\n if (state == kCreate) {\n\n // Create instance and let whichever thread finishes first assign its\n\n // local copy to the global instance. All other threads reclaim their\n\n // local copy.\n\n T* new_instance = T::CreateInstance();\n\n if (1 == InterlockedIncrement(&instance_count)) {\n\n InterlockedExchangePointer(reinterpret_cast<void * volatile*>(&instance),\n\n new_instance);\n\n } else {\n\n InterlockedDecrement(&instance_count);\n\n if (new_instance) {\n\n delete static_cast<T*>(new_instance);\n\n }\n\n }\n\n } else if (state == kDestroy) {\n\n T* old_value = static_cast<T*>(InterlockedExchangePointer(\n\n reinterpret_cast<void * volatile*>(&instance), NULL));\n\n if (old_value) {\n\n delete static_cast<T*>(old_value);\n\n }\n\n return NULL;\n\n }\n\n#endif // #ifndef _WIN32\n\n return instance;\n\n}\n\n\n", "file_path": "system_wrappers/include/static_instance.h", "rank": 2, "score": 188961.89034751803 }, { "content": "namespace webrtc {\n\n\n\n// Wrapper class for aligned arrays. Every row (and the first dimension) are\n\n// aligned to the given byte alignment.\n\ntemplate<typename T> class AlignedArray {\n\n public:\n\n AlignedArray(size_t rows, size_t cols, size_t alignment)\n\n : rows_(rows),\n\n cols_(cols) {\n\n RTC_CHECK_GT(alignment, 0);\n\n head_row_ = static_cast<T**>(AlignedMalloc(rows_ * sizeof(*head_row_),\n\n alignment));\n\n for (size_t i = 0; i < rows_; ++i) {\n\n head_row_[i] = static_cast<T*>(AlignedMalloc(cols_ * sizeof(**head_row_),\n\n alignment));\n\n }\n\n }\n\n\n\n ~AlignedArray() {\n\n for (size_t i = 0; i < rows_; ++i) {\n\n AlignedFree(head_row_[i]);\n\n }\n\n AlignedFree(head_row_);\n\n }\n\n\n\n T* const* Array() {\n\n return head_row_;\n\n }\n\n\n\n const T* const* Array() const {\n\n return head_row_;\n\n }\n\n\n\n T* Row(size_t row) {\n\n RTC_CHECK_LE(row, rows_);\n\n return head_row_[row];\n\n }\n\n\n\n const T* Row(size_t row) const {\n\n RTC_CHECK_LE(row, rows_);\n\n return head_row_[row];\n\n }\n\n\n\n T& At(size_t row, size_t col) {\n\n RTC_CHECK_LE(col, cols_);\n\n return Row(row)[col];\n\n }\n\n\n\n const T& At(size_t row, size_t col) const {\n\n RTC_CHECK_LE(col, cols_);\n\n return Row(row)[col];\n\n }\n\n\n\n size_t rows() const {\n\n return rows_;\n\n }\n\n\n\n size_t cols() const {\n\n return cols_;\n\n }\n\n\n\n private:\n\n size_t rows_;\n\n size_t cols_;\n\n T** head_row_;\n\n};\n\n\n", "file_path": "system_wrappers/include/aligned_array.h", "rank": 3, "score": 188961.89034751803 }, { "content": "namespace webrtc {\n\n\n\n// Returns a pointer to the first boundry of |alignment| bytes following the\n\n// address of |ptr|.\n\n// Note that there is no guarantee that the memory in question is available.\n\n// |ptr| has no requirements other than it can't be NULL.\n\nvoid* GetRightAlign(const void* ptr, size_t alignment);\n\n\n\n// Allocates memory of |size| bytes aligned on an |alignment| boundry.\n\n// The return value is a pointer to the memory. Note that the memory must\n\n// be de-allocated using AlignedFree.\n\nvoid* AlignedMalloc(size_t size, size_t alignment);\n\n// De-allocates memory created using the AlignedMalloc() API.\n\nvoid AlignedFree(void* mem_block);\n\n\n\n// Templated versions to facilitate usage of aligned malloc without casting\n\n// to and from void*.\n\ntemplate<typename T>\n\nT* GetRightAlign(const T* ptr, size_t alignment) {\n\n return reinterpret_cast<T*>(GetRightAlign(reinterpret_cast<const void*>(ptr),\n\n alignment));\n\n}\n\ntemplate<typename T>\n\nT* AlignedMalloc(size_t size, size_t alignment) {\n\n return reinterpret_cast<T*>(AlignedMalloc(size, alignment));\n\n}\n\n\n\n// Deleter for use with unique_ptr. E.g., use as\n\n// std::unique_ptr<Foo, AlignedFreeDeleter> foo;\n\nstruct AlignedFreeDeleter {\n\n inline void operator()(void* ptr) const {\n\n AlignedFree(ptr);\n\n }\n\n};\n\n\n", "file_path": "system_wrappers/include/aligned_malloc.h", "rank": 4, "score": 188961.89034751803 }, { "content": "namespace webrtc {\n\n\n\ntypedef std::numeric_limits<int16_t> limits_int16;\n\n\n\n// The conversion functions use the following naming convention:\n\n// S16: int16_t [-32768, 32767]\n\n// Float: float [-1.0, 1.0]\n\n// FloatS16: float [-32768.0, 32767.0]\n\nstatic inline int16_t FloatToS16(float v) {\n\n if (v > 0)\n\n return v >= 1 ? limits_int16::max()\n\n : static_cast<int16_t>(v * limits_int16::max() + 0.5f);\n\n return v <= -1 ? limits_int16::min()\n\n : static_cast<int16_t>(-v * limits_int16::min() - 0.5f);\n\n}\n\n\n\nstatic inline float S16ToFloat(int16_t v) {\n\n static const float kMaxInt16Inverse = 1.f / limits_int16::max();\n\n static const float kMinInt16Inverse = 1.f / limits_int16::min();\n\n return v * (v > 0 ? kMaxInt16Inverse : -kMinInt16Inverse);\n\n}\n\n\n\nstatic inline int16_t FloatS16ToS16(float v) {\n\n static const float kMaxRound = limits_int16::max() - 0.5f;\n\n static const float kMinRound = limits_int16::min() + 0.5f;\n\n if (v > 0)\n\n return v >= kMaxRound ? limits_int16::max()\n\n : static_cast<int16_t>(v + 0.5f);\n\n return v <= kMinRound ? limits_int16::min() : static_cast<int16_t>(v - 0.5f);\n\n}\n\n\n\nstatic inline float FloatToFloatS16(float v) {\n\n return v * (v > 0 ? limits_int16::max() : -limits_int16::min());\n\n}\n\n\n\nstatic inline float FloatS16ToFloat(float v) {\n\n static const float kMaxInt16Inverse = 1.f / limits_int16::max();\n\n static const float kMinInt16Inverse = 1.f / limits_int16::min();\n\n return v * (v > 0 ? kMaxInt16Inverse : -kMinInt16Inverse);\n\n}\n\n\n\nvoid FloatToS16(const float* src, size_t size, int16_t* dest);\n\nvoid S16ToFloat(const int16_t* src, size_t size, float* dest);\n\nvoid FloatS16ToS16(const float* src, size_t size, int16_t* dest);\n\nvoid FloatToFloatS16(const float* src, size_t size, float* dest);\n\nvoid FloatS16ToFloat(const float* src, size_t size, float* dest);\n\n\n\n// Copy audio from |src| channels to |dest| channels unless |src| and |dest|\n\n// point to the same address. |src| and |dest| must have the same number of\n\n// channels, and there must be sufficient space allocated in |dest|.\n\ntemplate <typename T>\n\nvoid CopyAudioIfNeeded(const T* const* src,\n\n int num_frames,\n\n int num_channels,\n\n T* const* dest) {\n\n for (int i = 0; i < num_channels; ++i) {\n\n if (src[i] != dest[i]) {\n\n std::copy(src[i], src[i] + num_frames, dest[i]);\n\n }\n\n }\n\n}\n\n\n\n// Deinterleave audio from |interleaved| to the channel buffers pointed to\n\n// by |deinterleaved|. There must be sufficient space allocated in the\n\n// |deinterleaved| buffers (|num_channel| buffers with |samples_per_channel|\n\n// per buffer).\n\ntemplate <typename T>\n\nvoid Deinterleave(const T* interleaved,\n\n size_t samples_per_channel,\n\n size_t num_channels,\n\n T* const* deinterleaved) {\n\n for (size_t i = 0; i < num_channels; ++i) {\n\n T* channel = deinterleaved[i];\n\n size_t interleaved_idx = i;\n\n for (size_t j = 0; j < samples_per_channel; ++j) {\n\n channel[j] = interleaved[interleaved_idx];\n\n interleaved_idx += num_channels;\n\n }\n\n }\n\n}\n\n\n\n// Interleave audio from the channel buffers pointed to by |deinterleaved| to\n\n// |interleaved|. There must be sufficient space allocated in |interleaved|\n\n// (|samples_per_channel| * |num_channels|).\n\ntemplate <typename T>\n\nvoid Interleave(const T* const* deinterleaved,\n\n size_t samples_per_channel,\n\n size_t num_channels,\n\n T* interleaved) {\n\n for (size_t i = 0; i < num_channels; ++i) {\n\n const T* channel = deinterleaved[i];\n\n size_t interleaved_idx = i;\n\n for (size_t j = 0; j < samples_per_channel; ++j) {\n\n interleaved[interleaved_idx] = channel[j];\n\n interleaved_idx += num_channels;\n\n }\n\n }\n\n}\n\n\n\n// Copies audio from a single channel buffer pointed to by |mono| to each\n\n// channel of |interleaved|. There must be sufficient space allocated in\n\n// |interleaved| (|samples_per_channel| * |num_channels|).\n\ntemplate <typename T>\n\nvoid UpmixMonoToInterleaved(const T* mono,\n\n int num_frames,\n\n int num_channels,\n\n T* interleaved) {\n\n int interleaved_idx = 0;\n\n for (int i = 0; i < num_frames; ++i) {\n\n for (int j = 0; j < num_channels; ++j) {\n\n interleaved[interleaved_idx++] = mono[i];\n\n }\n\n }\n\n}\n\n\n\ntemplate <typename T, typename Intermediate>\n\nvoid DownmixToMono(const T* const* input_channels,\n\n size_t num_frames,\n\n int num_channels,\n\n T* out) {\n\n for (size_t i = 0; i < num_frames; ++i) {\n\n Intermediate value = input_channels[0][i];\n\n for (int j = 1; j < num_channels; ++j) {\n\n value += input_channels[j][i];\n\n }\n\n out[i] = value / num_channels;\n\n }\n\n}\n\n\n\n// Downmixes an interleaved multichannel signal to a single channel by averaging\n\n// all channels.\n\ntemplate <typename T, typename Intermediate>\n\nvoid DownmixInterleavedToMonoImpl(const T* interleaved,\n\n size_t num_frames,\n\n int num_channels,\n\n T* deinterleaved) {\n\n RTC_DCHECK_GT(num_channels, 0);\n\n RTC_DCHECK_GT(num_frames, 0);\n\n\n\n const T* const end = interleaved + num_frames * num_channels;\n\n\n\n while (interleaved < end) {\n\n const T* const frame_end = interleaved + num_channels;\n\n\n\n Intermediate value = *interleaved++;\n\n while (interleaved < frame_end) {\n\n value += *interleaved++;\n\n }\n\n\n\n *deinterleaved++ = value / num_channels;\n\n }\n\n}\n\n\n\ntemplate <typename T>\n\nvoid DownmixInterleavedToMono(const T* interleaved,\n\n size_t num_frames,\n\n int num_channels,\n\n T* deinterleaved);\n\n\n\ntemplate <>\n\nvoid DownmixInterleavedToMono<int16_t>(const int16_t* interleaved,\n\n size_t num_frames,\n\n int num_channels,\n\n int16_t* deinterleaved);\n\n\n", "file_path": "common_audio/include/audio_util.h", "rank": 5, "score": 188961.89034751803 }, { "content": "namespace webrtc {\n\n\n\n// Please refer to http://www.etsi.org/deliver/etsi_ts/126100_126199/126114/\n\n// 12.07.00_60/ts_126114v120700p.pdf Section 7.4.5. The rotation of a frame is\n\n// the clockwise angle the frames must be rotated in order to display the frames\n\n// correctly if the display is rotated in its natural orientation.\n\ninline uint8_t ConvertVideoRotationToCVOByte(VideoRotation rotation) {\n\n switch (rotation) {\n\n case kVideoRotation_0:\n\n return 0;\n\n case kVideoRotation_90:\n\n return 1;\n\n case kVideoRotation_180:\n\n return 2;\n\n case kVideoRotation_270:\n\n return 3;\n\n }\n\n RTC_NOTREACHED();\n\n return 0;\n\n}\n\n\n\ninline VideoRotation ConvertCVOByteToVideoRotation(uint8_t cvo_byte) {\n\n // CVO byte: |0 0 0 0 C F R R|.\n\n const uint8_t rotation_bits = cvo_byte & 0x3;\n\n switch (rotation_bits) {\n\n case 0:\n\n return kVideoRotation_0;\n\n case 1:\n\n return kVideoRotation_90;\n\n case 2:\n\n return kVideoRotation_180;\n\n case 3:\n\n return kVideoRotation_270;\n\n default:\n\n RTC_NOTREACHED();\n\n return kVideoRotation_0;\n\n }\n\n}\n\n\n", "file_path": "modules/rtp_rtcp/include/rtp_cvo.h", "rank": 6, "score": 185956.25813354834 }, { "content": "namespace webrtc {\n\nnamespace field_trial {\n\n\n\n// Optionally initialize field trial from a string.\n\n// This method can be called at most once before any other call into webrtc.\n\n// E.g. before the peer connection factory is constructed.\n\n// Note: trials_string must never be destroyed.\n\nvoid InitFieldTrialsFromString(const char* trials_string);\n\n\n\nconst char* GetFieldTrialString();\n\n\n\n} // namespace field_trial\n", "file_path": "system_wrappers/include/field_trial_default.h", "rank": 7, "score": 185956.25813354834 }, { "content": " uint32_t state[5];\n", "file_path": "base/sha1.h", "rank": 8, "score": 183423.2899148612 }, { "content": "namespace webrtc {\n\n\n\nnamespace congestion_controller {\n\nint GetMinBitrateBps();\n\n} // namespace congestion_controller\n\n\n\nstatic const int64_t kBitrateWindowMs = 1000;\n\n\n\nextern const char* kBweTypeHistogram;\n\n\n\nenum BweNames {\n\n kReceiverNoExtension = 0,\n\n kReceiverTOffset = 1,\n\n kReceiverAbsSendTime = 2,\n\n kSendSideTransportSeqNum = 3,\n\n kBweNamesMax = 4\n\n};\n\n\n\nenum BandwidthUsage {\n\n kBwNormal = 0,\n\n kBwUnderusing = 1,\n\n kBwOverusing = 2,\n\n};\n\n\n\nenum RateControlState { kRcHold, kRcIncrease, kRcDecrease };\n\n\n\nenum RateControlRegion { kRcNearMax, kRcAboveMax, kRcMaxUnknown };\n\n\n\nstruct RateControlInput {\n\n RateControlInput(BandwidthUsage bw_state,\n\n const rtc::Optional<uint32_t>& incoming_bitrate,\n\n double noise_var)\n\n : bw_state(bw_state),\n\n incoming_bitrate(incoming_bitrate),\n\n noise_var(noise_var) {}\n\n\n\n BandwidthUsage bw_state;\n\n rtc::Optional<uint32_t> incoming_bitrate;\n\n double noise_var;\n\n};\n", "file_path": "modules/remote_bitrate_estimator/include/bwe_defines.h", "rank": 9, "score": 183091.13107690756 }, { "content": "namespace webrtc {\n\n\n\n///////////////////////////////////////////////////////////////////////////\n\n// enum ACMVADMode\n\n// An enumerator for aggressiveness of VAD\n\n// -VADNormal : least aggressive mode.\n\n// -VADLowBitrate : more aggressive than \"VADNormal\" to save on\n\n// bit-rate.\n\n// -VADAggr : an aggressive mode.\n\n// -VADVeryAggr : the most agressive mode.\n\n//\n\nenum ACMVADMode {\n\n VADNormal = 0,\n\n VADLowBitrate = 1,\n\n VADAggr = 2,\n\n VADVeryAggr = 3\n\n};\n\n\n\n///////////////////////////////////////////////////////////////////////////\n\n//\n\n// Enumeration of Opus mode for intended application.\n\n//\n\n// kVoip : optimized for voice signals.\n\n// kAudio : optimized for non-voice signals like music.\n\n//\n\nenum OpusApplicationMode {\n\n kVoip = 0,\n\n kAudio = 1,\n\n};\n\n\n", "file_path": "modules/audio_coding/include/audio_coding_module_typedefs.h", "rank": 10, "score": 180356.51422753293 }, { "content": "namespace webrtc {\n\n\n\nconst int16_t kMaxOneBytePictureId = 0x7F; // 7 bits\n\nconst int16_t kMaxTwoBytePictureId = 0x7FFF; // 15 bits\n\nconst uint8_t kNoSpatialIdx = 0xFF;\n\nconst uint8_t kNoGofIdx = 0xFF;\n\nconst uint8_t kNumVp9Buffers = 8;\n\nconst size_t kMaxVp9RefPics = 3;\n\nconst size_t kMaxVp9FramesInGof = 0xFF; // 8 bits\n\nconst size_t kMaxVp9NumberOfSpatialLayers = 8;\n\n\n\nenum TemporalStructureMode {\n\n kTemporalStructureMode1, // 1 temporal layer structure - i.e., IPPP...\n\n kTemporalStructureMode2, // 2 temporal layers 01...\n\n kTemporalStructureMode3, // 3 temporal layers 0212...\n\n kTemporalStructureMode4 // 3 temporal layers 02120212...\n\n};\n\n\n\nstruct GofInfoVP9 {\n\n void SetGofInfoVP9(TemporalStructureMode tm) {\n\n switch (tm) {\n\n case kTemporalStructureMode1:\n\n num_frames_in_gof = 1;\n\n temporal_idx[0] = 0;\n\n temporal_up_switch[0] = false;\n\n num_ref_pics[0] = 1;\n\n pid_diff[0][0] = 1;\n\n break;\n\n case kTemporalStructureMode2:\n\n num_frames_in_gof = 2;\n\n temporal_idx[0] = 0;\n\n temporal_up_switch[0] = false;\n\n num_ref_pics[0] = 1;\n\n pid_diff[0][0] = 2;\n\n\n\n temporal_idx[1] = 1;\n\n temporal_up_switch[1] = true;\n\n num_ref_pics[1] = 1;\n\n pid_diff[1][0] = 1;\n\n break;\n\n case kTemporalStructureMode3:\n\n num_frames_in_gof = 4;\n\n temporal_idx[0] = 0;\n\n temporal_up_switch[0] = false;\n\n num_ref_pics[0] = 1;\n\n pid_diff[0][0] = 4;\n\n\n\n temporal_idx[1] = 2;\n\n temporal_up_switch[1] = true;\n\n num_ref_pics[1] = 1;\n\n pid_diff[1][0] = 1;\n\n\n\n temporal_idx[2] = 1;\n\n temporal_up_switch[2] = true;\n\n num_ref_pics[2] = 1;\n\n pid_diff[2][0] = 2;\n\n\n\n temporal_idx[3] = 2;\n\n temporal_up_switch[3] = false;\n\n num_ref_pics[3] = 2;\n\n pid_diff[3][0] = 1;\n\n pid_diff[3][1] = 2;\n\n break;\n\n case kTemporalStructureMode4:\n\n num_frames_in_gof = 8;\n\n temporal_idx[0] = 0;\n\n temporal_up_switch[0] = false;\n\n num_ref_pics[0] = 1;\n\n pid_diff[0][0] = 4;\n\n\n\n temporal_idx[1] = 2;\n\n temporal_up_switch[1] = true;\n\n num_ref_pics[1] = 1;\n\n pid_diff[1][0] = 1;\n\n\n\n temporal_idx[2] = 1;\n\n temporal_up_switch[2] = true;\n\n num_ref_pics[2] = 1;\n\n pid_diff[2][0] = 2;\n\n\n\n temporal_idx[3] = 2;\n\n temporal_up_switch[3] = false;\n\n num_ref_pics[3] = 2;\n\n pid_diff[3][0] = 1;\n\n pid_diff[3][1] = 2;\n\n\n\n temporal_idx[4] = 0;\n\n temporal_up_switch[0] = false;\n\n num_ref_pics[4] = 1;\n\n pid_diff[4][0] = 4;\n\n\n\n temporal_idx[5] = 2;\n\n temporal_up_switch[1] = false;\n\n num_ref_pics[5] = 2;\n\n pid_diff[5][0] = 1;\n\n pid_diff[5][1] = 2;\n\n\n\n temporal_idx[6] = 1;\n\n temporal_up_switch[2] = false;\n\n num_ref_pics[6] = 2;\n\n pid_diff[6][0] = 2;\n\n pid_diff[6][1] = 4;\n\n\n\n temporal_idx[7] = 2;\n\n temporal_up_switch[3] = false;\n\n num_ref_pics[7] = 2;\n\n pid_diff[7][0] = 1;\n\n pid_diff[7][1] = 2;\n\n break;\n\n default:\n\n assert(false);\n\n }\n", "file_path": "modules/video_coding/codecs/vp9/include/vp9_globals.h", "rank": 11, "score": 180356.51422753293 }, { "content": "namespace webrtc {\n\n\n\nstruct RTPVideoHeaderVP8 {\n\n void InitRTPVideoHeaderVP8() {\n\n nonReference = false;\n\n pictureId = kNoPictureId;\n\n tl0PicIdx = kNoTl0PicIdx;\n\n temporalIdx = kNoTemporalIdx;\n\n layerSync = false;\n\n keyIdx = kNoKeyIdx;\n\n partitionId = 0;\n\n beginningOfPartition = false;\n\n }\n\n\n\n bool nonReference; // Frame is discardable.\n\n int16_t pictureId; // Picture ID index, 15 bits;\n\n // kNoPictureId if PictureID does not exist.\n\n int16_t tl0PicIdx; // TL0PIC_IDX, 8 bits;\n\n // kNoTl0PicIdx means no value provided.\n\n uint8_t temporalIdx; // Temporal layer index, or kNoTemporalIdx.\n\n bool layerSync; // This frame is a layer sync frame.\n\n // Disabled if temporalIdx == kNoTemporalIdx.\n\n int keyIdx; // 5 bits; kNoKeyIdx means not used.\n\n int partitionId; // VP8 partition ID\n\n bool beginningOfPartition; // True if this packet is the first\n\n // in a VP8 partition. Otherwise false\n", "file_path": "modules/video_coding/codecs/vp8/include/vp8_globals.h", "rank": 12, "score": 180356.51422753293 }, { "content": "namespace webrtc {\n\n\n\n// Ratio allocation between temporal streams:\n\n// Values as required for the VP8 codec (accumulating).\n\nstatic const float\n\n kVp8LayerRateAlloction[kMaxTemporalStreams][kMaxTemporalStreams] = {\n\n {1.0f, 1.0f, 1.0f, 1.0f}, // 1 layer\n\n {0.6f, 1.0f, 1.0f, 1.0f}, // 2 layers {60%, 40%}\n\n {0.4f, 0.6f, 1.0f, 1.0f}, // 3 layers {40%, 20%, 40%}\n\n {0.25f, 0.4f, 0.6f, 1.0f} // 4 layers {25%, 15%, 20%, 40%}\n\n};\n\n\n", "file_path": "modules/video_coding/codecs/vp8/include/vp8_common_types.h", "rank": 13, "score": 177743.3676784258 }, { "content": " public native State state();\n", "file_path": "sdk/android/api/org/webrtc/DataChannel.java", "rank": 14, "score": 175414.10688586725 }, { "content": " public State state() {\n\n return nativeState(nativeSource);\n", "file_path": "sdk/android/api/org/webrtc/MediaSource.java", "rank": 15, "score": 175414.10688586725 }, { "content": "namespace webrtc {\n\n\n\nusing AudioEncoderIsacFix = AudioEncoderIsacT<IsacFix>;\n\n\n", "file_path": "modules/audio_coding/codecs/isac/fix/include/audio_encoder_isacfix.h", "rank": 16, "score": 175243.49245577384 }, { "content": "namespace webrtc {\n\n\n\nusing AudioDecoderIsac = AudioDecoderIsacT<IsacFloat>;\n\n\n", "file_path": "modules/audio_coding/codecs/isac/main/include/audio_decoder_isac.h", "rank": 17, "score": 175243.49245577384 }, { "content": "namespace webrtc {\n\n\n\nusing AudioDecoderIsacFix = AudioDecoderIsacT<IsacFix>;\n\n\n", "file_path": "modules/audio_coding/codecs/isac/fix/include/audio_decoder_isacfix.h", "rank": 18, "score": 175243.49245577384 }, { "content": "namespace webrtc {\n\n\n\nusing AudioEncoderIsac = AudioEncoderIsacT<IsacFloat>;\n\n\n", "file_path": "modules/audio_coding/codecs/isac/main/include/audio_encoder_isac.h", "rank": 19, "score": 175243.49245577384 }, { "content": " private SessionState state = SessionState.RUNNING;\n", "file_path": "sdk/android/src/java/org/webrtc/Camera2Session.java", "rank": 20, "score": 173026.14882991544 }, { "content": " private SessionState state;\n", "file_path": "sdk/android/src/java/org/webrtc/Camera1Session.java", "rank": 21, "score": 173018.28174562106 }, { "content": " public State state() {\n\n return nativeState(nativeTrack);\n", "file_path": "sdk/android/api/org/webrtc/MediaStreamTrack.java", "rank": 22, "score": 170721.560726314 }, { "content": " public NetworkState(boolean connected, int type, int subtype) {\n\n this.connected = connected;\n\n this.type = type;\n\n this.subtype = subtype;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 23, "score": 169399.7889234131 }, { "content": " private final boolean connected;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 24, "score": 166455.50902787078 }, { "content": " public boolean isConnected() {\n\n return connected;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 25, "score": 166455.50902787078 }, { "content": " private final int subtype;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 26, "score": 166455.50902787078 }, { "content": " private final int type;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 27, "score": 166455.50902787078 }, { "content": "class AudioState final : public webrtc::AudioState,\n\n public webrtc::VoiceEngineObserver {\n\n public:\n\n explicit AudioState(const AudioState::Config& config);\n\n ~AudioState() override;\n\n\n\n VoiceEngine* voice_engine();\n\n\n\n rtc::scoped_refptr<AudioMixer> mixer();\n\n bool typing_noise_detected() const;\n\n\n\n private:\n\n // rtc::RefCountInterface implementation.\n\n int AddRef() const override;\n\n int Release() const override;\n\n\n\n // webrtc::VoiceEngineObserver implementation.\n\n void CallbackOnError(int channel_id, int err_code) override;\n\n\n\n rtc::ThreadChecker thread_checker_;\n", "file_path": "audio/audio_state.h", "rank": 28, "score": 165770.25238939092 }, { "content": " public NetworkState getCurrentNetworkState() {\n\n return connectivityManagerDelegate.getNetworkState();\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 29, "score": 163614.4242601796 }, { "content": " struct saved_state state;\n", "file_path": "modules/audio_processing/test/android/apmtest/jni/main.c", "rank": 30, "score": 163171.2701628983 }, { "content": " public int getNetworkType() {\n\n return type;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 31, "score": 160871.0583202902 }, { "content": "NS_ASSUME_NONNULL_BEGIN\n\n\n\nRTC_EXPORT\n\n@interface RTCMediaSource : NSObject\n\n\n\n/** The current state of the RTCMediaSource. */\n", "file_path": "sdk/objc/Framework/Headers/WebRTC/RTCMediaSource.h", "rank": 32, "score": 160414.69383026706 }, { "content": " RateControlInput(BandwidthUsage bw_state,\n\n const rtc::Optional<uint32_t>& incoming_bitrate,\n\n double noise_var)\n\n : bw_state(bw_state),\n\n incoming_bitrate(incoming_bitrate),\n\n noise_var(noise_var) {}\n\n\n", "file_path": "modules/remote_bitrate_estimator/include/bwe_defines.h", "rank": 33, "score": 158323.5153263114 }, { "content": " public int getNetworkSubType() {\n\n return subtype;\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 34, "score": 158220.32589390193 }, { "content": " NetworkState getNetworkState(NetworkInfo networkInfo) {\n\n if (networkInfo == null || !networkInfo.isConnected()) {\n\n return new NetworkState(false, -1, -1);\n\n }\n\n return new NetworkState(true, networkInfo.getType(), networkInfo.getSubtype());\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitorAutoDetect.java", "rank": 35, "score": 158220.32589390193 }, { "content": " public static void setAutoDetectConnectivityState(boolean shouldAutoDetect) {\n\n getInstance().setAutoDetectConnectivityStateInternal(shouldAutoDetect);\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitor.java", "rank": 36, "score": 154264.24952134804 }, { "content": " private void setAutoDetectConnectivityStateInternal(boolean shouldAutoDetect) {\n\n if (!shouldAutoDetect) {\n\n destroyAutoDetector();\n\n return;\n\n }\n\n if (autoDetector == null) {\n\n autoDetector = new NetworkMonitorAutoDetect(new NetworkMonitorAutoDetect.Observer() {\n\n\n\n @Override\n\n public void onConnectionTypeChanged(ConnectionType newConnectionType) {\n\n updateCurrentConnectionType(newConnectionType);\n\n }\n\n\n\n @Override\n\n public void onNetworkConnect(NetworkInformation networkInfo) {\n\n notifyObserversOfNetworkConnect(networkInfo);\n\n }\n\n\n\n @Override\n\n public void onNetworkDisconnect(long networkHandle) {\n\n notifyObserversOfNetworkDisconnect(networkHandle);\n\n }\n\n }, applicationContext);\n\n final NetworkMonitorAutoDetect.NetworkState networkState =\n\n autoDetector.getCurrentNetworkState();\n\n updateCurrentConnectionType(NetworkMonitorAutoDetect.getConnectionType(networkState));\n\n updateActiveNetworkList();\n\n }\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitor.java", "rank": 37, "score": 151178.6630477461 }, { "content": " private WebSocketConnectionState state;\n", "file_path": "examples/androidapp/src/org/appspot/apprtc/WebSocketChannelClient.java", "rank": 38, "score": 146495.49675639716 }, { "content": " @Override\n\n public void onNetworkDisconnect(long networkHandle) {\n\n notifyObserversOfNetworkDisconnect(networkHandle);\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitor.java", "rank": 39, "score": 145399.6550412394 }, { "content": " @Override\n\n public void onNetworkConnect(NetworkInformation networkInfo) {\n\n notifyObserversOfNetworkConnect(networkInfo);\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitor.java", "rank": 40, "score": 145399.65504123943 }, { "content": " @Override\n\n public void onConnectionTypeChanged(ConnectionType newConnectionType) {\n\n updateCurrentConnectionType(newConnectionType);\n", "file_path": "sdk/android/api/org/webrtc/NetworkMonitor.java", "rank": 41, "score": 142676.73272351007 }, { "content": "namespace webrtc {\n\n\n\n// Helper methods to create RtpParameters to use for sending/receiving.\n\n//\n\n// \"MakeMinimal\" methods contain the minimal necessary information for an\n\n// RtpSender or RtpReceiver to function. The \"MakeFull\" methods are the\n\n// opposite, and include all features that would normally be offered by a\n\n// PeerConnection, and in some cases additional ones.\n\n//\n\n// These methods are intended to be used for end-to-end testing (such as in\n\n// ortcfactory_integrationtest.cc), or unit testing that doesn't care about the\n\n// specific contents of the parameters. Tests should NOT assume that these\n\n// methods will not change; tests that are testing that a specific value in the\n\n// parameters is applied properly should construct the parameters in the test\n\n// itself.\n\n\n\ninline RtcpParameters MakeRtcpMuxParameters() {\n\n RtcpParameters rtcp_parameters;\n\n rtcp_parameters.mux = true;\n\n return rtcp_parameters;\n\n}\n\n\n\nRtpParameters MakeMinimalOpusParameters();\n\nRtpParameters MakeMinimalIsacParameters();\n\nRtpParameters MakeMinimalOpusParametersWithSsrc(uint32_t ssrc);\n\nRtpParameters MakeMinimalIsacParametersWithSsrc(uint32_t ssrc);\n\n\n\nRtpParameters MakeMinimalVp8Parameters();\n\nRtpParameters MakeMinimalVp9Parameters();\n\nRtpParameters MakeMinimalVp8ParametersWithSsrc(uint32_t ssrc);\n\nRtpParameters MakeMinimalVp9ParametersWithSsrc(uint32_t ssrc);\n\n\n\n// Will create an encoding with no SSRC (meaning \"match first SSRC seen\" for a\n\n// receiver, or \"pick one automatically\" for a sender).\n\nRtpParameters MakeMinimalOpusParametersWithNoSsrc();\n\nRtpParameters MakeMinimalIsacParametersWithNoSsrc();\n\nRtpParameters MakeMinimalVp8ParametersWithNoSsrc();\n\nRtpParameters MakeMinimalVp9ParametersWithNoSsrc();\n\n\n\n// Make audio parameters with all the available properties configured and\n\n// features used, and with multiple codecs offered. Obtained by taking a\n\n// snapshot of a default PeerConnection offer (and adding other things, like\n\n// bitrate limit).\n\nRtpParameters MakeFullOpusParameters();\n\nRtpParameters MakeFullIsacParameters();\n\n\n\n// Make video parameters with all the available properties configured and\n\n// features used, and with multiple codecs offered. Obtained by taking a\n\n// snapshot of a default PeerConnection offer (and adding other things, like\n\n// bitrate limit).\n\nRtpParameters MakeFullVp8Parameters();\n\nRtpParameters MakeFullVp9Parameters();\n\n\n", "file_path": "ortc/testrtpparameters.h", "rank": 42, "score": 135665.9355466766 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\nextern const int kTOffsetExtensionId;\n\nextern const int kAbsSendTimeExtensionId;\n\nextern const int kTransportSequenceNumberExtensionId;\n\nextern const int kVideoRotationExtensionId;\n\n} // namespace test\n", "file_path": "test/constants.h", "rank": 43, "score": 135665.9355466766 }, { "content": "namespace webrtc {\n\n\n\n// These structures are intended to mirror those defined by:\n\n// http://draft.ortc.org/#rtcrtpdictionaries*\n\n// Contains everything specified as of 2017 Jan 24.\n\n//\n\n// They are used when retrieving or modifying the parameters of an\n\n// RtpSender/RtpReceiver, or retrieving capabilities.\n\n//\n\n// Note on conventions: Where ORTC may use \"octet\", \"short\" and \"unsigned\"\n\n// types, we typically use \"int\", in keeping with our style guidelines. The\n\n// parameter's actual valid range will be enforced when the parameters are set,\n\n// rather than when the parameters struct is built. An exception is made for\n\n// SSRCs, since they use the full unsigned 32-bit range, and aren't expected to\n\n// be used for any numeric comparisons/operations.\n\n//\n\n// Additionally, where ORTC uses strings, we may use enums for things that have\n\n// a fixed number of supported values. However, for things that can be extended\n\n// (such as codecs, by providing an external encoder factory), a string\n\n// identifier is used.\n\n\n\nenum class FecMechanism {\n\n RED,\n\n RED_AND_ULPFEC,\n\n FLEXFEC,\n\n};\n\n\n\n// Used in RtcpFeedback struct.\n\nenum class RtcpFeedbackType {\n\n CCM,\n\n NACK,\n\n REMB, // \"goog-remb\"\n\n TRANSPORT_CC,\n\n};\n\n\n\n// Used in RtcpFeedback struct when type is NACK or CCM.\n\nenum class RtcpFeedbackMessageType {\n\n // Equivalent to {type: \"nack\", parameter: undefined} in ORTC.\n\n GENERIC_NACK,\n\n PLI, // Usable with NACK.\n\n FIR, // Usable with CCM.\n\n};\n\n\n\nenum class DtxStatus {\n\n DISABLED,\n\n ENABLED,\n\n};\n\n\n\nenum class DegradationPreference {\n\n MAINTAIN_FRAMERATE,\n\n MAINTAIN_RESOLUTION,\n\n BALANCED,\n\n};\n\n\n\nenum class PriorityType { VERY_LOW, LOW, MEDIUM, HIGH };\n\n\n\nstruct RtcpFeedback {\n\n RtcpFeedbackType type = RtcpFeedbackType::CCM;\n\n\n\n // Equivalent to ORTC \"parameter\" field with slight differences:\n\n // 1. It's an enum instead of a string.\n\n // 2. Generic NACK feedback is represented by a GENERIC_NACK message type,\n\n // rather than an unset \"parameter\" value.\n\n rtc::Optional<RtcpFeedbackMessageType> message_type;\n\n\n\n // Constructors for convenience.\n\n RtcpFeedback() {}\n\n explicit RtcpFeedback(RtcpFeedbackType type) : type(type) {}\n\n RtcpFeedback(RtcpFeedbackType type, RtcpFeedbackMessageType message_type)\n\n : type(type), message_type(message_type) {}\n\n\n\n bool operator==(const RtcpFeedback& o) const {\n\n return type == o.type && message_type == o.message_type;\n\n }\n\n bool operator!=(const RtcpFeedback& o) const { return !(*this == o); }\n\n};\n\n\n\n// RtpCodecCapability is to RtpCodecParameters as RtpCapabilities is to\n\n// RtpParameters. This represents the static capabilities of an endpoint's\n\n// implementation of a codec.\n\nstruct RtpCodecCapability {\n\n // Build MIME \"type/subtype\" string from |name| and |kind|.\n\n std::string mime_type() const { return MediaTypeToString(kind) + \"/\" + name; }\n\n\n\n // Used to identify the codec. Equivalent to MIME subtype.\n\n std::string name;\n\n\n\n // The media type of this codec. Equivalent to MIME top-level type.\n\n cricket::MediaType kind = cricket::MEDIA_TYPE_AUDIO;\n\n\n\n // Clock rate in Hertz. If unset, the codec is applicable to any clock rate.\n\n rtc::Optional<int> clock_rate;\n\n\n\n // Default payload type for this codec. Mainly needed for codecs that use\n\n // that have statically assigned payload types.\n\n rtc::Optional<int> preferred_payload_type;\n\n\n\n // Maximum packetization time supported by an RtpReceiver for this codec.\n\n // TODO(deadbeef): Not implemented.\n\n rtc::Optional<int> max_ptime;\n\n\n\n // Preferred packetization time for an RtpReceiver or RtpSender of this\n\n // codec.\n\n // TODO(deadbeef): Not implemented.\n\n rtc::Optional<int> ptime;\n\n\n\n // The number of audio channels supported. Unused for video codecs.\n\n rtc::Optional<int> num_channels;\n\n\n\n // Feedback mechanisms supported for this codec.\n\n std::vector<RtcpFeedback> rtcp_feedback;\n\n\n\n // Codec-specific parameters that must be signaled to the remote party.\n\n //\n\n // Corresponds to \"a=fmtp\" parameters in SDP.\n\n //\n\n // Contrary to ORTC, these parameters are named using all lowercase strings.\n\n // This helps make the mapping to SDP simpler, if an application is using\n\n // SDP. Boolean values are represented by the string \"1\".\n\n std::unordered_map<std::string, std::string> parameters;\n\n\n\n // Codec-specific parameters that may optionally be signaled to the remote\n\n // party.\n\n // TODO(deadbeef): Not implemented.\n\n std::unordered_map<std::string, std::string> options;\n\n\n\n // Maximum number of temporal layer extensions supported by this codec.\n\n // For example, a value of 1 indicates that 2 total layers are supported.\n\n // TODO(deadbeef): Not implemented.\n\n int max_temporal_layer_extensions = 0;\n\n\n\n // Maximum number of spatial layer extensions supported by this codec.\n\n // For example, a value of 1 indicates that 2 total layers are supported.\n\n // TODO(deadbeef): Not implemented.\n\n int max_spatial_layer_extensions = 0;\n\n\n\n // Whether the implementation can send/receive SVC layers with distinct\n\n // SSRCs. Always false for audio codecs. True for video codecs that support\n\n // scalable video coding with MRST.\n\n // TODO(deadbeef): Not implemented.\n\n bool svc_multi_stream_support = false;\n\n\n\n bool operator==(const RtpCodecCapability& o) const {\n\n return name == o.name && kind == o.kind && clock_rate == o.clock_rate &&\n\n preferred_payload_type == o.preferred_payload_type &&\n\n max_ptime == o.max_ptime && ptime == o.ptime &&\n\n num_channels == o.num_channels && rtcp_feedback == o.rtcp_feedback &&\n\n parameters == o.parameters && options == o.options &&\n\n max_temporal_layer_extensions == o.max_temporal_layer_extensions &&\n\n max_spatial_layer_extensions == o.max_spatial_layer_extensions &&\n\n svc_multi_stream_support == o.svc_multi_stream_support;\n\n }\n\n bool operator!=(const RtpCodecCapability& o) const { return !(*this == o); }\n\n};\n\n\n\n// Used in RtpCapabilities; represents the capabilities/preferences of an\n\n// implementation for a header extension.\n\n//\n\n// Just called \"RtpHeaderExtension\" in ORTC, but the \"Capability\" suffix was\n\n// added here for consistency and to avoid confusion with\n\n// RtpHeaderExtensionParameters.\n\n//\n\n// Note that ORTC includes a \"kind\" field, but we omit this because it's\n\n// redundant; if you call \"RtpReceiver::GetCapabilities(MEDIA_TYPE_AUDIO)\",\n\n// you know you're getting audio capabilities.\n\nstruct RtpHeaderExtensionCapability {\n\n // URI of this extension, as defined in RFC5285.\n\n std::string uri;\n\n\n\n // Preferred value of ID that goes in the packet.\n\n rtc::Optional<int> preferred_id;\n\n\n\n // If true, it's preferred that the value in the header is encrypted.\n\n // TODO(deadbeef): Not implemented.\n\n bool preferred_encrypt = false;\n\n\n\n // Constructors for convenience.\n\n RtpHeaderExtensionCapability() = default;\n\n explicit RtpHeaderExtensionCapability(const std::string& uri) : uri(uri) {}\n\n RtpHeaderExtensionCapability(const std::string& uri, int preferred_id)\n\n : uri(uri), preferred_id(preferred_id) {}\n\n\n\n bool operator==(const RtpHeaderExtensionCapability& o) const {\n\n return uri == o.uri && preferred_id == o.preferred_id &&\n\n preferred_encrypt == o.preferred_encrypt;\n\n }\n\n bool operator!=(const RtpHeaderExtensionCapability& o) const {\n\n return !(*this == o);\n\n }\n\n};\n\n\n\n// See webrtc/config.h. Has \"uri\" and \"id\" fields.\n\n// TODO(deadbeef): This is missing the \"encrypt\" flag, which is unimplemented.\n\ntypedef RtpExtension RtpHeaderExtensionParameters;\n\n\n\nstruct RtpFecParameters {\n\n // If unset, a value is chosen by the implementation.\n\n // Works just like RtpEncodingParameters::ssrc.\n\n rtc::Optional<uint32_t> ssrc;\n\n\n\n FecMechanism mechanism = FecMechanism::RED;\n\n\n\n // Constructors for convenience.\n\n RtpFecParameters() = default;\n\n explicit RtpFecParameters(FecMechanism mechanism) : mechanism(mechanism) {}\n\n RtpFecParameters(FecMechanism mechanism, uint32_t ssrc)\n\n : ssrc(ssrc), mechanism(mechanism) {}\n\n\n\n bool operator==(const RtpFecParameters& o) const {\n\n return ssrc == o.ssrc && mechanism == o.mechanism;\n\n }\n\n bool operator!=(const RtpFecParameters& o) const { return !(*this == o); }\n\n};\n\n\n\nstruct RtpRtxParameters {\n\n // If unset, a value is chosen by the implementation.\n\n // Works just like RtpEncodingParameters::ssrc.\n\n rtc::Optional<uint32_t> ssrc;\n\n\n\n // Constructors for convenience.\n\n RtpRtxParameters() = default;\n\n explicit RtpRtxParameters(uint32_t ssrc) : ssrc(ssrc) {}\n\n\n\n bool operator==(const RtpRtxParameters& o) const { return ssrc == o.ssrc; }\n\n bool operator!=(const RtpRtxParameters& o) const { return !(*this == o); }\n", "file_path": "api/rtpparameters.h", "rank": 44, "score": 135665.9355466766 }, { "content": "namespace webrtc {\n\n\n\n// Convert fixed point number with 8 bit fractional part, to floating point.\n\ninline float Q8ToFloat(uint32_t v) {\n\n return static_cast<float>(v) / (1 << 8);\n\n}\n\n\n\n// Convert fixed point number with 14 bit fractional part, to floating point.\n\ninline float Q14ToFloat(uint32_t v) {\n\n return static_cast<float>(v) / (1 << 14);\n\n}\n", "file_path": "audio/conversion.h", "rank": 45, "score": 135665.9355466766 }, { "content": "namespace webrtc {\n\n\n\n// NOTE: Some functions are templated for convenience, such that template-based\n\n// code dealing with AudioContentDescription and VideoContentDescription can\n\n// use this easily. Such methods are usable with cricket::AudioCodec and\n\n// cricket::VideoCodec.\n\n\n\n//***************************************************************************\n\n// Functions for converting from new webrtc:: structures to old cricket::\n\n// structures.\n\n//\n\n// As the return values imply, all of these functions do validation of the\n\n// parameters and return an error if they're invalid. It's expected that any\n\n// default values (such as video clock rate of 90000) have been filled by the\n\n// time the webrtc:: structure is being converted to the cricket:: one.\n\n//\n\n// These are expected to be used when parameters are passed into an RtpSender\n\n// or RtpReceiver, and need to be validated and converted so they can be\n\n// applied to the media engine level.\n\n//***************************************************************************\n\n\n\n// Returns error on invalid input. Certain message types are only valid for\n\n// certain feedback types.\n\nRTCErrorOr<cricket::FeedbackParam> ToCricketFeedbackParam(\n\n const RtcpFeedback& feedback);\n\n\n\n// Verifies that the codec kind is correct, and it has mandatory parameters\n\n// filled, with values in valid ranges.\n\ntemplate <typename C>\n\nRTCErrorOr<C> ToCricketCodec(const RtpCodecParameters& codec);\n\n\n\n// Verifies that payload types aren't duplicated, in addition to normal\n\n// validation.\n\ntemplate <typename C>\n\nRTCErrorOr<std::vector<C>> ToCricketCodecs(\n\n const std::vector<RtpCodecParameters>& codecs);\n\n\n\n// Validates that header extension IDs aren't duplicated.\n\nRTCErrorOr<cricket::RtpHeaderExtensions> ToCricketRtpHeaderExtensions(\n\n const std::vector<RtpHeaderExtensionParameters>& extensions);\n\n\n\n// SSRCs are allowed to be ommitted. This may be used for receive parameters\n\n// where SSRCs are unsignaled.\n\nRTCErrorOr<cricket::StreamParamsVec> ToCricketStreamParamsVec(\n\n const std::vector<RtpEncodingParameters>& encodings);\n\n\n\n//*****************************************************************************\n\n// Functions for converting from old cricket:: structures to new webrtc::\n\n// structures. Unlike the above functions, these are permissive with regards to\n\n// input validation; it's assumed that any necessary validation already\n\n// occurred.\n\n//\n\n// These are expected to be used either to convert from audio/video engine\n\n// capabilities to RtpCapabilities, or to convert from already-parsed SDP\n\n// (in the form of cricket:: structures) to webrtc:: structures. The latter\n\n// functionality is not yet implemented.\n\n//*****************************************************************************\n\n\n\n// Returns empty value if |cricket_feedback| is a feedback type not\n\n// supported/recognized.\n\nrtc::Optional<RtcpFeedback> ToRtcpFeedback(\n\n const cricket::FeedbackParam& cricket_feedback);\n\n\n\nstd::vector<RtpEncodingParameters> ToRtpEncodings(\n\n const cricket::StreamParamsVec& stream_params);\n\n\n\ntemplate <typename C>\n\nRtpCodecParameters ToRtpCodecParameters(const C& cricket_codec);\n\n\n\ntemplate <typename C>\n\nRtpCodecCapability ToRtpCodecCapability(const C& cricket_codec);\n\n\n\ntemplate <class C>\n\nRtpCapabilities ToRtpCapabilities(\n\n const std::vector<C>& cricket_codecs,\n\n const cricket::RtpHeaderExtensions& cricket_extensions);\n\n\n\ntemplate <class C>\n\nRtpParameters ToRtpParameters(\n\n const std::vector<C>& cricket_codecs,\n\n const cricket::RtpHeaderExtensions& cricket_extensions,\n\n const cricket::StreamParamsVec& stream_params);\n\n\n", "file_path": "ortc/rtpparametersconversion.h", "rank": 46, "score": 135665.9355466766 }, { "content": "class ConferenceTransport: public webrtc::Transport {\n\n public:\n\n ConferenceTransport();\n\n virtual ~ConferenceTransport();\n\n\n\n /* SetRtt()\n\n * Set RTT between local channels and reflector.\n\n *\n\n * Input:\n\n * rtt_ms : RTT in milliseconds.\n\n */\n\n void SetRtt(unsigned int rtt_ms);\n\n\n\n /* AddStream()\n\n * Adds a stream in the conference.\n\n *\n\n * Input:\n\n * file_name : name of the file to be added as microphone input.\n\n * format : format of the input file.\n\n *\n", "file_path": "voice_engine/test/auto_test/fakes/conference_transport.h", "rank": 47, "score": 134521.93233289904 }, { "content": "// Scoped helper class for directing Traces to Android's logcat facility. While\n\n// this object lives, Trace output will be sent to logcat.\n\nclass LogcatTraceContext : public webrtc::TraceCallback {\n\n public:\n\n LogcatTraceContext();\n\n ~LogcatTraceContext() override;\n\n\n\n // TraceCallback impl.\n\n void Print(TraceLevel level, const char* message, int length) override;\n\n};\n\n\n\n} // namespace webrtc\n\n\n\n#endif // WEBRTC_SYSTEM_WRAPPERS_INCLUDE_LOGCAT_TRACE_CONTEXT_H_\n", "file_path": "system_wrappers/include/logcat_trace_context.h", "rank": 48, "score": 134444.85699024884 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// Blocks until the user presses enter.\n\nvoid PressEnterToContinue();\n\n\n\n} // namespace test\n", "file_path": "test/run_loop.h", "rank": 49, "score": 134133.03587238723 }, { "content": "namespace webrtc {\n\n\n\nvoid InitializeAndroidObjects();\n\n\n", "file_path": "pc/test/androidtestinitializer.h", "rank": 50, "score": 134133.03587238723 }, { "content": "namespace webrtc {\n\n\n\n// SDP offer string from a Nightly FireFox build.\n\nstatic const char kFireFoxSdpOffer[] =\n\n \"v=0\\r\\n\"\n\n \"o=Mozilla-SIPUA 23551 0 IN IP4 0.0.0.0\\r\\n\"\n\n \"s=SIP Call\\r\\n\"\n\n \"t=0 0\\r\\n\"\n\n \"a=ice-ufrag:e5785931\\r\\n\"\n\n \"a=ice-pwd:36fb7878390db89481c1d46daa4278d8\\r\\n\"\n\n \"a=fingerprint:sha-256 A7:24:72:CA:6E:02:55:39:BA:66:DF:6E:CC:4C:D8:B0:1A:\"\n\n \"BF:1A:56:65:7D:F4:03:AD:7E:77:43:2A:29:EC:93\\r\\n\"\n\n \"m=audio 36993 RTP/SAVPF 109 0 8 101\\r\\n\"\n\n \"c=IN IP4 74.95.2.170\\r\\n\"\n\n \"a=rtpmap:109 opus/48000/2\\r\\n\"\n\n \"a=ptime:20\\r\\n\"\n\n \"a=rtcp-mux\\r\\n\"\n\n \"a=rtpmap:0 PCMU/8000\\r\\n\"\n\n \"a=rtpmap:8 PCMA/8000\\r\\n\"\n\n \"a=rtpmap:101 telephone-event/8000\\r\\n\"\n\n \"a=fmtp:101 0-15\\r\\n\"\n\n \"a=sendrecv\\r\\n\"\n\n \"a=candidate:0 1 UDP 2112946431 172.16.191.1 61725 typ host\\r\\n\"\n\n \"a=candidate:2 1 UDP 2112487679 172.16.131.1 58798 typ host\\r\\n\"\n\n \"a=candidate:4 1 UDP 2113667327 10.0.254.2 58122 typ host\\r\\n\"\n\n \"a=candidate:5 1 UDP 1694302207 74.95.2.170 36993 typ srflx raddr \"\n\n \"10.0.254.2 rport 58122\\r\\n\"\n\n \"a=candidate:0 2 UDP 2112946430 172.16.191.1 55025 typ host\\r\\n\"\n\n \"a=candidate:2 2 UDP 2112487678 172.16.131.1 63576 typ host\\r\\n\"\n\n \"a=candidate:4 2 UDP 2113667326 10.0.254.2 50962 typ host\\r\\n\"\n\n \"a=candidate:5 2 UDP 1694302206 74.95.2.170 41028 typ srflx raddr\"\n\n \" 10.0.254.2 rport 50962\\r\\n\"\n\n \"m=video 38826 RTP/SAVPF 120\\r\\n\"\n\n \"c=IN IP4 74.95.2.170\\r\\n\"\n\n \"a=rtcp-mux\\r\\n\"\n\n \"a=rtpmap:120 VP8/90000\\r\\n\"\n\n \"a=sendrecv\\r\\n\"\n\n \"a=candidate:0 1 UDP 2112946431 172.16.191.1 62017 typ host\\r\\n\"\n\n \"a=candidate:2 1 UDP 2112487679 172.16.131.1 59741 typ host\\r\\n\"\n\n \"a=candidate:4 1 UDP 2113667327 10.0.254.2 62652 typ host\\r\\n\"\n\n \"a=candidate:5 1 UDP 1694302207 74.95.2.170 38826 typ srflx raddr\"\n\n \" 10.0.254.2 rport 62652\\r\\n\"\n\n \"a=candidate:0 2 UDP 2112946430 172.16.191.1 63440 typ host\\r\\n\"\n\n \"a=candidate:2 2 UDP 2112487678 172.16.131.1 51847 typ host\\r\\n\"\n\n \"a=candidate:4 2 UDP 2113667326 10.0.254.2 58890 typ host\\r\\n\"\n\n \"a=candidate:5 2 UDP 1694302206 74.95.2.170 33611 typ srflx raddr\"\n\n \" 10.0.254.2 rport 58890\\r\\n\"\n\n#ifdef HAVE_SCTP\n\n \"m=application 45536 SCTP/DTLS 5000\\r\\n\"\n\n \"c=IN IP4 74.95.2.170\\r\\n\"\n\n \"a=fmtp:5000 protocol=webrtc-datachannel;streams=16\\r\\n\"\n\n \"a=sendrecv\\r\\n\"\n\n \"a=candidate:0 1 UDP 2112946431 172.16.191.1 60248 typ host\\r\\n\"\n\n \"a=candidate:2 1 UDP 2112487679 172.16.131.1 55925 typ host\\r\\n\"\n\n \"a=candidate:4 1 UDP 2113667327 10.0.254.2 65268 typ host\\r\\n\"\n\n \"a=candidate:5 1 UDP 1694302207 74.95.2.170 45536 typ srflx raddr\"\n\n \" 10.0.254.2 rport 65268\\r\\n\"\n\n \"a=candidate:0 2 UDP 2112946430 172.16.191.1 49162 typ host\\r\\n\"\n\n \"a=candidate:2 2 UDP 2112487678 172.16.131.1 59635 typ host\\r\\n\"\n\n \"a=candidate:4 2 UDP 2113667326 10.0.254.2 61232 typ host\\r\\n\"\n\n \"a=candidate:5 2 UDP 1694302206 74.95.2.170 45468 typ srflx raddr\"\n\n \" 10.0.254.2 rport 61232\\r\\n\"\n\n#endif\n\n ;\n\n\n\n// Audio SDP with a limited set of audio codecs.\n\nstatic const char kAudioSdp[] =\n\n \"v=0\\r\\n\"\n\n \"o=- 7859371131 2 IN IP4 192.168.30.208\\r\\n\"\n\n \"s=-\\r\\n\"\n\n \"c=IN IP4 192.168.30.208\\r\\n\"\n\n \"t=0 0\\r\\n\"\n\n \"m=audio 16000 RTP/SAVPF 0 8 126\\r\\n\"\n\n \"a=rtpmap:0 PCMU/8000\\r\\n\"\n\n \"a=rtpmap:8 PCMA/8000\\r\\n\"\n\n \"a=rtpmap:126 telephone-event/8000\\r\\n\"\n\n \"a=sendrecv\\r\\n\"\n\n \"a=rtcp:16000 IN IP4 192.168.30.208\\r\\n\"\n\n \"a=rtcp-mux\\r\\n\"\n\n \"a=crypto:1 AES_CM_128_HMAC_SHA1_80 \"\n\n \"inline:tvKIFjbMQ7W0/C2RzhwN0oQglj/7GJg+frdsNRxt\\r\\n\"\n\n \"a=ice-ufrag:AI2sRT3r\\r\\n\"\n\n \"a=ice-pwd:lByS9z2RSQlSE9XurlvjYmEm\\r\\n\"\n\n \"a=ssrc:4227871655 cname:GeAAgb6XCPNLVMX5\\r\\n\"\n\n \"a=ssrc:4227871655 msid:1NFAV3iD08ioO2339rQS9pfOI9mDf6GeG9F4 a0\\r\\n\"\n\n \"a=ssrc:4227871655 mslabel:1NFAV3iD08ioO2339rQS9pfOI9mDf6GeG9F4\\r\\n\"\n\n \"a=ssrc:4227871655 label:1NFAV3iD08ioO2339rQS9pfOI9mDf6GeG9F4a0\\r\\n\"\n\n \"a=mid:audio\\r\\n\";\n\n\n\nstatic const char kAudioSdpWithUnsupportedCodecs[] =\n\n \"v=0\\r\\n\"\n\n \"o=- 6858750541 2 IN IP4 192.168.30.208\\r\\n\"\n\n \"s=-\\r\\n\"\n\n \"c=IN IP4 192.168.30.208\\r\\n\"\n\n \"t=0 0\\r\\n\"\n\n \"m=audio 16000 RTP/SAVPF 0 8 18 110 126\\r\\n\"\n\n \"a=rtpmap:0 PCMU/8000\\r\\n\"\n\n \"a=rtpmap:8 PCMA/8000\\r\\n\"\n\n \"a=rtpmap:18 WeirdCodec1/8000\\r\\n\"\n\n \"a=rtpmap:110 WeirdCodec2/8000\\r\\n\"\n\n \"a=rtpmap:126 telephone-event/8000\\r\\n\"\n\n \"a=sendonly\\r\\n\"\n\n \"a=rtcp:16000 IN IP4 192.168.30.208\\r\\n\"\n\n \"a=rtcp-mux\\r\\n\"\n\n \"a=crypto:1 AES_CM_128_HMAC_SHA1_80 \"\n\n \"inline:tvKIFjbMQ7W0/C2RzhwN0oQglj/7GJg+frdsNRxt\\r\\n\"\n\n \"a=ice-ufrag:AI2sRT3r\\r\\n\"\n\n \"a=ice-pwd:lByS9z2RSQlSE9XurlvjYmEm\\r\\n\"\n\n \"a=ssrc:4227871655 cname:TsmD02HRfhkJBm4m\\r\\n\"\n\n \"a=ssrc:4227871655 msid:7nU0TApbB-n4dfPlCplWT9QTEsbBDS1IlpW3 a0\\r\\n\"\n\n \"a=ssrc:4227871655 mslabel:7nU0TApbB-n4dfPlCplWT9QTEsbBDS1IlpW3\\r\\n\"\n\n \"a=ssrc:4227871655 label:7nU0TApbB-n4dfPlCplWT9QTEsbBDS1IlpW3a0\\r\\n\"\n\n \"a=mid:audio\\r\\n\";\n\n\n", "file_path": "pc/test/testsdpstrings.h", "rank": 51, "score": 134133.03587238723 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// Running a test function on a separate thread, if required by the OS.\n\nvoid RunTest(void(*test)());\n\n\n\n} // namespace test\n", "file_path": "test/run_test.h", "rank": 52, "score": 134133.03587238723 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// This is the \"directory\" returned if the ProjectPath() function fails\n\n// to find the project root.\n\nextern const char* kCannotFindProjectRootDir;\n\n\n\n// Creates and returns the absolute path to the output directory where log files\n\n// and other test artifacts should be put. The output directory is generally a\n\n// directory named \"out\" at the top-level of the project, i.e. a subfolder to\n\n// the path returned by ProjectRootPath(). The exception is Android where we use\n\n// /sdcard/ instead.\n\n//\n\n// If symbolic links occur in the path they will be resolved and the actual\n\n// directory will be returned.\n\n//\n\n// Returns the path WITH a trailing path delimiter. If the project root is not\n\n// found, the current working directory (\"./\") is returned as a fallback.\n\nstd::string OutputPath();\n\n\n\n// Generates an empty file with a unique name in the specified directory and\n\n// returns the file name and path.\n\nstd::string TempFilename(const std::string &dir, const std::string &prefix);\n\n\n\n// Returns a path to a resource file for the currently executing platform.\n\n// Adapts to what filenames are currently present in the\n\n// [project-root]/resources/ dir.\n\n// Returns an absolute path according to this priority list (the directory\n\n// part of the path is left out for readability):\n\n// 1. [name]_[platform]_[architecture].[extension]\n\n// 2. [name]_[platform].[extension]\n\n// 3. [name]_[architecture].[extension]\n\n// 4. [name].[extension]\n\n// Where\n\n// * platform is either of \"win\", \"mac\" or \"linux\".\n\n// * architecture is either of \"32\" or \"64\".\n\n//\n\n// Arguments:\n\n// name - Name of the resource file. If a plain filename (no directory path)\n\n// is supplied, the file is assumed to be located in resources/\n\n// If a directory path is prepended to the filename, a subdirectory\n\n// hierarchy reflecting that path is assumed to be present.\n\n// extension - File extension, without the dot, i.e. \"bmp\" or \"yuv\".\n\nstd::string ResourcePath(const std::string& name,\n\n const std::string& extension);\n\n\n\n// Gets the current working directory for the executing program.\n\n// Returns \"./\" if for some reason it is not possible to find the working\n\n// directory.\n\nstd::string WorkingDir();\n\n\n\n// Creates a directory if it not already exists.\n\n// Returns true if successful. Will print an error message to stderr and return\n\n// false if a file with the same name already exists.\n\nbool CreateDir(const std::string& directory_name);\n\n\n\n// Checks if a file exists.\n\nbool FileExists(const std::string& file_name);\n\n\n\n// Checks if a directory exists.\n\nbool DirExists(const std::string& directory_name);\n\n\n\n// File size of the supplied file in bytes. Will return 0 if the file is\n\n// empty or if the file does not exist/is readable.\n\nsize_t GetFileSize(const std::string& filename);\n\n\n\n// Sets the executable path, i.e. the path to the executable that is being used\n\n// when launching it. This is usually the path relative to the working directory\n\n// but can also be an absolute path. The intention with this function is to pass\n\n// the argv[0] being sent into the main function to make it possible for\n\n// fileutils.h to find the correct project paths even when the working directory\n\n// is outside the project tree (which happens in some cases).\n\nvoid SetExecutablePath(const std::string& path_to_executable);\n\n\n\n} // namespace test\n", "file_path": "test/testsupport/fileutils.h", "rank": 53, "score": 134133.03587238723 }, { "content": "namespace webrtc {\n\n\n\ntemplate <unsigned long M> // NOLINT\n\ninline unsigned long Add(unsigned long a, unsigned long b) { // NOLINT\n\n RTC_DCHECK_LT(a, M);\n\n unsigned long t = M - b % M; // NOLINT\n\n unsigned long res = a - t; // NOLINT\n\n if (t > a)\n\n return res + M;\n\n return res;\n\n}\n\n\n\ntemplate <unsigned long M> // NOLINT\n\ninline unsigned long Subtract(unsigned long a, unsigned long b) { // NOLINT\n\n RTC_DCHECK_LT(a, M);\n\n unsigned long sub = b % M; // NOLINT\n\n if (a < sub)\n\n return M - (sub - a);\n\n return a - sub;\n\n}\n\n\n\n// Calculates the forward difference between two wrapping numbers.\n\n//\n\n// Example:\n\n// uint8_t x = 253;\n\n// uint8_t y = 2;\n\n//\n\n// ForwardDiff(x, y) == 5\n\n//\n\n// 252 253 254 255 0 1 2 3\n\n// #################################################\n\n// | | x | | | | | y | |\n\n// #################################################\n\n// |----->----->----->----->----->\n\n//\n\n// ForwardDiff(y, x) == 251\n\n//\n\n// 252 253 254 255 0 1 2 3\n\n// #################################################\n\n// | | x | | | | | y | |\n\n// #################################################\n\n// -->-----> |----->---\n\n//\n\ntemplate <typename T, T M>\n\ninline T ForwardDiff(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n RTC_DCHECK_LT(a, M);\n\n RTC_DCHECK_LT(b, M);\n\n return a <= b ? b - a : M - (a - b);\n\n}\n\n\n\ntemplate <typename T>\n\ninline T ForwardDiff(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n return b - a;\n\n}\n\n\n\n// Calculates the reverse difference between two wrapping numbers.\n\n//\n\n// Example:\n\n// uint8_t x = 253;\n\n// uint8_t y = 2;\n\n//\n\n// ReverseDiff(y, x) == 5\n\n//\n\n// 252 253 254 255 0 1 2 3\n\n// #################################################\n\n// | | x | | | | | y | |\n\n// #################################################\n\n// <-----<-----<-----<-----<-----|\n\n//\n\n// ReverseDiff(x, y) == 251\n\n//\n\n// 252 253 254 255 0 1 2 3\n\n// #################################################\n\n// | | x | | | | | y | |\n\n// #################################################\n\n// ---<-----| |<-----<--\n\n//\n\ntemplate <typename T, T M>\n\ninline T ReverseDiff(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n RTC_DCHECK_LT(a, M);\n\n RTC_DCHECK_LT(b, M);\n\n return b <= a ? a - b : M - (b - a);\n\n}\n\n\n\ntemplate <typename T>\n\ninline T ReverseDiff(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n return a - b;\n\n}\n\n\n\n// Calculates the minimum distance between to wrapping numbers.\n\n//\n\n// The minimum distance is defined as min(ForwardDiff(a, b), ReverseDiff(a, b))\n\ntemplate <typename T, T M>\n\ninline T MinDiff(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n return std::min(ForwardDiff<T, M>(a, b), ReverseDiff<T, M>(a, b));\n\n}\n\n\n\ntemplate <typename T>\n\ninline T MinDiff(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n return std::min(ForwardDiff(a, b), ReverseDiff(a, b));\n\n}\n\n\n", "file_path": "base/mod_ops.h", "rank": 54, "score": 134133.03587238723 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// Writes a |length| bytes array |buffer| to |filename| in isolated output\n\n// directory defined by swarming. If the file is existing, content will be\n\n// appended. Otherwise a new file will be created. This function returns false\n\n// if isolated output directory has not been defined, or |filename| indicates an\n\n// invalid or non-writable file, or underlying file system errors.\n\nbool WriteIsolatedOutput(const char* filename,\n\n const uint8_t* buffer,\n\n size_t length);\n\n\n\nbool WriteIsolatedOutput(const char* filename, const std::string& content);\n\n\n\n} // namespace test\n", "file_path": "test/testsupport/isolated_output.h", "rank": 55, "score": 132659.33427819004 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// Prints numerical information to stdout in a controlled format, for\n\n// post-processing. |measurement| is a description of the quantity being\n\n// measured, e.g. \"vm_peak\"; |modifier| is provided as a convenience and\n\n// will be appended directly to the name of the |measurement|, e.g.\n\n// \"_browser\"; |trace| is a description of the particular data point, e.g.\n\n// \"reference\"; |value| is the measured value; and |units| is a description\n\n// of the units of measure, e.g. \"bytes\". If |important| is true, the output\n\n// line will be specially marked, to notify the post-processor. The strings\n\n// may be empty. They should not contain any colons (:) or equals signs (=).\n\n// A typical post-processing step would be to produce graphs of the data\n\n// produced for various builds, using the combined |measurement| + |modifier|\n\n// string to specify a particular graph and the |trace| to identify a trace\n\n// (i.e., data series) on that graph.\n\nvoid PrintResult(const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n size_t value,\n\n const std::string& units,\n\n bool important);\n\n\n\nvoid AppendResult(std::string& output,\n\n const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n size_t value,\n\n const std::string& units,\n\n bool important);\n\n\n\n// Like the above version of PrintResult(), but takes a std::string value\n\n// instead of a size_t.\n\nvoid PrintResult(const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n const std::string& value,\n\n const std::string& units,\n\n bool important);\n\n\n\nvoid AppendResult(std::string& output,\n\n const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n const std::string& value,\n\n const std::string& units,\n\n bool important);\n\n\n\n// Like PrintResult(), but prints a (mean, standard deviation) result pair.\n\n// The |<values>| should be two comma-separated numbers, the mean and\n\n// standard deviation (or other error metric) of the measurement.\n\nvoid PrintResultMeanAndError(const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n const std::string& mean_and_error,\n\n const std::string& units,\n\n bool important);\n\n\n\nvoid AppendResultMeanAndError(std::string& output,\n\n const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n const std::string& mean_and_error,\n\n const std::string& units,\n\n bool important);\n\n\n\n// Like PrintResult(), but prints an entire list of results. The |values|\n\n// will generally be a list of comma-separated numbers. A typical\n\n// post-processing step might produce plots of their mean and standard\n\n// deviation.\n\nvoid PrintResultList(const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n const std::string& values,\n\n const std::string& units,\n\n bool important);\n\n\n\nvoid AppendResultList(std::string& output,\n\n const std::string& measurement,\n\n const std::string& modifier,\n\n const std::string& trace,\n\n const std::string& values,\n\n const std::string& units,\n\n bool important);\n\n\n\n// Prints memory commit charge stats for use by perf graphs.\n\nvoid PrintSystemCommitCharge(const std::string& test_name,\n\n size_t charge,\n\n bool important);\n\n\n\nvoid PrintSystemCommitCharge(FILE* target,\n\n const std::string& test_name,\n\n size_t charge,\n\n bool important);\n\n\n\nstd::string SystemCommitChargeToString(const std::string& test_name,\n\n size_t charge,\n\n bool important);\n\n\n\n// Converts list of values into comma-separated string for PrintResultList.\n\ntemplate <typename Container>\n\nstd::string ValuesToString(const Container& container) {\n\n if (container.empty())\n\n return \"\";\n\n\n\n std::stringstream ss;\n\n auto it = container.begin();\n\n while (true) {\n\n ss << *it;\n\n if (++it == container.end())\n\n break;\n\n ss << ',';\n\n }\n\n return ss.str();\n\n}\n\n\n\n} // namespace test\n", "file_path": "test/testsupport/perf_test.h", "rank": 56, "score": 132659.33427819004 }, { "content": "namespace webrtc {\n\n\n\n// enum for clockwise rotation.\n\nenum VideoRotation {\n\n kVideoRotation_0 = 0,\n\n kVideoRotation_90 = 90,\n\n kVideoRotation_180 = 180,\n\n kVideoRotation_270 = 270\n\n};\n\n\n", "file_path": "api/video/video_rotation.h", "rank": 57, "score": 132659.33427819004 }, { "content": "namespace webrtc {\n\n\n\nstatic inline size_t ChannelsFromLayout(AudioProcessing::ChannelLayout layout) {\n\n switch (layout) {\n\n case AudioProcessing::kMono:\n\n case AudioProcessing::kMonoAndKeyboard:\n\n return 1;\n\n case AudioProcessing::kStereo:\n\n case AudioProcessing::kStereoAndKeyboard:\n\n return 2;\n\n }\n\n RTC_NOTREACHED();\n\n return 0;\n\n}\n\n\n", "file_path": "modules/audio_processing/common.h", "rank": 58, "score": 132659.33427819004 }, { "content": "class LoopBackTransport : public webrtc::Transport {\n\n public:\n\n LoopBackTransport(webrtc::VoENetwork* voe_network, int channel)\n\n : packet_event_(webrtc::EventWrapper::Create()),\n\n thread_(NetworkProcess, this, \"LoopBackTransport\"),\n\n channel_(channel),\n\n voe_network_(voe_network),\n\n transmitted_packets_(0) {\n\n thread_.Start();\n\n }\n\n\n\n ~LoopBackTransport() { thread_.Stop(); }\n\n\n\n bool SendRtp(const uint8_t* data,\n\n size_t len,\n\n const webrtc::PacketOptions& options) override {\n\n StorePacket(Packet::Rtp, data, len);\n\n return true;\n\n }\n\n\n", "file_path": "voice_engine/test/auto_test/fixtures/after_initialization_fixture.h", "rank": 59, "score": 131905.94238109275 }, { "content": "class WrappedI420Buffer : public webrtc::VideoFrameBuffer {\n\n public:\n\n WrappedI420Buffer(int width,\n\n int height,\n\n const uint8_t* y_plane,\n\n int y_stride,\n\n const uint8_t* u_plane,\n\n int u_stride,\n\n const uint8_t* v_plane,\n\n int v_stride,\n\n const rtc::Callback0<void>& no_longer_used);\n\n int width() const override;\n\n int height() const override;\n\n\n\n const uint8_t* DataY() const override;\n\n const uint8_t* DataU() const override;\n\n const uint8_t* DataV() const override;\n\n int StrideY() const override;\n\n int StrideU() const override;\n\n int StrideV() const override;\n", "file_path": "common_video/include/video_frame_buffer.h", "rank": 60, "score": 131830.83399926467 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// The highest PSNR value our algorithms will return.\n\nextern double kMetricsPerfectPSNR;\n\n\n\n// Contains video quality metrics result for a single frame.\n\nstruct FrameResult {\n\n int frame_number;\n\n double value;\n\n};\n\n\n\n// Result from a PSNR/SSIM calculation operation.\n\n// The frames in this data structure are 0-indexed.\n\nstruct QualityMetricsResult {\n\n QualityMetricsResult() :\n\n average(0.0),\n\n min(std::numeric_limits<double>::max()),\n\n max(std::numeric_limits<double>::min()),\n\n min_frame_number(-1),\n\n max_frame_number(-1)\n\n {};\n\n double average;\n\n double min;\n\n double max;\n\n int min_frame_number;\n\n int max_frame_number;\n\n std::vector<FrameResult> frames;\n\n};\n\n\n\n// Calculates PSNR and SSIM values for the reference and test video files\n\n// (must be in I420 format). All calculated values are filled into the\n\n// QualityMetricsResult structs.\n\n//\n\n// PSNR values have the unit decibel (dB) where a high value means the test file\n\n// is similar to the reference file. The higher value, the more similar. The\n\n// maximum PSNR value is kMetricsInfinitePSNR. For more info about PSNR, see\n\n// http://en.wikipedia.org/wiki/PSNR.\n\n//\n\n// SSIM values range between -1.0 and 1.0, where 1.0 means the files are\n\n// identical. For more info about SSIM, see http://en.wikipedia.org/wiki/SSIM\n\n// This function only compares video frames up to the point when the shortest\n\n// video ends.\n\n// Return value:\n\n// 0 if successful, negative on errors:\n\n// -1 if the source file cannot be opened\n\n// -2 if the test file cannot be opened\n\n// -3 if any of the files are empty\n\n// -4 if any arguments are invalid.\n\nint I420MetricsFromFiles(const char* ref_filename,\n\n const char* test_filename,\n\n int width,\n\n int height,\n\n QualityMetricsResult* psnr_result,\n\n QualityMetricsResult* ssim_result);\n\n\n\n// Calculates PSNR values for the reference and test video files (must be in\n\n// I420 format). All calculated values are filled into the QualityMetricsResult\n\n// struct.\n\n//\n\n// PSNR values have the unit decibel (dB) where a high value means the test file\n\n// is similar to the reference file. The higher value, the more similar. The\n\n// maximum PSNR value is kMetricsInfinitePSNR. For more info about PSNR, see\n\n// http://en.wikipedia.org/wiki/PSNR.\n\n//\n\n// This function only compares video frames up to the point when the shortest\n\n// video ends.\n\n//\n\n// Return value:\n\n// 0 if successful, negative on errors:\n\n// -1 if the source file cannot be opened\n\n// -2 if the test file cannot be opened\n\n// -3 if any of the files are empty\n\n// -4 if any arguments are invalid.\n\nint I420PSNRFromFiles(const char* ref_filename,\n\n const char* test_filename,\n\n int width,\n\n int height,\n\n QualityMetricsResult* result);\n\n\n\n// Calculates SSIM values for the reference and test video files (must be in\n\n// I420 format). All calculated values are filled into the QualityMetricsResult\n\n// struct.\n\n// SSIM values range between -1.0 and 1.0, where 1.0 means the files are\n\n// identical.\n\n// This function only compares video frames up to the point when the shortest\n\n// video ends.\n\n// For more info about SSIM, see http://en.wikipedia.org/wiki/SSIM\n\n//\n\n// Return value:\n\n// 0 if successful, negative on errors:\n\n// -1 if the source file cannot be opened\n\n// -2 if the test file cannot be opened\n\n// -3 if any of the files are empty\n\n// -4 if any arguments are invalid.\n\nint I420SSIMFromFiles(const char* ref_filename,\n\n const char* test_filename,\n\n int width,\n\n int height,\n\n QualityMetricsResult* result);\n\n\n\n} // namespace test\n", "file_path": "test/testsupport/metrics/video_metrics.h", "rank": 61, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// A four-byte structure to store a color in BGRA format. This structure also\n\n// provides functions to be created from uint8_t array, say,\n\n// DesktopFrame::data(). It always uses BGRA order for internal storage to match\n\n// DesktopFrame::data().\n\nstruct RgbaColor final {\n\n // Creates a color with BGRA channels.\n\n RgbaColor(uint8_t blue, uint8_t green, uint8_t red, uint8_t alpha);\n\n\n\n // Creates a color with BGR channels, and set alpha channel to 255 (opaque).\n\n RgbaColor(uint8_t blue, uint8_t green, uint8_t red);\n\n\n\n // Creates a color from four-byte in BGRA order, i.e. DesktopFrame::data().\n\n explicit RgbaColor(const uint8_t* bgra);\n\n\n\n // Creates a color from BGRA channels in a uint format. Consumers should make\n\n // sure the memory order of the uint32_t is always BGRA from left to right, no\n\n // matter the system endian. This function creates an equivalent RgbaColor\n\n // instance from the ToUInt32() result of another RgbaColor instance.\n\n explicit RgbaColor(uint32_t bgra);\n\n\n\n // Returns true if |this| and |right| is the same color.\n\n bool operator==(const RgbaColor& right) const;\n\n\n\n // Returns true if |this| and |right| are different colors.\n\n bool operator!=(const RgbaColor& right) const;\n\n\n\n uint32_t ToUInt32() const;\n\n\n\n uint8_t blue;\n\n uint8_t green;\n\n uint8_t red;\n\n uint8_t alpha;\n\n};\n\nstatic_assert(\n\n DesktopFrame::kBytesPerPixel == sizeof(RgbaColor),\n\n \"A pixel in DesktopFrame should be safe to be represented by a RgbaColor\");\n\n\n", "file_path": "modules/desktop_capture/rgba_color.h", "rank": 62, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\nnamespace H264 {\n\n// The size of a full NALU start sequence {0 0 0 1}, used for the first NALU\n\n// of an access unit, and for SPS and PPS blocks.\n\nconst size_t kNaluLongStartSequenceSize = 4;\n\n\n\n// The size of a shortened NALU start sequence {0 0 1}, that may be used if\n\n// not the first NALU of an access unit or an SPS or PPS block.\n\nconst size_t kNaluShortStartSequenceSize = 3;\n\n\n\n// The size of the NALU type byte (1).\n\nconst size_t kNaluTypeSize = 1;\n\n\n\nenum NaluType : uint8_t {\n\n kSlice = 1,\n\n kIdr = 5,\n\n kSei = 6,\n\n kSps = 7,\n\n kPps = 8,\n\n kAud = 9,\n\n kEndOfSequence = 10,\n\n kEndOfStream = 11,\n\n kFiller = 12,\n\n kStapA = 24,\n\n kFuA = 28\n\n};\n\n\n\nenum SliceType : uint8_t { kP = 0, kB = 1, kI = 2, kSp = 3, kSi = 4 };\n\n\n\nstruct NaluIndex {\n\n // Start index of NALU, including start sequence.\n\n size_t start_offset;\n\n // Start index of NALU payload, typically type header.\n\n size_t payload_start_offset;\n\n // Length of NALU payload, in bytes, counting from payload_start_offset.\n\n size_t payload_size;\n\n};\n\n\n\n// Returns a vector of the NALU indices in the given buffer.\n\nstd::vector<NaluIndex> FindNaluIndices(const uint8_t* buffer,\n\n size_t buffer_size);\n\n\n\n// Get the NAL type from the header byte immediately following start sequence.\n\nNaluType ParseNaluType(uint8_t data);\n\n\n\n// Methods for parsing and writing RBSP. See section 7.4.1 of the H264 spec.\n\n//\n\n// The following sequences are illegal, and need to be escaped when encoding:\n\n// 00 00 00 -> 00 00 03 00\n\n// 00 00 01 -> 00 00 03 01\n\n// 00 00 02 -> 00 00 03 02\n\n// And things in the source that look like the emulation byte pattern (00 00 03)\n\n// need to have an extra emulation byte added, so it's removed when decoding:\n\n// 00 00 03 -> 00 00 03 03\n\n//\n\n// Decoding is simply a matter of finding any 00 00 03 sequence and removing\n\n// the 03 emulation byte.\n\n\n\n// Parse the given data and remove any emulation byte escaping.\n\nstd::vector<uint8_t> ParseRbsp(const uint8_t* data, size_t length);\n\n\n\n// Write the given data to the destination buffer, inserting and emulation\n\n// bytes in order to escape any data the could be interpreted as a start\n\n// sequence.\n\nvoid WriteRbsp(const uint8_t* bytes, size_t length, rtc::Buffer* destination);\n\n} // namespace H264\n", "file_path": "common_video/h264/h264_common.h", "rank": 63, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// A structure that specifies a GMM.\n\n// A GMM is formulated as\n\n// f(x) = w[0] * mixture[0] + w[1] * mixture[1] + ... +\n\n// w[num_mixtures - 1] * mixture[num_mixtures - 1];\n\n// Where a 'mixture' is a Gaussian density.\n\n\n\nstruct GmmParameters {\n\n // weight[n] = log(w[n]) - |dimension|/2 * log(2*pi) - 1/2 * log(det(cov[n]));\n\n // where cov[n] is the covariance matrix of mixture n;\n\n const double* weight;\n\n // pointer to the first element of a |num_mixtures|x|dimension| matrix\n\n // where kth row is the mean of the kth mixture.\n\n const double* mean;\n\n // pointer to the first element of a |num_mixtures|x|dimension|x|dimension|\n\n // 3D-matrix, where the kth 2D-matrix is the inverse of the covariance\n\n // matrix of the kth mixture.\n\n const double* covar_inverse;\n\n // Dimensionality of the mixtures.\n\n int dimension;\n\n // number of the mixtures.\n\n int num_mixtures;\n\n};\n\n\n\n// Evaluate the given GMM, according to |gmm_parameters|, at the given point\n\n// |x|. If the dimensionality of the given GMM is larger that the maximum\n\n// acceptable dimension by the following function -1 is returned.\n\ndouble EvaluateGmm(const double* x, const GmmParameters& gmm_parameters);\n\n\n", "file_path": "modules/audio_processing/vad/gmm.h", "rank": 64, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n#define MASK_32_BITS(x) (0xFFFFFFFF & (x))\n\n\n\ninline uint32_t MaskWord64ToUWord32(int64_t w64) {\n\n return static_cast<uint32_t>(MASK_32_BITS(w64));\n\n}\n\n\n\n#define VCM_MAX(a, b) (((a) > (b)) ? (a) : (b))\n\n#define VCM_MIN(a, b) (((a) < (b)) ? (a) : (b))\n\n\n\n#define VCM_DEFAULT_CODEC_WIDTH 352\n\n#define VCM_DEFAULT_CODEC_HEIGHT 288\n\n#define VCM_DEFAULT_FRAME_RATE 30\n\n#define VCM_MIN_BITRATE 30\n\n#define VCM_FLUSH_INDICATOR 4\n\n\n\n#define VCM_NO_RECEIVER_ID 0\n\n\n\ninline int32_t VCMId(const int32_t vcmId, const int32_t receiverId = 0) {\n\n return static_cast<int32_t>((vcmId << 16) + receiverId);\n\n}\n\n\n", "file_path": "modules/video_coding/internal_defines.h", "rank": 65, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\ninline int VoEId(int veId, int chId) {\n\n if (chId == -1) {\n\n const int dummyChannel(99);\n\n return (int)((veId << 16) + dummyChannel);\n\n }\n\n return (int)((veId << 16) + chId);\n\n}\n\n\n\ninline int VoEModuleId(int veId, int chId) {\n\n return (int)((veId << 16) + chId);\n\n}\n\n\n\n// Convert module ID to internal VoE channel ID\n\ninline int VoEChannelId(int moduleId) {\n\n return (int)(moduleId & 0xffff);\n\n}\n\n\n", "file_path": "voice_engine/voice_engine_defines.h", "rank": 66, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// Struct for holding RTP packets.\n\nstruct Packet {\n\n struct Priority {\n\n Priority() : codec_level(0), red_level(0) {}\n\n Priority(int codec_level, int red_level)\n\n : codec_level(codec_level), red_level(red_level) {\n\n CheckInvariant();\n\n }\n\n\n\n int codec_level;\n\n int red_level;\n\n\n\n // Priorities are sorted low-to-high, first on the level the codec\n\n // prioritizes it, then on the level of RED packet it is; i.e. if it is a\n\n // primary or secondary payload of a RED packet. For example: with Opus, an\n\n // Fec packet (which the decoder prioritizes lower than a regular packet)\n\n // will not be used if there is _any_ RED payload for the same\n\n // timeframe. The highest priority packet will have levels {0, 0}. Negative\n\n // priorities are not allowed.\n\n bool operator<(const Priority& b) const {\n\n CheckInvariant();\n\n b.CheckInvariant();\n\n if (codec_level == b.codec_level)\n\n return red_level < b.red_level;\n\n\n\n return codec_level < b.codec_level;\n\n }\n\n bool operator==(const Priority& b) const {\n\n CheckInvariant();\n\n b.CheckInvariant();\n\n return codec_level == b.codec_level && red_level == b.red_level;\n\n }\n", "file_path": "modules/audio_coding/neteq/packet.h", "rank": 67, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// SDP specification for a single audio codec.\n\n// NOTE: This class is still under development and may change without notice.\n\nstruct SdpAudioFormat {\n\n using Parameters = std::map<std::string, std::string>;\n\n\n\n SdpAudioFormat(const SdpAudioFormat&);\n\n SdpAudioFormat(SdpAudioFormat&&);\n\n SdpAudioFormat(const char* name, int clockrate_hz, int num_channels);\n\n SdpAudioFormat(const std::string& name, int clockrate_hz, int num_channels);\n\n SdpAudioFormat(const char* name,\n\n int clockrate_hz,\n\n int num_channels,\n\n const Parameters& param);\n\n SdpAudioFormat(const std::string& name,\n\n int clockrate_hz,\n\n int num_channels,\n\n const Parameters& param);\n\n ~SdpAudioFormat();\n\n\n\n SdpAudioFormat& operator=(const SdpAudioFormat&);\n\n SdpAudioFormat& operator=(SdpAudioFormat&&);\n\n\n\n friend bool operator==(const SdpAudioFormat& a, const SdpAudioFormat& b);\n\n friend bool operator!=(const SdpAudioFormat& a, const SdpAudioFormat& b) {\n\n return !(a == b);\n\n }\n\n\n\n std::string name;\n\n int clockrate_hz;\n\n int num_channels;\n\n Parameters parameters;\n", "file_path": "api/audio_codecs/audio_format.h", "rank": 68, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\nenum Operations {\n\n kNormal = 0,\n\n kMerge,\n\n kExpand,\n\n kAccelerate,\n\n kFastAccelerate,\n\n kPreemptiveExpand,\n\n kRfc3389Cng,\n\n kRfc3389CngNoPacket,\n\n kCodecInternalCng,\n\n kDtmf,\n\n kAlternativePlc,\n\n kAlternativePlcIncreaseTimestamp,\n\n kAudioRepetition,\n\n kAudioRepetitionIncreaseTimestamp,\n\n kUndefined = -1\n\n};\n\n\n\nenum Modes {\n\n kModeNormal = 0,\n\n kModeExpand,\n\n kModeMerge,\n\n kModeAccelerateSuccess,\n\n kModeAccelerateLowEnergy,\n\n kModeAccelerateFail,\n\n kModePreemptiveExpandSuccess,\n\n kModePreemptiveExpandLowEnergy,\n\n kModePreemptiveExpandFail,\n\n kModeRfc3389Cng,\n\n kModeCodecInternalCng,\n\n kModeDtmf,\n\n kModeError,\n\n kModeUndefined = -1\n\n};\n\n\n", "file_path": "modules/audio_coding/neteq/defines.h", "rank": 69, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\nnamespace ts {\n\n\n\nstatic const float kPi = 3.14159265358979323846f;\n\nstatic const int kChunkSizeMs = 10;\n\nenum {\n\n kSampleRate8kHz = 8000,\n\n kSampleRate16kHz = 16000,\n\n kSampleRate32kHz = 32000,\n\n kSampleRate48kHz = 48000\n\n};\n\n\n\n} // namespace ts\n", "file_path": "modules/audio_processing/transient/common.h", "rank": 70, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n// Mapping from AVCaptureDeviceFormat to cricket::VideoFormat for given input\n\n// device.\n\nstd::set<cricket::VideoFormat> GetSupportedVideoFormatsForDevice(\n\n AVCaptureDevice* device);\n\n\n\n// Sets device format for the provided capture device. Returns YES/NO depending\n\n// on success.\n\nbool SetFormatForCaptureDevice(AVCaptureDevice* device,\n\n AVCaptureSession* session,\n\n const cricket::VideoFormat& format);\n", "file_path": "sdk/objc/Framework/Classes/avfoundationformatmapper.h", "rank": 71, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// Clears a DesktopFrame |frame| by setting its data() into 0.\n\nvoid ClearDesktopFrame(DesktopFrame* frame);\n\n\n\n// Compares size() and data() of two DesktopFrames |left| and |right|.\n\nbool DesktopFrameDataEquals(const DesktopFrame& left,\n\n const DesktopFrame& right);\n\n\n", "file_path": "modules/desktop_capture/test_utils.h", "rank": 72, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// Size (in pixels) of each square block used for diffing. This must be a\n\n// multiple of sizeof(uint64)/8.\n\nconst int kBlockSize = 32;\n\n\n\n// Format: BGRA 32 bit.\n\nconst int kBytesPerPixel = 4;\n\n\n\n// Low level function to compare 2 vectors of pixels of size kBlockSize. Returns\n\n// whether the blocks differ.\n\nbool VectorDifference(const uint8_t* image1, const uint8_t* image2);\n\n\n\n// Low level function to compare 2 blocks of pixels of size\n\n// (kBlockSize, |height|). Returns whether the blocks differ.\n\nbool BlockDifference(const uint8_t* image1,\n\n const uint8_t* image2,\n\n int height,\n\n int stride);\n\n\n\n// Low level function to compare 2 blocks of pixels of size\n\n// (kBlockSize, kBlockSize). Returns whether the blocks differ.\n\nbool BlockDifference(const uint8_t* image1,\n\n const uint8_t* image2,\n\n int stride);\n\n\n", "file_path": "modules/desktop_capture/differ_block.h", "rank": 73, "score": 131241.46652513774 }, { "content": "namespace webrtc {\n\n\n\n// Table for Protection factor (code rate) of delta frames, for the XOR FEC.\n\n// Input is the packet loss and an effective rate (bits/frame).\n\n// Output is array kFecRateTable[k], where k = rate_i*129 + loss_j;\n\n// loss_j = 0,1,..128, and rate_i varies over some range.\n\n// TODO(brandtr): Consider replacing this big static table with a closed-form\n\n// expression instead.\n\nstatic const int kFecRateTableSize = 6450;\n\nstatic const unsigned char kFecRateTable[kFecRateTableSize] = {\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,\n\n 11, 11, 11, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39,\n\n 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39,\n\n 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39,\n\n 39, 39, 39, 39, 39, 39, 51, 51, 51, 51, 51, 51, 51, 51, 51,\n\n 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51,\n\n 51, 51, 51, 51, 51, 51, 51, 51, 51, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,\n\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 30, 30, 30,\n\n 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 56, 56, 56,\n\n 56, 56, 56, 56, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n\n 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n\n 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n\n 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87,\n\n 87, 87, 87, 87, 87, 87, 87, 87, 87, 78, 78, 78, 78, 78, 78,\n\n 78, 78, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 6, 6, 6, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\n 23, 23, 23, 23, 23, 23, 44, 44, 44, 44, 44, 44, 50, 50, 50,\n\n 50, 50, 50, 50, 50, 50, 68, 68, 68, 68, 68, 68, 68, 85, 85,\n\n 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,\n\n 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,\n\n 85, 85, 85, 85, 85, 85, 85, 85, 85, 105, 105, 105, 105, 105, 105,\n\n 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,\n\n 105, 105, 105, 88, 88, 88, 88, 88, 88, 88, 88, 88, 0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 19, 19, 19,\n\n 36, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,\n\n 55, 55, 55, 55, 55, 55, 69, 69, 69, 69, 69, 69, 69, 69, 69,\n\n 75, 75, 80, 80, 80, 80, 80, 97, 97, 97, 97, 97, 97, 97, 97,\n\n 97, 97, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102,\n\n 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102,\n\n 102, 102, 102, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116,\n\n 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 100, 100, 100,\n\n 100, 100, 100, 100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 4,\n\n 16, 16, 16, 16, 16, 16, 30, 35, 35, 47, 58, 58, 58, 58, 58,\n\n 58, 58, 58, 58, 58, 58, 58, 58, 58, 63, 63, 63, 63, 63, 63,\n\n 77, 77, 77, 77, 77, 77, 77, 82, 82, 82, 82, 94, 94, 94, 94,\n\n 94, 105, 105, 105, 105, 110, 110, 110, 110, 110, 110, 122, 122, 122, 122,\n\n 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122,\n\n 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 115, 115, 115, 115, 115, 115, 115, 115, 115,\n\n 0, 0, 0, 0, 0, 0, 0, 4, 14, 27, 27, 27, 27, 27, 31,\n\n 41, 52, 52, 56, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,\n\n 69, 69, 69, 69, 69, 69, 69, 69, 69, 79, 79, 79, 79, 83, 83,\n\n 83, 94, 94, 94, 94, 106, 106, 106, 106, 106, 115, 115, 115, 115, 125,\n\n 125, 125, 125, 125, 125, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 0, 3, 3,\n\n 3, 17, 28, 38, 38, 38, 38, 38, 47, 51, 63, 63, 63, 72, 72,\n\n 72, 72, 72, 72, 72, 76, 76, 76, 76, 80, 80, 80, 80, 80, 80,\n\n 80, 80, 80, 84, 84, 84, 84, 93, 93, 93, 105, 105, 105, 105, 114,\n\n 114, 114, 114, 114, 124, 124, 124, 124, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 0, 0, 0, 12, 12, 12, 35, 43, 47, 47, 47,\n\n 47, 47, 58, 58, 66, 66, 66, 70, 70, 70, 70, 70, 73, 73, 82,\n\n 82, 82, 86, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,\n\n 94, 105, 105, 105, 114, 114, 114, 114, 117, 117, 117, 117, 117, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0,\n\n 0, 24, 24, 24, 49, 53, 53, 53, 53, 53, 53, 61, 61, 64, 64,\n\n 64, 64, 70, 70, 70, 70, 78, 78, 88, 88, 88, 96, 106, 106, 106,\n\n 106, 106, 106, 106, 106, 106, 106, 112, 112, 112, 120, 120, 120, 124, 124,\n\n 124, 124, 124, 124, 124, 124, 124, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 0, 0, 5, 36, 36, 36, 55, 55,\n\n 55, 55, 55, 55, 55, 58, 58, 58, 58, 58, 64, 78, 78, 78, 78,\n\n 87, 87, 94, 94, 94, 103, 110, 110, 110, 110, 110, 110, 110, 110, 116,\n\n 116, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 0, 0, 18, 43, 43, 43, 53, 53, 53, 53, 53, 53, 53, 53,\n\n 58, 58, 58, 58, 71, 87, 87, 87, 87, 94, 94, 97, 97, 97, 109,\n\n 111, 111, 111, 111, 111, 111, 111, 111, 125, 125, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 31, 46, 46,\n\n 46, 48, 48, 48, 48, 48, 48, 48, 48, 66, 66, 66, 66, 80, 93,\n\n 93, 93, 93, 95, 95, 95, 95, 100, 115, 115, 115, 115, 115, 115, 115,\n\n 115, 115, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 0, 4, 40, 45, 45, 45, 45, 45, 45, 45, 45,\n\n 49, 49, 49, 74, 74, 74, 74, 86, 90, 90, 90, 90, 95, 95, 95,\n\n 95, 106, 120, 120, 120, 120, 120, 120, 120, 120, 120, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 14,\n\n 42, 42, 42, 42, 42, 42, 42, 42, 46, 56, 56, 56, 80, 80, 80,\n\n 80, 84, 84, 84, 84, 88, 99, 99, 99, 99, 111, 122, 122, 122, 122,\n\n 122, 122, 122, 122, 122, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 0, 26, 40, 40, 40, 40, 40, 40,\n\n 40, 40, 54, 66, 66, 66, 80, 80, 80, 80, 80, 80, 80, 84, 94,\n\n 106, 106, 106, 106, 116, 120, 120, 120, 120, 120, 120, 120, 120, 124, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 3, 34, 38, 38, 38, 38, 38, 42, 42, 42, 63, 72, 72, 76,\n\n 80, 80, 80, 80, 80, 80, 80, 89, 101, 114, 114, 114, 114, 118, 118,\n\n 118, 118, 118, 118, 118, 118, 118, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 12, 36, 36, 36, 36,\n\n 36, 36, 49, 49, 49, 69, 73, 76, 86, 86, 86, 86, 86, 86, 86,\n\n 86, 97, 109, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122,\n\n 122, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 22, 34, 34, 34, 34, 38, 38, 57, 57, 57, 69,\n\n 73, 82, 92, 92, 92, 92, 92, 92, 96, 96, 104, 117, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 29, 33,\n\n 33, 33, 33, 44, 44, 62, 62, 62, 69, 77, 87, 95, 95, 95, 95,\n\n 95, 95, 107, 107, 110, 120, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 31, 31, 31, 31, 31, 51, 51, 62,\n\n 65, 65, 73, 83, 91, 94, 94, 94, 94, 97, 97, 114, 114, 114, 122,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 29, 29, 29, 29, 29, 56, 56, 59, 70, 70, 79, 86, 89, 89,\n\n 89, 89, 89, 100, 100, 116, 116, 116, 122, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 28, 28, 28, 28, 28,\n\n 57, 57, 57, 76, 76, 83, 86, 86, 86, 86, 86, 89, 104, 104, 114,\n\n 114, 114, 124, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 27, 27, 27, 27, 30, 55, 55, 55, 80, 80, 83,\n\n 86, 86, 86, 86, 86, 93, 108, 108, 111, 111, 111, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 26, 26,\n\n 26, 26, 36, 53, 53, 53, 80, 80, 80, 90, 90, 90, 90, 90, 98,\n\n 107, 107, 107, 107, 107, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 26, 26, 26, 28, 42, 52, 54, 54,\n\n 78, 78, 78, 95, 95, 95, 97, 97, 104, 106, 106, 106, 106, 106, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 24, 24, 24, 33, 47, 49, 58, 58, 74, 74, 74, 97, 97, 97,\n\n 106, 106, 108, 108, 108, 108, 108, 108, 124, 124, 124, 124, 124, 124, 124,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 24, 24, 24, 39, 48,\n\n 50, 63, 63, 72, 74, 74, 96, 96, 96, 109, 111, 111, 111, 111, 111,\n\n 111, 111, 119, 119, 122, 122, 122, 122, 122, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 23, 23, 23, 43, 46, 54, 66, 66, 69, 77, 77,\n\n 92, 92, 92, 105, 113, 113, 113, 113, 113, 113, 113, 115, 117, 123, 123,\n\n 123, 123, 123, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 22, 22,\n\n 22, 44, 44, 59, 67, 67, 67, 81, 81, 89, 89, 89, 97, 112, 112,\n\n 112, 112, 112, 112, 112, 112, 119, 126, 126, 126, 126, 126, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 21, 21, 24, 43, 45, 63, 65, 65,\n\n 67, 85, 85, 87, 87, 87, 91, 109, 109, 109, 111, 111, 111, 111, 111,\n\n 123, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 21, 21, 28, 42, 50, 63, 63, 66, 71, 85, 85, 85, 85, 87,\n\n 92, 106, 106, 108, 114, 114, 114, 114, 114, 125, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 20, 20, 34, 41, 54,\n\n 62, 62, 69, 75, 82, 82, 82, 82, 92, 98, 105, 105, 110, 117, 117,\n\n 117, 117, 117, 124, 124, 126, 126, 126, 126, 126, 126, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 20, 20, 38, 40, 58, 60, 60, 73, 78, 80, 80,\n\n 80, 80, 100, 105, 107, 107, 113, 118, 118, 118, 118, 118, 120, 120, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 19, 21,\n\n 38, 40, 58, 58, 60, 75, 77, 77, 77, 81, 81, 107, 109, 109, 109,\n\n 114, 116, 116, 116, 116, 116, 116, 116, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 18, 25, 37, 44, 56, 56, 63, 75,\n\n 75, 75, 75, 88, 88, 111, 111, 111, 111, 112, 112, 112, 112, 112, 112,\n\n 112, 114, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 18, 30, 36, 48, 55, 55, 67, 73, 73, 73, 73, 97, 97, 110,\n\n 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 116, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 18, 34, 36, 52, 55,\n\n 55, 70, 72, 73, 73, 73, 102, 104, 108, 108, 108, 108, 109, 109, 109,\n\n 109, 109, 109, 109, 119, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 17, 35, 35, 52, 59, 59, 70, 70, 76, 76, 76,\n\n 99, 105, 105, 105, 105, 105, 111, 111, 111, 111, 111, 111, 111, 121, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 17, 34,\n\n 36, 51, 61, 62, 70, 70, 80, 80, 80, 93, 103, 103, 103, 103, 103,\n\n 112, 112, 112, 112, 112, 116, 118, 124, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 16, 33, 39, 50, 59, 65, 72, 72,\n\n 82, 82, 82, 91, 100, 100, 100, 100, 100, 109, 109, 109, 109, 109, 121,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 16, 32, 43, 48, 54, 66, 75, 75, 81, 83, 83, 92, 97, 97,\n\n 97, 99, 99, 105, 105, 105, 105, 105, 123, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 15, 31, 46, 47, 49,\n\n 69, 77, 77, 81, 85, 85, 93, 95, 95, 95, 100, 100, 102, 102, 102,\n\n 102, 102, 120, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 15, 30, 46, 48, 48, 70, 75, 79, 82, 87, 87,\n\n 92, 94, 94, 94, 103, 103, 103, 103, 103, 104, 104, 115, 120, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 15, 30,\n\n 45, 50, 50, 68, 70, 80, 85, 89, 89, 90, 95, 95, 95, 104, 104,\n\n 104, 104, 104, 109, 109, 112, 114, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 14, 29, 44, 54, 54, 64, 64, 83,\n\n 87, 88, 88, 88, 98, 98, 98, 103, 103, 103, 103, 103, 113, 113, 113,\n\n 113, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 0, 14, 29, 43, 56, 56, 61, 61, 84, 85, 88, 88, 88, 100, 100,\n\n 100, 102, 102, 102, 102, 102, 113, 116, 116, 116, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 14, 28, 42, 57, 57,\n\n 62, 62, 80, 80, 91, 91, 91, 100, 100, 100, 100, 100, 100, 100, 100,\n\n 109, 119, 119, 119, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 0, 14, 28, 42, 56, 56, 65, 66, 76, 76, 92, 92,\n\n 92, 97, 97, 97, 101, 101, 101, 101, 101, 106, 121, 121, 121, 126, 126,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 13, 27,\n\n 41, 55, 55, 67, 72, 74, 74, 90, 90, 90, 91, 91, 91, 105, 105,\n\n 105, 105, 105, 107, 122, 122, 122, 123, 123, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 0, 13, 27, 40, 54, 54, 67, 76, 76,\n\n 76, 85, 85, 85, 85, 85, 85, 112, 112, 112, 112, 112, 112, 121, 121,\n\n 121, 121, 121, 126, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,\n\n};\n\n\n", "file_path": "modules/video_coding/fec_rate_table.h", "rank": 74, "score": 129884.07997135539 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\nstruct SimulatorBuffers {\n\n SimulatorBuffers(int render_input_sample_rate_hz,\n\n int capture_input_sample_rate_hz,\n\n int render_output_sample_rate_hz,\n\n int capture_output_sample_rate_hz,\n\n size_t num_render_input_channels,\n\n size_t num_capture_input_channels,\n\n size_t num_render_output_channels,\n\n size_t num_capture_output_channels);\n\n ~SimulatorBuffers();\n\n\n\n void CreateConfigAndBuffer(int sample_rate_hz,\n\n size_t num_channels,\n\n Random* rand_gen,\n\n std::unique_ptr<AudioBuffer>* buffer,\n\n StreamConfig* config,\n\n std::vector<float*>* buffer_data,\n\n std::vector<float>* buffer_data_samples);\n\n\n\n void UpdateInputBuffers();\n\n\n\n std::unique_ptr<AudioBuffer> render_input_buffer;\n\n std::unique_ptr<AudioBuffer> capture_input_buffer;\n\n std::unique_ptr<AudioBuffer> render_output_buffer;\n\n std::unique_ptr<AudioBuffer> capture_output_buffer;\n\n StreamConfig render_input_config;\n\n StreamConfig capture_input_config;\n\n StreamConfig render_output_config;\n\n StreamConfig capture_output_config;\n\n std::vector<float*> render_input;\n\n std::vector<float> render_input_samples;\n\n std::vector<float*> capture_input;\n\n std::vector<float> capture_input_samples;\n\n std::vector<float*> render_output;\n\n std::vector<float> render_output_samples;\n\n std::vector<float*> capture_output;\n\n std::vector<float> capture_output_samples;\n\n};\n\n\n\n} // namespace test\n", "file_path": "modules/audio_processing/test/simulator_buffers.h", "rank": 75, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n#define MODEL_MODE 0\n\n\n\ntypedef unsigned char uint8_t;\n\nbool MbHasSkinColor(const uint8_t* y_src,\n\n const uint8_t* u_src,\n\n const uint8_t* v_src,\n\n const int stride_y,\n\n const int stride_u,\n\n const int stride_v,\n\n const int mb_row,\n\n const int mb_col);\n\n\n", "file_path": "modules/video_processing/util/skin_detection.h", "rank": 76, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Type used to identify windows on the desktop. Values are platform-specific:\n\n// - On Windows: HWND cast to intptr_t.\n\n// - On Linux (with X11): X11 Window (unsigned long) type cast to intptr_t.\n\n// - On OSX: integer window number.\n\ntypedef intptr_t WindowId;\n\n\n\nconst WindowId kNullWindowId = 0;\n\n\n\n// Type used to identify screens on the desktop. Values are platform-specific:\n\n// - On Windows: integer display device index.\n\n// - On OSX: CGDirectDisplayID cast to intptr_t.\n\n// - On Linux (with X11): TBD.\n\ntypedef intptr_t ScreenId;\n\n\n\n// The screen id corresponds to all screen combined together.\n\nconst ScreenId kFullDesktopScreenId = -1;\n\n\n\nconst ScreenId kInvalidScreenId = -2;\n\n\n\n// An integer to attach to each DesktopFrame to differentiate the generator of\n\n// the frame.\n\nnamespace DesktopCapturerId {\n\n constexpr uint32_t CreateFourCC(char a, char b, char c, char d) {\n\n return ((static_cast<uint32_t>(a)) |\n\n (static_cast<uint32_t>(b) << 8) |\n\n (static_cast<uint32_t>(c) << 16) |\n\n (static_cast<uint32_t>(d) << 24));\n\n }\n\n\n\n constexpr uint32_t kUnknown = 0;\n\n constexpr uint32_t kScreenCapturerWinGdi = CreateFourCC('G', 'D', 'I', ' ');\n\n constexpr uint32_t kScreenCapturerWinDirectx =\n\n CreateFourCC('D', 'X', 'G', 'I');\n\n} // namespace DesktopCapturerId\n\n\n", "file_path": "modules/desktop_capture/desktop_capture_types.h", "rank": 77, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// The function calculates the cross-correlation between two sequences\n\n// |sequence_1| and |sequence_2|. |sequence_1| is taken as reference, with\n\n// |sequence_1_length| as its length. |sequence_2| slides for the calculation of\n\n// cross-correlation. The result will be saved in |cross_correlation|.\n\n// |cross_correlation_length| correlation points are calculated.\n\n// The corresponding lag starts from 0, and increases with a step of\n\n// |cross_correlation_step|. The result is without normalization. To avoid\n\n// overflow, the result will be right shifted. The amount of shifts will be\n\n// returned.\n\n//\n\n// Input:\n\n// - sequence_1 : First sequence (reference).\n\n// - sequence_2 : Second sequence (sliding during calculation).\n\n// - sequence_1_length : Length of |sequence_1|.\n\n// - cross_correlation_length : Number of cross-correlations to calculate.\n\n// - cross_correlation_step : Step in the lag for the cross-correlation.\n\n//\n\n// Output:\n\n// - cross_correlation : The cross-correlation in Q(-right_shifts)\n\n//\n\n// Return:\n\n// Number of right shifts in cross_correlation.\n\n\n\nint CrossCorrelationWithAutoShift(const int16_t* sequence_1,\n\n const int16_t* sequence_2,\n\n size_t sequence_1_length,\n\n size_t cross_correlation_length,\n\n int cross_correlation_step,\n\n int32_t* cross_correlation);\n\n\n", "file_path": "modules/audio_coding/neteq/cross_correlation.h", "rank": 78, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\nnamespace test {\n\n\n\n// Returns test vector to use for the render signal in an\n\n// APM bitexactness test.\n\nstd::string GetApmRenderTestVectorFileName(int sample_rate_hz);\n\n\n\n// Returns test vector to use for the capture signal in an\n\n// APM bitexactness test.\n\nstd::string GetApmCaptureTestVectorFileName(int sample_rate_hz);\n\n\n\n// Extract float samples from a pcm file.\n\nvoid ReadFloatSamplesFromStereoFile(size_t samples_per_channel,\n\n size_t num_channels,\n\n InputAudioFile* stereo_pcm_file,\n\n rtc::ArrayView<float> data);\n\n\n\n// Verifies a frame against a reference and returns the results as an\n\n// AssertionResult.\n\n::testing::AssertionResult VerifyDeinterleavedArray(\n\n size_t samples_per_channel,\n\n size_t num_channels,\n\n rtc::ArrayView<const float> reference,\n\n rtc::ArrayView<const float> output,\n\n float element_error_bound);\n\n\n\n// Verifies a vector against a reference and returns the results as an\n\n// AssertionResult.\n\n::testing::AssertionResult VerifyArray(rtc::ArrayView<const float> reference,\n\n rtc::ArrayView<const float> output,\n\n float element_error_bound);\n\n\n\n} // namespace test\n", "file_path": "modules/audio_processing/test/bitexactness_tools.h", "rank": 79, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Find vector difference of dimension 16.\n\nextern bool VectorDifference_SSE2_W16(const uint8_t* image1,\n\n const uint8_t* image2);\n\n\n\n// Find vector difference of dimension 32.\n\nextern bool VectorDifference_SSE2_W32(const uint8_t* image1,\n\n const uint8_t* image2);\n\n\n", "file_path": "modules/desktop_capture/differ_vector_sse2.h", "rank": 80, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Allocates new memory in the unique_ptr to fit the raw message and returns the\n\n// number of bytes read.\n\nsize_t ReadMessageBytesFromFile(FILE* file, std::unique_ptr<uint8_t[]>* bytes);\n\n\n\n// Returns true on success, false on error or end-of-file.\n\nbool ReadMessageFromFile(FILE* file, ::google::protobuf::MessageLite* msg);\n\n\n", "file_path": "modules/audio_processing/test/protobuf_utils.h", "rank": 81, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// This is a copy of the cast included in the Chromium codebase here:\n\n// http://cs.chromium.org/src/third_party/cld/base/casts.h\n\ntemplate <class Dest, class Source>\n\ninline Dest bit_cast(const Source& source) {\n\n // A compile error here means your Dest and Source have different sizes.\n\n static_assert(sizeof(Dest) == sizeof(Source),\n\n \"Dest and Source have different sizes\");\n\n\n\n Dest dest;\n\n memcpy(&dest, &source, sizeof(dest));\n\n return dest;\n\n}\n\n\n\n// Converts the byte array with binary float representation to float.\n\n// Bytes must be in little-endian order.\n\n// Returns 0 if correct, -1 on error.\n\nint ConvertByteArrayToFloat(const uint8_t bytes[4], float* out);\n\n\n\n// Converts the byte array with binary double representation to double.\n\n// Bytes must be in little-endian order.\n\n// Returns 0 if correct, -1 on error.\n\nint ConvertByteArrayToDouble(const uint8_t bytes[8], double* out);\n\n\n\n// Converts a float to a byte array with binary float representation.\n\n// Bytes will be in little-endian order.\n\n// Returns 0 if correct, -1 on error.\n\nint ConvertFloatToByteArray(float value, uint8_t out_bytes[4]);\n\n\n\n// Converts a double to a byte array with binary double representation.\n\n// Bytes will be in little-endian order.\n\n// Returns 0 if correct, -1 on error.\n\nint ConvertDoubleToByteArray(double value, uint8_t out_bytes[8]);\n\n\n\n// Reads |length| 16-bit integers from |file| to |buffer|.\n\n// |file| must be previously opened.\n\n// Returns the number of 16-bit integers read or -1 on error.\n\nsize_t ReadInt16BufferFromFile(FileWrapper* file,\n\n size_t length,\n\n int16_t* buffer);\n\n\n\n// Reads |length| 16-bit integers from |file| and stores those values\n\n// (converting them) in |buffer|.\n\n// |file| must be previously opened.\n\n// Returns the number of 16-bit integers read or -1 on error.\n\nsize_t ReadInt16FromFileToFloatBuffer(FileWrapper* file,\n\n size_t length,\n\n float* buffer);\n\n\n\n// Reads |length| 16-bit integers from |file| and stores those values\n\n// (converting them) in |buffer|.\n\n// |file| must be previously opened.\n\n// Returns the number of 16-bit integers read or -1 on error.\n\nsize_t ReadInt16FromFileToDoubleBuffer(FileWrapper* file,\n\n size_t length,\n\n double* buffer);\n\n\n\n// Reads |length| floats in binary representation (4 bytes) from |file| to\n\n// |buffer|.\n\n// |file| must be previously opened.\n\n// Returns the number of floats read or -1 on error.\n\nsize_t ReadFloatBufferFromFile(FileWrapper* file, size_t length, float* buffer);\n\n\n\n// Reads |length| doubles in binary representation (8 bytes) from |file| to\n\n// |buffer|.\n\n// |file| must be previously opened.\n\n// Returns the number of doubles read or -1 on error.\n\nsize_t ReadDoubleBufferFromFile(FileWrapper* file,\n\n size_t length,\n\n double* buffer);\n\n\n\n// Writes |length| 16-bit integers from |buffer| in binary representation (2\n\n// bytes) to |file|. It flushes |file|, so after this call there are no\n\n// writings pending.\n\n// |file| must be previously opened.\n\n// Returns the number of doubles written or -1 on error.\n\nsize_t WriteInt16BufferToFile(FileWrapper* file,\n\n size_t length,\n\n const int16_t* buffer);\n\n\n\n// Writes |length| floats from |buffer| in binary representation (4 bytes) to\n\n// |file|. It flushes |file|, so after this call there are no writtings pending.\n\n// |file| must be previously opened.\n\n// Returns the number of doubles written or -1 on error.\n\nsize_t WriteFloatBufferToFile(FileWrapper* file,\n\n size_t length,\n\n const float* buffer);\n\n\n\n// Writes |length| doubles from |buffer| in binary representation (8 bytes) to\n\n// |file|. It flushes |file|, so after this call there are no writings pending.\n\n// |file| must be previously opened.\n\n// Returns the number of doubles written or -1 on error.\n\nsize_t WriteDoubleBufferToFile(FileWrapper* file,\n\n size_t length,\n\n const double* buffer);\n\n\n", "file_path": "modules/audio_processing/transient/file_utils.h", "rank": 82, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Struct that holds imaginary data produced from 128 point real-valued FFTs.\n\nstruct FftData {\n\n // Copies the data in src.\n\n void Assign(const FftData& src) {\n\n std::copy(src.re.begin(), src.re.end(), re.begin());\n\n std::copy(src.im.begin(), src.im.end(), im.begin());\n\n im[0] = im[kFftLengthBy2] = 0;\n\n }\n\n\n\n // Clears all the imaginary.\n\n void Clear() {\n\n re.fill(0.f);\n\n im.fill(0.f);\n\n }\n\n\n\n // Computes the power spectrum of the data.\n\n void Spectrum(Aec3Optimization optimization,\n\n std::array<float, kFftLengthBy2Plus1>* power_spectrum) const {\n\n RTC_DCHECK(power_spectrum);\n\n switch (optimization) {\n\n#if defined(WEBRTC_ARCH_X86_FAMILY)\n\n case Aec3Optimization::kSse2: {\n\n constexpr int kNumFourBinBands = kFftLengthBy2 / 4;\n\n constexpr int kLimit = kNumFourBinBands * 4;\n\n for (size_t k = 0; k < kLimit; k += 4) {\n\n const __m128 r = _mm_loadu_ps(&re[k]);\n\n const __m128 i = _mm_loadu_ps(&im[k]);\n\n const __m128 ii = _mm_mul_ps(i, i);\n\n const __m128 rr = _mm_mul_ps(r, r);\n\n const __m128 rrii = _mm_add_ps(rr, ii);\n\n _mm_storeu_ps(&(*power_spectrum)[k], rrii);\n\n }\n\n (*power_spectrum)[kFftLengthBy2] =\n\n re[kFftLengthBy2] * re[kFftLengthBy2] +\n\n im[kFftLengthBy2] * im[kFftLengthBy2];\n\n } break;\n\n#endif\n\n default:\n\n std::transform(re.begin(), re.end(), im.begin(),\n\n power_spectrum->begin(),\n\n [](float a, float b) { return a * a + b * b; });\n\n }\n", "file_path": "modules/audio_processing/aec3/fft_data.h", "rank": 83, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Table for adjusting FEC rate for NACK/FEC protection method\n\n// Table values are built as a sigmoid function, ranging from 0 to 100, based on\n\n// the HybridNackTH values defined in media_opt_util.h.\n\nconst uint16_t VCMNackFecTable[100] = {\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,\n\n 1, 2, 2, 2, 3, 3, 4, 5, 6, 7, 9, 10, 12, 15, 18,\n\n 21, 24, 28, 32, 37, 41, 46, 51, 56, 61, 66, 70, 74, 78, 81,\n\n 84, 86, 89, 90, 92, 93, 95, 95, 96, 97, 97, 98, 98, 99, 99,\n\n 99, 99, 99, 99, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n\n 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,\n\n};\n\n\n", "file_path": "modules/video_coding/nack_fec_tables.h", "rank": 84, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Coordinates in meters. The convention used is:\n\n// x: the horizontal dimension, with positive to the right from the camera's\n\n// perspective.\n\n// y: the depth dimension, with positive forward from the camera's\n\n// perspective.\n\n// z: the vertical dimension, with positive upwards.\n\ntemplate<typename T>\n\nstruct CartesianPoint {\n\n CartesianPoint() {\n\n c[0] = 0;\n\n c[1] = 0;\n\n c[2] = 0;\n\n }\n\n CartesianPoint(T x, T y, T z) {\n\n c[0] = x;\n\n c[1] = y;\n\n c[2] = z;\n\n }\n\n T x() const { return c[0]; }\n\n T y() const { return c[1]; }\n\n T z() const { return c[2]; }\n\n T c[3];\n", "file_path": "modules/audio_processing/beamformer/array_util.h", "rank": 85, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Converts NTP timestamp to RTP timestamp.\n\ninline uint32_t NtpToRtp(NtpTime ntp, uint32_t freq) {\n\n uint32_t tmp = (static_cast<uint64_t>(ntp.fractions()) * freq) >> 32;\n\n return ntp.seconds() * freq + tmp;\n\n}\n\n\n\n// Helper function for compact ntp representation:\n\n// RFC 3550, Section 4. Time Format.\n\n// Wallclock time is represented using the timestamp format of\n\n// the Network Time Protocol (NTP).\n\n// ...\n\n// In some fields where a more compact representation is\n\n// appropriate, only the middle 32 bits are used; that is, the low 16\n\n// bits of the integer part and the high 16 bits of the fractional part.\n\ninline uint32_t CompactNtp(NtpTime ntp) {\n\n return (ntp.seconds() << 16) | (ntp.fractions() >> 16);\n\n}\n\n// Converts interval between compact ntp timestamps to milliseconds.\n\n// This interval can be up to ~9.1 hours (2^15 seconds).\n\n// Values close to 2^16 seconds consider negative and result in minimum rtt = 1.\n\nint64_t CompactNtpRttToMs(uint32_t compact_ntp_interval);\n\n\n", "file_path": "modules/rtp_rtcp/source/time_util.h", "rank": 86, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Returns nullptr frame if |rect| is not contained by the bounds of |frame|.\n\nstd::unique_ptr<DesktopFrame> CreateCroppedDesktopFrame(\n\n std::unique_ptr<DesktopFrame> frame,\n\n const DesktopRect& rect);\n\n\n", "file_path": "modules/desktop_capture/cropped_desktop_frame.h", "rank": 87, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\nconst int kDefaultSampleRate = 44100;\n\n// Delay estimates for the two different supported modes. These values are based\n\n// on real-time round-trip delay estimates on a large set of devices and they\n\n// are lower bounds since the filter length is 128 ms, so the AEC works for\n\n// delays in the range [50, ~170] ms and [150, ~270] ms. Note that, in most\n\n// cases, the lowest delay estimate will not be utilized since devices that\n\n// support low-latency output audio often supports HW AEC as well.\n\nconst int kLowLatencyModeDelayEstimateInMilliseconds = 50;\n\nconst int kHighLatencyModeDelayEstimateInMilliseconds = 150;\n\n\n", "file_path": "modules/audio_device/android/audio_common.h", "rank": 88, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Test if the sequence number |a| is ahead or at sequence number |b|.\n\n//\n\n// If |M| is an even number and the two sequence numbers are at max distance\n\n// from each other, then the sequence number with the highest value is\n\n// considered to be ahead.\n\ntemplate <typename T, T M>\n\ninline bool AheadOrAt(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n const T maxDist = M / 2;\n\n if (!(M & 1) && MinDiff<T, M>(a, b) == maxDist)\n\n return b < a;\n\n return ForwardDiff<T, M>(b, a) <= maxDist;\n\n}\n\n\n\ntemplate <typename T>\n\ninline bool AheadOrAt(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n const T maxDist = std::numeric_limits<T>::max() / 2 + T(1);\n\n if (a - b == maxDist)\n\n return b < a;\n\n return ForwardDiff(b, a) < maxDist;\n\n}\n\n\n\n// Test if the sequence number |a| is ahead of sequence number |b|.\n\n//\n\n// If |M| is an even number and the two sequence numbers are at max distance\n\n// from each other, then the sequence number with the highest value is\n\n// considered to be ahead.\n\ntemplate <typename T, T M>\n\ninline bool AheadOf(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n return a != b && AheadOrAt<T, M>(a, b);\n\n}\n\n\n\ntemplate <typename T>\n\ninline bool AheadOf(T a, T b) {\n\n static_assert(std::is_unsigned<T>::value,\n\n \"Type must be an unsigned integer.\");\n\n return a != b && AheadOrAt(a, b);\n\n}\n\n\n\nnamespace internal {\n\n\n\ntemplate <typename T, typename M>\n\nstruct SeqNumComp;\n\n\n\ntemplate <typename T, T M>\n\nstruct SeqNumComp<T, std::integral_constant<T, M>> {\n\n bool operator()(T a, T b) const { return AheadOf<T, M>(a, b); }\n", "file_path": "modules/video_coding/sequence_number_util.h", "rank": 89, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Updates the audioFrame's energy (based on its samples).\n\nuint32_t AudioMixerCalculateEnergy(const AudioFrame& audio_frame);\n\n\n\n// Ramps up or down the provided audio frame. Ramp(0, 1, frame) will\n\n// linearly increase the samples in the frame from 0 to full volume.\n\nvoid Ramp(float start_gain, float target_gain, AudioFrame* audio_frame);\n\n\n\n// Downmixes or upmixes a frame between stereo and mono.\n\nvoid RemixFrame(size_t target_number_of_channels, AudioFrame* frame);\n\n\n", "file_path": "modules/audio_mixer/audio_frame_manipulator.h", "rank": 90, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\nenum { kResamplingDelay = 1 };\n\nenum { kResamplerBufferSize = FRAME_LEN * 4 };\n\n\n\n// Unless otherwise specified, functions return 0 on success and -1 on error.\n\nvoid* WebRtcAec_CreateResampler(); // Returns NULL on error.\n\nint WebRtcAec_InitResampler(void* resampInst, int deviceSampleRateHz);\n\nvoid WebRtcAec_FreeResampler(void* resampInst);\n\n\n\n// Estimates skew from raw measurement.\n\nint WebRtcAec_GetSkew(void* resampInst, int rawSkew, float* skewEst);\n\n\n\n// Resamples input using linear interpolation.\n\nvoid WebRtcAec_ResampleLinear(void* resampInst,\n\n const float* inspeech,\n\n size_t size,\n\n float skew,\n\n float* outspeech,\n\n size_t* size_out);\n\n\n", "file_path": "modules/audio_processing/aec/aec_resampler.h", "rank": 91, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\nnamespace H264 {\n\n\n\n// Map containting SDP codec parameters.\n\ntypedef std::map<std::string, std::string> CodecParameterMap;\n\n\n\n// All values are equal to ten times the level number, except level 1b which is\n\n// special.\n\nenum Level {\n\n kLevel1_b = 0,\n\n kLevel1 = 10,\n\n kLevel1_1 = 11,\n\n kLevel1_2 = 12,\n\n kLevel1_3 = 13,\n\n kLevel2 = 20,\n\n kLevel2_1 = 21,\n\n kLevel2_2 = 22,\n\n kLevel3 = 30,\n\n kLevel3_1 = 31,\n\n kLevel3_2 = 32,\n\n kLevel4 = 40,\n\n kLevel4_1 = 41,\n\n kLevel4_2 = 42,\n\n kLevel5 = 50,\n\n kLevel5_1 = 51,\n\n kLevel5_2 = 52\n\n};\n\n\n\nstruct ProfileLevelId {\n\n ProfileLevelId(Profile profile, Level level)\n\n : profile(profile), level(level) {}\n\n Profile profile;\n\n Level level;\n\n};\n\n\n\n// Parse profile level id that is represented as a string of 3 hex bytes.\n\n// Nothing will be returned if the string is not a recognized H264\n\n// profile level id.\n\nrtc::Optional<ProfileLevelId> ParseProfileLevelId(const char* str);\n\n\n\n// Parse profile level id that is represented as a string of 3 hex bytes\n\n// contained in an SDP key-value map. A default profile level id will be\n\n// returned if the profile-level-id key is missing. Nothing will be returned if\n\n// the key is present but the string is invalid.\n\nrtc::Optional<ProfileLevelId> ParseSdpProfileLevelId(\n\n const CodecParameterMap& params);\n\n\n\n// Given that a decoder supports up to a given frame size (in pixels) at up to a\n\n// given number of frames per second, return the highest H.264 level where it\n\n// can guarantee that it will be able to support all valid encoded streams that\n\n// are within that level.\n\nrtc::Optional<Level> SupportedLevel(int max_frame_pixel_count, float max_fps);\n\n\n\n// Returns canonical string representation as three hex bytes of the profile\n\n// level id, or returns nothing for invalid profile level ids.\n\nrtc::Optional<std::string> ProfileLevelIdToString(\n\n const ProfileLevelId& profile_level_id);\n\n\n\n// Generate codec parameters that will be used as answer in an SDP negotiation\n\n// based on local supported parameters and remote offered parameters. Both\n\n// |local_supported_params|, |remote_offered_params|, and |answer_params|\n\n// represent sendrecv media descriptions, i.e they are a mix of both encode and\n\n// decode capabilities. In theory, when the profile in |local_supported_params|\n\n// represent a strict superset of the profile in |remote_offered_params|, we\n\n// could limit the profile in |answer_params| to the profile in\n\n// |remote_offered_params|. However, to simplify the code, each supported H264\n\n// profile should be listed explicitly in the list of local supported codecs,\n\n// even if they are redundant. Then each local codec in the list should be\n\n// tested one at a time against the remote codec, and only when the profiles are\n\n// equal should this function be called. Therefore, this function does not need\n\n// to handle profile intersection, and the profile of |local_supported_params|\n\n// and |remote_offered_params| must be equal before calling this function. The\n\n// parameters that are used when negotiating are the level part of\n\n// profile-level-id and level-asymmetry-allowed.\n\nvoid GenerateProfileLevelIdForAnswer(\n\n const CodecParameterMap& local_supported_params,\n\n const CodecParameterMap& remote_offered_params,\n\n CodecParameterMap* answer_params);\n\n\n\n} // namespace H264\n", "file_path": "common_video/h264/profile_level_id.h", "rank": 92, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\nnamespace audiodevicemodule {\n\n\n\nvoid EnsureInitialized();\n\n\n\n} // namespace audiodevicemodule\n", "file_path": "modules/audio_device/android/ensure_initialized.h", "rank": 93, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Describes the configuration of a specific display.\n\nstruct MacDisplayConfiguration {\n\n MacDisplayConfiguration();\n\n MacDisplayConfiguration(const MacDisplayConfiguration& other);\n\n MacDisplayConfiguration(MacDisplayConfiguration&& other);\n\n ~MacDisplayConfiguration();\n\n\n\n MacDisplayConfiguration& operator=(const MacDisplayConfiguration& other);\n\n MacDisplayConfiguration& operator=(MacDisplayConfiguration&& other);\n\n\n\n // Cocoa identifier for this display.\n\n CGDirectDisplayID id = 0;\n\n\n\n // Bounds of this display in Density-Independent Pixels (DIPs).\n\n DesktopRect bounds;\n\n\n\n // Bounds of this display in physical pixels.\n\n DesktopRect pixel_bounds;\n\n\n\n // Scale factor from DIPs to physical pixels.\n\n float dip_to_pixel_scale = 1.0f;\n\n};\n\n\n\ntypedef std::vector<MacDisplayConfiguration> MacDisplayConfigurations;\n\n\n\n// Describes the configuration of the whole desktop.\n\nstruct MacDesktopConfiguration {\n\n // Used to request bottom-up or top-down coordinates.\n\n enum Origin { BottomLeftOrigin, TopLeftOrigin };\n\n\n\n MacDesktopConfiguration();\n\n MacDesktopConfiguration(const MacDesktopConfiguration& other);\n\n MacDesktopConfiguration(MacDesktopConfiguration&& other);\n\n ~MacDesktopConfiguration();\n\n\n\n MacDesktopConfiguration& operator=(const MacDesktopConfiguration& other);\n\n MacDesktopConfiguration& operator=(MacDesktopConfiguration&& other);\n\n\n\n // Returns the desktop & display configurations in Cocoa-style \"bottom-up\"\n\n // (the origin is the bottom-left of the primary monitor, and coordinates\n\n // increase as you move up the screen).\n\n static MacDesktopConfiguration GetCurrent(Origin origin);\n\n\n\n // Returns true if the given desktop configuration equals this one.\n\n bool Equals(const MacDesktopConfiguration& other);\n\n\n\n // Returns the pointer to the display configuration with the specified id.\n\n const MacDisplayConfiguration* FindDisplayConfigurationById(\n\n CGDirectDisplayID id);\n\n\n\n // Bounds of the desktop excluding monitors with DPI settings different from\n\n // the main monitor. In Density-Independent Pixels (DIPs).\n\n DesktopRect bounds;\n\n\n\n // Same as bounds, but expressed in physical pixels.\n\n DesktopRect pixel_bounds;\n\n\n\n // Scale factor from DIPs to physical pixels.\n\n float dip_to_pixel_scale = 1.0f;\n\n\n\n // Configurations of the displays making up the desktop area.\n\n MacDisplayConfigurations displays;\n\n};\n\n\n", "file_path": "modules/desktop_capture/mac/desktop_configuration.h", "rank": 94, "score": 129876.31855551223 }, { "content": "namespace webrtc {\n\n\n\n// Stores the values being returned from the echo subtractor.\n\nstruct SubtractorOutput {\n\n std::array<float, kBlockSize> e_main;\n\n std::array<float, kBlockSize> e_shadow;\n\n FftData E_main;\n\n FftData E_shadow;\n\n std::array<float, kFftLengthBy2Plus1> E2_main;\n\n std::array<float, kFftLengthBy2Plus1> E2_shadow;\n\n\n\n void Reset() {\n\n e_main.fill(0.f);\n\n e_shadow.fill(0.f);\n\n E_main.re.fill(0.f);\n\n E_main.im.fill(0.f);\n\n E_shadow.re.fill(0.f);\n\n E_shadow.im.fill(0.f);\n\n E2_main.fill(0.f);\n\n E2_shadow.fill(0.f);\n\n }\n\n};\n\n\n", "file_path": "modules/audio_processing/aec3/subtractor_output.h", "rank": 95, "score": 129876.31855551223 }, { "content": "#include \"webrtc/modules/audio_mixer/audio_mixer_impl.h\"\n\n#include \"webrtc/modules/audio_processing/include/audio_processing.h\"\n\n#include \"webrtc/system_wrappers/include/field_trial.h\"\n\n#include \"webrtc/system_wrappers/include/metrics.h\"\n\n#include \"webrtc/system_wrappers/include/trace.h\"\n\n#include \"webrtc/voice_engine/transmit_mixer.h\"\n\n\n\nnamespace cricket {\n\nnamespace {\n\n\n\nconstexpr size_t kMaxUnsignaledRecvStreams = 1;\n\n\n\nconst int kDefaultTraceFilter = webrtc::kTraceNone | webrtc::kTraceTerseInfo |\n\n webrtc::kTraceWarning | webrtc::kTraceError |\n\n webrtc::kTraceCritical;\n\nconst int kElevatedTraceFilter = kDefaultTraceFilter | webrtc::kTraceStateInfo |\n\n webrtc::kTraceInfo;\n\n\n\nconstexpr int kNackRtpHistoryMs = 5000;\n\n\n", "file_path": "media/engine/webrtcvoiceengine.cc", "rank": 96, "score": 35.004812378391144 }, { "content": "/*\n\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n\n *\n\n * Use of this source code is governed by a BSD-style license\n\n * that can be found in the LICENSE file in the root of the source\n\n * tree. An additional intellectual property rights grant can be found\n\n * in the file PATENTS. All contributing project authors may\n\n * be found in the AUTHORS file in the root of the source tree.\n\n */\n\n\n\n#include <memory>\n\n\n\n#include \"webrtc/audio/audio_state.h\"\n\n#include \"webrtc/modules/audio_mixer/audio_mixer_impl.h\"\n\n#include \"webrtc/test/gtest.h\"\n\n#include \"webrtc/test/mock_voice_engine.h\"\n\n\n\nnamespace webrtc {\n\nnamespace test {\n\nnamespace {\n\n\n\nconst int kSampleRate = 8000;\n\nconst int kNumberOfChannels = 1;\n\nconst int kBytesPerSample = 2;\n\n\n", "file_path": "audio/audio_state_unittest.cc", "rank": 97, "score": 34.58045069116149 }, { "content": "/*\n\n * Copyright 2016 The WebRTC Project Authors. All rights reserved.\n\n *\n\n * Use of this source code is governed by a BSD-style license\n\n * that can be found in the LICENSE file in the root of the source\n\n * tree. An additional intellectual property rights grant can be found\n\n * in the file PATENTS. All contributing project authors may\n\n * be found in the AUTHORS file in the root of the source tree.\n\n */\n\n\n\n#include \"webrtc/pc/trackmediainfomap.h\"\n\n\n\n#include <utility>\n\n\n\nnamespace webrtc {\n\n\n\nnamespace {\n\n\n\ntemplate <typename K, typename V>\n\nV FindValueOrNull(const std::map<K, V>& map, const K& key) {\n", "file_path": "pc/trackmediainfomap.cc", "rank": 98, "score": 34.43973650140756 }, { "content": "#include \"webrtc/modules/desktop_capture/mouse_cursor.h\"\n\n#include \"webrtc/modules/desktop_capture/x11/x_error_trap.h\"\n\n#include \"webrtc/system_wrappers/include/logging.h\"\n\n\n\nnamespace {\n\n\n\n// WindowCapturer returns window IDs of X11 windows with WM_STATE attribute.\n\n// These windows may not be immediate children of the root window, because\n\n// window managers may re-parent them to add decorations. However,\n\n// XQueryPointer() expects to be passed children of the root. This function\n\n// searches up the list of the windows to find the root child that corresponds\n\n// to |window|.\n\nWindow GetTopLevelWindow(Display* display, Window window) {\n\n while (true) {\n\n // If the window is in WithdrawnState then look at all of its children.\n\n ::Window root, parent;\n\n ::Window *children;\n\n unsigned int num_children;\n\n if (!XQueryTree(display, window, &root, &parent, &children,\n\n &num_children)) {\n", "file_path": "modules/desktop_capture/mouse_cursor_monitor_x11.cc", "rank": 99, "score": 33.98881990285615 } ]
C++
tests/src/memory_operations/interleavelo.cpp
mkeryell/MIPP
f562541b824d7d5a5cdbdecdf2bf357bc7b47f9e
#include <exception> #include <algorithm> #include <numeric> #include <random> #include <cmath> #include <mipp.h> #include <catch.hpp> template <typename T> void test_reg_interleavelo() { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::reg r1 = mipp::load<T>(inputs1); mipp::reg r2 = mipp::load<T>(inputs2); mipp::reg ri = mipp::interleavelo<T>(r1, r2); for (auto i = 0; i < mipp::N<T>(); i++) if (i % 2) REQUIRE(inputs2[i/2] == *((T*)&ri +i)); else REQUIRE(inputs1[i/2] == *((T*)&ri +i)); } #ifndef MIPP_NO #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave low - mipp::reg", "[mipp::interleavelo]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_reg_interleavelo<double>(); } #endif SECTION("datatype = float") { test_reg_interleavelo<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_reg_interleavelo<int64_t>(); } #endif SECTION("datatype = int32_t") { test_reg_interleavelo<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_reg_interleavelo<int16_t>(); } SECTION("datatype = int8_t") { test_reg_interleavelo<int8_t>(); } #endif } #endif #endif template <typename T> void test_Reg_interleavelo() { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::Reg<T> r1 = inputs1; mipp::Reg<T> r2 = inputs2; mipp::Reg<T> ri = mipp::interleavelo(r1, r2); for (auto i = 0; i < mipp::N<T>(); i++) if (i % 2) REQUIRE(ri[i] == inputs2[i/2]); else REQUIRE(ri[i] == inputs1[i/2]); } #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave low - mipp::Reg", "[mipp::interleavelo]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_Reg_interleavelo<double>(); } #endif SECTION("datatype = float") { test_Reg_interleavelo<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_Reg_interleavelo<int64_t>(); } #endif SECTION("datatype = int32_t") { test_Reg_interleavelo<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_Reg_interleavelo<int16_t>(); } SECTION("datatype = int8_t") { test_Reg_interleavelo<int8_t>(); } #endif } #endif template <typename T> void test_reg_interleavelo2() { if (mipp::N<T>() > 2) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::reg r1 = mipp::load<T>(inputs1); mipp::reg r2 = mipp::load<T>(inputs2); mipp::reg ri = mipp::interleavelo2<T>(r1, r2); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(*((T*)&ri +i) == inputs2[i/2]); else REQUIRE(*((T*)&ri +i) == inputs1[i/2]); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(*((T*)&ri + mipp::N<T>()/2 +i) == inputs2[mipp::N<T>()/2 + i/2]); else REQUIRE(*((T*)&ri + mipp::N<T>()/2 +i) == inputs1[mipp::N<T>()/2 + i/2]); } } #ifndef MIPP_NO #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave2 low - mipp::reg", "[mipp::interleavelo2]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_reg_interleavelo2<double>(); } #endif SECTION("datatype = float") { test_reg_interleavelo2<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_reg_interleavelo2<int64_t>(); } #endif SECTION("datatype = int32_t") { test_reg_interleavelo2<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_reg_interleavelo2<int16_t>(); } SECTION("datatype = int8_t") { test_reg_interleavelo2<int8_t>(); } #endif } #endif #endif template <typename T> void test_Reg_interleavelo2() { if (mipp::N<T>() > 2) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::Reg<T> r1 = inputs1; mipp::Reg<T> r2 = inputs2; mipp::Reg<T> ri = mipp::interleavelo2(r1, r2); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(*((T*)&ri +i) == inputs2[i/2]); else REQUIRE(*((T*)&ri +i) == inputs1[i/2]); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(ri[mipp::N<T>()/2 +i] == inputs2[mipp::N<T>()/2 + i/2]); else REQUIRE(ri[mipp::N<T>()/2 +i] == inputs1[mipp::N<T>()/2 + i/2]); } } #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave2 low - mipp::Reg", "[mipp::interleavelo2]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_Reg_interleavelo2<double>(); } #endif SECTION("datatype = float") { test_Reg_interleavelo2<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_Reg_interleavelo2<int64_t>(); } #endif SECTION("datatype = int32_t") { test_Reg_interleavelo2<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_Reg_interleavelo2<int16_t>(); } SECTION("datatype = int8_t") { test_Reg_interleavelo2<int8_t>(); } #endif } #endif template <typename T> void test_reg_interleavelo4() { if (mipp::N<T>() > 4) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::reg r1 = mipp::load<T>(inputs1); mipp::reg r2 = mipp::load<T>(inputs2); mipp::reg ri = mipp::interleavelo4<T>(r1, r2); for (auto j = 0; j < 4; j++) for (auto i = 0; i < mipp::N<T>()/4; i++) if (i % 2) REQUIRE(*((T*)&ri + j*mipp::N<T>()/4 +i) == inputs2[j*mipp::N<T>()/4 + i/2]); else REQUIRE(*((T*)&ri + j*mipp::N<T>()/4 +i) == inputs1[j*mipp::N<T>()/4 + i/2]); } } #ifndef MIPP_NO #if defined(MIPP_AVX512) TEST_CASE("Interleave4 low - mipp::reg", "[mipp::interleavelo4]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_reg_interleavelo4<double>(); } #endif SECTION("datatype = float") { test_reg_interleavelo4<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_reg_interleavelo4<int64_t>(); } #endif SECTION("datatype = int32_t") { test_reg_interleavelo4<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_reg_interleavelo4<int16_t>(); } SECTION("datatype = int8_t") { test_reg_interleavelo4<int8_t>(); } #endif } #endif #endif template <typename T> void test_Reg_interleavelo4() { if (mipp::N<T>() > 4) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::Reg<T> r1 = inputs1; mipp::Reg<T> r2 = inputs2; mipp::Reg<T> ri = mipp::interleavelo4(r1, r2); for (auto j = 0; j < 4; j++) for (auto i = 0; i < mipp::N<T>()/4; i++) if (i % 2) REQUIRE(ri[j*mipp::N<T>()/4 +i] == inputs2[j*mipp::N<T>()/4 + i/2]); else REQUIRE(ri[j*mipp::N<T>()/4 +i] == inputs1[j*mipp::N<T>()/4 + i/2]); } } #if defined(MIPP_AVX512) TEST_CASE("Interleave4 low - mipp::Reg", "[mipp::interleavelo4]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_Reg_interleavelo4<double>(); } #endif SECTION("datatype = float") { test_Reg_interleavelo4<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_Reg_interleavelo4<int64_t>(); } #endif SECTION("datatype = int32_t") { test_Reg_interleavelo4<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_Reg_interleavelo4<int16_t>(); } SECTION("datatype = int8_t") { test_Reg_interleavelo4<int8_t>(); } #endif } #endif
#include <exception> #include <algorithm> #include <numeric> #include <random> #include <cmath> #include <mipp.h> #include <catch.hpp> template <typename T> void test_reg_interleavelo() { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::reg r1 = mipp::load<T>(inputs1); mipp::reg r2 = mipp::load<T>(inputs2); mipp::reg ri = mipp::interleavelo<T>(r1, r2); for (auto i = 0; i < mipp::N<T>(); i++) if (i % 2) REQUIRE(inputs2[i/2] == *((T*)&ri +i)); else REQUIRE(inputs1[i/2] == *((T*)&ri +i)); } #ifndef MIPP_NO #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave low - mipp::reg", "[mipp::interleavelo]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_reg_interleavelo<double>(); } #endif SECTION("datatype = float") { test_reg_interleavelo<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_reg_interleavelo<int64_t>(); } #endif SECTION("datatype = int32_t") { test_reg_interleavelo<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_reg_interleavelo<int16_t>(); } SECTION("datatype = int8_t") { test_reg_interleavelo<int8_t>(); } #endif } #endif #endif template <typename T> void test_Reg_interleavelo() { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::Reg<T> r1 = inputs1; mipp::Reg<T> r2 = inputs2; mipp::Reg<T> ri = mipp::interleavelo(r1, r2); for (auto i = 0; i < mipp::N<T>(); i++) if (i % 2) REQUIRE(ri[i] == inputs2[i/2]); else REQUIRE(ri[i] == inputs1[i/2]); } #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave low - mipp::Reg", "[mipp::interleavelo]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_Reg_interleavelo<double>(); } #endif SECTION("datatype = float") { test_Reg_interleavelo<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_Reg_interleavelo<int64_t>(); } #endif SECTION("datatype = int32_t") { test_Reg_interleavelo<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_Reg_interleavelo<int16_t>(); } SECTION("datatype = int8_t") { test_Reg_interleavelo<int8_t>(); } #endif } #endif template <typename T> void test_reg_interleavelo2() { if (mipp::N<T>() > 2) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::reg r1 = mipp::load<T>(inputs1); mipp::reg r2 = mipp::load<T>(inputs2); mipp::reg ri = mipp::interleavelo2<T>(r1, r2); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(*((T*)&ri +i) == inputs2[i/2]); else REQUIRE(*((T*)&ri +i) == inputs1[i/2]); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(*((T*)&ri + mipp::N<T>()/2 +i) == inputs2[mipp::N<T>()/2 + i/2]); else REQUIRE(*((T*)&ri + mipp::N<T>()/2 +i) == inputs1[mipp::N<T>()/2 + i/2]); } } #ifndef MIPP_NO #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave2 low - mipp::reg", "[mipp::interleavelo2]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_reg_interleavelo2<double>(); } #endif SECTION("datatype = float") { test_reg_interleavelo2<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_reg_interleavelo2<int64_t>(); } #endif SECTION("datatype = int32_t") { test_reg_interleavelo2<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_reg_interleavelo2<int16_t>(); } SECTION("datatype = int8_t") { test_reg_interleavelo2<int8_t>(); } #endif } #endif #endif template <typename T> void test_Reg_interleavelo2() { if (mipp::N<T>() > 2) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::Reg<T> r1 = inputs1; mipp::Reg<T> r2 = inputs2; mipp::Reg<T> ri = mipp::interleavelo2(r1, r2); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(*((T*)&ri +i) == inputs2[i/2]); else REQUIRE(*((T*)&ri +i) == inputs1[i/2]); for (auto i = 0; i < mipp::N<T>()/2; i++) if (i % 2) REQUIRE(ri[mipp::N<T>()/2 +i] == inputs2[mipp::N<T>()/2 + i/2]); else REQUIRE(ri[mipp::N<T>()/2 +i] == inputs1[mipp::N<T>()/2 + i/2]); } } #if !defined(MIPP_AVX) || (defined(MIPP_AVX) && MIPP_INSTR_VERSION >= 2) TEST_CASE("Interleave2 low - mipp::Reg", "[mipp::interleavelo2]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_Reg_interleavelo2<double>(); } #endif SECTION("datatype = float") { test_Reg_interleavelo2<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_Reg_interleavelo2<int64_t>(); } #endif SECTION("datatype = int32_t") { test_Reg_interleavelo2<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_Reg_interleavelo2<int16_t>(); } SECTION("datatype = int8_t") { test_Reg_interleavelo2<int8_t>(); } #endif } #endif template <typename T> void test_reg_interleavelo4() { if (mipp::N<T>() > 4) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + mipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::reg r1 = mipp::load<T>(inputs1); mipp::reg r2 = mipp::load<T>(inputs2); mipp::reg ri = mipp::interleavelo4<T>(r1, r2); for (auto j = 0; j < 4; j++) for (auto i = 0; i < mipp::N<T>()/4; i++) if (i % 2) REQUIRE(*((T*)&ri + j*mipp::N<T>()/4 +i) == inputs2[j*mipp::N<T>()/4 + i/2]); else REQUIRE(*((T*)&ri + j*mipp::N<T>()/4 +i) == inputs1[j*mipp::N<T>()/4 + i/2]); } } #ifndef MIPP_NO #if defined(MIPP_AVX512) TEST_CASE("Interleave4 low - mipp::reg", "[mipp::interleavelo4]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_reg_interleavelo4<double>(); } #endif SECTION("datatype = float") { test_reg_interleavelo4<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_reg_interleavelo4<int64_t>(); } #endif SECTION("datatype = int32_t") { test_reg_interleavelo4<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_reg_interleavelo4<int16_t>(); } SECTION("datatype = int8_t") { test_reg_interleavelo4<int8_t>(); } #endif } #endif #endif template <typename T> void test_Reg_interleavelo4() { if (mipp::N<T>() > 4) { T inputs1[mipp::N<T>()], inputs2[mipp::N<T>()]; std::mt19937 g; std::iota (inputs1, inputs1 + m
#if defined(MIPP_AVX512) TEST_CASE("Interleave4 low - mipp::Reg", "[mipp::interleavelo4]") { #if defined(MIPP_64BIT) SECTION("datatype = double") { test_Reg_interleavelo4<double>(); } #endif SECTION("datatype = float") { test_Reg_interleavelo4<float>(); } #if defined(MIPP_64BIT) SECTION("datatype = int64_t") { test_Reg_interleavelo4<int64_t>(); } #endif SECTION("datatype = int32_t") { test_Reg_interleavelo4<int32_t>(); } #if defined(MIPP_BW) SECTION("datatype = int16_t") { test_Reg_interleavelo4<int16_t>(); } SECTION("datatype = int8_t") { test_Reg_interleavelo4<int8_t>(); } #endif } #endif
ipp::N<T>(), (T)0); std::shuffle(inputs1, inputs1 + mipp::N<T>(), g); std::iota (inputs2, inputs2 + mipp::N<T>(), (T)0); std::shuffle(inputs2, inputs2 + mipp::N<T>(), g); mipp::Reg<T> r1 = inputs1; mipp::Reg<T> r2 = inputs2; mipp::Reg<T> ri = mipp::interleavelo4(r1, r2); for (auto j = 0; j < 4; j++) for (auto i = 0; i < mipp::N<T>()/4; i++) if (i % 2) REQUIRE(ri[j*mipp::N<T>()/4 +i] == inputs2[j*mipp::N<T>()/4 + i/2]); else REQUIRE(ri[j*mipp::N<T>()/4 +i] == inputs1[j*mipp::N<T>()/4 + i/2]); } }
function_block-function_prefixed
[ { "content": "struct Converter<float> {\n\n static_assert(sizeof(float) == sizeof(int32_t), \"Important ULP matcher assumption violated\");\n\n Converter(float f) {\n\n std::memcpy(&i, &f, sizeof(f));\n\n }\n\n int32_t i;\n\n};\n\n\n\ntemplate <>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 0, "score": 91286.09037177375 }, { "content": " class ExceptionTranslator : public IExceptionTranslator {\n\n public:\n\n\n\n ExceptionTranslator( std::string(*translateFunction)( T& ) )\n\n : m_translateFunction( translateFunction )\n\n {}\n\n\n\n std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {\n\n try {\n\n if( it == itEnd )\n\n std::rethrow_exception(std::current_exception());\n\n else\n\n return (*it)->translate( it+1, itEnd );\n\n }\n\n catch( T& ex ) {\n\n return m_translateFunction( ex );\n\n }\n\n }\n\n\n\n protected:\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 1, "score": 84946.29576554237 }, { "content": " class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {\n\n public:\n\n ~ExceptionTranslatorRegistry();\n\n virtual void registerTranslator( const IExceptionTranslator* translator );\n\n virtual std::string translateActiveException() const override;\n\n std::string tryTranslators() const;\n\n\n\n private:\n\n std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;\n\n };\n\n}\n\n\n\n// end catch_exception_translator_registry.h\n\n#ifdef __OBJC__\n\n#import \"Foundation/Foundation.h\"\n\n#endif\n\n\n\nnamespace Catch {\n\n\n\n ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 2, "score": 81458.55169261768 }, { "content": "struct Converter<double> {\n\n static_assert(sizeof(double) == sizeof(int64_t), \"Important ULP matcher assumption violated\");\n\n Converter(double d) {\n\n std::memcpy(&i, &d, sizeof(d));\n\n }\n\n int64_t i;\n\n};\n\n\n\ntemplate <typename T>\n\nauto convert(T t) -> Converter<T> {\n\n return Converter<T>(t);\n\n}\n\n\n\ntemplate <typename FP>\n\nbool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {\n\n // Comparison with NaN should always be false.\n\n // This way we can rule it out before getting into the ugly details\n\n if (std::isnan(lhs) || std::isnan(rhs)) {\n\n return false;\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 3, "score": 79378.13735602572 }, { "content": " class ResultValueBase<void> : public ResultBase {\n\n protected:\n\n using ResultBase::ResultBase;\n\n };\n\n\n\n template<typename T = void>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 4, "score": 77149.87545517844 }, { "content": " class ExceptionTranslatorRegistrar {\n\n template<typename T>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 5, "score": 77108.25894407404 }, { "content": " class StartupExceptionRegistry {\n\n public:\n\n void add(std::exception_ptr const& exception) noexcept;\n\n std::vector<std::exception_ptr> const& getExceptions() const noexcept;\n\n private:\n\n std::vector<std::exception_ptr> m_exceptions;\n\n };\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_startup_exception_registry.h\n\nnamespace Catch {\n\n\n\n namespace {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 6, "score": 77108.25894407404 }, { "content": " class StartupExceptionRegistry;\n\n\n\n using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;\n\n\n\n struct IRegistryHub {\n\n virtual ~IRegistryHub();\n\n\n\n virtual IReporterRegistry const& getReporterRegistry() const = 0;\n\n virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;\n\n virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;\n\n\n\n virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;\n\n\n\n virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;\n\n };\n\n\n\n struct IMutableRegistryHub {\n\n virtual ~IMutableRegistryHub();\n\n virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;\n\n virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 7, "score": 77108.25894407404 }, { "content": "struct AutoReg : NonCopyable {\n\n AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;\n\n ~AutoReg();\n\n};\n\n\n\n} // end namespace Catch\n\n\n\n#if defined(CATCH_CONFIG_DISABLE)\n\n #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \\\n\n static void TestName()\n\n #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \\\n\n namespace{ \\\n\n struct TestName : ClassName { \\\n\n void test(); \\\n\n }; \\\n\n } \\\n\n void TestName::test()\n\n\n\n#endif\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 8, "score": 74994.27557756487 }, { "content": "enum class FloatingPointKind : uint8_t {\n\n Float,\n\n Double\n\n};\n\n}\n\n}\n\n}\n\n\n\nnamespace {\n\n\n\ntemplate <typename T>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 9, "score": 72971.3818383547 }, { "content": " enum class FloatingPointKind : uint8_t;\n\n\n\n struct WithinAbsMatcher : MatcherBase<double> {\n\n WithinAbsMatcher(double target, double margin);\n\n bool match(double const& matchee) const override;\n\n std::string describe() const override;\n\n private:\n\n double m_target;\n\n double m_margin;\n\n };\n\n\n\n struct WithinUlpsMatcher : MatcherBase<double> {\n\n WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);\n\n bool match(double const& matchee) const override;\n\n std::string describe() const override;\n\n private:\n\n double m_target;\n\n int m_ulps;\n\n FloatingPointKind m_type;\n\n };\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 10, "score": 72971.3818383547 }, { "content": "#include <exception>\n\n#include <algorithm>\n\n#include <numeric>\n\n#include <random>\n\n#include <cmath>\n\n#include <mipp.h>\n\n#include <catch.hpp>\n\n\n\ntemplate <typename T>\n\nvoid test_reg_low()\n\n{\n\n\tT inputs[mipp::N<T>()];\n\n\tstd::iota(inputs, inputs + mipp::N<T>(), (T)0);\n\n\n\n\tmipp::reg r = mipp::load<T>(inputs);\n\n\tmipp::reg_2 r_2 = mipp::low <T>(r);\n\n\n\n\tfor (auto i = 0; i < mipp::N<T>()/2; i++)\n\n\t\tREQUIRE(*((T*)&r_2 +i) == inputs[i]);\n\n}\n", "file_path": "tests/src/memory_operations/low.cpp", "rank": 11, "score": 44020.180569146134 }, { "content": "template <typename T>\n\nvoid test_Reg_low()\n\n{\n\n\tT inputs[mipp::N<T>()];\n\n\tstd::iota(inputs, inputs + mipp::N<T>(), (T)0);\n\n\n\n\tmipp::Reg <T> r = inputs;\n\n\tmipp::Reg_2<T> r_2 = r.low();\n\n\n\n\tfor (auto i = 0; i < mipp::N<T>()/2; i++)\n\n\t\tREQUIRE(r_2[i] == inputs[i]);\n\n}\n\n\n\nTEST_CASE(\"Low - mipp::Reg\", \"[mipp::low]\")\n\n{\n\n#if defined(MIPP_64BIT)\n\n\tSECTION(\"datatype = double\") { test_Reg_low<double>(); }\n\n#endif\n\n\tSECTION(\"datatype = float\") { test_Reg_low<float>(); }\n\n\n", "file_path": "tests/src/memory_operations/low.cpp", "rank": 12, "score": 44000.69257336553 }, { "content": "\n\n#ifndef MIPP_NO\n\nTEST_CASE(\"Low - mipp::reg\", \"[mipp::low]\")\n\n{\n\n#if defined(MIPP_64BIT)\n\n\tSECTION(\"datatype = double\") { test_reg_low<double>(); }\n\n#endif\n\n\tSECTION(\"datatype = float\") { test_reg_low<float>(); }\n\n\n\n#if defined(MIPP_64BIT)\n\n\tSECTION(\"datatype = int64_t\") { test_reg_low<int64_t>(); }\n\n#endif\n\n\tSECTION(\"datatype = int32_t\") { test_reg_low<int32_t>(); }\n\n#if defined(MIPP_BW)\n\n\tSECTION(\"datatype = int16_t\") { test_reg_low<int16_t>(); }\n\n\tSECTION(\"datatype = int8_t\") { test_reg_low<int8_t>(); }\n\n#endif\n\n}\n\n#endif\n\n\n", "file_path": "tests/src/memory_operations/low.cpp", "rank": 13, "score": 43990.497181064144 }, { "content": "#if defined(MIPP_64BIT)\n\n\tSECTION(\"datatype = int64_t\") { test_Reg_low<int64_t>(); }\n\n#endif\n\n\tSECTION(\"datatype = int32_t\") { test_Reg_low<int32_t>(); }\n\n#if defined(MIPP_BW)\n\n\tSECTION(\"datatype = int16_t\") { test_Reg_low<int16_t>(); }\n\n\tSECTION(\"datatype = int8_t\") { test_Reg_low<int8_t>(); }\n\n#endif\n\n}\n", "file_path": "tests/src/memory_operations/low.cpp", "rank": 14, "score": 43985.535632296276 }, { "content": "\n\n result_type operator()( result_type n ) const;\n\n result_type operator()() const;\n\n\n\n template<typename V>\n\n static void shuffle( V& vector ) {\n\n RandomNumberGenerator rng;\n\n std::shuffle( vector.begin(), vector.end(), rng );\n\n }\n\n };\n\n\n\n}\n\n\n\n// end catch_random_number_generator.h\n\n#include <cstdlib>\n\n\n\nnamespace Catch {\n\n\n\n void seedRng( IConfig const& config ) {\n\n if( config.rngSeed() != 0 )\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 15, "score": 40331.95961066822 }, { "content": " if( m_count < m_iterationsToRun )\n\n return true;\n\n return needsMoreIterations();\n\n }\n\n\n\n void increment() {\n\n ++m_count;\n\n }\n\n\n\n void reportStart();\n\n auto needsMoreIterations() -> bool;\n\n };\n\n\n\n} // end namespace Catch\n\n\n\n#define BENCHMARK( name ) \\\n\n for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )\n\n\n\n// end catch_benchmark.h\n\n// start catch_interfaces_exception.h\n\n\n\n// start catch_interfaces_registry_hub.h\n\n\n\n#include <string>\n\n#include <memory>\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 16, "score": 40331.65030677155 }, { "content": "// end catch_message.cpp\n\n// start catch_random_number_generator.cpp\n\n\n\n// start catch_random_number_generator.h\n\n\n\n#include <algorithm>\n\n\n\nnamespace Catch {\n\n\n\n struct IConfig;\n\n\n\n void seedRng( IConfig const& config );\n\n\n\n unsigned int rngSeed();\n\n\n\n struct RandomNumberGenerator {\n\n using result_type = unsigned int;\n\n\n\n static constexpr result_type (min)() { return 0; }\n\n static constexpr result_type (max)() { return 1000000; }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 17, "score": 40331.35910836464 }, { "content": " auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }\n\n template<typename T>\n\n auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }\n\n template<typename T>\n\n auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }\n\n\n\n template<typename LhsT, typename RhsT>\n\n auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }\n\n template<typename T>\n\n auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }\n\n template<typename T>\n\n auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }\n\n template<typename T>\n\n auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }\n\n template<typename T>\n\n auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }\n\n\n\n template<typename LhsT>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 18, "score": 40330.49792738907 }, { "content": "#include <cmath>\n\n#include <limits>\n\n\n\nnamespace {\n\n\n\n// Performs equivalent check of std::fabs(lhs - rhs) <= margin\n\n// But without the subtraction to allow for INFINITY in comparison\n\nbool marginComparison(double lhs, double rhs, double margin) {\n\n return (lhs + margin >= rhs) && (rhs + margin >= lhs);\n\n}\n\n\n\n}\n\n\n\nnamespace Catch {\n\nnamespace Detail {\n\n\n\n Approx::Approx ( double value )\n\n : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),\n\n m_margin( 0.0 ),\n\n m_scale( 0.0 ),\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 19, "score": 40330.32856035473 }, { "content": " handleExpr( expr.makeUnaryExpr() );\n\n }\n\n void handleExpr( ITransientExpression const& expr );\n\n\n\n void handleMessage(ResultWas::OfType resultType, StringRef const& message);\n\n\n\n void handleExceptionThrownAsExpected();\n\n void handleUnexpectedExceptionNotThrown();\n\n void handleExceptionNotThrownAsExpected();\n\n void handleThrowingCallSkipped();\n\n void handleUnexpectedInflightException();\n\n\n\n void complete();\n\n void setCompleted();\n\n\n\n // query\n\n auto allowThrows() const -> bool;\n\n };\n\n\n\n void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 20, "score": 40329.14406849059 }, { "content": " std::srand( config.rngSeed() );\n\n }\n\n unsigned int rngSeed() {\n\n return getCurrentContext().getConfig()->rngSeed();\n\n }\n\n\n\n RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {\n\n return std::rand() % n;\n\n }\n\n RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {\n\n return std::rand() % (max)();\n\n }\n\n\n\n}\n\n// end catch_random_number_generator.cpp\n\n// start catch_registry_hub.cpp\n\n\n\n// start catch_test_case_registry_impl.h\n\n\n\n#include <vector>\n\n#include <set>\n\n#include <algorithm>\n\n#include <ios>\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 21, "score": 40329.06194368099 }, { "content": " MatchNotOf<T> MatcherBase<T>::operator ! () const {\n\n return MatchNotOf<T>( *this );\n\n }\n\n\n\n } // namespace Impl\n\n\n\n} // namespace Matchers\n\n\n\nusing namespace Matchers;\n\nusing Matchers::Impl::MatcherBase;\n\n\n\n} // namespace Catch\n\n\n\n// end catch_matchers.h\n\n// start catch_matchers_floating.h\n\n\n\n#include <type_traits>\n\n#include <cmath>\n\n\n\nnamespace Catch {\n\nnamespace Matchers {\n\n\n\n namespace Floating {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 22, "score": 40328.56174716223 }, { "content": " }\n\n };\n\n\n\n void handleExpression( ITransientExpression const& expr );\n\n\n\n template<typename T>\n\n void handleExpression( ExprLhs<T> const& expr ) {\n\n handleExpression( expr.makeUnaryExpr() );\n\n }\n\n\n\n struct Decomposer {\n\n template<typename T>\n\n auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {\n\n return ExprLhs<T const&>{ lhs };\n\n }\n\n\n\n auto operator <=( bool value ) -> ExprLhs<bool> {\n\n return ExprLhs<bool>{ value };\n\n }\n\n };\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 23, "score": 40328.41022606723 }, { "content": " virtual void registerTest( TestCase const& testInfo ) = 0;\n\n virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;\n\n virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;\n\n virtual void registerStartupException() noexcept = 0;\n\n };\n\n\n\n IRegistryHub& getRegistryHub();\n\n IMutableRegistryHub& getMutableRegistryHub();\n\n void cleanUp();\n\n std::string translateActiveException();\n\n\n\n}\n\n\n\n// end catch_interfaces_registry_hub.h\n\n#if defined(CATCH_CONFIG_DISABLE)\n\n #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \\\n\n static std::string translatorName( signature )\n\n#endif\n\n\n\n#include <exception>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 24, "score": 40328.360925059256 }, { "content": "\n\n template<typename ReturnType>\n\n struct LambdaInvoker {\n\n static_assert( std::is_same<ReturnType, ParserResult>::value, \"Lambda must return void or clara::ParserResult\" );\n\n\n\n template<typename L, typename ArgType>\n\n static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {\n\n return lambda( arg );\n\n }\n\n };\n\n\n\n template<>\n\n struct LambdaInvoker<void> {\n\n template<typename L, typename ArgType>\n\n static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {\n\n lambda( arg );\n\n return ParserResult::ok( ParseResultType::Matched );\n\n }\n\n };\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 25, "score": 40328.26526694464 }, { "content": " }\n\n\n\n AutoReg::~AutoReg() = default;\n\n}\n\n// end catch_test_registry.cpp\n\n// start catch_test_spec.cpp\n\n\n\n#include <algorithm>\n\n#include <string>\n\n#include <vector>\n\n#include <memory>\n\n\n\nnamespace Catch {\n\n\n\n TestSpec::Pattern::~Pattern() = default;\n\n TestSpec::NamePattern::~NamePattern() = default;\n\n TestSpec::TagPattern::~TagPattern() = default;\n\n TestSpec::ExcludedPattern::~ExcludedPattern() = default;\n\n\n\n TestSpec::NamePattern::NamePattern( std::string const& name )\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 26, "score": 40327.92582170565 }, { "content": " }\n\n std::string describe() const override {\n\n return \"Equals: \" + ::Catch::Detail::stringify( m_comparator );\n\n }\n\n std::vector<T> const& m_comparator;\n\n };\n\n\n\n template<typename T>\n\n struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {\n\n UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}\n\n bool match(std::vector<T> const& vec) const override {\n\n // Note: This is a reimplementation of std::is_permutation,\n\n // because I don't want to include <algorithm> inside the common path\n\n if (m_target.size() != vec.size()) {\n\n return false;\n\n }\n\n auto lfirst = m_target.begin(), llast = m_target.end();\n\n auto rfirst = vec.begin(), rlast = vec.end();\n\n // Cut common prefix to optimize checking of permuted parts\n\n while (lfirst != llast && *lfirst != *rfirst) {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 27, "score": 40327.73742753617 }, { "content": "\n\n } // namespace Floating\n\n\n\n // The following functions create the actual matcher objects.\n\n // This allows the types to be inferred\n\n Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);\n\n Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);\n\n Floating::WithinAbsMatcher WithinAbs(double target, double margin);\n\n\n\n} // namespace Matchers\n\n} // namespace Catch\n\n\n\n// end catch_matchers_floating.h\n\n// start catch_matchers_generic.hpp\n\n\n\n#include <functional>\n\n#include <string>\n\n\n\nnamespace Catch {\n\nnamespace Matchers {\n\nnamespace Generic {\n\n\n\nnamespace Detail {\n\n std::string finalizeDescription(const std::string& desc);\n\n}\n\n\n\ntemplate <typename T>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 28, "score": 40327.50397649512 }, { "content": " };\n\n\n\n inline auto Column::operator + ( Column const& other ) -> Columns {\n\n Columns cols;\n\n cols += *this;\n\n cols += other;\n\n return cols;\n\n }\n\n}}} // namespace Catch::clara::TextFlow\n\n\n\n// ----------- end of #include from clara_textflow.hpp -----------\n\n// ........... back in clara.hpp\n\n\n\n#include <memory>\n\n#include <set>\n\n#include <algorithm>\n\n\n\n#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )\n\n#define CATCH_PLATFORM_WINDOWS\n\n#endif\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 29, "score": 40327.45130951514 }, { "content": " };\n\n\n\n using StringMatcher = Matchers::Impl::MatcherBase<std::string>;\n\n\n\n void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );\n\n\n\n template<typename ArgT, typename MatcherT>\n\n auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {\n\n return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );\n\n }\n\n\n\n} // namespace Catch\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \\\n\n do { \\\n\n Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) \", \" CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \\\n\n INTERNAL_CATCH_TRY { \\\n\n catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \\\n\n } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \\\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 30, "score": 40327.44574939611 }, { "content": " virtual ~IReporterRegistry();\n\n virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;\n\n virtual FactoryMap const& getFactories() const = 0;\n\n virtual Listeners const& getListeners() const = 0;\n\n };\n\n\n\n void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_interfaces_reporter.h\n\n#include <algorithm>\n\n#include <cstring>\n\n#include <cfloat>\n\n#include <cstdio>\n\n#include <assert.h>\n\n#include <memory>\n\n#include <ostream>\n\n\n\nnamespace Catch {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 31, "score": 40327.400661217005 }, { "content": "// end catch_tag_alias_registry.cpp\n\n// start catch_test_case_info.cpp\n\n\n\n#include <cctype>\n\n#include <exception>\n\n#include <algorithm>\n\n#include <sstream>\n\n\n\nnamespace Catch {\n\n\n\n TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {\n\n if( startsWith( tag, '.' ) ||\n\n tag == \"!hide\" )\n\n return TestCaseInfo::IsHidden;\n\n else if( tag == \"!throws\" )\n\n return TestCaseInfo::Throws;\n\n else if( tag == \"!shouldfail\" )\n\n return TestCaseInfo::ShouldFail;\n\n else if( tag == \"!mayfail\" )\n\n return TestCaseInfo::MayFail;\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 32, "score": 40327.0228732373 }, { "content": "#include <cstdio>\n\n#include <assert.h>\n\n#include <memory>\n\n\n\nnamespace Catch {\n\n void prepareExpandedExpression(AssertionResult& result) {\n\n result.getExpandedExpression();\n\n }\n\n\n\n // Because formatting using c++ streams is stateful, drop down to C is required\n\n // Alternatively we could use stringstream, but its performance is... not good.\n\n std::string getFormattedDuration( double duration ) {\n\n // Max exponent + 1 is required to represent the whole part\n\n // + 1 for decimal point\n\n // + 3 for the 3 decimal places\n\n // + 1 for null terminator\n\n const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;\n\n char buffer[maxDoubleSize];\n\n\n\n // Save previous errno, to prevent sprintf from overwriting it\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 33, "score": 40326.99929995703 }, { "content": " std::terminate();\n\n }\n\n }\n\n\n\n std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {\n\n return m_exceptions;\n\n }\n\n\n\n} // end namespace Catch\n\n// end catch_startup_exception_registry.cpp\n\n// start catch_stream.cpp\n\n\n\n#include <cstdio>\n\n#include <iostream>\n\n#include <fstream>\n\n#include <sstream>\n\n#include <vector>\n\n#include <memory>\n\n\n\n#if defined(__clang__)\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 34, "score": 40326.57328034936 }, { "content": " FatalConditionHandler();\n\n static void reset();\n\n ~FatalConditionHandler();\n\n\n\n private:\n\n static bool isSet;\n\n static ULONG guaranteeSize;\n\n static PVOID exceptionHandlerHandle;\n\n };\n\n\n\n} // namespace Catch\n\n\n\n#elif defined ( CATCH_CONFIG_POSIX_SIGNALS )\n\n\n\n#include <signal.h>\n\n\n\nnamespace Catch {\n\n\n\n struct FatalConditionHandler {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 35, "score": 40326.21311715204 }, { "content": " return cnt;\n\n }\n\n template <typename InputIterator, typename T>\n\n bool contains(InputIterator first, InputIterator last, T const& item) {\n\n for (; first != last; ++first) {\n\n if (*first == item) {\n\n return true;\n\n }\n\n }\n\n return false;\n\n }\n\n }\n\n\n\n template<typename T>\n\n struct ContainsElementMatcher : MatcherBase<std::vector<T>> {\n\n\n\n ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}\n\n\n\n bool match(std::vector<T> const &v) const override {\n\n for (auto const& el : v) {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 36, "score": 40326.19310707583 }, { "content": "\n\n auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {\n\n return new(std::nothrow) TestInvokerAsFunction( testAsFunction );\n\n }\n\n\n\n NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}\n\n\n\n AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {\n\n try {\n\n getMutableRegistryHub()\n\n .registerTest(\n\n makeTestCase(\n\n invoker,\n\n extractClassName( classOrMethod ),\n\n nameAndTags,\n\n lineInfo));\n\n } catch (...) {\n\n // Do not throw when constructing global objects, instead register the exception to be processed later\n\n getMutableRegistryHub().registerStartupException();\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 37, "score": 40326.0883376239 }, { "content": " void cli( clara::Parser const& newParser );\n\n ConfigData& configData();\n\n Config& config();\n\n private:\n\n int runInternal();\n\n\n\n clara::Parser m_cli;\n\n ConfigData m_configData;\n\n std::shared_ptr<Config> m_config;\n\n bool m_startupExceptions = false;\n\n };\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_session.h\n\n// start catch_version.h\n\n\n\n#include <iosfwd>\n\n\n\nnamespace Catch {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 38, "score": 40325.88297093767 }, { "content": "} // namespace Catch\n\n\n\n// end catch_matchers_string.h\n\n// start catch_matchers_vector.h\n\n\n\n#include <algorithm>\n\n\n\nnamespace Catch {\n\nnamespace Matchers {\n\n\n\n namespace Vector {\n\n namespace Detail {\n\n template <typename InputIterator, typename T>\n\n size_t count(InputIterator first, InputIterator last, T const& item) {\n\n size_t cnt = 0;\n\n for (; first != last; ++first) {\n\n if (*first == item) {\n\n ++cnt;\n\n }\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 39, "score": 40325.87844510252 }, { "content": " void AssertionHandler::setCompleted() {\n\n m_completed = true;\n\n }\n\n\n\n void AssertionHandler::handleUnexpectedInflightException() {\n\n m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );\n\n }\n\n\n\n void AssertionHandler::handleExceptionThrownAsExpected() {\n\n m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);\n\n }\n\n void AssertionHandler::handleExceptionNotThrownAsExpected() {\n\n m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);\n\n }\n\n\n\n void AssertionHandler::handleUnexpectedExceptionNotThrown() {\n\n m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );\n\n }\n\n\n\n void AssertionHandler::handleThrowingCallSkipped() {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 40, "score": 40325.660884286546 }, { "content": "#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)\n\n#include <tuple>\n\nnamespace Catch {\n\n namespace Detail {\n\n template<\n\n typename Tuple,\n\n std::size_t N = 0,\n\n bool = (N < std::tuple_size<Tuple>::value)\n\n >\n\n struct TupleElementPrinter {\n\n static void print(const Tuple& tuple, std::ostream& os) {\n\n os << (N ? \", \" : \" \")\n\n << ::Catch::Detail::stringify(std::get<N>(tuple));\n\n TupleElementPrinter<Tuple, N + 1>::print(tuple, os);\n\n }\n\n };\n\n\n\n template<\n\n typename Tuple,\n\n std::size_t N\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 41, "score": 40325.59135098268 }, { "content": " for (auto const& info : m_columnInfos)\n\n *this << info.name << ColumnBreak();\n\n *this << RowBreak();\n\n m_os << Catch::getLineOfChars<'-'>() << \"\\n\";\n\n }\n\n }\n\n void close() {\n\n if (m_isOpen) {\n\n *this << RowBreak();\n\n m_os << std::endl;\n\n m_isOpen = false;\n\n }\n\n }\n\n\n\n template<typename T>\n\n friend TablePrinter& operator << (TablePrinter& tp, T const& value) {\n\n tp.m_oss << value;\n\n return tp;\n\n }\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 42, "score": 40325.58588321245 }, { "content": " case RunTests::InRandomOrder:\n\n seedRng( config );\n\n RandomNumberGenerator::shuffle( sorted );\n\n break;\n\n case RunTests::InDeclarationOrder:\n\n // already in declaration order\n\n break;\n\n }\n\n return sorted;\n\n }\n\n bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {\n\n return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );\n\n }\n\n\n\n void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {\n\n std::set<TestCase> seenFunctions;\n\n for( auto const& function : functions ) {\n\n auto prev = seenFunctions.insert( function );\n\n CATCH_ENFORCE( prev.second,\n\n \"error: TEST_CASE( \\\"\" << function.name << \"\\\" ) already defined.\\n\"\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 43, "score": 40325.49570464184 }, { "content": "#include <string>\n\n#include <vector>\n\n\n\nnamespace Catch {\n\n using exceptionTranslateFunction = std::string(*)();\n\n\n\n struct IExceptionTranslator;\n\n using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;\n\n\n\n struct IExceptionTranslator {\n\n virtual ~IExceptionTranslator();\n\n virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;\n\n };\n\n\n\n struct IExceptionTranslatorRegistry {\n\n virtual ~IExceptionTranslatorRegistry();\n\n\n\n virtual std::string translateActiveException() const = 0;\n\n };\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 44, "score": 40325.449052965705 }, { "content": "#include <string>\n\n#include <vector>\n\n\n\nnamespace Catch {\n\nnamespace Matchers {\n\n namespace Impl {\n\n\n\n template<typename ArgT> struct MatchAllOf;\n\n template<typename ArgT> struct MatchAnyOf;\n\n template<typename ArgT> struct MatchNotOf;\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 45, "score": 40325.27415137256 }, { "content": "#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )\n\n\n\n// end catch_interfaces_exception.h\n\n// start catch_approx.h\n\n\n\n#include <type_traits>\n\n#include <stdexcept>\n\n\n\nnamespace Catch {\n\nnamespace Detail {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 46, "score": 40325.223177853164 }, { "content": "\n\n#include <cerrno>\n\n\n\nnamespace Catch {\n\n ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}\n\n ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }\n\n}\n\n// end catch_errno_guard.cpp\n\n// start catch_exception_translator_registry.cpp\n\n\n\n// start catch_exception_translator_registry.h\n\n\n\n#include <vector>\n\n#include <string>\n\n#include <memory>\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 47, "score": 40325.18676867464 }, { "content": " }\n\n\n\n template<typename T>\n\n auto operator|( T const &other ) const -> Parser {\n\n return Parser( *this ) |= other;\n\n }\n\n\n\n // Forward deprecated interface with '+' instead of '|'\n\n template<typename T>\n\n auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }\n\n template<typename T>\n\n auto operator+( T const &other ) const -> Parser { return operator|( other ); }\n\n\n\n auto getHelpColumns() const -> std::vector<HelpColumns> {\n\n std::vector<HelpColumns> cols;\n\n for (auto const &o : m_options) {\n\n auto childCols = o.getHelpColumns();\n\n cols.insert( cols.end(), childCols.begin(), childCols.end() );\n\n }\n\n return cols;\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 48, "score": 40325.07981455621 }, { "content": "\n\n public: // IMutableRegistryHub\n\n void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {\n\n m_reporterRegistry.registerReporter( name, factory );\n\n }\n\n void registerListener( IReporterFactoryPtr const& factory ) override {\n\n m_reporterRegistry.registerListener( factory );\n\n }\n\n void registerTest( TestCase const& testInfo ) override {\n\n m_testCaseRegistry.registerTest( testInfo );\n\n }\n\n void registerTranslator( const IExceptionTranslator* translator ) override {\n\n m_exceptionTranslatorRegistry.registerTranslator( translator );\n\n }\n\n void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {\n\n m_tagAliasRegistry.add( alias, tag, lineInfo );\n\n }\n\n void registerStartupException() noexcept override {\n\n m_exceptionRegistry.add(std::current_exception());\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 49, "score": 40325.04760852797 }, { "content": " for (auto it = m_unfinishedSections.rbegin(),\n\n itEnd = m_unfinishedSections.rend();\n\n it != itEnd;\n\n ++it)\n\n sectionEnded(*it);\n\n m_unfinishedSections.clear();\n\n }\n\n\n\n void RunContext::handleExpr(\n\n AssertionInfo const& info,\n\n ITransientExpression const& expr,\n\n AssertionReaction& reaction\n\n ) {\n\n m_reporter->assertionStarting( info );\n\n\n\n bool negated = isFalseTest( info.resultDisposition );\n\n bool result = expr.getResult() != negated;\n\n\n\n if( result ) {\n\n if (!m_includeSuccessfulResults) {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 50, "score": 40325.01821120178 }, { "content": " else\n\n writeSection( className, name, *childNode );\n\n }\n\n\n\n void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {\n\n for( auto const& assertion : sectionNode.assertions )\n\n writeAssertion( assertion );\n\n }\n\n\n\n void JunitReporter::writeAssertion( AssertionStats const& stats ) {\n\n AssertionResult const& result = stats.assertionResult;\n\n if( !result.isOk() ) {\n\n std::string elementName;\n\n switch( result.getResultType() ) {\n\n case ResultWas::ThrewException:\n\n case ResultWas::FatalErrorCondition:\n\n elementName = \"error\";\n\n break;\n\n case ResultWas::ExplicitFailure:\n\n elementName = \"failure\";\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 51, "score": 40325.003349456354 }, { "content": " static std::string convert(unsigned char c);\n\n };\n\n\n\n template<>\n\n struct StringMaker<std::nullptr_t> {\n\n static std::string convert(std::nullptr_t);\n\n };\n\n\n\n template<>\n\n struct StringMaker<float> {\n\n static std::string convert(float value);\n\n };\n\n template<>\n\n struct StringMaker<double> {\n\n static std::string convert(double value);\n\n };\n\n\n\n template <typename T>\n\n struct StringMaker<T*> {\n\n template <typename U>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 52, "score": 40324.8824574727 }, { "content": " // !TBD: see note in EqualsMatcher\n\n if (m_comparator.size() > v.size())\n\n return false;\n\n for (auto const& comparator : m_comparator) {\n\n auto present = false;\n\n for (const auto& el : v) {\n\n if (el == comparator) {\n\n present = true;\n\n break;\n\n }\n\n }\n\n if (!present) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n std::string describe() const override {\n\n return \"Contains: \" + ::Catch::Detail::stringify( m_comparator );\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 53, "score": 40324.85637337994 }, { "content": "\n\n#ifdef __OBJC__\n\n// start catch_objc.hpp\n\n\n\n#import <objc/runtime.h>\n\n\n\n#include <string>\n\n\n\n// NB. Any general catch headers included here must be included\n\n// in catch.hpp first to make sure they are included by the single\n\n// header for non obj-usage\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n// This protocol is really only here for (self) documenting purposes, since\n\n// all its methods are optional.\n\n@protocol OcFixture\n\n\n\n@optional\n\n\n\n-(void) setUp;\n\n-(void) tearDown;\n\n\n\n@end\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 54, "score": 40324.8290965676 }, { "content": " setTags(testCase, tags);\n\n }\n\n }\n\n\n\n } // anon namespace\n\n\n\n Session::Session() {\n\n static bool alreadyInstantiated = false;\n\n if( alreadyInstantiated ) {\n\n try { CATCH_INTERNAL_ERROR( \"Only one instance of Catch::Session can ever be used\" ); }\n\n catch(...) { getMutableRegistryHub().registerStartupException(); }\n\n }\n\n\n\n const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();\n\n if ( !exceptions.empty() ) {\n\n m_startupExceptions = true;\n\n Colour colourGuard( Colour::Red );\n\n Catch::cerr() << \"Errors occurred during startup!\" << '\\n';\n\n // iterate over all exceptions and notify user\n\n for ( const auto& ex_ptr : exceptions ) {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 55, "score": 40324.66968318055 }, { "content": "// end catch_tostring.h\n\n#include <iosfwd>\n\n\n\n#ifdef _MSC_VER\n\n#pragma warning(push)\n\n#pragma warning(disable:4389) // '==' : signed/unsigned mismatch\n\n#pragma warning(disable:4018) // more \"signed/unsigned mismatch\"\n\n#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)\n\n#pragma warning(disable:4180) // qualifier applied to function type has no meaning\n\n#endif\n\n\n\nnamespace Catch {\n\n\n\n struct ITransientExpression {\n\n auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }\n\n auto getResult() const -> bool { return m_result; }\n\n virtual void streamReconstructedExpression( std::ostream &os ) const = 0;\n\n\n\n ITransientExpression( bool isBinaryExpression, bool result )\n\n : m_isBinaryExpression( isBinaryExpression ),\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 56, "score": 40324.66643353957 }, { "content": " ++diff.testCases.failedButOk;\n\n else\n\n ++diff.testCases.passed;\n\n return diff;\n\n }\n\n\n\n}\n\n// end catch_totals.cpp\n\n// start catch_uncaught_exceptions.cpp\n\n\n\n#include <exception>\n\n\n\nnamespace Catch {\n\n bool uncaught_exceptions() {\n\n#if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)\n\n return std::uncaught_exceptions() > 0;\n\n#else\n\n return std::uncaught_exception();\n\n#endif\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 57, "score": 40324.5287505756 }, { "content": "\n\n#define CHECK( ... ) (void)(0)\n\n#define CHECK_FALSE( ... ) (void)(0)\n\n#define CHECKED_IF( ... ) if (__VA_ARGS__)\n\n#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))\n\n#define CHECK_NOFAIL( ... ) (void)(0)\n\n\n\n#define CHECK_THROWS( ... ) (void)(0)\n\n#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)\n\n#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define CHECK_NOTHROW( ... ) (void)(0)\n\n\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n#define CHECK_THAT( arg, matcher ) (void)(0)\n\n\n\n#define REQUIRE_THAT( arg, matcher ) (void)(0)\n\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 58, "score": 40324.524702579125 }, { "content": "\n\n void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->benchmarkStarting( benchmarkInfo );\n\n }\n\n void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->benchmarkEnded( benchmarkStats );\n\n }\n\n\n\n void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->testRunStarting( testRunInfo );\n\n }\n\n\n\n void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->testGroupStarting( groupInfo );\n\n }\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 59, "score": 40324.51235511796 }, { "content": " return clearBuffer;\n\n }\n\n\n\n void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->sectionEnded( sectionStats );\n\n }\n\n\n\n void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->testCaseEnded( testCaseStats );\n\n }\n\n\n\n void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->testGroupEnded( testGroupStats );\n\n }\n\n\n\n void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {\n\n for( auto const& reporter : m_reporters )\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 60, "score": 40324.43987006719 }, { "content": " return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;\n\n }\n\n\n\n template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n\n Approx& epsilon( T const& newEpsilon ) {\n\n double epsilonAsDouble = static_cast<double>(newEpsilon);\n\n if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {\n\n throw std::domain_error\n\n ( \"Invalid Approx::epsilon: \" +\n\n Catch::Detail::stringify( epsilonAsDouble ) +\n\n \", Approx::epsilon has to be between 0 and 1\" );\n\n }\n\n m_epsilon = epsilonAsDouble;\n\n return *this;\n\n }\n\n\n\n template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n\n Approx& margin( T const& newMargin ) {\n\n double marginAsDouble = static_cast<double>(newMargin);\n\n if( marginAsDouble < 0 ) {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 61, "score": 40324.40375244288 }, { "content": "} // namespace Catch\n\n\n\n// Separate std::chrono::duration specialization\n\n#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)\n\n#include <ctime>\n\n#include <ratio>\n\n#include <chrono>\n\n\n\nnamespace Catch {\n\n\n\ntemplate <class Ratio>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 62, "score": 40324.386749281446 }, { "content": "namespace Matchers {\n\n namespace Impl {\n\n\n\n std::string MatcherUntypedBase::toString() const {\n\n if( m_cachedToString.empty() )\n\n m_cachedToString = describe();\n\n return m_cachedToString;\n\n }\n\n\n\n MatcherUntypedBase::~MatcherUntypedBase() = default;\n\n\n\n } // namespace Impl\n\n} // namespace Matchers\n\n\n\nusing namespace Matchers;\n\nusing Matchers::Impl::MatcherBase;\n\n\n\n} // namespace Catch\n\n// end catch_matchers.cpp\n\n// start catch_matchers_floating.cpp\n\n\n\n#include <cstdlib>\n\n#include <cstdint>\n\n#include <cstring>\n\n#include <stdexcept>\n\n\n\nnamespace Catch {\n\nnamespace Matchers {\n\nnamespace Floating {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 63, "score": 40324.38322129713 }, { "content": " { SIGINT, \"SIGINT - Terminal interrupt signal\" },\n\n { SIGILL, \"SIGILL - Illegal instruction signal\" },\n\n { SIGFPE, \"SIGFPE - Floating point error signal\" },\n\n { SIGSEGV, \"SIGSEGV - Segmentation violation signal\" },\n\n { SIGTERM, \"SIGTERM - Termination request signal\" },\n\n { SIGABRT, \"SIGABRT - Abort (abnormal termination) signal\" }\n\n };\n\n\n\n void FatalConditionHandler::handleSignal( int sig ) {\n\n char const * name = \"<unknown signal>\";\n\n for (auto const& def : signalDefs) {\n\n if (sig == def.id) {\n\n name = def.name;\n\n break;\n\n }\n\n }\n\n reset();\n\n reportFatal(name);\n\n raise( sig );\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 64, "score": 40324.38251491515 }, { "content": " // Assertion handlers\n\n void handleExpr\n\n ( AssertionInfo const& info,\n\n ITransientExpression const& expr,\n\n AssertionReaction& reaction ) override;\n\n void handleMessage\n\n ( AssertionInfo const& info,\n\n ResultWas::OfType resultType,\n\n StringRef const& message,\n\n AssertionReaction& reaction ) override;\n\n void handleUnexpectedExceptionNotThrown\n\n ( AssertionInfo const& info,\n\n AssertionReaction& reaction ) override;\n\n void handleUnexpectedInflightException\n\n ( AssertionInfo const& info,\n\n std::string const& message,\n\n AssertionReaction& reaction ) override;\n\n void handleIncomplete\n\n ( AssertionInfo const& info ) override;\n\n void handleNonExpr\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 65, "score": 40324.31854572717 }, { "content": "\n\n template<typename RhsT>\n\n auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n\n return { static_cast<bool>(m_lhs > rhs), m_lhs, \">\", rhs };\n\n }\n\n template<typename RhsT>\n\n auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n\n return { static_cast<bool>(m_lhs < rhs), m_lhs, \"<\", rhs };\n\n }\n\n template<typename RhsT>\n\n auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n\n return { static_cast<bool>(m_lhs >= rhs), m_lhs, \">=\", rhs };\n\n }\n\n template<typename RhsT>\n\n auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {\n\n return { static_cast<bool>(m_lhs <= rhs), m_lhs, \"<=\", rhs };\n\n }\n\n\n\n auto makeUnaryExpr() const -> UnaryExpr<LhsT> {\n\n return UnaryExpr<LhsT>{ m_lhs };\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 66, "score": 40324.28713780219 }, { "content": " m_tagIsOpen = false;\n\n }\n\n }\n\n\n\n void XmlWriter::writeDeclaration() {\n\n m_os << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\";\n\n }\n\n\n\n void XmlWriter::newlineIfNecessary() {\n\n if( m_needsNewline ) {\n\n m_os << std::endl;\n\n m_needsNewline = false;\n\n }\n\n }\n\n}\n\n// end catch_xmlwriter.cpp\n\n// start catch_reporter_bases.cpp\n\n\n\n#include <cstring>\n\n#include <cfloat>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 67, "score": 40324.284339428814 }, { "content": "#endif// CATCH_CONFIG_DISABLE_MATCHERS\n\n#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)\n\n\n\n#define CATCH_CHECK( ... ) (void)(0)\n\n#define CATCH_CHECK_FALSE( ... ) (void)(0)\n\n#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)\n\n#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))\n\n#define CATCH_CHECK_NOFAIL( ... ) (void)(0)\n\n\n\n#define CATCH_CHECK_THROWS( ... ) (void)(0)\n\n#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)\n\n#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define CATCH_CHECK_NOTHROW( ... ) (void)(0)\n\n\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n#define CATCH_CHECK_THAT( arg, matcher ) (void)(0)\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 68, "score": 40324.27985408904 }, { "content": " m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );\n\n }\n\n\n\n auto AssertionHandler::allowThrows() const -> bool {\n\n return getCurrentContext().getConfig()->allowThrows();\n\n }\n\n\n\n void AssertionHandler::complete() {\n\n setCompleted();\n\n if( m_reaction.shouldDebugBreak ) {\n\n\n\n // If you find your debugger stopping you here then go one level up on the\n\n // call-stack for the code that caused it (typically a failed assertion)\n\n\n\n // (To go back to the test and change execution, jump over the throw, next)\n\n CATCH_BREAK_INTO_DEBUGGER();\n\n }\n\n if( m_reaction.shouldThrow )\n\n throw Catch::TestFailureException();\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 69, "score": 40324.246121855984 }, { "content": " AssertionReaction& reaction ) = 0;\n\n virtual void handleUnexpectedInflightException\n\n ( AssertionInfo const& info,\n\n std::string const& message,\n\n AssertionReaction& reaction ) = 0;\n\n virtual void handleIncomplete\n\n ( AssertionInfo const& info ) = 0;\n\n virtual void handleNonExpr\n\n ( AssertionInfo const &info,\n\n ResultWas::OfType resultType,\n\n AssertionReaction &reaction ) = 0;\n\n\n\n virtual bool lastAssertionPassed() = 0;\n\n virtual void assertionPassed() = 0;\n\n\n\n // Deprecated, do not use:\n\n virtual std::string getCurrentTestName() const = 0;\n\n virtual const AssertionResult* getLastResult() const = 0;\n\n virtual void exceptionEarlyReported() = 0;\n\n };\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 70, "score": 40324.168110547726 }, { "content": "} // end namespace Catch\n\n\n\n// end catch_commandline.h\n\n#include <fstream>\n\n#include <ctime>\n\n\n\nnamespace Catch {\n\n\n\n clara::Parser makeCommandLineParser( ConfigData& config ) {\n\n\n\n using namespace clara;\n\n\n\n auto const setWarning = [&]( std::string const& warning ) {\n\n auto warningSet = [&]() {\n\n if( warning == \"NoAssertions\" )\n\n return WarnAbout::NoAssertions;\n\n\n\n if ( warning == \"NoTests\" )\n\n return WarnAbout::NoTests;\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 71, "score": 40324.155080986275 }, { "content": "\n\n#define INFO( msg ) (void)(0)\n\n#define WARN( msg ) (void)(0)\n\n#define CAPTURE( msg ) (void)(0)\n\n\n\n#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n\n#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n\n#define METHOD_AS_TEST_CASE( method, ... )\n\n#define REGISTER_TEST_CASE( Function, ... ) (void)(0)\n\n#define SECTION( ... )\n\n#define FAIL( ... ) (void)(0)\n\n#define FAIL_CHECK( ... ) (void)(0)\n\n#define SUCCEED( ... ) (void)(0)\n\n#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))\n\n\n\n#endif\n\n\n\n#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )\n\n\n\n// \"BDD-style\" convenience wrappers\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 72, "score": 40324.076240084854 }, { "content": " if( !assertionResult.isOk() )\n\n populateReaction( reaction );\n\n }\n\n void RunContext::handleUnexpectedExceptionNotThrown(\n\n AssertionInfo const& info,\n\n AssertionReaction& reaction\n\n ) {\n\n handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);\n\n }\n\n\n\n void RunContext::handleUnexpectedInflightException(\n\n AssertionInfo const& info,\n\n std::string const& message,\n\n AssertionReaction& reaction\n\n ) {\n\n m_lastAssertionInfo = info;\n\n\n\n AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );\n\n data.message = message;\n\n AssertionResult assertionResult{ info, data };\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 73, "score": 40323.992251698364 }, { "content": "// See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause\n\n//\n\n// This project is hosted at https://github.com/philsquared/textflowcpp\n\n\n\n\n\n#include <cassert>\n\n#include <ostream>\n\n#include <sstream>\n\n#include <vector>\n\n\n\n#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH\n\n#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80\n\n#endif\n\n\n\nnamespace Catch { namespace clara { namespace TextFlow {\n\n\n\n inline auto isWhitespace( char c ) -> bool {\n\n static std::string chars = \" \\t\\n\\r\";\n\n return chars.find( c ) != std::string::npos;\n\n }\n\n inline auto isBreakableBefore( char c ) -> bool {\n\n static std::string chars = \"[({<|\";\n\n return chars.find( c ) != std::string::npos;\n\n }\n\n inline auto isBreakableAfter( char c ) -> bool {\n\n static std::string chars = \"])}>.,:;*+-=&/\\\\\";\n\n return chars.find( c ) != std::string::npos;\n\n }\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 74, "score": 40323.98514869541 }, { "content": "#define WHEN( desc ) SECTION( std::string(\" When: \") + desc )\n\n#define AND_WHEN( desc ) SECTION( std::string(\"And when: \") + desc )\n\n#define THEN( desc ) SECTION( std::string(\" Then: \") + desc )\n\n#define AND_THEN( desc ) SECTION( std::string(\" And: \") + desc )\n\n\n\nusing Catch::Detail::Approx;\n\n\n\n#else\n\n//////\n\n// If this config identifier is defined then all CATCH macros are prefixed with CATCH_\n\n#ifdef CATCH_CONFIG_PREFIX_ALL\n\n\n\n#define CATCH_REQUIRE( ... ) (void)(0)\n\n#define CATCH_REQUIRE_FALSE( ... ) (void)(0)\n\n\n\n#define CATCH_REQUIRE_THROWS( ... ) (void)(0)\n\n#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)\n\n#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 75, "score": 40323.978696765764 }, { "content": " void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->testCaseStarting( testInfo );\n\n }\n\n\n\n void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->sectionStarting( sectionInfo );\n\n }\n\n\n\n void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {\n\n for( auto const& reporter : m_reporters )\n\n reporter->assertionStarting( assertionInfo );\n\n }\n\n\n\n // The return value indicates if the messages buffer should be cleared:\n\n bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {\n\n bool clearBuffer = false;\n\n for( auto const& reporter : m_reporters )\n\n clearBuffer |= reporter->assertionEnded( assertionStats );\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 76, "score": 40323.954384104625 }, { "content": " m_mode = None;\n\n }\n\n\n\n void addFilter();\n\n };\n\n TestSpec parseTestSpec( std::string const& arg );\n\n\n\n} // namespace Catch\n\n\n\n#ifdef __clang__\n\n#pragma clang diagnostic pop\n\n#endif\n\n\n\n// end catch_test_spec_parser.h\n\n// start catch_interfaces_config.h\n\n\n\n#include <iosfwd>\n\n#include <string>\n\n#include <vector>\n\n#include <memory>\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 77, "score": 40323.941441870455 }, { "content": "#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )\n\n#define CATCH_GIVEN( desc )\n\n#define CATCH_WHEN( desc )\n\n#define CATCH_AND_WHEN( desc )\n\n#define CATCH_THEN( desc )\n\n#define CATCH_AND_THEN( desc )\n\n\n\n// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required\n\n#else\n\n\n\n#define REQUIRE( ... ) (void)(0)\n\n#define REQUIRE_FALSE( ... ) (void)(0)\n\n\n\n#define REQUIRE_THROWS( ... ) (void)(0)\n\n#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)\n\n#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)\n\n#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)\n\n#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)\n\n#endif // CATCH_CONFIG_DISABLE_MATCHERS\n\n#define REQUIRE_NOTHROW( ... ) (void)(0)\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 78, "score": 40323.91332148722 }, { "content": " }\n\n\n\n void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {\n\n m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );\n\n }\n\n\n\n std::string ExceptionTranslatorRegistry::translateActiveException() const {\n\n try {\n\n#ifdef __OBJC__\n\n // In Objective-C try objective-c exceptions first\n\n @try {\n\n return tryTranslators();\n\n }\n\n @catch (NSException *exception) {\n\n return Catch::Detail::stringify( [exception description] );\n\n }\n\n#else\n\n // Compiling a mixed mode project with MSVC means that CLR\n\n // exceptions will be caught in (...) as well. However, these\n\n // do not fill-in std::current_exception and thus lead to crash\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 79, "score": 40323.91085293143 }, { "content": " }\n\n void Session::libIdentify() {\n\n Catch::cout()\n\n << std::left << std::setw(16) << \"description: \" << \"A Catch test executable\\n\"\n\n << std::left << std::setw(16) << \"category: \" << \"testframework\\n\"\n\n << std::left << std::setw(16) << \"framework: \" << \"Catch Test\\n\"\n\n << std::left << std::setw(16) << \"version: \" << libraryVersion() << std::endl;\n\n }\n\n\n\n int Session::applyCommandLine( int argc, char const * const * argv ) {\n\n if( m_startupExceptions )\n\n return 1;\n\n\n\n auto result = m_cli.parse( clara::Args( argc, argv ) );\n\n if( !result ) {\n\n Catch::cerr()\n\n << Colour( Colour::Red )\n\n << \"\\nError(s) in input:\\n\"\n\n << Column( result.errorMessage() ).indent( 2 )\n\n << \"\\n\\n\";\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 80, "score": 40323.89435292007 }, { "content": "\n\n#if defined(_MSC_VER)\n\n#pragma warning(pop)\n\n#endif\n\n// end catch_reporter_console.cpp\n\n// start catch_reporter_junit.cpp\n\n\n\n#include <assert.h>\n\n#include <sstream>\n\n#include <ctime>\n\n#include <algorithm>\n\n\n\nnamespace Catch {\n\n\n\n namespace {\n\n std::string getCurrentTimestamp() {\n\n // Beware, this is not reentrant because of backward compatibility issues\n\n // Also, UTC only, again because of backward compatibility (%z is C++11)\n\n time_t rawtime;\n\n std::time(&rawtime);\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 81, "score": 40323.841332528886 }, { "content": " bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }\n\n bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }\n\n\n\n} // end namespace Catch\n\n// end catch_result_type.cpp\n\n// start catch_run_context.cpp\n\n\n\n#include <cassert>\n\n#include <algorithm>\n\n#include <sstream>\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 82, "score": 40323.83687965418 }, { "content": " std::size_t listTags( Config const& config );\n\n\n\n std::size_t listReporters( Config const& /*config*/ );\n\n\n\n Option<std::size_t> list( Config const& config );\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_list.h\n\n// start catch_text.h\n\n\n\nnamespace Catch {\n\n using namespace clara::TextFlow;\n\n}\n\n\n\n// end catch_text.h\n\n#include <limits>\n\n#include <algorithm>\n\n#include <iomanip>\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 83, "score": 40323.83687965418 }, { "content": "\n\n} // end namespace Catch\n\n// end catch_test_case_registry_impl.cpp\n\n// start catch_test_case_tracker.cpp\n\n\n\n#include <algorithm>\n\n#include <assert.h>\n\n#include <stdexcept>\n\n#include <memory>\n\n#include <sstream>\n\n\n\n#if defined(__clang__)\n\n# pragma clang diagnostic push\n\n# pragma clang diagnostic ignored \"-Wexit-time-destructors\"\n\n#endif\n\n\n\nnamespace Catch {\n\nnamespace TestCaseTracking {\n\n\n\n NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 84, "score": 40323.75527712713 }, { "content": " // of 256 tests has failed\n\n return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));\n\n }\n\n catch( std::exception& ex ) {\n\n Catch::cerr() << ex.what() << std::endl;\n\n return MaxExitCode;\n\n }\n\n }\n\n\n\n} // end namespace Catch\n\n// end catch_session.cpp\n\n// start catch_startup_exception_registry.cpp\n\n\n\nnamespace Catch {\n\n void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {\n\n try {\n\n m_exceptions.push_back(exception);\n\n }\n\n catch(...) {\n\n // If we run out of memory during start-up there's really not a lot more we can do about it\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 85, "score": 40323.69371289471 }, { "content": " void swap( StringRef& other ) noexcept;\n\n\n\n public: // operators\n\n auto operator == ( StringRef const& other ) const noexcept -> bool;\n\n auto operator != ( StringRef const& other ) const noexcept -> bool;\n\n\n\n auto operator[] ( size_type index ) const noexcept -> char;\n\n\n\n public: // named queries\n\n auto empty() const noexcept -> bool {\n\n return m_size == 0;\n\n }\n\n auto size() const noexcept -> size_type {\n\n return m_size;\n\n }\n\n\n\n auto numberOfCharacters() const noexcept -> size_type;\n\n auto c_str() const -> char const*;\n\n\n\n public: // substrings and searches\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 86, "score": 40323.66995964057 }, { "content": " throw std::domain_error\n\n ( \"Invalid Approx::margin: \" +\n\n Catch::Detail::stringify( marginAsDouble ) +\n\n \", Approx::Margin has to be non-negative.\" );\n\n\n\n }\n\n m_margin = marginAsDouble;\n\n return *this;\n\n }\n\n\n\n template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>\n\n Approx& scale( T const& newScale ) {\n\n m_scale = static_cast<double>(newScale);\n\n return *this;\n\n }\n\n\n\n std::string toString() const;\n\n\n\n private:\n\n double m_epsilon;\n\n double m_margin;\n\n double m_scale;\n\n double m_value;\n\n };\n\n}\n\n\n\ntemplate<>\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 87, "score": 40323.66642038128 }, { "content": " double durationInSeconds;\n\n };\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_section_info.h\n\n// start catch_timer.h\n\n\n\n#include <cstdint>\n\n\n\nnamespace Catch {\n\n\n\n auto getCurrentNanosecondsSinceEpoch() -> uint64_t;\n\n auto getEstimatedClockResolution() -> uint64_t;\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 88, "score": 40323.63002939796 }, { "content": " return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);\n\n}\n\n\n\nFloating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {\n\n return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);\n\n}\n\n\n\nFloating::WithinAbsMatcher WithinAbs(double target, double margin) {\n\n return Floating::WithinAbsMatcher(target, margin);\n\n}\n\n\n\n} // namespace Matchers\n\n} // namespace Catch\n\n\n\n// end catch_matchers_floating.cpp\n\n// start catch_matchers_generic.cpp\n\n\n\nstd::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {\n\n if (desc.empty()) {\n\n return \"matches undescribed predicate\";\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 89, "score": 40323.56405661911 }, { "content": " }\n\n\n\n bool WithinUlpsMatcher::match(double const& matchee) const {\n\n switch (m_type) {\n\n case FloatingPointKind::Float:\n\n return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);\n\n case FloatingPointKind::Double:\n\n return almostEqualUlps<double>(matchee, m_target, m_ulps);\n\n default:\n\n throw std::domain_error(\"Unknown FloatingPointKind value\");\n\n }\n\n }\n\n\n\n std::string WithinUlpsMatcher::describe() const {\n\n return \"is within \" + std::to_string(m_ulps) + \" ULPs of \" + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? \"f\" : \"\");\n\n }\n\n\n\n}// namespace Floating\n\n\n\nFloating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 90, "score": 40323.46297203776 }, { "content": " InRandomOrder\n\n }; };\n\n struct UseColour { enum YesOrNo {\n\n Auto,\n\n Yes,\n\n No\n\n }; };\n\n struct WaitForKeypress { enum When {\n\n Never,\n\n BeforeStart = 1,\n\n BeforeExit = 2,\n\n BeforeStartAndExit = BeforeStart | BeforeExit\n\n }; };\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 91, "score": 40323.3853886735 }, { "content": "#endif\n\n// end catch_stream.cpp\n\n// start catch_string_manip.cpp\n\n\n\n#include <algorithm>\n\n#include <ostream>\n\n#include <cstring>\n\n#include <cctype>\n\n\n\nnamespace Catch {\n\n\n\n bool startsWith( std::string const& s, std::string const& prefix ) {\n\n return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());\n\n }\n\n bool startsWith( std::string const& s, char prefix ) {\n\n return !s.empty() && s[0] == prefix;\n\n }\n\n bool endsWith( std::string const& s, std::string const& suffix ) {\n\n return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 92, "score": 40323.381327618146 }, { "content": " // Windows can easily distinguish between SO and SigSegV,\n\n // but SigInt, SigTerm, etc are handled differently.\n\n static SignalDefs signalDefs[] = {\n\n { EXCEPTION_ILLEGAL_INSTRUCTION, \"SIGILL - Illegal instruction signal\" },\n\n { EXCEPTION_STACK_OVERFLOW, \"SIGSEGV - Stack overflow\" },\n\n { EXCEPTION_ACCESS_VIOLATION, \"SIGSEGV - Segmentation violation signal\" },\n\n { EXCEPTION_INT_DIVIDE_BY_ZERO, \"Divide by zero error\" },\n\n };\n\n\n\n LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {\n\n for (auto const& def : signalDefs) {\n\n if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {\n\n reportFatal(def.name);\n\n }\n\n }\n\n // If its not an exception we care about, pass it along.\n\n // This stops us from eating debugger breaks etc.\n\n return EXCEPTION_CONTINUE_SEARCH;\n\n }\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 93, "score": 40323.335552053075 }, { "content": " })) {}\n\nConsoleReporter::~ConsoleReporter() = default;\n\n\n\nstd::string ConsoleReporter::getDescription() {\n\n return \"Reports test results as plain lines of text\";\n\n}\n\n\n\nvoid ConsoleReporter::noMatchingTestCases(std::string const& spec) {\n\n stream << \"No test cases matched '\" << spec << '\\'' << std::endl;\n\n}\n\n\n\nvoid ConsoleReporter::assertionStarting(AssertionInfo const&) {}\n\n\n\nbool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {\n\n AssertionResult const& result = _assertionStats.assertionResult;\n\n\n\n bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();\n\n\n\n // Drop out if result was successful but we're not printing them.\n\n if (!includeResults && result.getResultType() != ResultWas::Warning)\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 94, "score": 40323.31452315679 }, { "content": " assertionEnded( assertionResult );\n\n populateReaction( reaction );\n\n }\n\n\n\n void RunContext::populateReaction( AssertionReaction& reaction ) {\n\n reaction.shouldDebugBreak = m_config->shouldDebugBreak();\n\n reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);\n\n }\n\n\n\n void RunContext::handleIncomplete(\n\n AssertionInfo const& info\n\n ) {\n\n m_lastAssertionInfo = info;\n\n\n\n AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );\n\n data.message = \"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE\";\n\n AssertionResult assertionResult{ info, data };\n\n assertionEnded( assertionResult );\n\n }\n\n void RunContext::handleNonExpr(\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 95, "score": 40323.24367626987 }, { "content": "\n\n void printTotals(Totals const& totals);\n\n void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);\n\n\n\n void printTotalsDivider(Totals const& totals);\n\n void printSummaryDivider();\n\n\n\n private:\n\n bool m_headerPrinted = false;\n\n };\n\n\n\n} // end namespace Catch\n\n\n\n#if defined(_MSC_VER)\n\n#pragma warning(pop)\n\n#endif\n\n\n\n// end catch_reporter_console.h\n\n// start catch_reporter_junit.h\n\n\n\n// start catch_xmlwriter.h\n\n\n\n#include <vector>\n\n\n\nnamespace Catch {\n\n\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 96, "score": 40323.236405697586 }, { "content": " FatalConditionHandler::FatalConditionHandler() {\n\n isSet = true;\n\n // 32k seems enough for Catch to handle stack overflow,\n\n // but the value was found experimentally, so there is no strong guarantee\n\n guaranteeSize = 32 * 1024;\n\n exceptionHandlerHandle = nullptr;\n\n // Register as first handler in current chain\n\n exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);\n\n // Pass in guarantee size to be filled\n\n SetThreadStackGuarantee(&guaranteeSize);\n\n }\n\n\n\n void FatalConditionHandler::reset() {\n\n if (isSet) {\n\n RemoveVectoredExceptionHandler(exceptionHandlerHandle);\n\n SetThreadStackGuarantee(&guaranteeSize);\n\n exceptionHandlerHandle = nullptr;\n\n isSet = false;\n\n }\n\n }\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 97, "score": 40323.217787159425 }, { "content": " catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \\\n\n } \\\n\n catch( ... ) { \\\n\n catchAssertionHandler.handleExceptionThrownAsExpected(); \\\n\n } \\\n\n else \\\n\n catchAssertionHandler.handleThrowingCallSkipped(); \\\n\n INTERNAL_CATCH_REACT( catchAssertionHandler ) \\\n\n } while( false )\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \\\n\n do { \\\n\n Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) \", \" CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \\\n\n if( catchAssertionHandler.allowThrows() ) \\\n\n try { \\\n\n static_cast<void>(expr); \\\n\n catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \\\n\n } \\\n\n catch( exceptionType const& ) { \\\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 98, "score": 40323.15407956365 }, { "content": "\n\n virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;\n\n virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;\n\n\n\n virtual void pushScopedMessage( MessageInfo const& message ) = 0;\n\n virtual void popScopedMessage( MessageInfo const& message ) = 0;\n\n\n\n virtual void handleFatalErrorCondition( StringRef message ) = 0;\n\n\n\n virtual void handleExpr\n\n ( AssertionInfo const& info,\n\n ITransientExpression const& expr,\n\n AssertionReaction& reaction ) = 0;\n\n virtual void handleMessage\n\n ( AssertionInfo const& info,\n\n ResultWas::OfType resultType,\n\n StringRef const& message,\n\n AssertionReaction& reaction ) = 0;\n\n virtual void handleUnexpectedExceptionNotThrown\n\n ( AssertionInfo const& info,\n", "file_path": "tests/lib/Catch2/include/catch.hpp", "rank": 99, "score": 40323.13478939818 } ]
C++
MagicSquareAndPipes.cpp
Sigrec/School-Projects
54dec4b6d38eb9b0c020c02d2a7f57b14e52bce2
#include <iostream> #include <unistd.h> #include <sys/utsname.h> #include <math.h> #include <cstring> #include <sys/wait.h> #define SQUARE_SIZE 9 // The max number of characters that can be used for a sequence void DisplaySystemInfo(){ printf("System Info: \n"); char domainname[256]; char hostname[256]; utsname userdata; if (getdomainname(domainname, 256) == 0){ printf("Domain Name: %s\n", domainname); } else { perror("getdomainname() error"); } if (gethostname(hostname, 256) == 0){ printf("Host Name: %s\n", hostname); } else { perror("gethostname() error"); } if (uname(&userdata) == 0){ printf("System Name: %s\n", userdata.sysname); printf("Node Name: %s\n", userdata.nodename); printf("Release: %s\n", userdata.release); printf("Version: %s\n", userdata.version); printf("Machine: %s\n", userdata.machine); printf("Domain Name: %s\n\n", userdata.domainname); } else { perror("uname() error"); } } char GenerateMagicSquare(char *sequence){ int square[3][3]; char answer; int size = sqrt(SQUARE_SIZE); for (int x = 0; x < size; x++){ for (int y = 0; y < size; y++){ square[x][y] = (int) (sequence[y + (x * 3)] - '0'); } } int magicNum = square[0][0] + square[0][1] + square[0][2]; int topLeftToBottomRightDiag = 0, topRightToBottomLeftDiag = 0, rows = 0, cols = 0; for (int x = 0; x < size; x++){ topLeftToBottomRightDiag += square[x][x]; topRightToBottomLeftDiag += square[x][(size - 1) - x]; for (int y = 0; y < size; y++){ rows += square[x][y]; cols += square[y][x]; } if (rows != cols){ answer = 'F'; goto EXIT; } rows = 0; cols = 0; } if ((topLeftToBottomRightDiag == topRightToBottomLeftDiag) && (topRightToBottomLeftDiag == magicNum)){ answer = 'T'; } else{ answer = 'F'; } EXIT: return answer; } bool ValidMagicSquare(char *sequence){ bool validSeq = true; int inputSize = strlen(sequence); for (int x = 0; x < inputSize - 1; x++){ if (!isdigit(sequence[x])){ printf("Input Magic Square Contains Non-Numerical Characters, TRY AGAIN\n"); validSeq = false; goto NEXT; } } NEXT: if (inputSize < SQUARE_SIZE){ printf("Input Magic Square Sequence is too Small, TRY AGAIN\n"); validSeq = false; } else if (inputSize > SQUARE_SIZE) { printf("Input Magic Square Sequence is too Big, TRY AGAIN\n"); validSeq = false; } return validSeq; } int main(int argc, char **argv) { char *inputSquare; do{ printf("Enter 9 Digit Sequence: "); scanf("%s", inputSquare); } while(!ValidMagicSquare(inputSquare)); int client[2]; int server[2]; if (pipe(client) < 0){ fprintf(stderr, "Client Pipe Failed -> %s\n", strerror(errno)); } if (pipe(server) < 0){ fprintf(stderr, "Server Pipe Failed -> %s\n", strerror(errno)); } pid_t pid = fork(); if (pid < 0){ fprintf(stderr, "Fork Failed: %s\n", strerror(errno)); exit(0); } if (pid == 0){ close(client[1]); close(server[0]); char userInputSquare[SQUARE_SIZE + 1]; if (read(client[0], &userInputSquare, sizeof(char) * SQUARE_SIZE + 1) < 0){ fprintf(stderr, "Read From Pipe Failed: %s\n", strerror(errno)); } char answer = GenerateMagicSquare(userInputSquare); if (write(server[1], &answer, sizeof(char) * 2) < 0){ fprintf(stderr, "Write to Pipe Failed: %s\n", strerror(errno)); } close(client[0]); close(server[1]); } else{ system("clear"); close(client[0]); close(server[1]); char answer[2]; if (write(client[1], inputSquare, sizeof(char) * SQUARE_SIZE + 1) < 0){ fprintf(stderr, "Write to Client Failed -> %s", strerror(errno)); } if (read(server[0], answer, sizeof(char) * 2) < 0){ fprintf(stderr, "Read From Pipe Failed: %s", strerror(errno)); } wait(NULL); printf("Sequence Tested: %s\nMagic Square Result: %s\n\n", inputSquare, answer); DisplaySystemInfo(); close(server[0]); close(client[1]); } return 0; }
#include <iostream> #include <unistd.h> #include <sys/utsname.h> #include <math.h> #include <cstring> #include <sys/wait.h> #define SQUARE_SIZE 9 // The max number of characters that can be used for a sequence void DisplaySystemInfo(){ printf("System Info: \n"); char domainname[256]; char hostname[256]; utsname userdata; if (getdomainname(domainname, 256) == 0){ printf("Domain Name: %s\n", domainname); } else { perror("getdomainname() error"); }
if (uname(&userdata) == 0){ printf("System Name: %s\n", userdata.sysname); printf("Node Name: %s\n", userdata.nodename); printf("Release: %s\n", userdata.release); printf("Version: %s\n", userdata.version); printf("Machine: %s\n", userdata.machine); printf("Domain Name: %s\n\n", userdata.domainname); } else { perror("uname() error"); } } char GenerateMagicSquare(char *sequence){ int square[3][3]; char answer; int size = sqrt(SQUARE_SIZE); for (int x = 0; x < size; x++){ for (int y = 0; y < size; y++){ square[x][y] = (int) (sequence[y + (x * 3)] - '0'); } } int magicNum = square[0][0] + square[0][1] + square[0][2]; int topLeftToBottomRightDiag = 0, topRightToBottomLeftDiag = 0, rows = 0, cols = 0; for (int x = 0; x < size; x++){ topLeftToBottomRightDiag += square[x][x]; topRightToBottomLeftDiag += square[x][(size - 1) - x]; for (int y = 0; y < size; y++){ rows += square[x][y]; cols += square[y][x]; } if (rows != cols){ answer = 'F'; goto EXIT; } rows = 0; cols = 0; } if ((topLeftToBottomRightDiag == topRightToBottomLeftDiag) && (topRightToBottomLeftDiag == magicNum)){ answer = 'T'; } else{ answer = 'F'; } EXIT: return answer; } bool ValidMagicSquare(char *sequence){ bool validSeq = true; int inputSize = strlen(sequence); for (int x = 0; x < inputSize - 1; x++){ if (!isdigit(sequence[x])){ printf("Input Magic Square Contains Non-Numerical Characters, TRY AGAIN\n"); validSeq = false; goto NEXT; } } NEXT: if (inputSize < SQUARE_SIZE){ printf("Input Magic Square Sequence is too Small, TRY AGAIN\n"); validSeq = false; } else if (inputSize > SQUARE_SIZE) { printf("Input Magic Square Sequence is too Big, TRY AGAIN\n"); validSeq = false; } return validSeq; } int main(int argc, char **argv) { char *inputSquare; do{ printf("Enter 9 Digit Sequence: "); scanf("%s", inputSquare); } while(!ValidMagicSquare(inputSquare)); int client[2]; int server[2]; if (pipe(client) < 0){ fprintf(stderr, "Client Pipe Failed -> %s\n", strerror(errno)); } if (pipe(server) < 0){ fprintf(stderr, "Server Pipe Failed -> %s\n", strerror(errno)); } pid_t pid = fork(); if (pid < 0){ fprintf(stderr, "Fork Failed: %s\n", strerror(errno)); exit(0); } if (pid == 0){ close(client[1]); close(server[0]); char userInputSquare[SQUARE_SIZE + 1]; if (read(client[0], &userInputSquare, sizeof(char) * SQUARE_SIZE + 1) < 0){ fprintf(stderr, "Read From Pipe Failed: %s\n", strerror(errno)); } char answer = GenerateMagicSquare(userInputSquare); if (write(server[1], &answer, sizeof(char) * 2) < 0){ fprintf(stderr, "Write to Pipe Failed: %s\n", strerror(errno)); } close(client[0]); close(server[1]); } else{ system("clear"); close(client[0]); close(server[1]); char answer[2]; if (write(client[1], inputSquare, sizeof(char) * SQUARE_SIZE + 1) < 0){ fprintf(stderr, "Write to Client Failed -> %s", strerror(errno)); } if (read(server[0], answer, sizeof(char) * 2) < 0){ fprintf(stderr, "Read From Pipe Failed: %s", strerror(errno)); } wait(NULL); printf("Sequence Tested: %s\nMagic Square Result: %s\n\n", inputSquare, answer); DisplaySystemInfo(); close(server[0]); close(client[1]); } return 0; }
if (gethostname(hostname, 256) == 0){ printf("Host Name: %s\n", hostname); } else { perror("gethostname() error"); }
if_condition
[ { "content": "\tprivate final String cityName;\n", "file_path": "Dijkstra Airport Project/City.java", "rank": 0, "score": 20715.04630860246 }, { "content": "#include <iostream>\n\n#include <vector>\n\n#include \"Part3ThreadedModifier.h\"\n\n#include \"FileModifyException.h\"\n\n#include \"FileManipulation.h\"\n\n#include \"Util.h\"\n\n#include \"Modifier.h\"\n\n\n\nusing namespace std;\n\nstd::vector<EntryInfo> outputEntries;\n\nconst char* outputFile;\n\n\n\nvoid Part3ThreadedModifier::doSetup(IOType ioType) {\n\n pthread_mutex_init(&mutex, nullptr);\n\n pthread_cond_init(&condition, nullptr);\n\n}\n\n\n\nvoid Part3ThreadedModifier::modifyAndCopyFile(const char *sourceFile, const char *destFile) {\n\n outputFile = destFile;\n\n std::vector<EntryInfo> entries = FileManipulation::readFromFile(FileManipulation::getReadFD(sourceFile), true);\n", "file_path": "Binary File Manipulation/Part3ThreadedModifier.cpp", "rank": 3, "score": 11.481052974980756 }, { "content": "#include \"FileManipulation.h\"\n\n#include \"FileModifyException.h\"\n\n#include \"Util.h\"\n\n#include <iostream>\n\n#include <cstdio>\n\n#include <fcntl.h>\n\n#include <unistd.h>\n\n#include <ctime>\n\n#include <vector>\n\n#include <cstring>\n\n\n\nint numItems;\n\ntime_t dateAndTime;\n\nint itemID;\n\nint quantity;\n\nfloat price;\n\nconst int bufferSize = 50;\n\nchar itemName[bufferSize];\n\nchar* copy;\n\n\n", "file_path": "Binary File Manipulation/FileManipulation.cpp", "rank": 4, "score": 11.150794792164316 }, { "content": "#include <unistd.h>\n\n#include <iostream>\n\n#include <cstring>\n\n#include <vector>\n\n#include <sys/wait.h>\n\n#include \"Part2MultiProcessModifier.h\"\n\n#include \"PipeMaker.h\"\n\n#include \"FileModifyException.h\"\n\n#include \"FileManipulation.h\"\n\n#include \"Util.h\"\n\n\n\nusing namespace std;\n\nint childFD, parentFD, pid;\n\n\n\nvoid Part2MultiProcessModifier::doSetup(IOType ioType) {\n\n if (ioType == IOType::WRITE){\n\n return;\n\n }\n\n\n\n PipeMaker pipe;\n", "file_path": "Binary File Manipulation/Part2MultiProcessModifier.cpp", "rank": 7, "score": 9.744951014281932 }, { "content": "#include \"Part1SimpleFileModifier.h\"\n\n#include \"FileModifyException.h\"\n\n#include \"FileManipulation.h\"\n\n#include <vector>\n\n#include \"Util.h\"\n\n\n\nusing namespace std;\n\n\n\nvoid Part1SimpleFileModifier::modifyAndCopyFile(const char *sourceFile, const char *destFile) {\n\n std::vector<EntryInfo> entries = FileManipulation::readFromFile(FileManipulation::getReadFD(sourceFile), true);\n\n FileManipulation::writeToFile(FileManipulation::getWriteFD(destFile), entries);\n\n}", "file_path": "Binary File Manipulation/Part1SimpleFileModifier.cpp", "rank": 8, "score": 9.411401099682719 }, { "content": "#include <iostream>\n\n#include <unistd.h>\n\n#include <cstring>\n\n#include <sys/socket.h>\n\n#include <arpa/inet.h>\n\n#include \"Part4SocketModifier.h\"\n\n#include \"FileModifyException.h\"\n\n#include \"PipeMaker.h\"\n\n#include \"FileManipulation.h\"\n\n#include \"Util.h\"\n\n\n\nvoid Part4SocketModifier::doSetup(IOType ioType) {\n\n this->ioType = ioType;\n\n if (ioType == IOType::WRITE){\n\n return;\n\n }\n\n\n\n PipeMaker pipe;\n\n int pid2 = fork();\n\n if (pid2 > 0){\n", "file_path": "Binary File Manipulation/Part4SocketModifier.cpp", "rank": 10, "score": 8.420177824191338 }, { "content": " copy = new char[bufferSize];\n\n strncpy(copy, itemName, bufferSize);\n\n read(fd, &quantity, sizeof(int));\n\n read(fd, &price, sizeof(float));\n\n EntryInfo entry = {.timestamp = dateAndTime, .itemID = itemID, .itemName = copy + '\\0', .quantity = quantity, .price = price};\n\n entries.insert(entries.end(), entry);\n\n count++;\n\n }\n\n\n\n if (newEntries){\n\n numItems += 2;\n\n EntryInfo newEntry1 = {.timestamp = 1612195200, .itemID = 4636152, .itemName = \"A Programming Guide to Linux Commands, Editors, and Shell Programming by Sobell\", .quantity = 70, .price = 70.99};\n\n EntryInfo newEntry2 = {.timestamp = 1613412000, .itemID = 6530927, .itemName = \"Advanced Programming in the UNIX Environment by Stevens and Rago\", .quantity = 68, .price = 89.99};\n\n entries.push_back(newEntry1); entries.push_back(newEntry2);\n\n }\n\n\n\n for (auto& entry : entries){\n\n copy = new char[bufferSize];\n\n strncpy(copy, entry.itemName, bufferSize - 1);\n\n entry.itemName = copy;\n", "file_path": "Binary File Manipulation/FileManipulation.cpp", "rank": 12, "score": 6.391603761745859 }, { "content": " }\n\n\n\n close(fd);\n\n return entries;\n\n}\n\n\n\nint FileManipulation::getWriteFD(const char *destFile){\n\n int fd = open(destFile, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);\n\n if (fd < 0){\n\n std::cerr << \"Destination File Error: \" << strerror(errno) << std::endl; exit(1);\n\n }\n\n return fd;\n\n}\n\nvoid FileManipulation::writeToFile(int fd, std::vector<EntryInfo> entries){\n\n write(fd, &numItems, sizeof(int));\n\n for (auto const& entry : entries){\n\n write(fd, &entry.timestamp, sizeof(time_t));\n\n write(fd, &entry.itemID, sizeof(int));\n\n write(fd, entry.itemName, bufferSize * sizeof(char));\n\n write(fd, &entry.quantity, sizeof(int));\n\n write(fd, &entry.price, sizeof(float));\n\n }\n\n\n\n close(fd);\n\n}", "file_path": "Binary File Manipulation/FileManipulation.cpp", "rank": 13, "score": 6.301672292945685 }, { "content": "\n\n#define MIN_SLEEP_DURATION 25 //Min time spent for the operations of eating and sleeping in miliseconds\n\n#define MAX_SLEEP_DURATION 49 //Max time spent for the operations of eating and sleeping in miliseconds\n\n\n\nsem_t utensil[5]; //The 5 sempahores used to represent the available forks on the table\n\nsem_t room; //Semaphore used to limit the number of philosophers in the room at once\n\ndouble timeSpentEating[] = {0,0,0,0,0,0,0,0,0,0}; //Stores the time spent and the number of times the philosopher ate\n\ndouble timeSpentThinking[] = {0,0,0,0,0,0,0,0,0,0}; //Stores the time spent and the number of times the philosopher thought\n\n\n\n/********************************************************************************************************************************************\n\n * double EatOrThink()\n\n * Author: Sean Njenga\n\n * Modified on: 20 October 2021\n\n * by: Sean Njenga\n\n * Description: Generates a random long number between in range [25,49], and then sleeps for that number of milliseconds.\n\n * Records and returns the entire time spent in the method.\n\n * \n\n * Parameters: \n\n * EatOrThink O/P double The amount of time spent in this method.\n\n ********************************************************************************************************************************************/\n", "file_path": "DiningPhilosopherProblem.cpp", "rank": 14, "score": 6.1877801008799995 }, { "content": "int FileManipulation::getReadFD(const char *sourceFile){\n\n int fd = open(sourceFile, O_RDONLY, S_IRUSR);\n\n if (fd < 0) {\n\n std::cerr << \"Source File Error: \" << strerror(errno) << std::endl; exit(1);\n\n }\n\n return fd;\n\n}\n\nstd::vector<EntryInfo> FileManipulation::readFromFile(int fd, bool newEntries){\n\n read(fd, &numItems, sizeof(int));\n\n if (numItems < 0){\n\n close(fd);\n\n throw FileModifyException(\"File is Empty\");\n\n }\n\n\n\n int count = 1;\n\n std::vector<EntryInfo> entries;\n\n while (count <= numItems){\n\n read(fd, &dateAndTime, sizeof(time_t));\n\n read(fd, &itemID, sizeof(int));\n\n read(fd, itemName, bufferSize * sizeof(char));\n", "file_path": "Binary File Manipulation/FileManipulation.cpp", "rank": 15, "score": 6.0441220237344515 }, { "content": " * Author: Sean Njenga\n\n * Modified on: 10 November 2021\n\n * by: Sean Njenga\n\n * Description: Creates the arrays to store the generated data and runs a \"Monte Carlo Simulation\" against three different page replacement\n\n * algorithms, Least Recently Used (LRU), First In First Out (FIFO), and Clock over 1000 experiments. Each randomly generated \n\n * memory page must contain one-thousand page numbers separated into ten regions where each region has a base page number equal\n\n * to ten times its region number. Then memory page value is adjusted using a normal, random number distribution with a mean of \n\n * ten and a standard deviation of two.\n\n * \n\n * Parameters: \n\n* main O/P int Status code (not currently used). \n\n ********************************************************************************************************************************************/\n\nint main(){\n\n int lruResults[MAX_WORKING_SET_SIZE - MIN_WORKING_SET_SIZE + 1] = { };\n\n int fifoResults[MAX_WORKING_SET_SIZE - MIN_WORKING_SET_SIZE + 1] = { };\n\n int clockResults[MAX_WORKING_SET_SIZE - MIN_WORKING_SET_SIZE + 1] = { };\n\n int data[TOTAL_MEMORY_PAGES]; // Array of pages or data to use for testing algorithms.\n\n\n\n std::default_random_engine gen;\n\n std::normal_distribution<float> normalDis(MU, SIGMA); // Generate normal distribution given mean and standard deviation\n", "file_path": "MonteCarloSim.cpp", "rank": 16, "score": 5.938500805932119 }, { "content": " for (int x = 0; x < 7; x++){\n\n pthread_cond_signal(&condition);\n\n pthread_cond_wait(&condition, &mutex);\n\n outputEntries.push_back(infoBtwThreads);\n\n }\n\n pthread_mutex_unlock(&mutex);\n\n FileManipulation::writeToFile(FileManipulation::getWriteFD(outputFile), outputEntries);\n\n}\n\n\n\n// Use this as the starting point for the thread you create\n\nvoid *Part3ThreadedModifier::threadEntry(void* arg) noexcept{\n\n Part3ThreadedModifier* modifier = (Part3ThreadedModifier*) arg;\n\n try{\n\n modifier->outputThread();\n\n } catch (FileModifyException e){\n\n cerr << \"Receiving thread failed: \" << e.what() << endl;\n\n exit(1);\n\n } catch (exception e){\n\n cerr << \"Receiving thread failed: \" << e.what() << endl;\n\n exit(1);\n\n } catch (...){\n\n cerr << \"Unknown error in receiving thread: \" << endl;\n\n exit(1);\n\n }\n\n return nullptr;\n\n}", "file_path": "Binary File Manipulation/Part3ThreadedModifier.cpp", "rank": 18, "score": 5.627832298010057 }, { "content": "/********************************************************************************************************************************************\n\n * File: Pgrm2.cpp\n\n * Author: Sean Njenga\n\n * UTDid: sin170000\n\n * Section: CE 4348.501\n\n * Modified on: 20 October 2021\n\n * by: Sean Njenga\n\n * \n\n * Procedures:\n\n * main - Inits/destroys semaphores, creates/cancels threads, and prints out statistics after 5 min. \n\n * Philosopher - Continually read/write semaphores, and calls eat or think when appropriate. \n\n * EatOrThink - Sleeps for a random time in range [25,49] ms, and returns the entire time spent in the method. \n\n * ******************************************************************************************************************************************/\n\n\n\n#include <semaphore.h>\n\n#include <chrono>\n\n#include <unistd.h>\n\n#include <pthread.h>\n\n#include <iostream>\n\n#include <thread>\n", "file_path": "DiningPhilosopherProblem.cpp", "rank": 20, "score": 4.766699374448434 }, { "content": "\n\n/********************************************************************************************************************************************\n\n * int main(int argc, char *argv[]) \n\n * Author: Sean Njenga\n\n * Modified on: 20 October 2021\n\n * by: Sean Njenga\n\n * Description: Creates semaphores and philosopher threads, after 5 minutes it cancels the threads and destroys the semaphores.\n\n * Then prints statistics to the console, and records the total running time of the program. \n\n * \n\n * Parameters: \n\n * argc I/P int The number of arguments on the command line. \n\n * argv I/P char *[] The arguments on the command line.\n\n * main O/P int Status code (not currently used).\n\n ********************************************************************************************************************************************/\n\nint main(int argc, char *argv[]) {\n\n srand(time(NULL)); \n\n auto start = std::chrono::high_resolution_clock::now(); //Stores the time the program begins running\n\n\n\n for(int x = 0; x < 5; x++) {\n\n sem_init(&utensil[x], 0, 1); //Create 5 utensil semaphores with a value of 1\n", "file_path": "DiningPhilosopherProblem.cpp", "rank": 23, "score": 4.629756294956093 }, { "content": "double EatOrThink() {\n\n auto start = std::chrono::high_resolution_clock::now(); //Gets an accurate start time for EatOrThink()\n\n long timeRan = MIN_SLEEP_DURATION + (rand() % (MAX_SLEEP_DURATION - MIN_SLEEP_DURATION) + 1); //Generates a random number in range [25,49]\n\n std::this_thread::sleep_for(std::chrono::milliseconds(timeRan)); //Sleeps for a random number of miliseconds in range [25,49]\n\n auto stop = std::chrono::high_resolution_clock::now(); //Gets an accurate stop time for EatOrThink()\n\n\n\n return std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count(); //Calculate the time spent eating or thinking\n\n}\n\n\n\n/********************************************************************************************************************************************\n\n * void* Philosopher(void* idNum) \n\n * Author: William Stallings\n\n * Modified on: 20 October 2021\n\n * by: Sean Njenga\n\n * Description: Loops indefinitely, when a philosopher is in the room he eats, and when he is outside the room he thinks. \n\n * It increments semaphores when it moves into the room and picks up forks. \n\n * Decrements semaphores when it puts down the forks and leaves the room. \n\n * \n\n * Parameters: \n\n * idNum I/P void* Pointer to the ID of the philosopher. \n", "file_path": "DiningPhilosopherProblem.cpp", "rank": 24, "score": 4.50145171610318 }, { "content": "\n\nconst int MU = 10; // Mean value for the normal distribution\n\nconst int SIGMA = 2; // Standard deviation value for the normal distribution\n\nconst int MIN_WORKING_SET_SIZE = 4; // The minimum working set size or minimum frame size to be tested\n\nconst int MAX_WORKING_SET_SIZE = 20; // The maximum working set size or maximum frame size to be tested\n\nconst int TOTAL_MEMORY_PAGES = 1000; // The total number of random memory page values to generate\n\nconst int NUM_EXPERIMENTS = 1000; // The total number of experiments to run\n\n\n\n\n\n/********************************************************************************************************************************************\n\n * int LRUReplacementAlgo(int &wss, int data[])\n\n * Author: Sean Njenga\n\n * Modified on: 14 November 2021\n\n * by: Sean Njenga\n\n * Description: Performs the LRU page replacement algorithm on the provided dataset. Where if a new memory page needs to be allocated in the existing frame, it \n\n * removes the memory page that has not been the most used recently in the frame with the newest memory page at the end of the \n\n * queue. Signaling that the newest page is the most recently used memory page\n\n * Parameters: \n\n * LRUReplacementAlgo O/P int Returns the total number of page faults caused by the LRU algorithm givin the frame size\n\n * wss I/P int The current working set size or frame size to store pages\n", "file_path": "MonteCarloSim.cpp", "rank": 25, "score": 4.146249118026102 }, { "content": "/********************************************************************************************************************************************\n\n * File: MonteCarloSim.cpp\n\n * Author: Sean Njenga\n\n * UTDid: sin170000\n\n * Section: CE 4348.501\n\n * Modified on: 14 November 2021\n\n * by: Sean Njenga\n\n * \n\n * Procedures:\n\n * main - Runs a Monte Carlo Simulation on 3 page replacement algorithm's, providing the randomly generated data\n\n * LRUReplacementAlgo - Performs the LRU Page Replacement Algo on a dataset, and counts pagefaults after frame allocation\n\n * FIFOReplacementAlgo - Performs the FIFO Page Replacement Algo on a dataset, and counts pagefaults after frame allocation\n\n * ClockReplacementAlgo - Performs the Clock Page Replacement Algo on a dataset, and counts pagefaults after frame allocation\n\n * ******************************************************************************************************************************************/\n\n\n\n#include <iostream>\n\n#include <random>\n\n#include <deque>\n\n#include <algorithm>\n\n#include <cmath>\n", "file_path": "MonteCarloSim.cpp", "rank": 26, "score": 4.142628100905667 }, { "content": " pipe.setUpToWrite();\n\n }\n\n else if (pid2 == 0){ //Child process\n\n pipe.setUpToRead();\n\n execl(\"21S_CS3377_Project\", \"21S_CS3377_Project\", \"4\", \"3\", nullptr);\n\n }\n\n else{ //Parent process\n\n std::cerr << \"Fork Failed: \" << strerror(errno) << std::endl; exit(1);\n\n }\n\n}\n\n\n\nvoid Part4SocketModifier::modifyAndCopyFile(const char *sourceFile, const char *destFile) {\n\n if (ioType == IOType::READ){ //Parent process\n\n int sockFD;\n\n struct sockaddr_in serverAddress;\n\n if ((sockFD = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror(\"Parent Socket Failed\"); };\n\n\n\n serverAddress.sin_family = AF_INET;\n\n serverAddress.sin_port = htons(Util::portNumber);\n\n if (inet_pton(AF_INET, \"127.0.0.1\", &serverAddress.sin_addr) <= 0) { perror(\"Inet Pton Failed\"); }\n", "file_path": "Binary File Manipulation/Part4SocketModifier.cpp", "rank": 27, "score": 4.063142041797915 }, { "content": "\n\n for (int experiments = 0; experiments < NUM_EXPERIMENTS; experiments++) // Loops for however many number of experiments the user wants to run\n\n {\n\n for (int trace = 0; trace < TOTAL_MEMORY_PAGES; trace++) // Generates the 1000 randomly generated memory page values\n\n {\n\n data[trace] = ( 10 * (int) ( trace / 100 ) ) + (int) normalDis(gen);\n\n }\n\n\n\n for (int wss = MIN_WORKING_SET_SIZE; wss <= MAX_WORKING_SET_SIZE; wss++) // Tests the algorithms against the randomly generated data against multiple frame size in range [4,20]\n\n {\n\n lruResults[wss - MIN_WORKING_SET_SIZE] += LRUReplacementAlgo(wss, data); // Run the LRU algorithm and total up the number of page faults for each given frame size (wss)\n\n fifoResults[wss - MIN_WORKING_SET_SIZE] += FIFOReplacementAlgo(wss, data); // Run the FIFO algorithm and total up the number of page faults for each given frame size (wss)\n\n clockResults[wss - MIN_WORKING_SET_SIZE] += ClockReplacementAlgo(wss, data); // Run the Clock algorithm and total up the number of page faults for each given frame size (wss)\n\n }\n\n }\n\n\n\n std::cout << \"LRU Replacement Algo Sim Using Queue\" << std::endl;\n\n for (int wss = MIN_WORKING_SET_SIZE; wss <= MAX_WORKING_SET_SIZE; wss++) // Print the average page fault count for the LRU page replacement algorthim after the monte carlo sim for each working set size in range [4,20]\n\n {\n\n std::cout << \"Working Set Size (\" << wss << \") -> PFC = \" << lruResults[wss - MIN_WORKING_SET_SIZE] / TOTAL_MEMORY_PAGES << std::endl;\n", "file_path": "MonteCarloSim.cpp", "rank": 28, "score": 3.747876913920165 }, { "content": "#ifndef PROJECTTEMPLATE_FILEMANIPULATION_H\n\n#define PROJECTTEMPLATE_FILEMANIPULATION_H\n\n\n\n#include \"Util.h\"\n\n#include <vector>\n\n\n", "file_path": "Binary File Manipulation/FileManipulation.h", "rank": 30, "score": 3.2080084827941846 }, { "content": " pid = fork();\n\n if (pid < 0){\n\n std::cerr << \"Fork Failed: \" << strerror(errno) << std::endl; exit(1);\n\n }\n\n else if (pid == 0){ //Child process\n\n childFD = pipe.setUpToRead();\n\n execl(\"21S_CS3377_Project\", \"21S_CS3377_Project\", \"2\", \"3\", NULL);\n\n }\n\n else{ //Parent process\n\n parentFD = pipe.setUpToWrite();\n\n }\n\n}\n\n\n\nvoid Part2MultiProcessModifier::modifyAndCopyFile(const char *sourceFile, const char *destFile) {\n\n if (pid == 0){ //Child process\n\n //Read from standard input and write to destFile\n\n FileManipulation::writeToFile(FileManipulation::getWriteFD(destFile), FileManipulation::readFromFile(STDIN_FILENO, true));\n\n close(childFD);\n\n exit(0);\n\n }\n", "file_path": "Binary File Manipulation/Part2MultiProcessModifier.cpp", "rank": 31, "score": 3.1616320830744877 }, { "content": " else if (pid > 0) { //Parent process\n\n std::vector<EntryInfo> entries = FileManipulation::readFromFile(FileManipulation::getReadFD(sourceFile), false); //Read from the source file\n\n FileManipulation::writeToFile(parentFD, entries); //Write to pipe\n\n\n\n //wait for child\n\n wait(NULL);\n\n// int code;\n\n// int rc = wait(&code);\n\n// if (code != 0){\n\n// std::cerr << \"Child Exit/Wait Error: \" << strerror(errno) << std::endl;\n\n// }\n\n close(parentFD);\n\n ", "file_path": "Binary File Manipulation/Part2MultiProcessModifier.cpp", "rank": 32, "score": 3.105473015582943 }, { "content": " * Philosopher O/P void* Pointer to thread location (not currently used).\n\n ********************************************************************************************************************************************/\n\n[[noreturn]] void* Philosopher(void* idNum) {\n\n int count = *((int *)idNum); //Sets count to the value being pointed at by int* idNum.\n\n while(true) { //Loop forever (until the thread is cancelled)\n\n timeSpentThinking[count] += EatOrThink(); //Think, and store the time spent doing so. \n\n timeSpentThinking[count + 5] += 1; //Increments the # of times the phil. has thought\n\n \n\n sem_wait(&room); //Enter the room if there is space\n\n sem_wait(&utensil[count]); //Pick up the left fork\n\n sem_wait(&utensil[(count + 1) % 5]); //Pick up the right fork\n\n \n\n timeSpentEating[count] += EatOrThink(); //Eat, and store the time spent doing so.\n\n timeSpentEating[count + 5] += 1; //Increments the # of times the philosopher have eatin\n\n \n\n sem_post(&utensil[(count + 1) % 5]); //Put down the right fork\n\n sem_post(&utensil[count]); //Put down the left fork\n\n sem_post(&room); //Leave the room\n\n }\n\n}\n", "file_path": "DiningPhilosopherProblem.cpp", "rank": 33, "score": 3.067304765324223 }, { "content": "def PrintTelemetry():\n\n \"\"\"Read various info from the copter\"\"\"\n\n \n\n vehicle.wait_ready('autopilot_version')\n\n print(f\"Autopilot version: {vehicle.version}\")\n\n\n\n # Does the firmware support the companion pc to set the attitude?\n\n print(f\"Supports set attitude from companion: {vehicle.capabilities.set_attitude_target_local_ned}\")\n\n\n\n # Get the actual position\n\n print(f\"Position: {vehicle.location.global_relative_frame}\")\n\n\n\n # Get the actual attitude roll, pitch, yaw\n\n print('Attitude: %s' % vehicle.attitude)\n\n\n\n # Get the actual velocity (m/s)\n\n print('Velocity: %s (m/s)' % vehicle.velocity) # North, east, down\n\n\n\n # When did we receive the last heartbeat\n\n print('Last Heartbeat: %s' % vehicle.last_heartbeat)\n\n\n\n # Is the vehicle good to Arm?\n\n print('Is the vehicle armable: %s' % vehicle.is_armable)\n\n\n\n # Which is the total ground speed?\n\n print('Groundspeed: %s' % vehicle.groundspeed) # (%)\n\n\n\n # What is the actual flight mode?\n\n print('Mode: %s' % vehicle.mode.name)\n\n\n\n # Is thestate estimation filter ok?\n", "file_path": "Drone Project/GeneralDroneFunctions.py", "rank": 34, "score": 2.9949736362990347 }, { "content": " pthread_mutex_lock(&mutex);\n\n\n\n pthread_t outputThread;\n\n pthread_create(&outputThread, nullptr, threadEntry, this);\n\n\n\n for (int x = 0; x < entries.size(); x++){\n\n pthread_cond_wait(&condition, &mutex);\n\n infoBtwThreads = entries[x];;\n\n pthread_cond_signal(&condition);\n\n }\n\n pthread_mutex_unlock(&mutex);\n\n pthread_join(outputThread, nullptr);\n\n\n\n //Clean-up\n\n pthread_mutex_destroy(&mutex);\n\n pthread_cond_destroy(&condition);\n\n}\n\n\n\nvoid Part3ThreadedModifier::outputThread() {\n\n pthread_mutex_lock(&mutex);\n", "file_path": "Binary File Manipulation/Part3ThreadedModifier.cpp", "rank": 35, "score": 2.9934322190904403 }, { "content": " std::deque<int> process(wss); \n\n std::vector<int> flagCache(wss, 0); // Creates an array to track the use bit of each frame. \n\n int pageFaultCount = 0;\n\n\n\n int pointer = 0; // Used as the pointer for the \"circular buffer\"\n\n bool flag = false; \n\n\n\n for(int x = 0; x < TOTAL_MEMORY_PAGES; x++)\n\n { \n\n flag = false; // Used to keep track if a memory page is in the frame already\n\n\n\n for(int y = 0; y < wss; y++) // Check to see if the memory page exists in the frame already\n\n {\n\n if(process.at(y) == data[x]) \n\n {\n\n flag = true; \n\n flagCache[y] = 1; // Sets the use bit of the frame to 1. \n\n }\n\n }\n\n\n", "file_path": "MonteCarloSim.cpp", "rank": 37, "score": 2.7466932450675134 }, { "content": "class FlightPath {\n\n\tprotected String startingCity, destination;\n\n\tprotected int val;\n\n\tprotected FlightPath next;\n\n\n\n\tprotected FlightPath(String startingCity, String destination, int val) {\n\n\t\tthis.startingCity = startingCity;\n\n\t\tthis.destination = destination;\n\n\t\tthis.val = val;\n\n\t\tnext = null;\n\n\t}\n", "file_path": "Dijkstra Airport Project/FlightPath.java", "rank": 38, "score": 2.739736329718843 }, { "content": "#ifndef INC_21S_CS3377_PROJECT_PART4SOCKETMODIFIER_H\n\n#define INC_21S_CS3377_PROJECT_PART4SOCKETMODIFIER_H\n\n\n\n\n\n#include \"Modifier.h\"\n\n\n", "file_path": "Binary File Manipulation/Part4SocketModifier.h", "rank": 39, "score": 2.44119237957428 }, { "content": "#ifndef INC_21S_CS3377_PROJECT_PART3THREADEDMODIFIER_H\n\n#define INC_21S_CS3377_PROJECT_PART3THREADEDMODIFIER_H\n\n\n\n#include \"Modifier.h\"\n\n\n", "file_path": "Binary File Manipulation/Part3ThreadedModifier.h", "rank": 40, "score": 2.44119237957428 }, { "content": " }\n\n sem_init(&room, 0, 4); //Create the room semaphore with a value of 4\n\n\n\n pthread_t treadId[5]; //Create 5 thread IDs for the philosophers\n\n \n\n for(int x = 0; x < 5; x++) {\n\n pthread_create(&treadId[x], NULL, Philosopher, &x); //Create a thread for philosopher #i from 0 to 5\n\n std::this_thread::sleep_for(std::chrono::microseconds(1)); //Provides a 1us delay before creating the next thread\n\n }\n\n std::this_thread::sleep_for(std::chrono::minutes(5));\n\n\n\n for(int i=0; i<5; i++) {\n\n pthread_cancel(treadId[i]); //Terminate philosopher threads\n\n }\n\n\n\n for(int x = 0; x < 5; x++) {\n\n printf(\"Philosopher #%d thought %.0f number of times, for a total of %.2f seconds, or %.0f ms.\\n\",\n\n x + 1, timeSpentThinking[x + 5], timeSpentThinking[x] / 1000, timeSpentThinking[x]); //Prints out the number of times the philosopher thought, and for how long\n\n printf(\"Philosopher #%d ate %.0f number of times, for a total of %.2f seconds, or %.0f ms.\\n\\n\",\n\n x + 1, timeSpentEating[x + 5], timeSpentEating[x] / 1000, timeSpentEating[x]); //Prints out the number of times the philosopher ate, and for how long\n", "file_path": "DiningPhilosopherProblem.cpp", "rank": 41, "score": 2.4285619326834103 }, { "content": "//\n\n// Created by erik on 2/2/21.\n\n//\n\n\n\n#ifndef INC_21S_CS3377_PROJECT_PART1SIMPLEFILEMODIFIER_H\n\n#define INC_21S_CS3377_PROJECT_PART1SIMPLEFILEMODIFIER_H\n\n\n\n\n\n#include \"Modifier.h\"\n\n\n", "file_path": "Binary File Manipulation/Part1SimpleFileModifier.h", "rank": 42, "score": 2.369333895792862 }, { "content": "//\n\n// Created by Erik Peterson on 2/10/21.\n\n//\n\n\n\n#ifndef INC_21S_CS3377_PROJECT_PART2MULTIPROCESSMODIFIER_H\n\n#define INC_21S_CS3377_PROJECT_PART2MULTIPROCESSMODIFIER_H\n\n\n\n\n\n#include \"Modifier.h\"\n\n\n", "file_path": "Binary File Manipulation/Part2MultiProcessModifier.h", "rank": 43, "score": 2.334968053629871 }, { "content": "\tprotected void findShortestPath(String sourceCity) {\n\n\t\tif (!flights.containsKey(sourceCity)) { //Checks to see if the flight is in the flight plan and if not print error\n\n\t\t\tSystem.err.printf(\"Flight doesn't contain start vertex \\\"%s\\\"\\n\", sourceCity);\n\n\t\t\treturn;\n\n\t\t}\n\n\t\t//Get all the flights for the starter city\n\n\t\tCity source = flights.get(sourceCity);\n\n\t\tsource.val = 0;\n\n\n\n\t\t//Get the paths and add it to Priority Queue\n\n\t\tPriorityQueue<City> cityPaths = new PriorityQueue<>();\n\n\t\t//FlightQueue<City> cityPaths = new FlightQueue<>();\n\n\t\tfor (City curr : flights.values()) {\n\n\t\t\tcurr.prev = curr == source ? source : null;\n\n\t\t\tcurr.val = curr == source ? 0 : Integer.MAX_VALUE;\n\n\t\t\tcityPaths.offer(curr);\n\n\t\t}\n\n\n\n\t\tCity startingCity, destinationCity;\n\n\t\t// vertex with shortest val (first iteration will return source)\n\n\t\twhile (!cityPaths.isEmpty()) {\n\n\t\t\t// vertex with shortest val (first iteration will return source)\n\n\t\t\tstartingCity = cityPaths.poll();\n\n\t\t\tif (startingCity.val == Integer.MAX_VALUE){\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\t//System.out.println(startingCity.toString());\n\n\n\n\t\t\t//Find time/cost of each neighboring edge\n\n\t\t\tfor (HashMap.Entry<City, Integer> city : startingCity.adjacentCities.entrySet()) {\n\n\t\t\t\tdestinationCity = city.getKey(); //The neighbor\n\n\t\t\t\tint alternateDist = startingCity.val + city.getValue();\n\n\t\t\t\t//System.out.println(\"Test: \" + alternateDist);\n\n\t\t\t\tif (alternateDist < destinationCity.val) { //Checks to see if a shorter path is found\n\n\t\t\t\t\t//cityPaths.remove(destinationCity);\n\n\t\t\t\t\tdestinationCity.val = alternateDist;\n\n\t\t\t\t\tdestinationCity.prev = startingCity;\n\n\t\t\t\t\tcityPaths.offer(destinationCity);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n", "file_path": "Dijkstra Airport Project/FlightMap.java", "rank": 44, "score": 2.3304811103417546 }, { "content": " }\n\n\n\n for(int x = 0; x < 5; x++) {\n\n sem_destroy(&utensil[x]); //Release the resources used for the utensil semaphores\n\n }\n\n sem_destroy(&room); //Release the resources used for the room semaphore\n\n\n\n auto stop = std::chrono::high_resolution_clock::now(); //Store the time the program stops running\n\n printf(\"Total Running time: %ld minutes \\n\",\n\n std::chrono::duration_cast<std::chrono::minutes>(stop - start).count()); //Print the total time the program was running\n\n\n\n return 0;\n\n}", "file_path": "DiningPhilosopherProblem.cpp", "rank": 45, "score": 2.2389369595230804 }, { "content": " }\n\n\n\n std::cout << \"\\nFIFO Replacement Algo Sim\" << std::endl;\n\n for (int wss = MIN_WORKING_SET_SIZE; wss <= MAX_WORKING_SET_SIZE; wss++) // Print the average page fault count for the FIFO page replacement algorthim after the monte carlo sim for each working set size in range [4,20]\n\n {\n\n std::cout << \"Working Set Size (\" << wss << \") -> PFC = \" << fifoResults[wss - MIN_WORKING_SET_SIZE] / TOTAL_MEMORY_PAGES << std::endl;\n\n }\n\n\n\n std::cout << \"\\nClock Replacement Algo Sim\" << std::endl;\n\n for (int wss = MIN_WORKING_SET_SIZE; wss <= MAX_WORKING_SET_SIZE; wss++) // Print the average page fault count for the Clock page replacement algorthim after the monte carlo sim for each working set size in range [4,20]\n\n {\n\n std::cout << \"Working Set Size (\" << wss << \") -> PFC = \" << clockResults[wss - MIN_WORKING_SET_SIZE] / TOTAL_MEMORY_PAGES << std::endl;\n\n }\n\n}", "file_path": "MonteCarloSim.cpp", "rank": 46, "score": 1.6910599429505782 }, { "content": " else if (flagCache[pointer] == 1) // Checks if a memory page has not been flagged to replace\n\n { \n\n flagCache[pointer] = 0; // Sets the flag to 0 if it was visited\n\n if(pointer == wss - 1) // Check to see if the pointer is at the last frame to reset\n\n { \n\n pointer = 0; // Reset all pages flag to 0\n\n } else \n\n {\n\n pointer++;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n return pageFaultCount - wss; //Returns number of page faults that occured after the frame is fully allocated\n\n}\n\n\n\n\n\n/********************************************************************************************************************************************\n\n * int FIFOReplacementAlgo(int &wss, int data[])\n", "file_path": "MonteCarloSim.cpp", "rank": 47, "score": 1.6421029025764895 }, { "content": " process.push_back(data[x]); // Push the new page into the back of the deque, since it's the last visited memory page\n\n }\n\n }\n\n return pageFaultCount - wss; //Returns number of page faults that occured after the frame is fully allocated\n\n}\n\n\n\n/********************************************************************************************************************************************\n\n * int ClockReplacementAlgo(int wss, int data[])\n\n * Author: Sean Njenga\n\n * Modified on: 11 November 2021\n\n * by: Sean Njenga\n\n * Description: Performs the Clock page replacement algorithm on the provided dataset. Where every memory page has a \"flag\" and if it is 0\n\n * it means it can be replaced by a new memory page. If it is 1 then it resets that memory page to 0 and moves to the next \n\n * nemory page in the frame.\n\n * Parameters: \n\n * ClockReplacementAlgo O/P int Returns the total number of page faults caused by the Clock algorithm givin the frame size (wss)\n\n * wss I/P int The current working set size or frame size to store pages\n\n * data I/P int[] The randomly generated memory page values to test \n\n ********************************************************************************************************************************************/\n\nint ClockReplacementAlgo(int wss, int data[]){\n", "file_path": "MonteCarloSim.cpp", "rank": 48, "score": 1.5733366141510636 }, { "content": "\n\n int waitTime = 1;\n\n while (connect(sockFD, (struct sockaddr*) &serverAddress, sizeof(serverAddress))) {\n\n if (errno != ECONNREFUSED) {\n\n throw FileModifyException(\"Error connecting\");\n\n }\n\n std::cout << \"Not ready to connect yet...\\n\";\n\n sleep(waitTime);\n\n waitTime = waitTime * 2;\n\n }\n\n\n\n FileManipulation::writeToFile(sockFD, FileManipulation::readFromFile(FileManipulation::getReadFD(sourceFile), false)); //Write to socket\n\n close(sockFD);\n\n }\n\n else{ //Child process\n\n int finalSockFD, childSockFD;\n\n struct sockaddr_in childAddress;\n\n if ((childSockFD = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror(\"Child Socket Failed\"); };\n\n\n\n childAddress.sin_family = AF_INET;\n", "file_path": "Binary File Manipulation/Part4SocketModifier.cpp", "rank": 49, "score": 1.226926223803325 }, { "content": " childAddress.sin_addr.s_addr = INADDR_ANY;\n\n childAddress.sin_port = htons(Util::portNumber);\n\n int addrSize = sizeof(childAddress);\n\n\n\n if (bind(childSockFD, (struct sockaddr*) &childAddress, addrSize) < 0) { perror(\"Bind Failed\"); }\n\n if (listen(childSockFD, 1) < 0) { perror(\"Listen Failed\"); }\n\n if ((finalSockFD = accept(childSockFD, (struct sockaddr*) &childAddress, (socklen_t*) &addrSize)) < 0) { perror(\"Accept Failed\"); };\n\n\n\n FileManipulation::writeToFile(FileManipulation::getWriteFD(destFile), FileManipulation::readFromFile(finalSockFD, true));\n\n close(finalSockFD); close(childSockFD); exit(0);\n\n }\n\n}", "file_path": "Binary File Manipulation/Part4SocketModifier.cpp", "rank": 50, "score": 1.197438180106968 }, { "content": " }\n\n else if (process[y] == 0 && replacePage == true) // Frame not fully allocated yet (hit)\n\n {\n\n process[y] = data[x];\n\n replacePage = false; // Value already replaced\n\n break;\n\n }\n\n \n\n timeSpentInFrame[y] += 1; // Page isn't present in the frame and frame fully allocated so increase time memory page has spent in frame\n\n \n\n if (timeSpentInFrame[y] >= mostTimeSpentInFrame) // Check to see if there is a new least recently used memory page\n\n {\n\n mostTimeSpentInFramePage = y; // The new frame page that we want to replace since it is the LRU now\n\n mostTimeSpentInFrame = timeSpentInFrame[y]; // The new highest amount of time a memory page has been in the frame\n\n }\n\n }\n\n\n\n if (replacePage == true) // The page is not present in the frame so it needs to be replaced (fault)\n\n {\n\n pageFaultCount++;\n", "file_path": "MonteCarloSim.cpp", "rank": 51, "score": 1.15612586988959 }, { "content": " * by: Sean Njenga\n\n * Description: Performs the FIFO page replacement algorithm on the provided dataset. Where if a new memory page needs to be allocated it \n\n * removes the memory page (first-in or front of queue) that has been in the frame the longest and replaces it with the newest\n\n * memory page at the end of the queue.\n\n * Parameters: \n\n * FIFOReplacementAlgo O/P int Returns the total number of page faults caused by the FIFO algorithm givin the frame size\n\n * wss I/P int The current working set size or frame size to store pages\n\n * data I/P int[] The randomly generated memory page values to test \n\n ********************************************************************************************************************************************/\n\nint FIFOReplacementAlgo(int &wss, int data[]){\n\n int pageFaultCount = 0;\n\n std::deque<int> process(wss); // Holds the current # of pages or processes in the frame\n\n\n\n for (int x = 0; x < TOTAL_MEMORY_PAGES; x++)\n\n {\n\n auto search = std::find(process.begin(), process.end(), data[x]);\n\n if (search == process.end()) // Frame does not contain page (fault) \n\n {\n\n pageFaultCount++;\n\n process.pop_front(); // Remove first element in frame since it was the first one in\n", "file_path": "MonteCarloSim.cpp", "rank": 52, "score": 0.9367340846668761 }, { "content": " * data I/P int[] The randomly generated memory page values to test \n\n ********************************************************************************************************************************************/\n\nint LRUReplacementAlgo(int &wss, int data[]){\n\n int pageFaultCount = 0;\n\n std::vector<int> process(wss, 0); // The frane containing the memory pages\n\n std::vector<int> timeSpentInFrame(wss, 1); // Contains how long each memory page in frame has been in the frame\n\n int mostTimeSpentInFramePage = 0; // The memory page that has been in the frame the longest\n\n int mostTimeSpentInFrame = 1; // The current time the least recently used memory page has been in frame\n\n bool replacePage; // Determines whether a memory page in frame needs to be replaced\n\n\n\n for (int x = 0; x < TOTAL_MEMORY_PAGES; x++) \n\n {\n\n replacePage = true;\n\n for (int y = 0; y < wss; y++) // Compare the current memory page to every existing memory page in frame\n\n {\n\n if (data[x] == process[y]) // If the page is already in the frame decrease time spent by 1 and break out of while so it can go to next value (hit)\n\n {\n\n timeSpentInFrame[y] -= 1; // Decrease the amount of time the memory page has been in frame\n\n replacePage = false; // No value needs to be replaced\n\n continue;\n", "file_path": "MonteCarloSim.cpp", "rank": 53, "score": 0.9073440187275654 }, { "content": "\"\"\"\n\n\tPlease stick to the syntax conventions when adding new functions\n\n\tUncomment the main at the bottom to test anything\n\n\"\"\"\n\nfrom dronekit import connect, mavutil, VehicleMode, LocationGlobalRelative, APIException\n\nimport time\n\nimport socket\n\nimport math\n\nimport argparse # Allows to input vals from command line to use them in python\n\n\n\ndef ConnectToCopter():\n\n parser = argparse.ArgumentParser(description='commands')\n\n parser.add_argument('--connect')\n\n args = parser.parse_args()\n\n\n\n # Gives value after --connect; the IP address\n\n connection_string = args.connect\n\n\n\n if not connection_string: # If the connection string is empty; none provided\n\n # Create a SITL drone instance instead of launching one beforehand\n\n import dronekit_sitl\n\n sitl = dronekit_sitl.start_default()\n\n connection_string = sitl.connection_string()\n\n\n\n vehicle = connect(connection_string, wait_ready=True)\n\n return vehicle\n\n\n\ndef ArmDrone():\n\n print(\"Copter Pre-Arm Checks\")\n\n while not vehicle.is_armable: # Ensure autopilot is ready\n\n print(\" Waiting for Copter to initialise...\")\n\n time.sleep(1)\n\n print(\"Copter is Armed\")\n\n\n\n while vehicle.gps_0.fix_type < 2: # Ensure GPS is ready\n\n print(\" Waiting for GPS to initialise...\", vehicle.gps_0.fix_type)\n\n time.sleep(1)\n\n print(\"Copter GPS Ready\")\n\n\n\n print(\"Enabling GUIDED Mode for Copter\")\n\n vehicle.mode = VehicleMode(\"GUIDED\") # Copter is armed in GUIDED mode\n\n while vehicle.mode != \"GUIDED\":\n\n print(\"Drone is not in GUIDED Mode...\")\n\n time.sleep(1)\n\n print(\"Drone is in GUIDED Mode\")\n\n\n\n print(\"Arming Copter\")\n\n vehicle.armed = True\n\n while not vehicle.armed: # Ensure vehicle is armed before take off\n\n print(\" Waiting for Copter arming...\")\n\n time.sleep(1)\n\n print(\"Drone is Armed\")\n\n \n\ndef TakeOffDrone(elevation):\n\n print(\"Flying up to \", elevation, \"m\")\n\n vehicle.simple_takeoff(elevation) # Begin takeoff procedure to reach elevation\n\n\n\n reachedElevation = False\n\n while reachedElevation == False: # While the target elevation has not been reached\n\n currDroneHeight = vehicle.location.global_relative_frame.alt\n\n print(\"Current drone elevation: \", currDroneHeight)\n\n\n\n if currDroneHeight >= (.95 * elevation): # If the drone is at the target elevation (account for timing)\n\n reachedElevation = True\n\n time.sleep(1)\n\n print(\"Drone has reached target elevation\")\n\n \n\n\n\ndef FrameVelocityControl(velX, velY, velZ):\n\n \"\"\" Move copter in direction based on specified velocity vectors, velX and VelY are parallel to the North and East direction (not to the front and sie of the vehicle). velZ is perpendicular to the plane of velX and velY, with a positive value towards the ground (so up is negative) following right-hand convention\n\n\n\n\tvelX > 0 -> fly North\n\n\tvelX < 0 -> fly South\n\n\tvelY > 0 -> fly East\n\n\tvelY < 0 -> fly West\n\n\tvelZ < 0 -> ascend\n\n\tvelZ > 0 -> descend\n\n\n\n\t# Send command to copter on a 1Hz cycle\n\n # for x in range(0, duration):\n\n # vehicle.send_mavlink(instructions)\n\n # time.sleep(1)\n\n\n\n\tLocal Tangent Plane Coorindaties Wiki -> https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates\n\n \"\"\"\n\n instructions = vehicle.message_factory.set_position_target_local_ned_encode(\n\n 0, # time_boot_ms (not used)\n\n 0, 0, # target system, target component\n\n mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame\n\n 0b0000111111000111, # type_mask (only speeds enabled)\n\n 0, 0, 0, # x, y, z positions (not used)\n\n velX, velY, velZ, # x, y, z velocity in m/s\n\n 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)\n\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlin\n\n vehicle.send_mavlink(instructions)\n\n\n\ndef GimbalMovement(pitch, roll, yaw, locationRoi):\n\n \"\"\"\n\n Rotates the camera to a specific vector in space and tracks a location of interest.\n\n\n\n @param pitch [byte], Gimbal pitch in degrees relative to the vehicle (see diagram for attitude). A value of 0 represents a camera pointed straight ahead relative to the front of the vehicle, while -90 points the camera straight down.\n\n\n\n @param roll [byte] - Gimbal roll in degrees relative to the vehicle (see diagram for attitude).\n\n\n\n @param yaw [byte] - Gimbal yaw in degrees relative to global frame (0 is North, 90 is West, 180 is South etc.)\n\n target_location(roi)\n\n \"\"\"\n\n # Point gimbal in desired direction\n\n vehicle.gimbal.rotate(pitch, roll, yaw)\n\n time.sleep(10)\n\n\n\n # Set gimbal/camera to track specified location in global relative frame\n\n vehicle.gimbal.target_location(locationRoi)\n\n\n\ndef DownloadChallenge():\n\n \"\"\"Download current challenge from the copter\"\"\"\n\n \n\n commands = vehicle.commands\n\n commands.download()\n\n commands.wait_ready() # Wait until download is finished\n\n\n\ndef ClearCurrentChallenge():\n\n \"\"\"Clears the Current mission (challenge)\"\"\"\n\n \n\n # commands = vehicle.commands\n\n print(\"Clearing current challenge/mission from vehicle\")\n\n vehicle.commands.clear() # Clear current mission\n\n vehicle.flush()\n\n\n\n\n\n\"\"\"(Unsure about how getting challange file works still) Get challenge file from copter\"\"\"\n\ndef GetCurrentChallenge(challenge):\n\n vehicle.mode = VehicleMode(\"AUTO\")\n\n while vehicle.mode != \"AUTO\":\n\n print(\"Setting copter into AUTO mode...\")\n\n time.sleep(1)\n\n print(\"Vehicle is in AUTO mode\")\n\n\n\n\n\ndef PrintTelemetry():\n\n \"\"\"Read various info from the copter\"\"\"\n\n \n\n vehicle.wait_ready('autopilot_version')\n\n print(f\"Autopilot version: {vehicle.version}\")\n\n\n\n # Does the firmware support the companion pc to set the attitude?\n\n print(f\"Supports set attitude from companion: {vehicle.capabilities.set_attitude_target_local_ned}\")\n\n\n\n # Get the actual position\n\n print(f\"Position: {vehicle.location.global_relative_frame}\")\n\n\n\n # Get the actual attitude roll, pitch, yaw\n\n print('Attitude: %s' % vehicle.attitude)\n\n\n\n # Get the actual velocity (m/s)\n\n print('Velocity: %s (m/s)' % vehicle.velocity) # North, east, down\n\n\n\n # When did we receive the last heartbeat\n\n print('Last Heartbeat: %s' % vehicle.last_heartbeat)\n\n\n\n # Is the vehicle good to Arm?\n\n print('Is the vehicle armable: %s' % vehicle.is_armable)\n\n\n\n # Which is the total ground speed?\n\n print('Groundspeed: %s' % vehicle.groundspeed) # (%)\n\n\n\n # What is the actual flight mode?\n\n print('Mode: %s' % vehicle.mode.name)\n\n\n\n # Is thestate estimation filter ok?\n\n print('EKF Ok: %s' % vehicle.ekf_ok)\n\n\n\n\"\"\"Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a \n\n specified region of interest (LocationGlobal).\n\n The vehicle may also turn to face the ROI.\n\n\"\"\"\n\ndef SetLocationRoi(location):\n\n # create the MAV_CMD_DO_SET_ROI command\n\n locMsg = vehicle.message_factory.command_long_encode(\n\n 0, 0, # target system, target component\n\n mavutil.mavlink.MAV_CMD_DO_SET_ROI, # command\n\n 0, # confirmation\n\n 0, 0, 0, 0, # params 1-4\n\n location.lat,\n\n location.lon,\n\n location.alt\n\n )\n\n\n\n # Send command to copter\n\n vehicle.send_mavlink(locMsg)\n\n\n\ndef LandDrone():\n\n print(\"Setting copter into LAND mode\")\n\n vehicle.mode = VehicleMode('LAND')\n\n while vehicle.mode != 'LAND':\n\n time.sleep(1)\n\n print(\"Initiating landing now...\")\n\n\n\n while vehicle.armed: # While the drone has not landed\n\n currDroneHeight = vehicle.location.global_relative_frame.alt\n\n print(\"Current drone elevation: \", currDroneHeight)\n\n time.sleep(1)\n\n\t\n\n print(\"The copter has landed!\")\n\n\n\ndef GoToTargetBody(north, east, down):\n\n \"\"\"\n\n Send command to request the vehicle fly to a specified\n\n location in the North, East, Down frame of the drone's body. So north is direction that\n\n drone is facing.\n\n \"\"\"\n\n msg = vehicle.message_factory.set_position_target_local_ned_encode(\n\n 0, # time_boot_ms (not used)\n\n 0, 0, # target system, target component\n\n mavutil.mavlink.MAV_FRAME_BODY_NED, # frame\n\n 0b0000111111111000, # type_mask (only positions enabled)\n\n north, east, down,\n\n 0, 0, 0, # x, y, z velocity in m/s (not used)\n\n 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)\n\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)\n\n\t# send command to vehicle\n\n vehicle.send_mavlink(msg)\n\n\n\ndef GetDistanceInMeters(aLoc1, aLoc2):\n\n \"\"\" Returns the ground distance in metres between two LocationGlobal objects.\n\n This method is an approximation, and will not be accurate over large distances and close to the\n\n earth's poles. It comes from the ArduPilot test code:\n\n https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py\n\n \"\"\"\n\n dlat = aLoc2.lat - aLoc1.lat\n\n dlong = aLoc2.lon - aLoc1.lon\n\n return math.sqrt((dlat * dlat) + (dlong * dlong)) * 1.113195e5\n\n\n\ndef YardsToMeters(yards):\n\n\treturn yards * 0.9144\n\n\n\ndef FeetToMeters(feet):\n\n\treturn feet * 0.3048\n\n\n\n\"\"\"\n\n----------------------\n\n-------- Main --------\n\n----------------------\n\n\n\n# Connect to vehicle UDP endpoint or simulator\n\nvehicle = connect('127.0.0.1:14550', wait_ready=True)\n\ncurMode = \"CHALLENGE1_TEST\" # Set to \"GROUND\" when not testing\n\nwayPointCount = 0\n\n\n\n#while True:\n\nif curMode == \"GROUND\":\n\n\ttime.sleep(2)\n\n\tif wayPointCount > 0: # exampl if else for determing challenge not functional right now\n\n\t\tprint(\"Valid Challenge Uploaded -> Procees\")\n\n\t\tcurMode = \"CHALLENGE1_TEST\"\n\nelif curMode == \"CHALLENGE1_TEST\":\n\n\ttargetMeters = YardsToMeters(30)\n\n\ttargetAltitude = FeetToMeters(25)\n\n \n\n\tArmDrone()\n\n\tTakeOffDrone(targetAltitude)\n\n\thomeLocation = vehicle.location.global_relative_frame\n\n\tvehicle.airspeed = 4\n\n\n\n\t#Fly North for 10 seconds\n\n\tFrameVelocityControl(targetMeters, 0, 0)\n\n\n\n\tGoToTargetBody(targetMeters, 0, 0)\n\n \n\n\twhile vehicle.mode.name == \"GUIDED\":\n\n\t\tdistanceTraveled = GetDistanceInMeters(vehicle.location.global_relative_frame, homeLocation)\n\n\t\tprint(f\"Distance traveled: {distanceTraveled}\")\n\n\t\tif distanceTraveled >= YardsToMeters(30) * 0.99:\n\n\t\t\tprint(\"Target Reached\")\n\n\t\t\tprint(f\"Final distance traveled: {distanceTraveled}\")\n\n\t\t\tbreak\n\n\t\ttime.sleep(1)\n\n\n\n\tLandDrone()\n\nelif curMode == \"BASIC_TEST\":\n\n\t# Prep drone for flight and rise to a altidude of 15\n\n\tArmDrone()\n\n\tTakeOffDrone(15)\n\n\n\n\t# Rn this just switches the vehicle mode to AUTO\n\n\t#GetCurrentChallenge(vehicle)\n\n\n\n\t# Fly North and up\n\n\tFrameVelocityControl(2, 0, -0.5)\n\n\n\n\t# Print various telemetry data\n\n\tPrintTelemetry()\n\n\n\n\t# Land Drone wherever it currently is at\n\n\tLandDrone()\n\n\n\n\t# Stop copter from running\n\n\tvehicle.close()\n", "file_path": "Drone Project/GeneralDroneFunctions.py", "rank": 54, "score": 0.7404553505856861 } ]
C++
soundmaker.cpp
increpare/beatio
68fa8400f4d97d85f1df1b0ffe372c6d9b5dae69
#include "soundmaker.h" extern "C" { #include <sndfile.h> } #include <math.h> #include <iostream> #include <QFileInfo> using namespace std; #ifndef M_PI #define M_PI 3.14159265358979323846264338 #endif #define SAMPLE_RATE 44100 #define AMPLITUDE (0.5 * 0x7F000000) #define LEFT_FREQ (344.0 / SAMPLE_RATE) #define RIGHT_FREQ (466.0 / SAMPLE_RATE) SoundMaker::SoundMaker() { } SoundMaker::~SoundMaker() { } bool SoundMaker::SaveWave(QVector<Note> onsets,const QString& filename) { int temp; int* buffer = this->GenerateWave(onsets,temp); int length = onsets.size()>0 ? ceil(onsets.last().onset)+1 : 0; int sample_count = SAMPLE_RATE*length; SNDFILE *file ; SF_INFO sfinfo ; memset (&sfinfo, 0, sizeof (sfinfo)) ; sfinfo.samplerate = SAMPLE_RATE ; sfinfo.frames = sample_count ; sfinfo.channels = 2 ; sfinfo.format = (SF_FORMAT_WAV | SF_FORMAT_PCM_16); if (! (file = sf_open (filename.toLatin1().data(), SFM_WRITE, &sfinfo))) { cout << "Error : Not able to open output file.\n"; return false ; } ; if (sf_write_int (file, buffer, sfinfo.channels * sample_count) != sfinfo.channels * sample_count) puts (sf_strerror (file)) ; sf_close (file) ; std::cout<<"DELETE BUFFER5"<<std::endl; delete [] buffer; buffer=0; return true; } void SoundMaker::unloadInstrument(int i) { instruments.remove(i); } void SoundMaker::unloadInstruments() { instruments.empty(); } bool SoundMaker::loadInstrument(const QString& samplefilename) { SNDFILE *infile; SF_INFO sfinfo; memset (&sfinfo, 0, sizeof (sfinfo)) ; if (! (infile = sf_open (samplefilename.toLatin1(), SFM_READ, &sfinfo))) { printf ("Error : could not open file : %s\n", samplefilename.toLatin1().data()) ; puts (sf_strerror (NULL)) ; exit (1) ; } if (! sf_format_check (&sfinfo) || !(sfinfo.channels==1||sfinfo.channels==2) || (sfinfo.samplerate!=SAMPLE_RATE)) { sf_close (infile) ; printf ("Invalid encoding\n") ; return false; } QVector<int> sample; int *buf = new int[sfinfo.frames*2]; int num = sf_read_int(infile,buf,sfinfo.frames*sfinfo.channels); if (sfinfo.samplerate==2) { for (int i=0;i<num;i++) { sample.push_back(buf[i]); } } else { for (int i=0;i<num;i++) { sample.push_back(buf[i]); sample.push_back(buf[i]); } } std::cout<<"DELETE BUFFER4"<<std::endl; delete [] buf; buf=0; sf_close (infile); this->instruments.push_back(sample); QFileInfo fileInfo = QFileInfo(samplefilename); this->names.push_back(fileInfo.baseName()); return true; } int* SoundMaker::GenerateWave(QVector<Note> onsets, int& framecount) { if (onsets.size()==0) return false; int length = ceil(onsets.last().onset)+1; int frame_count = SAMPLE_RATE*length; framecount=frame_count; SF_INFO sfinfo ; int k ; int *buffer ; buffer = new int[2 * frame_count]; memset (&sfinfo, 0, sizeof (sfinfo)) ; sfinfo.samplerate = SAMPLE_RATE ; sfinfo.frames = frame_count ; sfinfo.channels = 2 ; sfinfo.format = (SF_FORMAT_WAV | SF_FORMAT_PCM_24); int cur=0; QVector< NoteN > notePointers; for (k = 0 ; k < frame_count ; k++) { for (int i=notePointers.size()-1;i>=0;i--) { NoteN& point = notePointers[i]; point.onset++; if (2*notePointers[i].onset>=instruments[point.instrument].size()-1) { notePointers.remove(i); } } while (cur<onsets.size() && (onsets[cur].onset*SAMPLE_RATE)<k) { if (onsets[cur].instrument>=0) { NoteN newNote = onsets[cur]; newNote.onset=0; notePointers.push_back(newNote); } cur++; } int l=0; int r=0; for (int i=notePointers.size()-1;i>=0;i--) { int oldl=l; l+=instruments[notePointers[i].instrument][2*notePointers[i].onset]; if ((l<0)!=(oldl<0) && ((oldl<0) == (instruments[notePointers[i].instrument][2*notePointers[i].onset]<0))) { if (l!=0 && oldl!=0) { if (oldl>0) l=INT_MAX; else l=INT_MIN; } } int oldr=r; r+=instruments[notePointers[i].instrument][2*notePointers[i].onset+1]; if ((r<0)!=(oldr<0) && ((oldr<0) == (instruments[notePointers[i].instrument][2*notePointers[i].onset+1]<0))) { if (r!=0 && oldr!=0) { if (oldr>0) r=INT_MAX; else r=INT_MIN; } } } buffer [2 * k] = l; buffer [2 * k + 1] = r; } std::cout<<"BUFFER4"<<buffer<<std::endl; return buffer; }
#include "soundmaker.h" extern "C" { #include <sndfile.h> } #include <math.h> #include <iostream> #include <QFileInfo> using namespace std; #ifndef M_PI #define M_PI 3.14159265358979323846264338 #endif #define SAMPLE_RATE 44100 #define AMPLITUDE (0.5 * 0x7F000000) #define LEFT_FREQ (344.0 / SAMPLE_RATE) #define RIGHT_FREQ (466.0 / SAMPLE_RATE) SoundMaker::SoundMaker() { } SoundMaker::~SoundMaker() { } bool SoundMaker::SaveWave(QVector<Note> onsets,const QString& filename) { int temp; int* buffer = this->GenerateWave(onsets,temp); int length = onsets.size()>0 ? ceil(onsets.last().onset)+1 : 0; int sample_count = SAMPLE_RATE*length; SNDFILE *file ; SF_INFO sfinfo ; memset (&sfinfo, 0, sizeof (sfinfo)) ; sfinfo.samplerate = SAMPLE_RATE ; sfinfo.frames = sample_count ; sfinfo.channels = 2 ; sfinfo.format = (SF_FORMAT_WAV | SF_FORMAT_PCM_16); if (! (file = sf_open (filename.toLatin1().data(), SFM_WRITE, &sfinfo))) { cout << "Error : Not able to open output file.\n"; return false ; } ; if (sf_write_int (file, buffer, sfinfo.channels * sample_count) != sfinfo.channels * sample_count) puts (sf_strerror (file)) ; sf_close (file) ; std::cout<<"DELETE BUFFER5"<<std::endl; delete [] buffer; buffer=0; return true; } void SoundMaker::unloadInstrument(int i) { instruments.remove(i); } void SoundMaker::unloadInstruments() { instruments.empty(); } bool SoundMaker::loadInstrument(const QString& samplefilename) { SNDFILE *infile; SF_INFO sfinfo; memset (&sfinfo, 0, sizeof (sfinfo)) ; if (! (infile = sf_open (samplefilename.toLatin1(), SFM_READ, &sfinfo))) { printf ("Error : could not open file : %s\n", samplefilename.toLatin1().data()) ; puts (sf_strerror (NULL)) ; exit (1) ; } if (! sf_format_check (&sfinfo) || !(sfinfo.channels==1||sfinfo.channels==2) || (sfinfo.samplerate!=SAMPLE_RATE)) { sf_close (infile) ; printf ("Invalid encoding\n") ; return false; } QVector<int> sample; int *buf = new int[sfinfo.frames*2]; int num = sf_read_int(infile,buf,sfinfo.frames*sfinfo.channels); if (sfinfo.samplerate==2) { for (int i=0;i<num;i++) { sample.push_back(buf[i]); } } else { for (int i=0;i<num;i++) { sample.push_back(buf[i]); sample.push_back(buf[i]); } } std::cout<<"DELETE BUFFER4"<<std::endl; delete [] buf; buf=0; sf_close (infile); this->instruments.push_back(sample); QFileInfo fileInfo = QFileInfo(samplefilename); this->names.push_back(fileInfo.baseName()); return true; }
int* SoundMaker::GenerateWave(QVector<Note> onsets, int& framecount) { if (onsets.size()==0) return false; int length = ceil(onsets.last().onset)+1; int frame_count = SAMPLE_RATE*length; framecount=frame_count; SF_INFO sfinfo ; int k ; int *buffer ; buffer = new int[2 * frame_count]; memset (&sfinfo, 0, sizeof (sfinfo)) ; sfinfo.samplerate = SAMPLE_RATE ; sfinfo.frames = frame_count ; sfinfo.channels = 2 ; sfinfo.format = (SF_FORMAT_WAV | SF_FORMAT_PCM_24); int cur=0; QVector< NoteN > notePointers; for (k = 0 ; k < frame_count ; k++) { for (int i=notePointers.size()-1;i>=0;i--) { NoteN& point = notePointers[i]; point.onset++; if (2*notePointers[i].onset>=instruments[point.instrument].size()-1) { notePointers.remove(i); } } while (cur<onsets.size() && (onsets[cur].onset*SAMPLE_RATE)<k) { if (onsets[cur].instrument>=0) { NoteN newNote = onsets[cur]; newNote.onset=0; notePointers.push_back(newNote); } cur++; } int l=0; int r=0; for (int i=notePointers.size()-1;i>=0;i--) { int oldl=l; l+=instruments[notePointers[i].instrument][2*notePointers[i].onset]; if ((l<0)!=(oldl<0) && ((oldl<0) == (instruments[notePointers[i].instrument][2*notePointers[i].onset]<0))) { if (l!=0 && oldl!=0) { if (oldl>0) l=INT_MAX; else l=INT_MIN; } } int oldr=r; r+=instruments[notePointers[i].instrument][2*notePointers[i].onset+1]; if ((r<0)!=(oldr<0) && ((oldr<0) == (instruments[notePointers[i].instrument][2*notePointers[i].onset+1]<0))) { if (r!=0 && oldr!=0) { if (oldr>0) r=INT_MAX; else r=INT_MIN; } } } buffer [2 * k] = l; buffer [2 * k + 1] = r; } std::cout<<"BUFFER4"<<buffer<<std::endl; return buffer; }
function_block-full_function
[ { "content": " {\n\n //int value=(int)(32767.0*sin(2.0*M_PI*((double)(i))*(double)(400)/SYSTEM_FREQ));\n\n int value = _buffer[i];\n\n //putShort(start, value&65535);\n\n putShort(start, (value/65536)&65535);\n\n start += 2;\n\n }\n\n\n\n std::cout<<\"DELETE BUFFER2\"<<std::endl;\n\n delete [] _buffer;\n\n _buffer=0;\n\n this->pos=0;\n\n this->framecount=_framecount;\n\n}\n\n\n\nGenerator::~Generator()\n\n{\n\n if (buffer)\n\n {\n\n std::cout<<\"DELETE BUFFER3\"<<std::endl;\n", "file_path": "generator.cpp", "rank": 7, "score": 20.860584451761635 }, { "content": " int* buffer = this->helper.soundMaker.GenerateWave(onsets,framecount);\n\n\n\n std::cout<<\"NEW GEN1\"<<std::endl;\n\n\n\n gen = new Generator(this,&this->helper,buffer,framecount);//,buffer,framecount*2);\n\n gen->start();\n\n audioOutput->start(gen);\n\n\n\n }\n\n }\n\n break;\n\n }\n\n\n\n}\n\n\n\n\n\n\n\n\n\nvoid Window::setSave()\n\n{\n", "file_path": "window.cpp", "rank": 8, "score": 19.956775715965293 }, { "content": "// delete [] buffer;\n\n//}\n\n//\n\n//void Generator::start()\n\n//{\n\n// open(QIODevice::ReadOnly);\n\n//}\n\n//\n\n//void Generator::stop()\n\n//{\n\n// close();\n\n//}\n\n//\n\n//int Generator::putShort(char *t, unsigned int value)\n\n//{\n\n// *(unsigned char *)(t++)=value&255;\n\n// *(unsigned char *)(t)=(value/256)&255;\n\n// return 2;\n\n//}\n\n//\n", "file_path": "generator.cpp", "rank": 10, "score": 17.15997365732522 }, { "content": "//int Generator::putShort(char *t, unsigned int value)\n\n//{\n\n// *(unsigned char *)(t++)=value&255;\n\n// *(unsigned char *)(t)=(value/256)&255;\n\n// return 2;\n\n//}\n\n//\n\n//int Generator::fillData(char *start, int frequency, int seconds,int* _buffer, int buffer_size)\n\n//{\n\n// /*\n\n// std::cout<<\"BUFFER2\"<<_buffer<<std::endl;\n\n// int i, len=0;\n\n// int value;\n\n// for(i=0; i<buffer_size; i++) {\n\n// value=(int)(32767.0*sin(2.0*M_PI*((double)(i))*(double)(frequency)/SYSTEM_FREQ));\n\n// _buffer++;\n\n// putShort(start, value);\n\n// start += 4;\n\n// len+=2;\n\n// }\n", "file_path": "generator.cpp", "rank": 11, "score": 15.401879872664914 }, { "content": "void Window::setPlay()\n\n{\n\n switch (audioOutput->state())\n\n {\n\n case QAudio::ActiveState:\n\n {\n\n if (gen)\n\n {\n\n this->helper.playing=false;\n\n std::cout<<\"stopping=\";\n\n audioOutput->stop(); \n\n delete gen;\n\n gen=0;\n\n playButton->setText(\"Play\");\n\n }\n\n else\n\n {\n\n std::cout<<\"OOPS1523\"<<std::endl;\n\n }\n\n }\n", "file_path": "window.cpp", "rank": 12, "score": 15.0523240864559 }, { "content": "#include \"generator.h\"\n\n#include <math.h>\n\n#include <iostream>\n\n#include \"helper.h\"\n\n///*\n\n//Generator::Generator(QObject *parent,int* _intbuffer, int _buffer_size)\n\n// :QIODevice( parent )\n\n//{\n\n//\n\n// total_size=_buffer_size;\n\n// finished = false;\n\n// buffer = new char[_buffer_size*2];//just try it out\n\n// t=buffer;\n\n// len=fillData(t,_intbuffer,_buffer_size);\n\n// pos = 0;\n\n// total = len;\n\n//}\n\n//\n\n//Generator::~Generator()\n\n//{\n", "file_path": "generator.cpp", "rank": 13, "score": 15.034094955417025 }, { "content": " delete [] buffer;\n\n buffer=0;\n\n }\n\n}\n\n\n\nvoid Generator::start()\n\n{\n\n open(QIODevice::ReadOnly);\n\n}\n\n\n\nvoid Generator::stop()\n\n{\n\n close();\n\n}\n\n\n\nqint64 Generator::readData(char *data, qint64 maxlen)\n\n{\n\n int len = maxlen;\n\n if (len > framecount*4)\n\n len = framecount*4;\n", "file_path": "generator.cpp", "rank": 14, "score": 14.258963203924115 }, { "content": "\n\n#include <QtGui>\n\n#include <QtGlobal>\n\n#include \"helper.h\"\n\n#include <iostream>\n\n#include <QFileDialog>\n\n#include \"glwidget.h\"\n\n#include \"window.h\"\n\n\n\nvoid SelectionData::set(const QVector<QPoint>& selection)\n\n{\n\n this->selection=selection;\n\n if (this->selection.size()>0)\n\n {\n\n// this->sel\n\n }\n\n update();\n\n}\n\n\n\nvoid SelectionData::push_back(const QPoint &newPoint)\n", "file_path": "helper.cpp", "rank": 15, "score": 14.080440824581865 }, { "content": " }\n\n\n\n audioOutput = new QAudioOutput(settings,parent);\n\n parent->connect(audioOutput,SIGNAL(notify()),SLOT(status()));\n\n parent->connect(audioOutput,SIGNAL(stateChanged(QAudio::State)),SLOT(state(QAudio::State)));\n\n\n\n audioOutput->start(gen);\n\n}\n\n\n\nAudio::~Audio()\n\n{\n\n delete [] buffer;\n\n}\n\n\n\nvoid Audio::deviceChanged(int idx)\n\n{\n\n timer->stop();\n\n gen->stop();\n\n audioOutput->stop();\n\n audioOutput->disconnect(this);\n", "file_path": "audio.cpp", "rank": 16, "score": 13.910487076336157 }, { "content": "// void start();\n\n// void stop();\n\n//\n\n// char *t;\n\n// int len;\n\n// int pos;\n\n// int total;\n\n// char *buffer;\n\n// bool finished;\n\n// int chunk_size;\n\n// int total_size;\n\n//\n\n//\n\n// qint64 readData(char *data, qint64 maxlen);\n\n// qint64 writeData(const char *data, qint64 len);\n\n//\n\n//private:\n\n// int putShort(char *t, unsigned int value);\n\n// int fillData(char *start,int* _intbuffer,int _buffer_size);\n\n//};*/\n", "file_path": "generator.h", "rank": 18, "score": 13.849639262037043 }, { "content": "//\n\n//class Generator : public QIODevice\n\n//{\n\n// Q_OBJECT\n\n//public:\n\n// Generator(QObject *parent,int* _buffer, int _buffer_size);\n\n// ~Generator();\n\n//\n\n// void start();\n\n// void stop();\n\n//\n\n// char *t;\n\n// int len;\n\n// int pos;\n\n// int total;\n\n// char *buffer;\n\n// bool finished;\n\n// int chunk_size;\n\n// int total_len;\n\n//\n\n// qint64 readData(char *data, qint64 maxlen);\n\n// qint64 writeData(const char *data, qint64 len);\n\n//\n\n//private:\n\n// int putShort(char *t, unsigned int value);\n\n// int fillData(char *start, int frequency, int seconds,int* _buffer, int buffer_size);\n\n//};\n\n\n", "file_path": "generator.h", "rank": 19, "score": 13.712805656276275 }, { "content": " qSort(toDelete);\n\n\n\n for (int i=toDelete.size()-1;i>=0;i--)\n\n {\n\n std::cout<<\"deleting\"<<toDelete.size()<<\",\"<<toDelete[i]<<std::endl;\n\n int n = toDelete[i];\n\n this->beatGroups.remove(n);\n\n for (int j=0;j<anchors.size();j++)\n\n {\n\n Anchor& a = anchors[j];\n\n if (a.first.x()>n)\n\n {\n\n a.first.setX(a.first.x()-1);\n\n }\n\n if (a.second.x()>n)\n\n {\n\n a.second.setX(a.second.x()-1);\n\n }\n\n }\n\n }\n", "file_path": "helper.cpp", "rank": 20, "score": 13.593804815054183 }, { "content": " break;\n\n default:\n\n {\n\n QVector<Note> onsets = this->helper.generateOnsets();\n\n if (onsets.size()>0)\n\n {\n\n if (gen)\n\n {\n\n delete gen;\n\n gen=0;\n\n }\n\n playButton->setText(\"Stop\");\n\n\n\n std::cout<<\"playing\"<<std::endl;\n\n this->helper.playing=true;\n\n this->helper.playpos=0;\n\n //this->helper.soundMaker.loadInstrument(\"sound.wav\");\n\n //std::cout<<\"instrumentcount \"<<helper.soundMaker.instruments.size()<<std::endl;\n\n\n\n int framecount;\n", "file_path": "window.cpp", "rank": 21, "score": 13.069590408122904 }, { "content": " break;\n\n }}\n\n\n\nvoid Window::setViewAll()\n\n{\n\n this->helper.focus = -this->helper.bounds.topLeft();\n\n this->helper.scale = std::min(static_cast<qreal>(this->openGL->width())/this->helper.bounds.width(),static_cast<qreal>(this->openGL->height())/this->helper.bounds.height());\n\n this->helper.playpos=0;\n\n}\n\n\n\nvoid Window::selectInstrument()\n\n{\n\n\n\n}\n\n\n\nvoid Window::createMenu()\n\n{\n\n menuBar = new QMenuBar;\n\n\n\n fileMenu = new QMenu(tr(\"&File\"));\n", "file_path": "window.cpp", "rank": 22, "score": 12.9221306317592 }, { "content": "\n\n#include <QtGui>\n\n#include <QSplitter>\n\n#include <QDialog>\n\n\n\n#include \"widget.h\"\n\n#include \"window.h\"\n\n#include <iostream>\n\n\n\n#include <QAudioOutput>\n\n#include <QBoxLayout>\n\n#include <QSpacerItem>\n\n#include <QGroupBox>\n\n#include <QFileDialog>\n\n\n\nint computeListViewMinimumWidth(QAbstractItemView* view) {\n\nint minWidth = 0;\n\nQAbstractItemModel* model = view->model();\n\n\n\n// Too bad view->viewOptions() is protected\n", "file_path": "window.cpp", "rank": 23, "score": 12.683580321418122 }, { "content": " if (audioOutput->state() == QAudio::StoppedState)\n\n return;\n\n\n\n int l;\n\n int out;\n\n\n\n int chunks = audioOutput->bytesFree()/audioOutput->periodSize();\n\n while(chunks) {\n\n l = gen->read(buffer,audioOutput->periodSize());\n\n if (l > 0)\n\n out = output->write(buffer,l);\n\n if (l != audioOutput->periodSize())\n\n break;\n\n chunks--;\n\n }\n\n}\n\n\n\nvoid Audio::toggle()\n\n{\n\n // Change between pull and push modes\n", "file_path": "audio.cpp", "rank": 24, "score": 12.619777301974402 }, { "content": " exitAction = fileMenu->addAction(tr(\"E&xit\"));\n\n menuBar->addMenu(fileMenu);\n\n\n\n //connect(exitAction, SIGNAL(triggered()), this, SLOT(accept()));\n\n}\n\n//! [1]\n\n\n\nvoid Window::addInstrument()\n\n{ /*\n\n dialog(this);\n\n dialog.setFileMode(QFileDialog::ExistingFiles);\n\n dialog.setNameFilter(trUtf8(\"Splits (*.wav)\"));\n\n dialog.setLabelText(\"Select WAV file\");\n\n QStringList fileNames;\n\n if (dialog.exec())*/\n\n {\n\n QStringList fileNames = QFileDialog::getOpenFileNames(this,\"Select samples to load\",\"\",\"(*.wav)\");\n\n for (int i=0;i<fileNames.size();i++)\n\n {\n\n QString selectedFile = fileNames[i];\n", "file_path": "window.cpp", "rank": 25, "score": 12.473785960079828 }, { "content": " std::cout<<\"not order-preerving : \"<<a1<<\",\"<<a2<<\",\"<<b1<<\",\"<<b2<<std::endl;\n\n return false;\n\n }\n\n bFound=true;\n\n }\n\n else\n\n {\n\n std::cout<<\"can't have more than two constraints\"<<std::endl;\n\n\n\n return false;\n\n }\n\n }\n\n }\n\n\n\n //2: check no cycles AND\n\n //3: arrange into tree\n\n anchors.push_back(anchor);\n\n bool bResult = tryGenForest();\n\n anchors.pop_back();\n\n\n", "file_path": "helper.cpp", "rank": 26, "score": 12.202737693558852 }, { "content": "\n\nprivate:\n\n QAudioDeviceInfo device;\n\n Generator* gen;\n\n QAudioOutput* audioOutput;\n\n QIODevice* output;\n\n QAudioFormat settings;\n\n QTimer* timer;\n\n char* buffer;\n\n\n\n QMenuBar *menuBar;\n\n QMenu *fileMenu;\n\n QAction *exitAction;\n\n GLWidget *openGL;\n\n\n\n Helper helper;\n\n\n\n void createMenu();\n\n};\n\n//! [0]\n\n\n\n#endif\n", "file_path": "window.h", "rank": 27, "score": 12.186535174739824 }, { "content": " QVector<Note> onsets = this->helper.generateOnsets();\n\n if (onsets.size()>0)\n\n {\n\n QString fileName = QFileDialog::getSaveFileName(this,\"Select samples to load\",\"\",\"(*.wav)\");\n\n this->helper.soundMaker.SaveWave(onsets, fileName);\n\n }\n\n}\n\n\n\nvoid Window::keyPressEvent(QKeyEvent *event)\n\n{\n\n if (!this->openGL)\n\n return;\n\n\n\n switch( event->key() )\n\n {\n\n case Qt::Key_Backspace:\n\n case Qt::Key_Delete:\n\n this->openGL->helper->deleteSelection();\n\n break;\n\n default:\n", "file_path": "window.cpp", "rank": 28, "score": 12.129758730417986 }, { "content": " t=buffer;\n\n len=fillData(t,FREQ,SECONDS); /* mono FREQHz sine */\n\n pos = 0;\n\n total = len;\n\n}\n\n\n\nGenerator::~Generator()\n\n{\n\n delete [] buffer;\n\n}\n\n\n\nvoid Generator::start()\n\n{\n\n open(QIODevice::ReadOnly);\n\n}\n\n\n\nvoid Generator::stop()\n\n{\n\n close();\n\n}\n", "file_path": "audio.cpp", "rank": 29, "score": 12.008974352828147 }, { "content": " qWarning() << \"byteFree = \" << audioOutput->bytesFree() << \" bytes, elapsedUSecs = \" << audioOutput->elapsedUSecs() << \", processedUSecs = \" << audioOutput->processedUSecs();\n\n}\n\n\n\n\n\nvoid Window::writeMore()\n\n{\n\n if (!audioOutput)\n\n return;\n\n\n\n if (audioOutput->state() == QAudio::StoppedState)\n\n return;\n\n\n\n int l;\n\n int out;\n\n\n\n int chunks = audioOutput->bytesFree()/audioOutput->periodSize();\n\n while(chunks) {\n\n l = gen->read(buffer,audioOutput->periodSize());\n\n if (l > 0)\n\n out = output->write(buffer,l);\n", "file_path": "window.cpp", "rank": 30, "score": 11.893229860015447 }, { "content": "//\n\n\n\n\n\nint putShort(char *t, unsigned int value)\n\n{\n\n *(unsigned char *)(t++)=value&255;\n\n *(unsigned char *)(t)=(value/256)&255;\n\n return 2;\n\n}\n\n\n\nGenerator::Generator(QObject *parent, Helper *helper, int* _buffer, int _framecount)\n\n :QIODevice( parent )\n\n{\n\n this->helper=helper;\n\n done=false;\n\n pos=0;\n\n\n\n buffer = new char[_framecount*4];\n\n char* start=buffer;\n\n for (int i=0;i<_framecount*2;i++)\n", "file_path": "generator.cpp", "rank": 31, "score": 11.81799861868831 }, { "content": " return bResult;\n\n}\n\n\n\nbool Helper::tryGenForest()\n\n{\n\n forest.clear();\n\n\n\n for (int i=0;i<this->beatGroups.size();i++)\n\n {\n\n forest.push_back(AnchorTree(i));\n\n }\n\n\n\n for (int i=0;i<this->anchors.size();i++)\n\n {\n\n int constrained = this->anchors[i].first.x();\n\n int constraining = this->anchors[i].second.x();\n\n\n\n if (forest[constrained].searchFor(constraining))\n\n {\n\n std::cout<<\"recursive constraints\"<<std::endl;\n", "file_path": "helper.cpp", "rank": 32, "score": 11.660952866047111 }, { "content": "// len=fillData(t,FREQ,SECONDS,0,0); /* mono FREQHz sine */\n\n// pos = 0;\n\n// total = len;\n\n//}\n\n//\n\n//Generator::~Generator()\n\n//{\n\n// delete [] buffer;\n\n//}\n\n//\n\n//void Generator::start()\n\n//{\n\n// open(QIODevice::ReadOnly);\n\n//}\n\n//\n\n//void Generator::stop()\n\n//{\n\n// close();\n\n//}\n\n//\n", "file_path": "generator.cpp", "rank": 33, "score": 11.314749680205379 }, { "content": "\n\n settings.setFrequency(SYSTEM_FREQ);\n\n settings.setChannels(1);\n\n settings.setSampleSize(16);\n\n settings.setCodec(\"audio/pcm\");\n\n settings.setByteOrder(QAudioFormat::LittleEndian);\n\n settings.setSampleType(QAudioFormat::SignedInt);\n\n\n\n QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());\n\n if (!info.isFormatSupported(settings)) {\n\n qWarning()<<\"default format not supported try to use nearest\";\n\n settings = info.nearestFormat(settings);\n\n }\n\n\n\n if(settings.sampleSize() != 16) {\n\n qWarning()<<\"audio device doesn't support 16 bit samples, example cannot run\";\n\n button->setDisabled(true);\n\n button2->setDisabled(true);\n\n audioOutput = 0;\n\n return;\n", "file_path": "audio.cpp", "rank": 34, "score": 11.208354088511992 }, { "content": " }\n\n else\n\n {\n\n std::cerr<<\"Undoing mid-operation.\"<<std::endl;\n\n }\n\n\n\n}\n\n\n\nvoid Helper::onBeatGroupsChanged()\n\n{\n\n bool set=false;\n\n for (int i=0;i<this->beatGroups.size();i++)\n\n {\n\n if (!set)\n\n {\n\n set=true;\n\n this->bounds.setLeft(this->beatGroups[i].rect.left());\n\n this->bounds.setRight(this->beatGroups[i].rect.right());\n\n this->bounds.setTop(this->beatGroups[i].rect.top());\n\n this->bounds.setBottom(this->beatGroups[i].rect.bottom());\n", "file_path": "helper.cpp", "rank": 35, "score": 11.174717407292357 }, { "content": " for (int i=this->beatGroups.size()-1;i>=0;i--)\n\n {\n\n BeatGroup& bg = this->beatGroups[i];\n\n if (bg.beats.size()==0)\n\n {\n\n\n\n }\n\n }\n\n}\n\n\n\nvoid Helper::beginTransaction()\n\n{\n\n if (performingoperation)\n\n {\n\n std::cerr<<\"BEGINNING A TRANSACTION BEFORE HAVING ENDED THE PREVIOUS ONE\"<<std::endl;\n\n }\n\n {\n\n performingoperation=true;\n\n State s;\n\n s.anchors=this->anchors;\n", "file_path": "helper.cpp", "rank": 36, "score": 10.74247319435943 }, { "content": "\n\n#include <QtGui>\n\n#include <iostream>\n\n#include \"glwidget.h\"\n\n#include \"helper.h\"\n\n\n\n//! [0]\n\nGLWidget::GLWidget(Helper *helper, Window *parent)\n\n : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), helper(helper)\n\n{\n\n _parent=parent;\n\n helper->parent=this;\n\n elapsed = 0;\n\n //setFixedSize(200, 200);\n\n this->setMinimumSize(200,200);\n\n setAutoFillBackground(false);\n\n}\n\n//! [0]\n\n\n\n//! [1]\n", "file_path": "glwidget.cpp", "rank": 37, "score": 10.52260405163121 }, { "content": "#include \"audio.h\"\n\n\n\n#include <QDebug>\n\n#include <QAudioOutput>\n\n#include <QAudioDeviceInfo>\n\n#include <math.h>\n\n\n\n#ifndef M_PI\n\n#define M_PI 3.14159265358979323846\n\n#endif\n\n\n\n#define SECONDS 1\n\n#define FREQ 600\n\n#define SYSTEM_FREQ 44100\n\n\n\nGenerator::Generator(QObject *parent)\n\n :QIODevice( parent )\n\n{\n\n finished = false;\n\n buffer = new char[SECONDS*SYSTEM_FREQ*4+1000];\n", "file_path": "audio.cpp", "rank": 38, "score": 10.505168319966414 }, { "content": "//\n\n// return 0;\n\n//}*/\n\n//\n\n//\n\n//\n\n//Generator::Generator(QObject *parent,int* _buffer, int _buffer_size)\n\n//\n\n// :QIODevice( parent )\n\n//{\n\n// /*\n\n// finished = false;\n\n// buffer = new char[SECONDS*SYSTEM_FREQ*4+1000];\n\n// t=buffer;\n\n// len=fillData(t,FREQ,SECONDS,_buffer,_buffer_size); // mono FREQHz sine\n\n// pos = 0;\n\n// total = len;*/\n\n// finished = false;\n\n// buffer = new char[SECONDS*SYSTEM_FREQ*4+1000];\n\n// t=buffer;\n", "file_path": "generator.cpp", "rank": 39, "score": 10.046708007633658 }, { "content": "#ifndef AUDIO_H\n\n#define AUDIO_H\n\n\n\n\n\n\n\n\n\n#define BUFFER_SIZE 32768\n\n\n\n#include <QObject>\n\n#include <QMainWindow>\n\n#include <QIODevice>\n\n#include <QTimer>\n\n#include <QPushButton>\n\n#include <QComboBox>\n\n\n\n#include <QAudioOutput>\n\n#define BUFFER_SIZE 32768\n\n\n", "file_path": "audio.h", "rank": 40, "score": 9.84202257484581 }, { "content": " delete audioOutput;\n\n\n\n device = deviceBox->itemData(idx).value<QAudioDeviceInfo>();\n\n audioOutput = new QAudioOutput(device,settings,this);\n\n connect(audioOutput,SIGNAL(notify()),SLOT(status()));\n\n connect(audioOutput,SIGNAL(stateChanged(QAudio::State)),SLOT(state(QAudio::State)));\n\n gen->start();\n\n audioOutput->start(gen);\n\n}\n\n\n\nvoid Audio::status()\n\n{\n\n qWarning() << \"byteFree = \" << audioOutput->bytesFree() << \" bytes, elapsedUSecs = \" << audioOutput->elapsedUSecs() << \", processedUSecs = \" << audioOutput->processedUSecs();\n\n}\n\n\n\nvoid Audio::writeMore()\n\n{\n\n if (!audioOutput)\n\n return;\n\n\n", "file_path": "audio.cpp", "rank": 41, "score": 9.828851683102938 }, { "content": " return false;\n\n }\n\n\n\n if (!forest[constraining].searchFor(constrained))\n\n {\n\n forest[constraining].children.push_back(&forest[constrained]);\n\n }\n\n }\n\n\n\n //from here on, index does not correspond to label\n\n\n\n return true;\n\n}\n\n\n\nvoid Helper::deleteSelection()\n\n{\n\n QVector<QPoint> selection = this->selection.getSelection();\n\n\n\n for (int i=anchors.size()-1;i>=0;i--)\n\n {\n", "file_path": "helper.cpp", "rank": 42, "score": 9.734393863314432 }, { "content": "\n\n#ifndef HELPER_H\n\n#define HELPER_H\n\n\n\n#include <QBrush>\n\n#include <QFont>\n\n#include <QPen>\n\n#include <QStack>\n\n#include <QSound>\n\n#include <iostream>\n\n\n\n#include \"soundmaker.h\"\n\n\n\nQT_BEGIN_NAMESPACE\n", "file_path": "helper.h", "rank": 43, "score": 9.728804096575745 }, { "content": " audioOutput = new QAudioOutput(settings,this);\n\n audioOutput->setBufferSize(BUFFER_SIZE);\n\n \n\n connect(audioOutput,SIGNAL(notify()),SLOT(status()));\n\n connect(audioOutput,SIGNAL(stateChanged(QAudio::State)),SLOT(state(QAudio::State)));\n\n\n\n timer = new QTimer(this);\n\n connect(timer,SIGNAL(timeout()),SLOT(writeMore()));\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n // Set up overall layout\n\n QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom);\n\n layout->setSpacing(1);\n", "file_path": "window.cpp", "rank": 44, "score": 9.637320420951488 }, { "content": " void terminateTransaction();\n\n void cacheState();\n\n void undo();\n\n\n\n Highlight hovering;\n\n\n\n void paint(QPainter *painter, QPaintEvent *event, qreal elapsed);\n\n\n\n enum ToolMode {TM_None,TM_Select,TM_Create,TM_Drag, TM_Anchor, TM_Move} toolmode;\n\n\n\n void onBeatGroupsChanged();\n\n void onAnchorsChanged();\n\n bool onAnchorsChangedInner();\n\n bool setDockingPositions(AnchorTree& tree);\n\n\n\n bool canAdd(const Anchor& anchor);\n\n bool dragging;\n\n\n\n void deleteSelection();\n\n\n", "file_path": "helper.h", "rank": 45, "score": 9.306278234103505 }, { "content": "\n\n settings.setSampleRate(SYSTEM_FREQ);\n\n settings.setChannelCount(2);\n\n settings.setSampleSize(16);\n\n settings.setCodec(\"audio/pcm\");\n\n settings.setByteOrder(QAudioFormat::LittleEndian);\n\n settings.setSampleType(QAudioFormat::SignedInt);\n\n\n\n QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());\n\n if (!info.isFormatSupported(settings)) {\n\n qWarning()<<\"default format not supported try to use nearest\";\n\n settings = info.nearestFormat(settings);\n\n }\n\n\n\n if(settings.sampleSize() != 16) {\n\n qWarning()<<\"audio device doesn't support 16 bit samples, example cannot run\";\n\n audioOutput = 0;\n\n return;\n\n }\n\n\n", "file_path": "window.cpp", "rank": 46, "score": 9.305807898693164 }, { "content": "//int Generator::fillData(char *start,int* _intbuffer,int _buffer_size)\n\n//{\n\n//\n\n// int i, len=0;\n\n// int value;\n\n// for(i=0; i<_buffer_size; i++) {\n\n// value=(int)(32767.0*sin(2.0*M_PI*((double)(i))*(double)(400.0)/SYSTEM_FREQ));\n\n// putShort(start, value);\n\n// start += 4;\n\n// len+=2;\n\n// _intbuffer++;\n\n// }\n\n// return len;\n\n//\n\n//}\n\n//\n\n//qint64 Generator::readData(char *data, qint64 maxlen)\n\n//{\n\n// int len = maxlen;\n\n// if (len > 16384)\n", "file_path": "generator.cpp", "rank": 48, "score": 9.047704750944934 }, { "content": " }\n\n this->helper->toolmode=Helper::TM_None;\n\n helper->pressed=false;\n\n}\n\n//! [3]\n\n\n\n//! [4]\n\nvoid GLWidget::wheelEvent ( QWheelEvent * event )\n\n{\n\n const qreal scalespeed = 1.05;\n\n\n\n int numDegrees = event->delta() / 8;\n\n\n\n QPointF oldCursorPosScreen = (helper->focus+helper->cursorPos)*helper->scale;\n\n\n\n this->helper->scale=std::min(std::max(this->helper->scale*pow(scalespeed,numDegrees),0.1),10.0);\n\n helper->focus = oldCursorPosScreen/helper->scale-helper->cursorPos;\n\n\n\n\n\n event->accept();\n\n}\n\n//! [4]\n\n\n", "file_path": "glwidget.cpp", "rank": 49, "score": 9.021857222329462 }, { "content": "#ifndef GENERATOR_H\n\n#define GENERATOR_H\n\n\n\n#include <QIODevice>\n\n\n\n#define BUFFER_SIZE 32768\n\n#ifndef M_PI\n\n#define M_PI 3.14159265358979323846\n\n#endif\n\n\n\n#define SYSTEM_FREQ 44100\n\n//\n\n///*\n\n//class Generator : public QIODevice\n\n//{\n\n// Q_OBJECT\n\n//public:\n\n// Generator(QObject *parent,int* _buffer, int _buffer_size);\n\n// ~Generator();\n\n//\n", "file_path": "generator.h", "rank": 50, "score": 8.96158033554013 }, { "content": "\n\n#ifndef WINDOW_H\n\n#define WINDOW_H\n\n\n\n#include <QWidget>\n\n#include <QMenuBar>\n\n#include <QMenu>\n\n#include <QAudioOutput>\n\n#include <QAudioDeviceInfo>\n\n#include <QPushButton>\n\n#include <QLabel>\n\n#include <QSlider>\n\n#include <QListWidget>\n\n#include <QComboBox>\n\n#include <QListWidgetItem>\n\n\n\n#include \"helper.h\"\n\n#include \"glwidget.h\"\n\n\n\nQT_BEGIN_NAMESPACE\n", "file_path": "window.h", "rank": 51, "score": 8.495672024782754 }, { "content": " {\n\n int sample = this->_parent->beatGroups[this->selection[i].x()].beats[this->selection[i].y()].sample;\n\n selectedInsts.insert(sample);\n\n // make a multiple selection (i'm not sure, maybe you need to use QItemSelection) \n\n }\n\n\n\n if (selectedInsts.size()==1)\n\n {\n\n int selected=*selectedInsts.begin();\n\n myListWidget->setCurrentItem(myListWidget->item(selected));\n\n }\n\n else\n\n {\n\n myListWidget->setCurrentItem(0);\n\n }\n\n}\n\n\n\n//! [0]\n\nHelper::Helper():\n\n defaultBeat(),\n", "file_path": "helper.cpp", "rank": 52, "score": 8.335126849226715 }, { "content": " {\n\n a.second.setY(a.second.y()+1);\n\n }\n\n }\n\n QVector<Beat>& beats = this->beatGroups[p.x()].beats;\n\n beats.insert(beats.begin()+p.y(),this->defaultBeat);\n\n}\n\n\n\n//after calling this, should try delete all beatgroups with no members\n\nvoid Helper::RemoveBeat(const QPoint& p)\n\n{\n\n Q_ASSERT(p.x()<this->beatGroups.size() && p.y()<this->beatGroups[p.x()].beats.size());\n\n\n\n //change anchors\n\n for (int i=this->anchors.size()-1;i>=0;i--)\n\n {\n\n bool bShouldRemove=false;\n\n Anchor& a=anchors[i];\n\n if (a.first.x()==p.x()&&a.first.y()>p.y())\n\n {\n", "file_path": "helper.cpp", "rank": 53, "score": 8.306796650568351 }, { "content": " while (!onAnchorsChangedInner()){}\n\n\n\n this->onBeatGroupsChanged();\n\n}\n\n\n\n\n\nbool Helper::onAnchorsChangedInner()\n\n{\n\n tryGenForest();\n\n\n\n for (int i=0;i<forest.size();i++)\n\n {\n\n if (!setDockingPositions(forest[i]))\n\n return false;\n\n }\n\n\n\n return true;\n\n}\n\n\n\n\n", "file_path": "helper.cpp", "rank": 54, "score": 8.212144466624794 }, { "content": "\n\n timer->stop();\n\n audioOutput->stop();\n\n\n\n if (pullMode) {\n\n button->setText(\"Click for Pull Mode\");\n\n output = audioOutput->start();\n\n pullMode = false;\n\n timer->start(20);\n\n } else {\n\n button->setText(\"Click for Push Mode\");\n\n pullMode = true;\n\n audioOutput->start(gen);\n\n }\n\n}\n\n\n\nvoid Audio::togglePlay()\n\n{\n\n // toggle suspend/resume\n\n if (audioOutput->state() == QAudio::SuspendedState) {\n", "file_path": "audio.cpp", "rank": 55, "score": 8.10984472759293 }, { "content": "// total_len=buffer_size;\n\n// return len;*/\n\n// int i, len=0;\n\n// int value;\n\n// for(i=0; i<seconds*SYSTEM_FREQ; i++) {\n\n// value=(int)(32767.0*sin(2.0*M_PI*((double)(i))*(double)(frequency)/SYSTEM_FREQ));\n\n// putShort(start, value);\n\n// start += 4;\n\n// len+=2;\n\n// }\n\n// return len;\n\n//}\n\n//\n\n//qint64 Generator::readData(char *data, qint64 maxlen)\n\n//{\n\n// int len = maxlen;\n\n// if (len > 16384)\n\n// len = 16384;\n\n///*\n\n// if (len < (SECONDS*SYSTEM_FREQ*2)-pos) {\n", "file_path": "generator.cpp", "rank": 56, "score": 7.741581835491393 }, { "content": "\n\n if (len < (framecount*4)-pos) {\n\n // Normal\n\n memcpy(data,buffer+pos,len);\n\n pos+=len;\n\n return len;\n\n } else {\n\n // Whats left and reset to start\n\n qint64 left = (framecount*4)-pos;\n\n memcpy(data,buffer+pos,left);\n\n pos=0;\n\n std::cout<<\"BLIP\";\n\n this->helper->playpos=BUFFER_SIZE/SYSTEM_FREQ;\n\n return left;\n\n }\n\n}\n\n\n\nqint64 Generator::writeData(const char *data, qint64 len)\n\n{\n\n Q_UNUSED(data);\n\n Q_UNUSED(len);\n\n\n\n return 0;\n\n}\n\n\n", "file_path": "generator.cpp", "rank": 58, "score": 7.586154727412808 }, { "content": " for (int j=0;j<selection.size();j++)\n\n {\n\n if (anchors[i].first.x()==selection[j].x() || anchors[i].second.x()==selection[j].x())\n\n {\n\n anchors.remove(i);\n\n break;\n\n }\n\n }\n\n }\n\n\n\n QVector<int> toDelete;\n\n\n\n for (int i=0;i<selection.size();i++)\n\n {\n\n if (toDelete.indexOf(selection[i].x())<0)\n\n {\n\n toDelete.push_back(selection[i].x());\n\n }\n\n }\n\n\n", "file_path": "helper.cpp", "rank": 59, "score": 7.444612125809359 }, { "content": " playButton = new QPushButton(\"&play\");\n\n connect(playButton, SIGNAL(clicked()), this,SLOT(setPlay()));\n\n toolbar->addWidget(playButton,0);\n\n QPushButton *button4 = new QPushButton(\"&view all\");\n\n connect(button4, SIGNAL(clicked()), this,SLOT(setViewAll()));\n\n toolbar->addWidget(button4,0);\n\n\n\n\n\n QSpacerItem *toolbarSpacer = new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Expanding);\n\n toolbar->addSpacerItem(toolbarSpacer);\n\n\n\n // Splitter main occupies main area\n\n QHBoxLayout *splitter = new QHBoxLayout;\n\n layout->addLayout(splitter,1);\n\n\n\n // main area on the left\n\n openGL = new GLWidget(&helper, this);\n\n\n\n openGL->setMouseTracking(true);\n\n openGL->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);\n", "file_path": "window.cpp", "rank": 60, "score": 7.322736584850513 }, { "content": "\n\nint Generator::putShort(char *t, unsigned int value)\n\n{\n\n *(unsigned char *)(t++)=value&255;\n\n *(unsigned char *)(t)=(value/256)&255;\n\n return 2;\n\n}\n\n\n\nint Generator::fillData(char *start, int frequency, int seconds)\n\n{\n\n int i, len=0;\n\n int value;\n\n for(i=0; i<seconds*SYSTEM_FREQ; i++) {\n\n value=(int)(32767.0*sin(2.0*M_PI*((double)(i))*(double)(frequency)/SYSTEM_FREQ));\n\n putShort(start, value);\n\n start += 4;\n\n len+=2;\n\n }\n\n return len;\n\n}\n", "file_path": "audio.cpp", "rank": 61, "score": 6.935760363795455 }, { "content": "\n\n#include <QApplication>\n\n#include \"window.h\"\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n QApplication app(argc, argv);\n\n Window window;\n\n window.show();\n\n return app.exec();\n\n}\n", "file_path": "main.cpp", "rank": 62, "score": 6.831054924186461 }, { "content": " selection(this)\n\n{\n\n playing=false;\n\n if (QMultimedia::Available!=0)\n\n {\n\n std::cerr<<\"ERROR - sound notavailable\"<<std::endl;\n\n }\n\n\n\n background = QBrush(QColor(100, 100, 140));\n\n scorePen = QPen(QColor(110, 110, 200));\n\n circleBrush = QBrush(QColor(100,100,255,30));\n\n circlePen = QPen(Qt::black);\n\n circlePen.setWidth(1);\n\n circlePen.setCosmetic(true);\n\n defaultBeatCount=4;\n\n\n\n\n\n clearBrush = QBrush();\n\n clearPen = QPen(Qt::transparent);\n\n\n", "file_path": "helper.cpp", "rank": 63, "score": 6.802852882337533 }, { "content": "\n\n this->helper.soundMaker.loadInstrument(selectedFile);\n\n }\n\n repopulateInstrumentList();\n\n }\n\n}\n\n\n\nvoid Window::repopulateInstrumentList()\n\n{\n\n this->soundSelector->clear();\n\n for (int i=0;i<this->helper.soundMaker.names.size();i++)\n\n {\n\n this->soundSelector->addItem(this->helper.soundMaker.names[i]);\n\n }\n\n}\n\n\n\n\n\nvoid Window::listWidgetItemClicked( QListWidgetItem *item )\n\n{\n\n const QVector<QPoint> selection = this->helper.selection.getSelection();\n", "file_path": "window.cpp", "rank": 64, "score": 6.785902199668147 }, { "content": "{\n\n this->selection.push_back(newPoint);\n\n if (this->selection.size()>0)\n\n {\n\n// this->selection.s\n\n }\n\n update();\n\n}\n\n\n\nvoid SelectionData::update()\n\n{\n\n QListWidget* myListWidget = this->_parent->parent->_parent->soundSelector;\n\n\n\n QItemSelectionModel * selectionModel = myListWidget->selectionModel();\n\n\n\n // clear the selection\n\n selectionModel->clearSelection(); // or QItemSelectionModel::clear()\n\n\n\n QSet<int> selectedInsts;\n\n for (int i=0;i<this->selection.size();i++)\n", "file_path": "helper.cpp", "rank": 65, "score": 6.6989970888813115 }, { "content": " bool tryGenForest();\n\n\n\n QVector<BeatGroup> beatGroups;\n\n\n\n void InsertBeatAfter(const QPoint& p);\n\n void RemoveBeat(const QPoint& p);\n\n void ClearEmptyBeatGroups();\n\n\n\n QVector<QPointF> selectionDiffs;\n\n\n\n QVector <int> movingTargets;\n\n\n\n QVector<AnchorTree> forest;\n\n\n\n QVector<QPair<QPoint,QPoint> > anchors;\n\n\n\n QPointF dragFrom;\n\n QPointF cursorPos;\n\n\n\n QPointF focus;\n", "file_path": "helper.h", "rank": 66, "score": 6.698397829931616 }, { "content": " qreal scale;\n\n qreal bpm;\n\n\n\n QRectF bounds;\n\n\n\n QPoint anchorFrom;\n\n\n\n bool pressed;\n\n\n\n qreal playpos;\n\n bool playing;\n\n\n\n GLWidget* parent;\n\n\n\n QRectF getEdgeHitBox(int i,int j);\n\n QRectF getCellHitBox(int i,int j);\n\n QRectF getAnchorHitBox(int n);\n\n\n\nprivate:\n\n QBrush background;\n", "file_path": "helper.h", "rank": 67, "score": 6.57537146236006 }, { "content": "\n\nqint64 Generator::writeData(const char *data, qint64 len)\n\n{\n\n Q_UNUSED(data);\n\n Q_UNUSED(len);\n\n\n\n return 0;\n\n}\n\n\n\nAudio::Audio(QWidget *parent)\n\n{\n\n this->parent=parent;\n\n\n\n buffer = new char[BUFFER_SIZE];\n\n\n\n gen = new Generator(parent);\n\n\n\n pullMode = parent;\n\n\n\n gen->start();\n", "file_path": "audio.cpp", "rank": 68, "score": 6.499646924289552 }, { "content": " for (int i=0;i<this->anchors.size();i++)\n\n {\n\n if (this->anchors[i].first==from)\n\n {\n\n std::cout<<\"this cell is already linked : \"<<std::endl;\n\n return false;\n\n }\n\n if (this->anchors[i].first.x()==from.x())\n\n {\n\n if (!bFound)\n\n {\n\n //4: ensure pairs are in right order\n\n qreal a1 = this->beatGroups[from.x()].getCellX(from.y());\n\n qreal a2 = this->beatGroups[to.x()].getCellX(to.y());\n\n\n\n qreal b1 = this->beatGroups[anchors[i].first.x()].getCellX(anchors[i].first.y());\n\n qreal b2 = this->beatGroups[anchors[i].second.x()].getCellX(anchors[i].second.y());\n\n\n\n if ( (a1<b1) != (a2<b2))\n\n {\n", "file_path": "helper.cpp", "rank": 69, "score": 6.498281074065978 }, { "content": "\n\nvoid Window::moreBeats()\n\n{\n\n this->helper.defaultBeatCount++;\n\n this->cellCountLabel->setText(QString().setNum(this->helper.defaultBeatCount));\n\n}\n\n\n\n\n\nvoid Window::fewerBeats()\n\n{\n\n this->helper.defaultBeatCount--;\n\n if (this->helper.defaultBeatCount<1)\n\n this->helper.defaultBeatCount=1;\n\n this->cellCountLabel->setText(QString().setNum(this->helper.defaultBeatCount));\n\n}\n\n\n\n\n\n\n\nvoid Window::status()\n\n{\n", "file_path": "window.cpp", "rank": 70, "score": 6.258101813606787 }, { "content": " }\n\n\n\n\n\n break;\n\n }\n\n }\n\n */\n\n}\n\n//! [3]\n\n\n\n//! [3]\n\nvoid GLWidget::mouseReleaseEvent(QMouseEvent * event)\n\n{ \n\n\n\n const QPointF& from = this->helper->dragFrom;\n\n const QPointF& to = this->helper->cursorPos;\n\n qreal left = std::min(from.x(),to.x());\n\n qreal right = std::max(from.x(),to.x());\n\n qreal top = std::min(from.y(),to.y());\n\n qreal bottom = std::max(from.y(),to.y());\n", "file_path": "glwidget.cpp", "rank": 71, "score": 6.155227067127921 }, { "content": " QRectF& parentRect = this->beatGroups[tree.label].rect;\n\n\n\n for (int i=0;i<tree.children.size();i++)\n\n {\n\n QRectF& childRect = this->beatGroups[tree.children[i]->label].rect;\n\n\n\n if (parentRect.bottom()+12>childRect.top())\n\n {\n\n childRect.moveTop(parentRect.bottom()+12);\n\n }\n\n\n\n if (!setDockingPositions(*tree.children[i]))\n\n return false;\n\n }\n\n\n\n return true;\n\n}\n\n\n\nvoid Helper::onAnchorsChanged()\n\n{\n", "file_path": "helper.cpp", "rank": 72, "score": 6.083669978526226 }, { "content": "\n\n#include <QtGui>\n\n#include \"widget.h\"\n\n#include \"helper.h\"\n\n\n\n\n\n//! [0]\n\nWidget::Widget(Helper *helper, QWidget *parent)\n\n : QWidget(parent), helper(helper)\n\n{\n\n elapsed = 0;\n\n setFixedSize(200, 200);\n\n}\n\n//! [0]\n\n\n\n//! [1]\n\nvoid Widget::animate()\n\n{\n\n elapsed = (elapsed + qobject_cast<QTimer*>(sender())->interval()) % 1000;\n\n repaint();\n", "file_path": "widget.cpp", "rank": 73, "score": 5.9890180585753825 }, { "content": " if (l != audioOutput->periodSize())\n\n break;\n\n chunks--;\n\n }\n\n}\n\n\n\nvoid Window::state(QAudio::State state)\n\n{\n\n qWarning() << \" state=\" << state;\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "window.cpp", "rank": 74, "score": 5.983581128285897 }, { "content": " Q_ASSERT(index>=0);\n\n\n\n this->helper.beatGroups[selection[i].x()].beats[selection[i].y()].sample=-1;\n\n }\n\n }\n\n else\n\n {\n\n previousSelectedListWidgetItem = item;\n\n\n\n for (int i=0;i<selection.size();i++)\n\n {\n\n Q_ASSERT(index>=0);\n\n\n\n this->helper.beatGroups[selection[i].x()].beats[selection[i].y()].sample=index;\n\n }\n\n }\n\n this->helper.defaultBeat.sample=index;\n\n }\n\n}\n\n\n", "file_path": "window.cpp", "rank": 75, "score": 5.926771749285869 }, { "content": " \");\n\n selectedProperties->addWidget(volumeSlider);\n\n\n\n QLabel *panningLabel = new QLabel(\"panning\");\n\n selectedProperties->addWidget(panningLabel);\n\n panningSlider = new QSlider(Qt::Horizontal);\n\n selectedProperties->addWidget(panningSlider);\n\n\n\n\n\n // QLabel *sampleLabel = new QLabel(\"sound\");\n\n // selectedProperties->addWidget(sampleLabel);\n\n soundSelector = new QListWidget();\n\n soundSelector->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Expanding);\n\n //soundSelector->setFixedWidth(selectedProperties->geometry().width());\n\n rightPanel->addWidget(soundSelector);\n\n QPushButton *addInstrumentButton = new QPushButton(\"add new sample\");\n\n rightPanel->addWidget(addInstrumentButton,0);\n\n connect(addInstrumentButton,SIGNAL(clicked()),this,SLOT(addInstrument()));\n\n\n\n connect( soundSelector, SIGNAL( itemClicked( QListWidgetItem * ) ),\n", "file_path": "window.cpp", "rank": 76, "score": 5.903237338173124 }, { "content": " }\n\n else\n\n {\n\n this->bounds.setLeft(std::min(this->bounds.left(),this->beatGroups[i].rect.left()));\n\n this->bounds.setRight(std::max(this->bounds.right(),this->beatGroups[i].rect.right()));\n\n this->bounds.setTop(std::min(this->bounds.top(),this->beatGroups[i].rect.top()));\n\n this->bounds.setBottom(std::max(this->bounds.bottom(),this->beatGroups[i].rect.bottom()));\n\n }\n\n }\n\n}\n\n\n\n// A little weird...should probably keep the forest around allways instead of\n\n// recalculating it each time.\n\nbool Helper::canAdd(const Anchor& anchor)\n\n{\n\n QPoint from = anchor.first;\n\n QPoint to = anchor.second;\n\n\n\n //1: can't add if there are already two lines coming from here\n\n bool bFound=false;\n", "file_path": "helper.cpp", "rank": 77, "score": 5.871616327231267 }, { "content": " this->beatGroups=s.beatGroups;\n\n this->onAnchorsChanged();\n\n }\n\n else\n\n {\n\n std::cerr<<\"Terminating a transaction that was never begun.\"<<std::endl;\n\n }\n\n}\n\n\n\nvoid Helper::undo()\n\n{\n\n if (!performingoperation)\n\n {\n\n if (this->stack.size()>0)\n\n {\n\n State s = this->stack.pop();\n\n this->anchors=s.anchors;\n\n this->beatGroups=s.beatGroups;\n\n this->onAnchorsChanged();\n\n }\n", "file_path": "helper.cpp", "rank": 78, "score": 5.845674931370228 }, { "content": " a.first.setY(a.first.y()+1);\n\n bShouldRemove=true;\n\n }\n\n if (a.second.x()==p.x()&&a.second.y()>p.y())\n\n {\n\n a.second.setY(a.second.y()+1);\n\n bShouldRemove=true;\n\n }\n\n\n\n if (bShouldRemove)\n\n {\n\n this->anchors.remove(i);\n\n }\n\n }\n\n this->beatGroups[p.x()].beats.remove(p.y());\n\n}\n\n\n\n//need to call 'tidy up after alteration' functions after here\n\nvoid Helper::ClearEmptyBeatGroups()\n\n{\n", "file_path": "helper.cpp", "rank": 79, "score": 5.761055082250791 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "glwidget.cpp", "rank": 80, "score": 5.738167252417364 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "window.h", "rank": 81, "score": 5.738167252417364 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "window.cpp", "rank": 82, "score": 5.738167252417363 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "helper.cpp", "rank": 83, "score": 5.738167252417364 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "main.cpp", "rank": 84, "score": 5.738167252417364 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "widget.h", "rank": 85, "score": 5.738167252417363 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "glwidget.h", "rank": 86, "score": 5.738167252417364 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "helper.h", "rank": 87, "score": 5.738167252417364 }, { "content": "/****************************************************************************\n\n**\n\n** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n\n** All rights reserved.\n\n** Contact: Nokia Corporation ([email protected])\n\n**\n\n** This file is part of the examples of the Qt Toolkit.\n\n**\n\n** $QT_BEGIN_LICENSE:LGPL$\n\n** Commercial Usage\n\n** Licensees holding valid Qt Commercial licenses may use this file in\n\n** accordance with the Qt Commercial License Agreement provided with the\n\n** Software or, alternatively, in accordance with the terms contained in\n\n** a written agreement between you and Nokia.\n\n**\n\n** GNU Lesser General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU Lesser\n\n** General Public License version 2.1 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.LGPL included in the\n\n** packaging of this file. Please review the following information to\n", "file_path": "widget.cpp", "rank": 88, "score": 5.738167252417363 }, { "content": "\n\n this->selection.clear();\n\n\n\n this->onAnchorsChanged();\n\n}\n\n\n\nbool Helper::setDockingPositions(AnchorTree& tree)\n\n{\n\n QPair<int,qreal> anchor1;\n\n QPair<int,qreal> anchor2;\n\n\n\n Anchor* pAnchor1=0;\n\n Anchor* pAnchor2=0;\n\n\n\n anchor1.first=-1;\n\n anchor2.first=-1;\n\n\n\n for (int j=0;j<anchors.size();j++)\n\n {\n\n if (anchors[j].first.x()==tree.label)\n", "file_path": "helper.cpp", "rank": 89, "score": 5.72605577503621 }, { "content": " qWarning() << \"status: Suspended, resume()\";\n\n audioOutput->resume();\n\n button2->setText(\"Click To Suspend\");\n\n } else if (audioOutput->state() == QAudio::ActiveState) {\n\n qWarning() << \"status: Active, suspend()\";\n\n audioOutput->suspend();\n\n button2->setText(\"Click To Resume\");\n\n } else if (audioOutput->state() == QAudio::StoppedState) {\n\n qWarning() << \"status: Stopped, resume()\";\n\n audioOutput->resume();\n\n button2->setText(\"Click To Suspend\");\n\n } else if (audioOutput->state() == QAudio::IdleState) {\n\n qWarning() << \"status: IdleState\";\n\n }\n\n}\n\n\n\nvoid Audio::state(QAudio::State state)\n\n{\n\n qWarning() << \" state=\" << state;\n\n}\n", "file_path": "audio.cpp", "rank": 90, "score": 5.547029396561515 }, { "content": " }\n\n break;\n\n }\n\n}\n\n\n\nQRectF Helper::getAnchorHitBox(int n)\n\n{\n\n n++;//to stop warning\n\n return QRectF();\n\n}\n\n\n\nvoid Helper::paint(QPainter *painter, QPaintEvent *event, qreal elapsed)\n\n{\n\n painter->fillRect(event->rect(), background);\n\n int w = this->parent->width();\n\n int h = this->parent->height();\n\n\n\n\n\n //painter->translate(100, 100);\n\n\n", "file_path": "helper.cpp", "rank": 91, "score": 5.463680630702114 }, { "content": " this, SLOT( listWidgetItemClicked( QListWidgetItem * )));\n\n\n\n //QSpacerItem *rightPanelSpacer = new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Expanding);\n\n //rightPanel->addSpacerItem(rightPanelSpacer);\n\n\n\n\n\n QTimer *timer = new QTimer(this);\n\n connect(timer, SIGNAL(timeout()), openGL, SLOT(animate()));\n\n\n\n timer->start(50);\n\n\n\n setWindowTitle(tr(\"2D Painting on Native and OpenGL Widgets\"));\n\n}\n\n\n\n\n\n#define SECONDS 1\n\n#define FREQ 600\n\n#define SYSTEM_FREQ 44100\n\n\n\n\n", "file_path": "window.cpp", "rank": 92, "score": 5.3194283633431105 }, { "content": "\n\n if (diff>cellWidth || diff<-cellWidth)\n\n {\n\n bool toRight = diff>cellWidth;\n\n if (toRight)\n\n {\n\n helper->dragFrom.setX(helper->dragFrom.x()-cellWidth);\n\n }\n\n else\n\n {\n\n helper->dragFrom.setX(helper->dragFrom.x()+cellWidth);\n\n }\n\n\n\n for (int i=this->helper->anchors.size()-1;i>=0;i--)\n\n {\n\n Anchor& a = this->helper->anchors[i];\n\n if (a.first.x()==movingTarget)\n\n {\n\n int cell = a.first.y();\n\n if (!toRight && cell>0)\n", "file_path": "glwidget.cpp", "rank": 93, "score": 5.073233630194231 }, { "content": "** ensure the GNU Lesser General Public License version 2.1 requirements\n\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\n\n**\n\n** In addition, as a special exception, Nokia gives you certain additional\n\n** rights. These rights are described in the Nokia Qt LGPL Exception\n\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n\n**\n\n** GNU General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU\n\n** General Public License version 3.0 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.GPL included in the\n\n** packaging of this file. Please review the following information to\n\n** ensure the GNU General Public License version 3.0 requirements will be\n\n** met: http://www.gnu.org/copyleft/gpl.html.\n\n**\n\n** If you have questions regarding the use of this file, please contact\n\n** Nokia at [email protected].\n\n** $QT_END_LICENSE$\n\n**\n\n****************************************************************************/\n\n\n\n#ifndef WIDGET_H\n\n#define WIDGET_H\n\n\n\n#include <QWidget>\n\n\n\n//! [0]\n", "file_path": "widget.h", "rank": 94, "score": 4.775375639338009 }, { "content": " this->performingoperation=false;\n\n}\n\n\n\nQVector<Note> Helper::generateOnsets()\n\n{\n\n QVector<Note> onsets;\n\n\n\n qreal leftmost = this->bounds.left();\n\n\n\n for (int i=0;i<this->beatGroups.size();i++)\n\n {\n\n BeatGroup& bg = this->beatGroups[i];\n\n for (int j=0;j<bg.beats.size();j++)\n\n {\n\n Note s;\n\n s.instrument=bg.beats[j].sample;\n\n s.pan=bg.beats[j].pan;\n\n s.volumn=bg.beats[j].vol;\n\n s.onset=(bg.getCellX(j)-leftmost)/100;\n\n onsets.push_back(s);\n", "file_path": "helper.cpp", "rank": 95, "score": 4.761260234160229 }, { "content": " }\n\n }\n\n\n\n qSort(onsets);\n\n return onsets;\n\n}\n\n\n\nvoid Helper::InsertBeatAfter(const QPoint& p)\n\n{\n\n Q_ASSERT(p.x()<this->beatGroups.size() && p.y()<this->beatGroups[p.x()].beats.size());\n\n\n\n //change anchors\n\n for (int i=0;i<this->anchors.size();i++)\n\n {\n\n Anchor& a=anchors[i];\n\n if (a.first.x()==p.x()&&a.first.y()>p.y())\n\n {\n\n a.first.setY(a.first.y()+1);\n\n }\n\n if (a.second.x()==p.x()&&a.second.y()>p.y())\n", "file_path": "helper.cpp", "rank": 96, "score": 4.651436335645406 }, { "content": " std::cerr<<\"wrong order\"<<anchor1.second<<\",\"<<anchor2.second<<std::endl;\n\n qSwap(anchor1.second,anchor2.second);\n\n // swap anchor components aswell\n\n {\n\n int y1 = pAnchor1->first.y();\n\n int y2 = pAnchor2->first.y();\n\n pAnchor1->first.setY(y2);\n\n pAnchor2->first.setY(y1);\n\n }\n\n return false;\n\n }\n\n\n\n BeatGroup& bg = this->beatGroups[tree.label];\n\n QRectF& rect = bg.rect;\n\n\n\n qreal cell_dist = bg.getCellX(anchor2.first) - bg.getCellX(anchor1.first);\n\n rect.setWidth(rect.width()*(anchor2.second-anchor1.second)/cell_dist);\n\n rect.moveLeft(anchor1.second-bg.cellWidth()*anchor1.first);\n\n }\n\n\n", "file_path": "helper.cpp", "rank": 97, "score": 4.572481884907839 }, { "content": " splitter->addWidget(openGL);\n\n\n\n // panel on the right\n\n QGroupBox* rightPanelBox = new QGroupBox();\n\n rightPanelBox->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Expanding);\n\n rightPanelBox->setFixedWidth(200);\n\n splitter->addWidget(rightPanelBox);\n\n\n\n\n\n QVBoxLayout* rightPanel = new QVBoxLayout;\n\n rightPanel->setSpacing(1);\n\n rightPanel->setMargin(1);\n\n rightPanelBox->setLayout(rightPanel);\n\n/*\n\n // Piece Properties\n\n QGroupBox *piecePropertiesBox = new QGroupBox();\n\n rightPanel->addWidget(piecePropertiesBox);\n\n\n\n QVBoxLayout *pieceProperties = new QVBoxLayout;\n\n piecePropertiesBox->setLayout(pieceProperties);\n", "file_path": "window.cpp", "rank": 98, "score": 4.503661137925885 }, { "content": "** ensure the GNU Lesser General Public License version 2.1 requirements\n\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\n\n**\n\n** In addition, as a special exception, Nokia gives you certain additional\n\n** rights. These rights are described in the Nokia Qt LGPL Exception\n\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n\n**\n\n** GNU General Public License Usage\n\n** Alternatively, this file may be used under the terms of the GNU\n\n** General Public License version 3.0 as published by the Free Software\n\n** Foundation and appearing in the file LICENSE.GPL included in the\n\n** packaging of this file. Please review the following information to\n\n** ensure the GNU General Public License version 3.0 requirements will be\n\n** met: http://www.gnu.org/copyleft/gpl.html.\n\n**\n\n** If you have questions regarding the use of this file, please contact\n\n** Nokia at [email protected].\n\n** $QT_END_LICENSE$\n\n**\n\n****************************************************************************/\n", "file_path": "window.h", "rank": 99, "score": 4.46556117305151 } ]
C++
perf_test/blas/blas1/KokkosBlas_team_dot_perf_test.cpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
#include <Kokkos_Core.hpp> #include <KokkosBlas1_team_dot.hpp> #include <Kokkos_Random.hpp> struct Params { int use_cuda = 0; int use_openmp = 0; int use_threads = 0; int m = 100000; int repeat = 1; }; void print_options() { std::cerr << "Options:\n" << std::endl; std::cerr << "\tBACKEND: '--threads[numThreads]' | '--openmp [numThreads]' | " "'--cuda [cudaDeviceIndex]'" << std::endl; std::cerr << "\tIf no BACKEND selected, serial is the default." << std::endl; std::cerr << "\t[Optional] --repeat :: how many times to repeat overall " "dot (symbolic + repeated numeric)" << std::endl; } int parse_inputs(Params& params, int argc, char** argv) { for (int i = 1; i < argc; ++i) { if (0 == strcasecmp(argv[i], "--help") || 0 == strcasecmp(argv[i], "-h")) { print_options(); exit(0); } else if (0 == strcasecmp(argv[i], "--threads")) { params.use_threads = atoi(argv[++i]); } else if (0 == strcasecmp(argv[i], "--openmp")) { params.use_openmp = atoi(argv[++i]); } else if (0 == strcasecmp(argv[i], "--cuda")) { params.use_cuda = atoi(argv[++i]) + 1; } else if (0 == strcasecmp(argv[i], "--m")) { params.m = atoi(argv[++i]); } else if (0 == strcasecmp(argv[i], "--repeat")) { params.repeat = atoi(argv[++i]); } else { std::cerr << "Unrecognized command line argument #" << i << ": " << argv[i] << std::endl; print_options(); return 1; } } return 0; } template <class Vector, class ExecSpace> struct teamDotFunctor { static_assert(Kokkos::Impl::is_view<Vector>::value, "Vector is not a " "Kokkos::View."); using Scalar = typename Vector::non_const_value_type; using execution_space = ExecSpace; typedef typename Kokkos::TeamPolicy<execution_space> team_policy; typedef typename team_policy::member_type team_member; Vector x; Vector y; KOKKOS_INLINE_FUNCTION void operator()(const team_member& team) const { KokkosBlas::Experimental::dot(team, x, y); } teamDotFunctor(Vector X_, Vector Y_) { x = X_; y = Y_; } }; template <class ExecSpace> void run(int m, int repeat) { using Scalar = double; using MemSpace = typename ExecSpace::memory_space; using policy = Kokkos::TeamPolicy<ExecSpace>; Kokkos::View<Scalar*, MemSpace> x("X", m); Kokkos::View<Scalar*, MemSpace> y("Y", m); Kokkos::deep_copy(x, 3.0); Kokkos::deep_copy(y, 2.0); std::cout << "Running BLAS Level 1 Kokkos Teams-based implementation DOT " "performance experiment (" << ExecSpace::name() << ")\n"; std::cout << "Each test input vector has a length of " << m << std::endl; teamDotFunctor<Kokkos::View<Scalar*, MemSpace>, ExecSpace> teamDotFunctorWarmUpInstance(x, y); Kokkos::parallel_for("TeamDotUsage -- Warm Up Run", policy(1, Kokkos::AUTO), teamDotFunctorWarmUpInstance); Kokkos::fence(); Kokkos::Timer timer; teamDotFunctor<Kokkos::View<Scalar*, MemSpace>, ExecSpace> teamDotFunctorLiveTestInstance(x, y); Kokkos::parallel_for("TeamDotUsage -- Live Test", policy(1, Kokkos::AUTO), teamDotFunctorLiveTestInstance); ExecSpace().fence(); double total = timer.seconds(); double avg = total / repeat; size_t flopsPerRun = (size_t)2 * m; printf("Avg DOT time: %f s.\n", avg); printf("Avg DOT FLOP/s: %.3e\n", flopsPerRun / avg); } int main(int argc, char** argv) { Params params; if (parse_inputs(params, argc, argv)) { return 1; } const int device_id = params.use_cuda - 1; const int num_threads = std::max(params.use_openmp, params.use_threads); Kokkos::initialize(Kokkos::InitArguments(num_threads, -1, device_id)); bool useThreads = params.use_threads != 0; bool useOMP = params.use_openmp != 0; bool useCUDA = params.use_cuda != 0; bool useSerial = !useThreads && !useOMP && !useCUDA; if (useThreads) { #if defined(KOKKOS_ENABLE_THREADS) run<Kokkos::Threads>(params.m, params.repeat); #else std::cout << "ERROR: PThreads requested, but not available.\n"; return 1; #endif } if (useOMP) { #if defined(KOKKOS_ENABLE_OPENMP) run<Kokkos::OpenMP>(params.m, params.repeat); #else std::cout << "ERROR: OpenMP requested, but not available.\n"; return 1; #endif } if (useCUDA) { #if defined(KOKKOS_ENABLE_CUDA) run<Kokkos::Cuda>(params.m, params.repeat); #else std::cout << "ERROR: CUDA requested, but not available.\n"; return 1; #endif } if (useSerial) { #if defined(KOKKOS_ENABLE_SERIAL) run<Kokkos::Serial>(params.m, params.repeat); #else std::cout << "ERROR: Serial device requested, but not available; here, " "implementation of dot is explicitly parallel.\n"; return 1; #endif } Kokkos::finalize(); return 0; }
#include <Kokkos_Core.hpp> #include <KokkosBlas1_team_dot.hpp> #include <Kokkos_Random.hpp> struct Params { int use_cuda = 0; int use_openmp = 0; int use_threads = 0; int m = 100000; int repeat = 1; }; void print_options() { std::cerr << "Options:\n" << std::endl; std::cerr << "\tBACKEND: '--threads[numThreads]' | '--openmp [numThreads]' | " "'--cuda [cudaDeviceIndex]'" << std::endl; std::cerr << "\tIf no BACKEND selected, serial is the default." << std::endl; std:
eturn 1; #endif } if (useSerial) { #if defined(KOKKOS_ENABLE_SERIAL) run<Kokkos::Serial>(params.m, params.repeat); #else std::cout << "ERROR: Serial device requested, but not available; here, " "implementation of dot is explicitly parallel.\n"; return 1; #endif } Kokkos::finalize(); return 0; }
:cerr << "\t[Optional] --repeat :: how many times to repeat overall " "dot (symbolic + repeated numeric)" << std::endl; } int parse_inputs(Params& params, int argc, char** argv) { for (int i = 1; i < argc; ++i) { if (0 == strcasecmp(argv[i], "--help") || 0 == strcasecmp(argv[i], "-h")) { print_options(); exit(0); } else if (0 == strcasecmp(argv[i], "--threads")) { params.use_threads = atoi(argv[++i]); } else if (0 == strcasecmp(argv[i], "--openmp")) { params.use_openmp = atoi(argv[++i]); } else if (0 == strcasecmp(argv[i], "--cuda")) { params.use_cuda = atoi(argv[++i]) + 1; } else if (0 == strcasecmp(argv[i], "--m")) { params.m = atoi(argv[++i]); } else if (0 == strcasecmp(argv[i], "--repeat")) { params.repeat = atoi(argv[++i]); } else { std::cerr << "Unrecognized command line argument #" << i << ": " << argv[i] << std::endl; print_options(); return 1; } } return 0; } template <class Vector, class ExecSpace> struct teamDotFunctor { static_assert(Kokkos::Impl::is_view<Vector>::value, "Vector is not a " "Kokkos::View."); using Scalar = typename Vector::non_const_value_type; using execution_space = ExecSpace; typedef typename Kokkos::TeamPolicy<execution_space> team_policy; typedef typename team_policy::member_type team_member; Vector x; Vector y; KOKKOS_INLINE_FUNCTION void operator()(const team_member& team) const { KokkosBlas::Experimental::dot(team, x, y); } teamDotFunctor(Vector X_, Vector Y_) { x = X_; y = Y_; } }; template <class ExecSpace> void run(int m, int repeat) { using Scalar = double; using MemSpace = typename ExecSpace::memory_space; using policy = Kokkos::TeamPolicy<ExecSpace>; Kokkos::View<Scalar*, MemSpace> x("X", m); Kokkos::View<Scalar*, MemSpace> y("Y", m); Kokkos::deep_copy(x, 3.0); Kokkos::deep_copy(y, 2.0); std::cout << "Running BLAS Level 1 Kokkos Teams-based implementation DOT " "performance experiment (" << ExecSpace::name() << ")\n"; std::cout << "Each test input vector has a length of " << m << std::endl; teamDotFunctor<Kokkos::View<Scalar*, MemSpace>, ExecSpace> teamDotFunctorWarmUpInstance(x, y); Kokkos::parallel_for("TeamDotUsage -- Warm Up Run", policy(1, Kokkos::AUTO), teamDotFunctorWarmUpInstance); Kokkos::fence(); Kokkos::Timer timer; teamDotFunctor<Kokkos::View<Scalar*, MemSpace>, ExecSpace> teamDotFunctorLiveTestInstance(x, y); Kokkos::parallel_for("TeamDotUsage -- Live Test", policy(1, Kokkos::AUTO), teamDotFunctorLiveTestInstance); ExecSpace().fence(); double total = timer.seconds(); double avg = total / repeat; size_t flopsPerRun = (size_t)2 * m; printf("Avg DOT time: %f s.\n", avg); printf("Avg DOT FLOP/s: %.3e\n", flopsPerRun / avg); } int main(int argc, char** argv) { Params params; if (parse_inputs(params, argc, argv)) { return 1; } const int device_id = params.use_cuda - 1; const int num_threads = std::max(params.use_openmp, params.use_threads); Kokkos::initialize(Kokkos::InitArguments(num_threads, -1, device_id)); bool useThreads = params.use_threads != 0; bool useOMP = params.use_openmp != 0; bool useCUDA = params.use_cuda != 0; bool useSerial = !useThreads && !useOMP && !useCUDA; if (useThreads) { #if defined(KOKKOS_ENABLE_THREADS) run<Kokkos::Threads>(params.m, params.repeat); #else std::cout << "ERROR: PThreads requested, but not available.\n"; return 1; #endif } if (useOMP) { #if defined(KOKKOS_ENABLE_OPENMP) run<Kokkos::OpenMP>(params.m, params.repeat); #else std::cout << "ERROR: OpenMP requested, but not available.\n"; return 1; #endif } if (useCUDA) { #if defined(KOKKOS_ENABLE_CUDA) run<Kokkos::Cuda>(params.m, params.repeat); #else std::cout << "ERROR: CUDA requested, but not available.\n"; r
random
[ { "content": "struct MultiGemm<int,int,int,Kokkos::Cuda,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, int alpha,\n\n Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::Cuda> A, Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::Cuda> B,\n\n int beta, Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::Cuda> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n;\n\ncublasZgemm(transB,transA, n, m, k, alpha, B.data(), ldb, A.data(), lda, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 0, "score": 227687.33809366587 }, { "content": "struct MultiGemm<int,int,int,Kokkos::Cuda,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, int alpha,\n\n Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::Cuda> A, Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::Cuda> B,\n\n int beta, Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::Cuda> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncublasZgemm ( transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n\n\n\n\n\n\n\n#endif\n\n\n\n}\n\n}\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 1, "score": 227687.33809366587 }, { "content": "struct MultiGemm<int,int,int,Kokkos::Serial,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, int alpha,\n\n Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::Serial> A, Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::Serial> B,\n\n int beta, Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::Serial> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n;\n\ncblas_zgemm (CblasRowMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 2, "score": 227459.12126211816 }, { "content": "struct MultiGemm<int,int,int,Kokkos::Serial,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, int alpha,\n\n Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::Serial> A, Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::Serial> B,\n\n int beta, Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::Serial> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncblas_zgemm (CblasColMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 3, "score": 227459.12126211816 }, { "content": "struct ParamTag {\n\n typedef TA transA;\n\n typedef TB transB;\n\n};\n\n\n\ntemplate <typename DeviceType, typename ViewType, typename ScalarType,\n\n typename ParamTagType, typename AlgoTagType>\n", "file_path": "unit_test/batched/dense/Test_Batched_SerialGemm.hpp", "rank": 4, "score": 200222.62098661566 }, { "content": "struct OrdinalTraits<int> {\n\n static KOKKOS_INLINE_FUNCTION int invalid () { return -1; }\n\n};\n\n\n\ntemplate<>\n", "file_path": "src/sparse/KokkosSparse_OrdinalTraits.hpp", "rank": 5, "score": 187155.0908894961 }, { "content": "struct MultiGemm<int,int,int,Kokkos::OpenMP,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, int alpha,\n\n Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::OpenMP> A, Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::OpenMP> B,\n\n int beta, Kokkos::View<int**,Kokkos::LayoutRight,Kokkos::OpenMP> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n;\n\ncblas_zgemm (CblasRowMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 6, "score": 186400.1326898546 }, { "content": "struct MultiGemm<int,int,int,Kokkos::OpenMP,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, int alpha,\n\n Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::OpenMP> A, Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::OpenMP> B,\n\n int beta, Kokkos::View<int**,Kokkos::LayoutLeft,Kokkos::OpenMP> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncblas_zgemm (CblasColMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n\n\n\n#endif\n\n\n\n#ifdef KOKKOS_ENABLE_CUDA\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 7, "score": 186400.1326898546 }, { "content": "struct OrdinalTraits<short int> {\n\n static KOKKOS_INLINE_FUNCTION short int invalid () { return -1; }\n\n};\n\n\n\ntemplate<>\n", "file_path": "src/sparse/KokkosSparse_OrdinalTraits.hpp", "rank": 8, "score": 176572.57265797778 }, { "content": "struct OrdinalTraits<unsigned int> {\n\n static KOKKOS_INLINE_FUNCTION unsigned int invalid () { return UINT_MAX; }\n\n};\n\n\n\ntemplate<>\n", "file_path": "src/sparse/KokkosSparse_OrdinalTraits.hpp", "rank": 9, "score": 176572.57265797778 }, { "content": "struct SpaceInstance<Kokkos::Cuda> {\n\n static Kokkos::Cuda create() {\n\n cudaStream_t stream;\n\n cudaStreamCreate(&stream);\n\n return Kokkos::Cuda(stream);\n\n }\n\n static void destroy(Kokkos::Cuda& space) {\n\n cudaStream_t stream = space.cuda_stream();\n\n cudaStreamDestroy(stream);\n\n }\n\n static bool overlap() {\n\n bool value = true;\n\n auto local_rank_str = std::getenv(\"CUDA_LAUNCH_BLOCKING\");\n\n if (local_rank_str) {\n\n value = (std::atoi(local_rank_str) == 0);\n\n }\n\n return value;\n\n }\n\n};\n\n#endif\n\n\n\n#ifdef KOKKOS_ENABLE_HIP\n\ntemplate <>\n", "file_path": "src/common/KokkosKernels_ExecSpaceUtils.hpp", "rank": 10, "score": 174133.80407228688 }, { "content": "struct MultiGemm<double,double,double,Kokkos::Cuda,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, double alpha,\n\n Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::Cuda> A, Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::Cuda> B,\n\n double beta, Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::Cuda> C){\n\nconst int m=C.extent(0); \n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\t \n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n; \n\ncublasDgemm(transB,transA, n, m, k, alpha, B.data(), ldb, A.data(), lda, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 11, "score": 171774.74297995958 }, { "content": "struct MultiGemm<float,float,float,Kokkos::Cuda,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, float alpha,\n\n Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::Cuda> A, Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::Cuda> B,\n\n float beta, Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::Cuda> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncublasSgemm ( transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 12, "score": 171774.74297995958 }, { "content": "struct MultiGemm<double,double,double,Kokkos::Cuda,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, double alpha,\n\n Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::Cuda> A, Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::Cuda> B,\n\n double beta, Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::Cuda> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncublasDgemm (transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n\n\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 13, "score": 171774.74297995958 }, { "content": "struct MultiGemm<float,float,float,Kokkos::Cuda,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, float alpha,\n\n Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::Cuda> A, Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::Cuda> B,\n\n float beta, Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::Cuda> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n;\n\ncublasSgemm(transB,transA, n, m, k, alpha, B.data(), ldb, A.data(), lda, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 14, "score": 171774.74297995958 }, { "content": "struct MultiGemm<float,float,float,Kokkos::Serial,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, float alpha,\n\n Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::Serial> A, Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::Serial> B,\n\n float beta, Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::Serial> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n; \n\ncblas_sgemm (CblasRowMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 15, "score": 171546.52614841188 }, { "content": "struct MultiGemm<double,double,double,Kokkos::Serial,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, double alpha,\n\n Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::Serial> A, Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::Serial> B,\n\n double beta, Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::Serial> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncblas_dgemm (CblasColMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 16, "score": 171546.52614841188 }, { "content": "struct MultiGemm<float,float,float,Kokkos::Serial,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, float alpha,\n\n Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::Serial> A, Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::Serial> B,\n\n float beta, Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::Serial> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncblas_sgemm (CblasColMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 17, "score": 171546.52614841188 }, { "content": "struct MultiGemm<double,double,double,Kokkos::Serial,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, double alpha,\n\n Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::Serial> A, Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::Serial> B,\n\n double beta, Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::Serial> C){\n\nconst int m=C.extent(0); \n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\t \n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n; \n\ncblas_dgemm (CblasRowMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 18, "score": 171546.52614841188 }, { "content": "struct OrdinalTraits<unsigned short int> {\n\n static KOKKOS_INLINE_FUNCTION unsigned short int invalid () { return USHRT_MAX; }\n\n};\n\n\n\ntemplate<>\n", "file_path": "src/sparse/KokkosSparse_OrdinalTraits.hpp", "rank": 19, "score": 167570.7396300615 }, { "content": "struct ReturnTeamPolicyType<Kokkos::Cuda> {\n\n using PolicyType = Kokkos::TeamPolicy<Kokkos::Cuda>;\n\n\n\n static inline\n\n PolicyType get_policy(int nt, int ts) {\n\n return PolicyType(nt,ts);\n\n }\n\n\n\n template <class ExecInstanceType>\n\n static inline\n\n PolicyType get_policy(int nt, int ts, ExecInstanceType stream) {\n\n return PolicyType(stream,nt,ts);\n\n }\n\n};\n\n#endif\n\n\n\ntemplate <class SpaceType>\n", "file_path": "src/sparse/impl/KokkosSparse_sptrsv_solve_impl.hpp", "rank": 20, "score": 167481.34783198131 }, { "content": "struct ReturnRangePolicyType<Kokkos::Cuda> {\n\n using PolicyType = Kokkos::RangePolicy<Kokkos::Cuda>;\n\n\n\n static inline\n\n PolicyType get_policy(int nt, int ts) {\n\n return PolicyType(nt,ts);\n\n }\n\n\n\n template <class ExecInstanceType>\n\n static inline\n\n PolicyType get_policy(int nt, int ts, ExecInstanceType stream) {\n\n return PolicyType(stream,nt,ts);\n\n }\n\n};\n\n#endif\n\n#ifdef KOKKOS_ENABLE_HIP\n\ntemplate <>\n", "file_path": "src/sparse/impl/KokkosSparse_sptrsv_solve_impl.hpp", "rank": 21, "score": 167481.34783198131 }, { "content": "struct ReturnRangePolicyType<Kokkos::Serial> {\n\n using PolicyType = Kokkos::RangePolicy<Kokkos::Serial>;\n\n\n\n static inline\n\n PolicyType get_policy(int nt, int ts) {\n\n return PolicyType(nt,ts);\n\n }\n\n\n\n template <class ExecInstanceType>\n\n static inline\n\n PolicyType get_policy(int nt, int ts, ExecInstanceType ) {\n\n return PolicyType(nt,ts);\n\n //return PolicyType(ExecInstanceType(),nt,ts);\n\n }\n\n};\n\n#endif\n\n#ifdef KOKKOS_ENABLE_OPENMP\n\ntemplate <>\n", "file_path": "src/sparse/impl/KokkosSparse_sptrsv_solve_impl.hpp", "rank": 22, "score": 167210.2834487576 }, { "content": "struct ReturnTeamPolicyType<Kokkos::Serial> {\n\n using PolicyType = Kokkos::TeamPolicy<Kokkos::Serial>;\n\n\n\n static inline\n\n PolicyType get_policy(int nt, int ts) {\n\n return PolicyType(nt,ts);\n\n }\n\n\n\n template <class ExecInstanceType>\n\n static inline\n\n PolicyType get_policy(int nt, int ts, ExecInstanceType ) {\n\n return PolicyType(nt,ts);\n\n //return PolicyType(ExecInstanceType(),nt,ts);\n\n }\n\n};\n\n#endif\n\n#ifdef KOKKOS_ENABLE_OPENMP\n\ntemplate <>\n", "file_path": "src/sparse/impl/KokkosSparse_sptrsv_solve_impl.hpp", "rank": 23, "score": 167210.2834487576 }, { "content": "struct is_bsr_matrix : public std::false_type {};\n\ntemplate <typename... P>\n", "file_path": "src/sparse/KokkosSparse_BsrMatrix.hpp", "rank": 24, "score": 165290.08872060018 }, { "content": "struct InnerProductSpaceTraits<std::complex<T> >\n\n{\n\n typedef std::complex<T> val_type;\n\n typedef typename ArithTraits<val_type>::mag_type mag_type;\n\n typedef val_type dot_type;\n\n\n\n static mag_type norm (const val_type& x) {\n\n return ArithTraits<val_type>::abs (x);\n\n }\n\n static dot_type dot (const val_type& x, const val_type& y) {\n\n return std::conj (x) * y;\n\n }\n\n};\n\n\n\n#ifdef HAVE_KOKKOSKERNELS_QUADMATH\n\n\n\n/// \\brief Partial specialization for __float128.\n\n///\n\n/// CUDA does not support __float128 in device functions, so none of\n\n/// the class methods in this specialization are marked as device\n\n/// functions.\n\ntemplate<>\n", "file_path": "src/Kokkos_InnerProductSpaceTraits.hpp", "rank": 25, "score": 163073.77720891603 }, { "content": "struct SerialSVDFunctor_Full\n\n{\n\n SerialSVDFunctor_Full(const Matrix& A_, const Matrix& U_, const Matrix& Vt_, const Vector& sigma_, const Vector& work_)\n\n : A(A_), U(U_), Vt(Vt_), sigma(sigma_), work(work_)\n\n {}\n\n\n\n //NOTE: this functor is only meant to be launched with a single element range policy\n\n KOKKOS_INLINE_FUNCTION void operator()(int) const\n\n {\n\n KokkosBatched::SerialSVD::invoke(KokkosBatched::SVD_USV_Tag(), A, U, sigma, Vt, work);\n\n }\n\n\n\n Matrix A;\n\n Matrix U;\n\n Matrix Vt;\n\n Vector sigma;\n\n Vector work;\n\n};\n\n\n\ntemplate<typename Matrix, typename Vector>\n", "file_path": "unit_test/batched/dense/Test_Batched_SerialSVD.hpp", "rank": 26, "score": 158570.97896407856 }, { "content": "struct Functor_TestBatchedSerialGemm {\n\n ViewType _a, _b, _c;\n\n\n\n ScalarType _alpha, _beta;\n\n\n\n KOKKOS_INLINE_FUNCTION\n\n Functor_TestBatchedSerialGemm(const ScalarType alpha, const ViewType &a,\n\n const ViewType &b, const ScalarType beta,\n\n const ViewType &c)\n\n : _a(a), _b(b), _c(c), _alpha(alpha), _beta(beta) {}\n\n\n\n KOKKOS_INLINE_FUNCTION\n\n void operator()(const ParamTagType &, const int k) const {\n\n auto aa = Kokkos::subview(_a, k, Kokkos::ALL(), Kokkos::ALL());\n\n auto bb = Kokkos::subview(_b, k, Kokkos::ALL(), Kokkos::ALL());\n\n auto cc = Kokkos::subview(_c, k, Kokkos::ALL(), Kokkos::ALL());\n\n\n\n SerialGemm<typename ParamTagType::transA, typename ParamTagType::transB,\n\n AlgoTagType>::invoke(_alpha, aa, bb, _beta, cc);\n\n }\n", "file_path": "unit_test/batched/dense/Test_Batched_SerialGemm.hpp", "rank": 27, "score": 156508.7091287975 }, { "content": "struct SerialSVDFunctor_SingularValuesOnly\n\n{\n\n SerialSVDFunctor_SingularValuesOnly(const Matrix& A_, const Vector& sigma_, const Vector& work_)\n\n : A(A_), sigma(sigma_), work(work_)\n\n {}\n\n\n\n //NOTE: this functor is only meant to be launched with a single element range policy\n\n KOKKOS_INLINE_FUNCTION void operator()(int) const\n\n {\n\n KokkosBatched::SerialSVD::invoke(KokkosBatched::SVD_S_Tag(), A, sigma, work);\n\n }\n\n\n\n Matrix A;\n\n Vector sigma;\n\n Vector work;\n\n};\n\n\n\ntemplate<typename Scalar, typename Layout, typename Device>\n\nvoid testSerialSVD(int m, int n, int deficiency, double maxval = 1.0)\n\n{\n", "file_path": "unit_test/batched/dense/Test_Batched_SerialSVD.hpp", "rank": 28, "score": 156508.7091287975 }, { "content": "struct Params\n\n{\n\n int use_cuda = 0;\n\n int use_openmp = 0;\n\n int use_threads = 0;\n\n int use_mkl = 0;\n\n int use_cusparse = 0;\n\n bool sorted = true;\n\n std::string amtx;\n\n std::string bmtx;\n\n std::string cmtx;\n\n int m = 10000;\n\n int n = 10000;\n\n int nnzPerRow = 30;\n\n bool bDiag = false; //Whether B should be diagonal only (requires A square)\n\n bool verbose = false;\n\n int repeat = 1;\n\n int numericRepeat = 1; //how many times to call numeric per overall run\n\n};\n\n\n", "file_path": "perf_test/sparse/KokkosSparse_spadd.cpp", "rank": 29, "score": 156145.84642232396 }, { "content": "/// \\brief TplParams abstracts underlying handle or execution queue type.\n\nstruct TplParams {\n\n union {\n\n#if defined(KOKKOSKERNELS_ENABLE_TPL_MKL)\n\n //queue mkl_queue;\n\n // TODO: Add queue header? Cannot find any declarations in intel-18, let alone oneAPI 2021\n\n#endif // KOKKOSKERNELS_ENABLE_TPL_MKL\n\n\n\n#if defined(KOKKOSKERNELS_ENABLE_TPL_ARMPL)\n\n // TODO: Add armpl handle type in KokkosKernels to expose nintern & nbatch?\n\n#endif // KOKKOSKERNELS_ENABLE_TPL_ARMPL\n\n\n\n#if defined(KOKKOSKERNELS_ENABLE_TPL_CUBLAS)\n\n cublasHandle_t *cublas_handle;\n\n#endif // KOKKOSKERNELS_ENABLE_TPL_CUBLAS\n\n\n\n#if defined(KOKKOSKERNELS_ENABLE_TPL_MAGMA)\n\n magma_queue_t *magma_queue;\n\n#endif // KOKKOSKERNELS_ENABLE_TPL_MAGMA\n\n\n\n uint8_t empty_union; // suppress empty union build warning\n\n };\n\n};\n\n\n", "file_path": "src/batched/dense/KokkosBatched_Kernel_Handle.hpp", "rank": 30, "score": 150663.07052327 }, { "content": "struct SharedParamTag {\n\n using transA = TA;\n\n using transB = TB;\n\n using batchLayout = BL;\n\n};\n\n} // namespace Test\n\n#endif\n", "file_path": "test_common/KokkosKernels_TestUtils.hpp", "rank": 31, "score": 150656.39333521028 }, { "content": "struct SerialRCM\n\n{\n\n using size_type = typename rowmap_t::non_const_value_type;\n\n using lno_t = typename entries_t::non_const_value_type;\n\n using host_rowmap_t = Kokkos::View<size_type*, Kokkos::HostSpace>;\n\n using host_lno_view_t = Kokkos::View<lno_t*, Kokkos::HostSpace>;\n\n\n\n lno_t numVerts;\n\n host_rowmap_t rowmap;\n\n host_lno_view_t entries;\n\n\n\n SerialRCM(const rowmap_t& rowmap_, const entries_t& entries_) :\n\n numVerts(rowmap_.extent(0) - 1),\n\n rowmap(Kokkos::view_alloc(Kokkos::WithoutInitializing, \"HostRowmap\"), rowmap_.extent(0)),\n\n entries(Kokkos::view_alloc(Kokkos::WithoutInitializing, \"HostEntries\"), entries_.extent(0))\n\n {\n\n Kokkos::deep_copy(rowmap, rowmap_);\n\n Kokkos::deep_copy(entries, entries_);\n\n }\n\n\n", "file_path": "src/graph/impl/KokkosGraph_BFS_impl.hpp", "rank": 32, "score": 150314.86729282493 }, { "content": "struct SerialGemm {\n\n template <typename ScalarType, typename AViewType, typename BViewType,\n\n typename CViewType>\n\n KOKKOS_INLINE_FUNCTION static int invoke(const ScalarType alpha,\n\n const AViewType &A,\n\n const BViewType &B,\n\n const ScalarType beta,\n\n const CViewType &C);\n\n};\n\n\n\n///\n\n/// Team Gemm\n\n///\n\n\n\ntemplate <typename MemberType, typename ArgTransA, typename ArgTransB,\n\n typename ArgAlgo>\n", "file_path": "src/batched/dense/KokkosBatched_Gemm_Decl.hpp", "rank": 33, "score": 150314.86729282493 }, { "content": "struct impl_gemm_choose_copy_layout<Kokkos::Cuda,LayoutA,LayoutAScratch> {\n\n using type = LayoutA;\n\n};\n\n#endif\n\n\n\n#ifdef KOKKOS_ENABLE_HIP\n\ntemplate<class LayoutA, class LayoutAScratch>\n", "file_path": "src/blas/impl/KokkosBlas3_gemm_impl.hpp", "rank": 34, "score": 149591.56593397367 }, { "content": "struct is_bsr_matrix<BsrMatrix<P...>> : public std::true_type {};\n\ntemplate <typename... P>\n", "file_path": "src/sparse/KokkosSparse_BsrMatrix.hpp", "rank": 35, "score": 148811.43548132235 }, { "content": "struct ParamTag {\n\n typedef TA transA;\n\n typedef TB transB;\n\n};\n\n\n\n template <typename DeviceType, typename ViewType, typename ScalarType,\n\n typename ParamTagType, typename AlgoTagType>\n", "file_path": "unit_test/batched/dense/Test_Batched_TeamGemm.hpp", "rank": 36, "score": 148107.99263648002 }, { "content": "struct Params {\n\n int use_cuda = 0;\n\n int use_openmp = 0;\n\n int use_threads = 0;\n\n int m = 5000;\n\n int n = 5000;\n\n int repeat = 1;\n\n bool layoutLeft = true;\n\n};\n\n\n\nvoid print_options() {\n\n std::cerr << \"Options\\n\" << std::endl;\n\n\n\n std::cerr << \"\\tBACKEND: '--threads[numThreads]' | '--openmp [numThreads]' | \"\n\n \"'--cuda [cudaDeviceIndex]'\"\n\n << std::endl;\n\n std::cerr << \"\\tIf none selected, serial is used.\" << std::endl;\n\n std::cerr << \"\\t[Optional] --repeat :: how many times to repeat overall \"\n\n \"spadd (symbolic + repeated numeric)\"\n\n << std::endl;\n", "file_path": "perf_test/blas/blas2/KokkosBlas2_gemv_perf_test.cpp", "rank": 37, "score": 148107.99263648002 }, { "content": "struct Params {\n\n int use_cuda = 0;\n\n int use_openmp = 0;\n\n int use_threads = 0;\n\n // m is vector length\n\n int m = 100000;\n\n int repeat = 1;\n\n};\n\n\n\nvoid print_options() {\n\n std::cerr << \"Options:\\n\" << std::endl;\n\n\n\n std::cerr << \"\\tBACKEND: '--threads[numThreads]' | '--openmp [numThreads]' | \"\n\n \"'--cuda [cudaDeviceIndex]'\"\n\n << std::endl;\n\n std::cerr << \"\\tIf no BACKEND selected, serial is the default.\" << std::endl;\n\n std::cerr << \"\\t[Optional] --repeat :: how many times to repeat overall \"\n\n \"dot (symbolic + repeated numeric)\"\n\n << std::endl;\n\n std::cerr << \"\\t[Optional] --m :: desired length of test vectors; test \"\n", "file_path": "perf_test/blas/blas1/KokkosBlas_dot_perf_test.cpp", "rank": 38, "score": 148107.99263648002 }, { "content": "struct CudaBlasSingleton {\n\n cublasHandle_t handle;\n\n\n\n CudaBlasSingleton();\n\n\n\n static CudaBlasSingleton & singleton();\n\n};\n\n\n\n}\n\n}\n\n#endif // KOKKOSKERNELS_ENABLE_TPL_CUBLAS\n\n\n\n// If LAPACK TPL is enabled, it is preferred over magma's LAPACK\n\n#ifdef KOKKOSKERNELS_ENABLE_TPL_MAGMA\n\n#include \"magma_v2.h\"\n\n\n\nnamespace KokkosBlas {\n\nnamespace Impl {\n\n\n", "file_path": "src/impl/tpls/KokkosBlas_tpl_spec.hpp", "rank": 39, "score": 148076.25619426955 }, { "content": "struct TestSerialRadix2Functor\n\n{\n\n //Sort by keys, while permuting values\n\n using Key = typename KeyView::value_type;\n\n using UnsignedKey = typename std::make_unsigned<Key>::type;\n\n using Value = typename ValView::value_type;\n\n\n\n TestSerialRadix2Functor(KeyView& keys_, KeyView& keysAux_, ValView& values_, ValView& valuesAux_, OrdView& counts_, OrdView& offsets_)\n\n : keys(keys_), keysAux(keysAux_), values(values_), valuesAux(valuesAux_), counts(counts_), offsets(offsets_)\n\n {}\n\n KOKKOS_INLINE_FUNCTION void operator()(const int i) const\n\n {\n\n int off = offsets(i);\n\n KokkosKernels::SerialRadixSort2<int, UnsignedKey, Value>(\n\n (UnsignedKey*) keys.data() + off, (UnsignedKey*) keysAux.data() + off,\n\n values.data() + off, valuesAux.data() + off, counts(i));\n\n }\n\n KeyView keys;\n\n KeyView keysAux;\n\n ValView values;\n", "file_path": "unit_test/common/Test_Common_Sorting.hpp", "rank": 40, "score": 147774.60952900854 }, { "content": "struct TestSerialRadixFunctor\n\n{\n\n using Key = typename KeyView::value_type;\n\n using UnsignedKey = typename std::make_unsigned<Key>::type;\n\n\n\n TestSerialRadixFunctor(KeyView& keys_, KeyView& keysAux_, OrdView& counts_, OrdView& offsets_)\n\n : keys(keys_), keysAux(keysAux_), counts(counts_), offsets(offsets_)\n\n {}\n\n KOKKOS_INLINE_FUNCTION void operator()(const int i) const\n\n {\n\n int off = offsets(i);\n\n KokkosKernels::SerialRadixSort<int, UnsignedKey>(\n\n (UnsignedKey*) keys.data() + off, (UnsignedKey*) keysAux.data() + off, counts(i));\n\n }\n\n KeyView keys;\n\n KeyView keysAux;\n\n OrdView counts;\n\n OrdView offsets;\n\n};\n\n\n\ntemplate<typename KeyView, typename ValView, typename OrdView>\n", "file_path": "unit_test/common/Test_Common_Sorting.hpp", "rank": 41, "score": 147774.60952900854 }, { "content": "struct Params\n\n{\n\n int use_cuda = 0;\n\n int use_openmp = 0;\n\n int use_threads = 0;\n\n int m = 1000;\n\n int n = 1000;\n\n int k = 1000;\n\n int repeat = 1;\n\n};\n\n\n\nvoid print_options(){\n\n std::cerr << \"Options\\n\" << std::endl;\n\n\n\n std::cerr << \"\\tBACKEND: '--threads[numThreads]' | '--openmp [numThreads]' | '--cuda [cudaDeviceIndex]'\" << std::endl;\n\n std::cerr << \"\\tIf none selected, serial is used.\" << std::endl;\n\n std::cerr << \"\\t[Optional] --repeat :: how many times to repeat overall spadd (symbolic + repeated numeric)\" << std::endl;\n\n std::cerr << \"\\t[Optional] --m :: Rows in A\" << std::endl;\n\n std::cerr << \"\\t[Optional] --n :: Columns in A / Rows in B\" << std::endl;\n\n std::cerr << \"\\t[Optional] --k :: Columns in B\" << std::endl;\n", "file_path": "perf_test/blas/blas3/KokkosBlas3_gemm_standalone_perf_test.cpp", "rank": 42, "score": 145678.2839714811 }, { "content": "struct batched_params {\n\n int team_size;\n\n int vector_len;\n\n};\n\ntypedef struct batched_params batched_params_t;\n\n\n\n/**\n\n * @brief struct gemm_simd_args encapsulates the data types required\n\n * for allocating and passing a single matrix to the KokkosBatched gemm\n\n * kernels. To invoke gemm on a batch of matrices, three instances of this\n\n * struct are required, one for each matrix, A, B, and C.\n\n *\n\n * @var vec_3d: 3-rank view type used for allocating the underlying data.\n\n * A reference must be kept to this object to ensure the\n\n * data is not free'd by the C++ runtime.\n\n * @var mat_4d: 4-rank view type used for populating the simd view with\n\n random values.\n\n * @var ivec_4d: 4-rank view type used for passing to math kernels. This\n\n * view type is used for leveraging simd instructions on\n\n * both the host and device.\n\n */\n", "file_path": "perf_test/blas/blas3/KokkosBlas3_gemm_perf_test.hpp", "rank": 43, "score": 145678.2839714811 }, { "content": "struct ParamTag {\n\n typedef TA transA;\n\n typedef TB transB;\n\n};\n\n\n\n template <typename DeviceType, typename ViewType, typename ScalarType,\n\n typename ParamTagType, typename AlgoTagType>\n", "file_path": "unit_test/batched/dense/Test_Batched_TeamVectorGemm.hpp", "rank": 44, "score": 145678.2839714811 }, { "content": "struct SerialTag {};\n", "file_path": "perf_test/blas/blas3/KokkosBlas3_gemm_perf_test.hpp", "rank": 46, "score": 145352.66454086333 }, { "content": "struct SerialSimdTag {};\n", "file_path": "perf_test/blas/blas3/KokkosBlas3_gemm_perf_test.hpp", "rank": 47, "score": 143040.95478933412 }, { "content": "struct is_bsr_matrix<const BsrMatrix<P...>> : public std::true_type {};\n\n//----------------------------------------------------------------------------\n\n\n\n} // namespace Experimental\n\n} // namespace KokkosSparse\n\n#endif\n", "file_path": "src/sparse/KokkosSparse_BsrMatrix.hpp", "rank": 48, "score": 142894.37018184375 }, { "content": "struct SameSizeTuplePrefixComparator<0, 0> {\n\n template <class Tuple1, class Tuple2>\n\n static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {\n\n return true;\n\n }\n\n};\n\n\n\ntemplate <int k>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 49, "score": 141863.86188815432 }, { "content": "struct SerialBatchDim3Tag {};\n", "file_path": "perf_test/blas/blas3/KokkosBlas3_gemm_perf_test.hpp", "rank": 50, "score": 140832.1216751509 }, { "content": "struct SameSizeTuplePrefixComparator<0, 0> {\n\n template <class Tuple1, class Tuple2>\n\n static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {\n\n return true;\n\n }\n\n};\n\n\n\ntemplate <int k>\n", "file_path": "tpls/gtest/gtest/gtest-test-part.h", "rank": 51, "score": 139133.8920519738 }, { "content": "struct SerialSimdBatchDim3Tag {};\n", "file_path": "perf_test/blas/blas3/KokkosBlas3_gemm_perf_test.hpp", "rank": 52, "score": 138719.44729351217 }, { "content": "struct TuplePrefixPrinter<0> {\n\n template <typename Tuple>\n\n static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}\n\n\n\n template <typename Tuple>\n\n static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}\n\n};\n\n// We have to specialize the entire TuplePrefixPrinter<> class\n\n// template here, even though the definition of\n\n// TersePrintPrefixToStrings() is the same as the generic version, as\n\n// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't\n\n// support specializing a method template of a class template.\n\ntemplate <>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 53, "score": 137642.94531359742 }, { "content": "struct TuplePrefixPrinter<1> {\n\n template <typename Tuple>\n\n static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {\n\n UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>::\n\n Print(::std::tr1::get<0>(t), os);\n\n }\n\n\n\n template <typename Tuple>\n\n static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {\n\n ::std::stringstream ss;\n\n UniversalTersePrint(::std::tr1::get<0>(t), &ss);\n\n strings->push_back(ss.str());\n\n }\n\n};\n\n\n\n// Helper function for printing a tuple. T must be instantiated with\n\n// a tuple type.\n\ntemplate <typename T>\n\nvoid PrintTupleTo(const T& t, ::std::ostream* os) {\n\n *os << \"(\";\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 54, "score": 137625.33107851993 }, { "content": "struct TuplePrefixPrinter<0> {\n\n template <typename Tuple>\n\n static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}\n\n\n\n template <typename Tuple>\n\n static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}\n\n};\n\n// We have to specialize the entire TuplePrefixPrinter<> class\n\n// template here, even though the definition of\n\n// TersePrintPrefixToStrings() is the same as the generic version, as\n\n// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't\n\n// support specializing a method template of a class template.\n\ntemplate <>\n", "file_path": "tpls/gtest/gtest/gtest-test-part.h", "rank": 55, "score": 134770.87236255105 }, { "content": "struct TuplePrefixPrinter<1> {\n\n template <typename Tuple>\n\n static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {\n\n UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>::\n\n Print(::std::tr1::get<0>(t), os);\n\n }\n\n\n\n template <typename Tuple>\n\n static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {\n\n ::std::stringstream ss;\n\n UniversalTersePrint(::std::tr1::get<0>(t), &ss);\n\n strings->push_back(ss.str());\n\n }\n\n};\n\n\n\n// Helper function for printing a tuple. T must be instantiated with\n\n// a tuple type.\n\ntemplate <typename T>\n\nvoid PrintTupleTo(const T& t, ::std::ostream* os) {\n\n *os << \"(\";\n", "file_path": "tpls/gtest/gtest/gtest-test-part.h", "rank": 56, "score": 134753.25812747356 }, { "content": "struct MultiGemm<double,double,double,Kokkos::OpenMP,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, double alpha,\n\n Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::OpenMP> A, Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::OpenMP> B,\n\n double beta, Kokkos::View<double**,Kokkos::LayoutRight,Kokkos::OpenMP> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n; \n\ncblas_dgemm (CblasRowMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 57, "score": 130339.1359376075 }, { "content": "struct MultiGemm<float,float,float,Kokkos::OpenMP,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, float alpha,\n\n Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::OpenMP> A, Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::OpenMP> B,\n\n float beta, Kokkos::View<float**,Kokkos::LayoutLeft,Kokkos::OpenMP> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncblas_sgemm (CblasColMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 58, "score": 130339.1359376075 }, { "content": "struct MultiGemm<double,double,double,Kokkos::OpenMP,Kokkos::LayoutLeft,Kokkos::LayoutLeft,Kokkos::LayoutLeft,int,2>{\n\n static void GEMM(const char transA, const char transB, double alpha,\n\n Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::OpenMP> A, Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::OpenMP> B,\n\n double beta, Kokkos::View<double**,Kokkos::LayoutLeft,Kokkos::OpenMP> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? m : k;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? k : n;\n\nconst int ldc= m;\n\ncblas_dgemm (CblasColMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n\n\n}\n\n};\n\n\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 59, "score": 130339.1359376075 }, { "content": "struct MultiGemm<float,float,float,Kokkos::OpenMP,Kokkos::LayoutRight,Kokkos::LayoutRight,Kokkos::LayoutRight,int,2>{\n\n static void GEMM(const char transA, const char transB, float alpha,\n\n Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::OpenMP> A, Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::OpenMP> B,\n\n float beta, Kokkos::View<float**,Kokkos::LayoutRight,Kokkos::OpenMP> C){\n\nconst int m=C.extent(0);\n\nconst int n=C.extent(1);\n\nconst int k= (transA == 'N'||transA == 'n') ? A.extent(1) : A.extent(0);\n\nconst int lda=(transA == 'N'||transA == 'n') ? k : m;\n\nconst int ldb=(transA == 'N'||transA == 'n') ? n : k;\n\nconst int ldc= n;\n\ncblas_sgemm (CblasRowMajor, transA, transB, m, n, k, alpha, A.data(), lda, B.data(), ldb, beta, C.data(), ldc);\n\n\n\n}\n\n};\n\n\n", "file_path": "src/stage/blas3/Kokkos_Blas3_impl.hpp", "rank": 60, "score": 130339.1359376075 }, { "content": "struct spmv_tpl_spec_avail<const SCALAR, const int, Kokkos::Device<EXECSPACE, Kokkos::HostSpace>, Kokkos::MemoryTraits<Kokkos::Unmanaged>, const int, \\\n\n\t\t\t const SCALAR*, Kokkos::LayoutLeft, Kokkos::Device<EXECSPACE, Kokkos::HostSpace>, Kokkos::MemoryTraits<Kokkos::Unmanaged | Kokkos::RandomAccess>, \\\n\n\t\t\t SCALAR*, Kokkos::LayoutLeft, Kokkos::Device<EXECSPACE, Kokkos::HostSpace>, Kokkos::MemoryTraits<Kokkos::Unmanaged> > { \\\n\n enum : bool { value = true }; \\\n\n};\n\n\n\n#ifdef KOKKOS_ENABLE_SERIAL\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(float, Kokkos::Serial)\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(double, Kokkos::Serial)\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(Kokkos::complex<float>, Kokkos::Serial)\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(Kokkos::complex<double>, Kokkos::Serial)\n\n#endif\n\n\n\n#ifdef KOKKOS_ENABLE_OPENMP\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(float, Kokkos::OpenMP)\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(double, Kokkos::OpenMP)\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(Kokkos::complex<float>, Kokkos::OpenMP)\n\nKOKKOSSPARSE_SPMV_TPL_SPEC_AVAIL_MKL(Kokkos::complex<double>, Kokkos::OpenMP)\n\n#endif\n\n\n\n#endif\n\n\n\n// Specialization struct which defines whether a specialization exists\n\ntemplate<class AT, class AO, class AD, class AM, class AS,\n", "file_path": "src/impl/tpls/KokkosSparse_spmv_tpl_spec_avail.hpp", "rank": 61, "score": 129076.58994119304 }, { "content": "struct SolveModeAndAlgo<Kokkos::CudaSpace> {\n\n typedef Mode::Team mode_type;\n\n typedef Algo::Level2::Unblocked algo_type; \n\n};\n\n#endif\n\n\n\nint main(int argc, char* argv[]) {\n\n Kokkos::initialize(argc, argv);\n\n {\n\n#if defined(KOKKOS_ENABLE_CUDA) && defined(KOKKOSBATCHED_PROFILE)\n\n cudaProfilerStop();\n\n#endif\n\n Kokkos::print_configuration(std::cout);\n\n\n\n //typedef Kokkos::Details::ArithTraits<value_type> ats;\n\n Kokkos::Timer timer;\n\n\n\n ///\n\n /// input arguments parsing\n\n ///\n", "file_path": "perf_test/batched/KokkosBatched_Test_BlockTridiagDirect.cpp", "rank": 62, "score": 128203.30153192344 }, { "content": "struct FactorizeModeAndAlgo<Kokkos::CudaSpace> {\n\n typedef Mode::Team mode_type;\n\n typedef Algo::Level3::Unblocked algo_type; \n\n};\n\n#endif\n\n\n\ntemplate<typename ActiveMemorySpace>\n", "file_path": "perf_test/batched/KokkosBatched_Test_BlockTridiagDirect.cpp", "rank": 63, "score": 128203.30153192344 }, { "content": "struct SolveModeAndAlgo<Kokkos::CudaSpace> {\n\n typedef Mode::Team mode_type;\n\n typedef Algo::Level2::Unblocked algo_type; \n\n};\n\n#endif\n\n\n\nint main(int argc, char* argv[]) {\n\n Kokkos::initialize(argc, argv);\n\n {\n\n#if defined(KOKKOS_ENABLE_CUDA) && defined(KOKKOSBATCHED_PROFILE)\n\n cudaProfilerStop();\n\n#endif\n\n Kokkos::print_configuration(std::cout);\n\n\n\n //typedef Kokkos::Details::ArithTraits<value_type> ats;\n\n Kokkos::Timer timer;\n\n\n\n ///\n\n /// input arguments parsing\n\n ///\n", "file_path": "perf_test/batched/KokkosBatched_Test_BlockTridiagJacobi.cpp", "rank": 64, "score": 128203.30153192344 }, { "content": "struct InverseDiagonalsModeAndAlgo<Kokkos::CudaSpace> {\n\n typedef Mode::Team mode_type;\n\n typedef Algo::Level3::Unblocked algo_type; \n\n};\n\n#endif\n\n\n\ntemplate<typename ActiveMemorySpace>\n", "file_path": "perf_test/batched/KokkosBatched_Test_BlockTridiagJacobi.cpp", "rank": 65, "score": 126259.39920769597 }, { "content": "class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {\n\n // The usual test fixture members go here too.\n\n};\n\n\n\nTEST_F(BaseTest, HasFoo) {\n\n // This is an ordinary non-parameterized test.\n\n}\n\n\n\nTEST_P(DerivedTest, DoesBlah) {\n\n // GetParam works just the same here as if you inherit from TestWithParam.\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n}\n\n\n\n#endif // 0\n\n\n\n\n\n#if !GTEST_OS_SYMBIAN\n\n# include <utility>\n\n#endif\n\n\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 66, "score": 124479.80034457683 }, { "content": "class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {\n\n // The usual test fixture members go here too.\n\n};\n\n\n\nTEST_F(BaseTest, HasFoo) {\n\n // This is an ordinary non-parameterized test.\n\n}\n\n\n\nTEST_P(DerivedTest, DoesBlah) {\n\n // GetParam works just the same here as if you inherit from TestWithParam.\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n}\n\n\n\n#endif // 0\n\n\n\n\n\n#if !GTEST_OS_SYMBIAN\n\n# include <utility>\n\n#endif\n\n\n", "file_path": "tpls/gtest/gtest/gtest-test-part.h", "rank": 67, "score": 120308.51630783881 }, { "content": "struct TestOneCase<CrsMatrixType, 0> {\n\n static void test(bool& /* success */, std::ostream& /*out*/,\n\n // Teuchos::FancyOStream& /* out */,\n\n const CrsMatrixType& /* A */, const bool /* replace */,\n\n const bool /* sorted */, const bool /* atomic */,\n\n const bool /* debug */) {}\n\n};\n\n\n\ntemplate <class CrsMatrixType>\n\nvoid testOneCase(bool& success, std::ostream& out,\n\n // Teuchos::FancyOStream& out,\n\n const CrsMatrixType& A, const bool replace, const bool sorted,\n\n const bool atomic, const bool debug = false) {\n\n // Teuchos::OSTab tab0 (out);\n\n out << \"replace: \" << (replace ? \"true\" : \"false\")\n\n << \", sorted: \" << (sorted ? \"true\" : \"false\")\n\n << \", atomic: \" << (atomic ? \"true\" : \"false\") << endl;\n\n // Teuchos::OSTab tab1 (out);\n\n\n\n constexpr int maxNumEntriesToModify = 128;\n", "file_path": "unit_test/sparse/Test_Sparse_replaceSumIntoLonger.hpp", "rank": 68, "score": 119618.75324213976 }, { "content": "struct TestOneCase<CrsMatrixType, 1> {\n\n static void test(bool& success, std::ostream& out,\n\n // Teuchos::FancyOStream& out,\n\n const CrsMatrixType& A, const bool replace,\n\n const bool sorted, const bool atomic,\n\n const bool debug = false) {\n\n constexpr int numEntriesToModify = 1;\n\n testOneCaseImpl<CrsMatrixType, numEntriesToModify>(success, out, A, replace,\n\n sorted, atomic, debug);\n\n // This is the base case, so don't recurse on numEntriesToModify.\n\n }\n\n};\n\n\n\n// We might never call this second base case of numEntriesToModify =\n\n// 0, but it ensures that the template recursion always terminates,\n\n// even if maxNumEntriesToModify (see below) is 0.\n\ntemplate <class CrsMatrixType>\n", "file_path": "unit_test/sparse/Test_Sparse_replaceSumIntoLonger.hpp", "rank": 69, "score": 119602.90212429903 }, { "content": "struct ReturnRangePolicyType<Kokkos::OpenMP> {\n\n using PolicyType = Kokkos::RangePolicy<Kokkos::OpenMP>;\n\n\n\n static inline\n\n PolicyType get_policy(int nt, int ts) {\n\n return PolicyType(nt,ts);\n\n }\n\n\n\n template <class ExecInstanceType>\n\n static inline\n\n PolicyType get_policy(int nt, int ts, ExecInstanceType ) {\n\n return PolicyType(nt,ts);\n\n //return PolicyType(ExecInstanceType(),nt,ts);\n\n }\n\n};\n\n#endif\n\n#ifdef KOKKOS_ENABLE_CUDA\n\ntemplate <>\n", "file_path": "src/sparse/impl/KokkosSparse_sptrsv_solve_impl.hpp", "rank": 70, "score": 118624.02516332755 }, { "content": "struct ReturnTeamPolicyType<Kokkos::OpenMP> {\n\n using PolicyType = Kokkos::TeamPolicy<Kokkos::OpenMP>;\n\n\n\n static inline\n\n PolicyType get_policy(int nt, int ts) {\n\n return PolicyType(nt,ts);\n\n }\n\n\n\n template <class ExecInstanceType>\n\n static inline\n\n PolicyType get_policy(int nt, int ts, ExecInstanceType ) {\n\n return PolicyType(nt,ts);\n\n //return PolicyType(ExecInstanceType(),nt,ts);\n\n }\n\n};\n\n#endif\n\n#ifdef KOKKOS_ENABLE_CUDA\n\ntemplate <>\n", "file_path": "src/sparse/impl/KokkosSparse_sptrsv_solve_impl.hpp", "rank": 71, "score": 118624.02516332755 }, { "content": "struct SPMV_Struct_Functor {\n\n typedef typename AMatrix::non_const_size_type size_type;\n\n typedef typename AMatrix::non_const_ordinal_type ordinal_type;\n\n typedef typename AMatrix::non_const_value_type value_type;\n\n typedef typename AMatrix::execution_space execution_space;\n\n typedef typename execution_space::scratch_memory_space scratch_space;\n\n typedef typename KokkosSparse::SparseRowViewConst<AMatrix> row_view_const;\n\n typedef typename Kokkos::TeamPolicy<execution_space> team_policy;\n\n typedef typename team_policy::member_type team_member;\n\n typedef Kokkos::Details::ArithTraits<value_type> ATV;\n\n typedef Kokkos::View<ordinal_type*, scratch_space,\n\n Kokkos::MemoryTraits<Kokkos::Unmanaged> > shared_ordinal_1d;\n\n using y_value_type = typename YVector::non_const_value_type;\n\n\n\n // Tags to perform SPMV on interior and boundaries\n\n struct interior3ptTag{}; // 1D FD and FE discretization\n\n struct interior5ptTag{}; // 2D FD discretization\n\n struct interior9ptTag{}; // 2D FE discretization\n\n struct interior7ptTag{}; // 3D FD discretization\n\n struct interior27ptTag{}; // 3D FE discretization\n", "file_path": "src/sparse/impl/KokkosSparse_spmv_struct_impl.hpp", "rank": 72, "score": 117124.32211873075 }, { "content": "struct SPMV_Struct_Transpose_Functor {\n\n typedef typename AMatrix::execution_space execution_space;\n\n typedef typename AMatrix::non_const_ordinal_type ordinal_type;\n\n typedef typename AMatrix::non_const_value_type value_type;\n\n typedef typename Kokkos::TeamPolicy<execution_space> team_policy;\n\n typedef typename team_policy::member_type team_member;\n\n typedef Kokkos::Details::ArithTraits<value_type> ATV;\n\n typedef typename YVector::non_const_value_type coefficient_type;\n\n typedef typename YVector::non_const_value_type y_value_type;\n\n\n\n const coefficient_type alpha;\n\n AMatrix m_A;\n\n XVector m_x;\n\n const coefficient_type beta;\n\n YVector m_y;\n\n const ordinal_type rows_per_thread;\n\n\n\n SPMV_Struct_Transpose_Functor (const coefficient_type& alpha_,\n\n const AMatrix& m_A_,\n\n const XVector& m_x_,\n", "file_path": "src/sparse/impl/KokkosSparse_spmv_struct_impl.hpp", "rank": 73, "score": 116309.35246378533 }, { "content": "struct SPMV_MV_Struct_Transpose_Functor {\n\n typedef typename AMatrix::execution_space execution_space;\n\n typedef typename AMatrix::non_const_ordinal_type ordinal_type;\n\n typedef typename AMatrix::non_const_value_type A_value_type;\n\n typedef typename YVector::non_const_value_type y_value_type;\n\n typedef typename Kokkos::TeamPolicy<execution_space> team_policy;\n\n typedef typename team_policy::member_type team_member;\n\n typedef typename YVector::non_const_value_type coefficient_type;\n\n\n\n const coefficient_type alpha;\n\n AMatrix m_A;\n\n XVector m_x;\n\n const coefficient_type beta;\n\n YVector m_y;\n\n\n\n const ordinal_type n;\n\n const ordinal_type rows_per_thread;\n\n\n\n SPMV_MV_Struct_Transpose_Functor (const coefficient_type& alpha_,\n\n const AMatrix& m_A_,\n", "file_path": "src/sparse/impl/KokkosSparse_spmv_struct_impl.hpp", "rank": 74, "score": 115512.29323051655 }, { "content": "struct SPMV_MV_Struct_LayoutLeft_Functor {\n\n typedef typename AMatrix::execution_space execution_space;\n\n typedef typename AMatrix::non_const_ordinal_type ordinal_type;\n\n typedef typename AMatrix::non_const_value_type A_value_type;\n\n typedef typename YVector::non_const_value_type y_value_type;\n\n typedef typename Kokkos::TeamPolicy<execution_space> team_policy;\n\n typedef typename team_policy::member_type team_member;\n\n typedef typename YVector::non_const_value_type coefficient_type;\n\n\n\n const coefficient_type alpha;\n\n AMatrix m_A;\n\n XVector m_x;\n\n const coefficient_type beta;\n\n YVector m_y;\n\n //! The number of columns in the input and output MultiVectors.\n\n ordinal_type n;\n\n ordinal_type rows_per_thread;\n\n int vector_length;\n\n\n\n SPMV_MV_Struct_LayoutLeft_Functor (const coefficient_type& alpha_,\n", "file_path": "src/sparse/impl/KokkosSparse_spmv_struct_impl.hpp", "rank": 75, "score": 114732.56041566518 }, { "content": "enum BASE_KOKKOS_BATCHED_ALGOS : int { KK_SERIAL = BaseTplAlgos::N, N };\n\n}\n\n\n\n#define N_BASE_ALGOS BaseKokkosBatchedAlgos::N\n\n\n", "file_path": "src/batched/dense/KokkosBatched_Kernel_Handle.hpp", "rank": 76, "score": 114719.95826140465 }, { "content": "struct spmv_struct_tpl_spec_avail {\n\n enum : bool { value = false };\n\n};\n\n\n\n// Specialization struct which defines whether a specialization exists\n\ntemplate<class AT, class AO, class AD, class AM, class AS,\n", "file_path": "src/impl/tpls/KokkosSparse_spmv_struct_tpl_spec_avail.hpp", "rank": 77, "score": 113969.5951330206 }, { "content": "struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {\n\n typedef T0 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 78, "score": 113352.56973050733 }, { "content": "struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {\n\n typedef T1 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 79, "score": 113339.36258223584 }, { "content": "struct spmv_mv_struct_tpl_spec_avail {\n\n enum : bool { value = false };\n\n};\n\n\n\n}\n\n}\n\n\n\n#endif // KOKKOSPARSE_SPMV_STRUCT_TPL_SPEC_AVAIL_HPP_\n", "file_path": "src/impl/tpls/KokkosSparse_spmv_struct_tpl_spec_avail.hpp", "rank": 80, "score": 113222.8622774794 }, { "content": "struct TagInit{}; // The init tag for beta!=0 and beta !=1 \n", "file_path": "src/blas/impl/KokkosBlas3_gemm_dotbased_impl.hpp", "rank": 81, "score": 111739.7625190226 }, { "content": "struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {\n\n typedef T0 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "tpls/gtest/gtest/gtest-test-part.h", "rank": 82, "score": 110876.89716558627 }, { "content": "struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {\n\n typedef T1 type;\n\n};\n\n\n\ntemplate <GTEST_10_TYPENAMES_(T)>\n", "file_path": "tpls/gtest/gtest/gtest-test-part.h", "rank": 83, "score": 110863.69001731479 }, { "content": "struct copy_crs_data {\n\n using execution_space = typename graph_type::device_type::execution_space;\n\n using cusparse_int_type = typename Kokkos::View<int*,\n\n\t\t\t\t\t\t typename graph_type::entries_type::array_layout,\n\n\t\t\t\t\t\t typename graph_type::device_type>;\n\n\n\n // Dispatch tags\n\n struct rowPtrTag{};\n\n struct colIndTag{};\n\n\n\n typename graph_type::row_map_type::const_type Arowptr;\n\n typename graph_type::entries_type::const_type Acolind;\n\n cusparse_int_type cusparse_Arowptr, cusparse_Acolind;\n\n\n\n copy_crs_data(typename graph_type::row_map_type::const_type Arowptr_,\n\n\t\ttypename graph_type::entries_type::const_type Acolind_,\n\n\t\tcusparse_int_type cusparse_Arowptr_,\n\n\t\tcusparse_int_type cusparse_Acolind_) :\n\n Arowptr(Arowptr_), Acolind(Acolind_),\n\n cusparse_Arowptr(cusparse_Arowptr_),\n", "file_path": "perf_test/sparse/KokkosSparse_spmv_struct_tuning.cpp", "rank": 84, "score": 109745.60422879082 }, { "content": "class cuda : public ::testing::Test {\n\nprotected:\n\n static void SetUpTestCase()\n\n {\n\n }\n\n\n\n static void TearDownTestCase()\n\n {\n\n }\n\n};\n\n\n\n#define TestCategory cuda\n\n#define TestExecSpace Kokkos::Cuda\n\n\n\n#endif // TEST_CUDA_HPP\n", "file_path": "unit_test/cuda/Test_Cuda.hpp", "rank": 85, "score": 109663.11321453202 }, { "content": "class serial : public ::testing::Test {\n\nprotected:\n\n static void SetUpTestCase()\n\n {\n\n }\n\n\n\n static void TearDownTestCase()\n\n {\n\n }\n\n};\n\n\n\n#define TestCategory serial\n\n#define TestExecSpace Kokkos::Serial\n\n\n\n#endif // TEST_SERIAL_HPP\n", "file_path": "unit_test/serial/Test_Serial.hpp", "rank": 86, "score": 109230.80641082955 }, { "content": "struct Dot<RV, XV, YV, 1, 1, false, KOKKOSKERNELS_IMPL_COMPILE_LIBRARY>\n\n{\n\n //Check some things about the template parameters at compile time to get nice error messages,\n\n //before using them under the assumption they are valid.\n\n static_assert (Kokkos::Impl::is_view<XV>::value, \"KokkosBlas::Impl::\"\n\n \"Dot<1-D>: XV is not a Kokkos::View.\");\n\n static_assert (Kokkos::Impl::is_view<YV>::value, \"KokkosBlas::Impl::\"\n\n \"Dot<1-D>: YV is not a Kokkos::View.\");\n\n static_assert (Kokkos::Impl::is_view<RV>::value, \"KokkosBlas::Impl::\"\n\n \"Dot<1-D>: RV is not a Kokkos::View.\");\n\n static_assert (RV::rank == 0, \"KokkosBlas::Impl::Dot<1-D>: \"\n\n \"RV is not rank 0.\");\n\n static_assert (XV::rank == 1, \"KokkosBlas::Impl::Dot<1-D>: \"\n\n \"XV is not rank 1.\");\n\n static_assert (YV::rank == 1, \"KokkosBlas::Impl::Dot<1-D>: \"\n\n \"YV is not rank 1.\");\n\n static_assert (std::is_same<typename RV::value_type,typename RV::non_const_value_type>::value,\n\n \"KokkosBlas::Dot<1D>: R is const. \"\n\n \"It must be nonconst, because it is an output argument \"\n\n \"(we have to be able to write to its entries).\");\n", "file_path": "src/blas/impl/KokkosBlas1_dot_spec.hpp", "rank": 87, "score": 106675.61160416319 }, { "content": "// A unique type used as the default value for the arguments of class\n\n// template Types. This allows us to simulate variadic templates\n\n// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't\n\n// support directly.\n\nstruct None {};\n\n\n\n// The following family of struct and struct templates are used to\n\n// represent type lists. In particular, TypesN<T1, T2, ..., TN>\n\n// represents a type list with N types (T1, T2, ..., and TN) in it.\n\n// Except for Types0, every struct in the family has two member types:\n\n// Head for the first type in the list, and Tail for the rest of the\n\n// list.\n\n\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 88, "score": 104335.00876347302 }, { "content": "struct Types1 {\n\n typedef T1 Head;\n\n typedef Types0 Tail;\n\n};\n\ntemplate <typename T1, typename T2>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 89, "score": 104321.92663383145 }, { "content": "struct Types4 {\n\n typedef T1 Head;\n\n typedef Types3<T2, T3, T4> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 90, "score": 104321.92663383145 }, { "content": "// The empty type list.\n\nstruct Types0 {};\n\n\n\n// Type lists of length 1, 2, 3, and so on.\n\n\n\ntemplate <typename T1>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 91, "score": 104321.92663383145 }, { "content": "struct Perf {\n\n size_t global_elem_count ;\n\n size_t global_node_count ;\n\n size_t newton_iter_count ;\n\n size_t cg_iter_count ;\n\n double map_ratio ;\n\n double fill_node_set ;\n\n double scan_node_count ;\n\n double fill_graph_entries ;\n\n double sort_graph_entries ;\n\n double fill_element_graph ;\n\n double create_sparse_matrix ;\n\n double fill_time ;\n\n double bc_time ;\n\n double matvec_time ;\n\n double cg_time ;\n\n double newton_residual ;\n\n double error_max ;\n\n\n\n};\n", "file_path": "example/fenl/fenl.hpp", "rank": 92, "score": 104321.92663383145 }, { "content": "struct Types3 {\n\n typedef T1 Head;\n\n typedef Types2<T2, T3> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 93, "score": 104321.92663383145 }, { "content": "struct Types2 {\n\n typedef T1 Head;\n\n typedef Types1<T2> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 94, "score": 104321.92663383145 }, { "content": "struct Types9 {\n\n typedef T1 Head;\n\n typedef Types8<T2, T3, T4, T5, T6, T7, T8, T9> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5,\n\n typename T6, typename T7, typename T8, typename T9, typename T10>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 95, "score": 104321.92663383145 }, { "content": "struct Types8 {\n\n typedef T1 Head;\n\n typedef Types7<T2, T3, T4, T5, T6, T7, T8> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5,\n\n typename T6, typename T7, typename T8, typename T9>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 96, "score": 104321.92663383145 }, { "content": "struct Types7 {\n\n typedef T1 Head;\n\n typedef Types6<T2, T3, T4, T5, T6, T7> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5,\n\n typename T6, typename T7, typename T8>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 97, "score": 104321.92663383145 }, { "content": "struct Types6 {\n\n typedef T1 Head;\n\n typedef Types5<T2, T3, T4, T5, T6> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5,\n\n typename T6, typename T7>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 98, "score": 104321.92663383145 }, { "content": "struct Types5 {\n\n typedef T1 Head;\n\n typedef Types4<T2, T3, T4, T5> Tail;\n\n};\n\n\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5,\n\n typename T6>\n", "file_path": "tpls/gtest/gtest/gtest.h", "rank": 99, "score": 104321.92663383145 } ]
C++
tools/clang/lib/Analysis/CallGraph.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
#include "clang/Analysis/CallGraph.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/StmtVisitor.h" #include "llvm/Support/GraphWriter.h" using namespace clang; namespace { class CGBuilder : public StmtVisitor<CGBuilder> { CallGraph *G; CallGraphNode *CallerNode; public: CGBuilder(CallGraph *g, CallGraphNode *N) : G(g), CallerNode(N) {} void VisitStmt(Stmt *S) { VisitChildren(S); } void VisitCallExpr(CallExpr *CE) { if (FunctionDecl *CalleeDecl = CE->getDirectCallee()) if (G->includeInGraph(CalleeDecl)) { CallGraphNode *CalleeNode = G->getOrInsertNode(CalleeDecl); CallerNode->addCallee(CalleeNode, G); } } void VisitChildren(Stmt *S) { for (Stmt::child_range I = S->children(); I; ++I) if (*I) static_cast<CGBuilder*>(this)->Visit(*I); } }; } CallGraph::CallGraph() { Root = getOrInsertNode(0); } CallGraph::~CallGraph() { if (!FunctionMap.empty()) { for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end(); I != E; ++I) delete I->second; FunctionMap.clear(); } } bool CallGraph::includeInGraph(const Decl *D) { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (!FD->isThisDeclarationADefinition() || FD->isDependentContext()) return false; IdentifierInfo *II = FD->getIdentifier(); if (II && II->getName().startswith("__inline")) return false; } if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { if (!ID->isThisDeclarationADefinition()) return false; } return true; } void CallGraph::addNodeForDecl(Decl* D, bool IsGlobal) { assert(D); if (FunctionMap.find(D) != FunctionMap.end()) return; CallGraphNode *Node = getOrInsertNode(D); if (IsGlobal) Root->addCallee(Node, this); CGBuilder builder(this, Node); if (Stmt *Body = D->getBody()) builder.Visit(Body); } CallGraphNode *CallGraph::getNode(const Decl *F) const { FunctionMapTy::const_iterator I = FunctionMap.find(F); if (I == FunctionMap.end()) return 0; return I->second; } CallGraphNode *CallGraph::getOrInsertNode(Decl *F) { CallGraphNode *&Node = FunctionMap[F]; if (Node) return Node; Node = new CallGraphNode(F); if (F != 0) ParentlessNodes.insert(Node); return Node; } void CallGraph::print(raw_ostream &OS) const { OS << " --- Call graph Dump --- \n"; for (const_iterator I = begin(), E = end(); I != E; ++I) { OS << " Function: "; if (I->second == Root) OS << "< root >"; else I->second->print(OS); OS << " calls: "; for (CallGraphNode::iterator CI = I->second->begin(), CE = I->second->end(); CI != CE; ++CI) { assert(*CI != Root && "No one can call the root node."); (*CI)->print(OS); OS << " "; } OS << '\n'; } OS.flush(); } void CallGraph::dump() const { print(llvm::errs()); } void CallGraph::viewGraph() const { llvm::ViewGraph(this, "CallGraph"); } StringRef CallGraphNode::getName() const { if (const FunctionDecl *D = dyn_cast_or_null<FunctionDecl>(FD)) if (const IdentifierInfo *II = D->getIdentifier()) return II->getName(); return "< >"; } void CallGraphNode::print(raw_ostream &os) const { os << getName(); } void CallGraphNode::dump() const { print(llvm::errs()); } namespace llvm { template <> struct DOTGraphTraits<const CallGraph*> : public DefaultDOTGraphTraits { DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} static std::string getNodeLabel(const CallGraphNode *Node, const CallGraph *CG) { if (CG->getRoot() == Node) { return "< root >"; } return Node->getName(); } }; }
#include "clang/Analysis/CallGraph.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/StmtVisitor.h" #include "llvm/Support/GraphWriter.h" using namespace clang; namespace { class CGBuilder : public StmtVisitor<CGBuilder> { CallGraph *G; CallGraphNode *CallerNode; public: CGBuilder(CallGraph *g, CallGraphNode *N) : G(g), CallerNode(N) {} void VisitStmt(Stmt *S) { VisitChildren(S); } void VisitCallExpr(CallExpr *CE) { if (FunctionDecl *CalleeDecl = CE->getDirectCallee()) if (G->includeInGraph(CalleeDecl)) { CallGraphNode *CalleeNode = G->getOrInsertNode(CalleeDecl); CallerNode->addCallee(CalleeNode, G); } } void VisitChildren(Stmt *S) { for (Stmt::child_range I = S->children(); I; ++I) if (*I) static_cast<CGBuilder*>(this)->Visit(*I); } }; } CallGraph::CallGraph() { Root = getOrInsertNode(0); } CallGraph::~CallGraph() { if (!FunctionMap.empty()) { for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end(); I != E; ++I) delete I->second; FunctionMap.clear(); } } bool CallGraph::includeInGraph(const Decl *D) { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (!FD->isThisDeclarationADefinition() || FD->isDependentContext()) return false; IdentifierInfo *II = FD->getIdentifier(); if (II && II->getName().startswith("__inline")) return false; } if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { if (!ID->isThisDeclarationADefinition()) return false; } return true; } void CallGraph::addNodeForDecl(Decl* D, bool IsGlobal) { assert(D); if (FunctionMap.find(D) != FunctionMap.end()) return; CallGraphNode *Node = getOrInsertNode(D); if (IsGlobal) Root->addCallee(Node, this); CGBuilder builder(this, Node); if (Stmt *Body = D->getBody()) builder.Visit(Body); } CallGraphNode *CallGraph::getNode(const Decl *F) const { FunctionMapTy::const_iterator I = FunctionMap.find(F); if (I == FunctionMap.end()) return 0; return I->second; } CallGraphNode *CallGraph::getOrInsertNode(Decl *F) { CallGraphNode *&Node = FunctionMap[F]; if (Node) return Node; Node = new CallGraphNode(F); if (F != 0) ParentlessNodes.insert(Node); return Node; } void CallGraph::print(raw_ostream &OS) const { OS << " --- Call graph Dump --- \n"; for (const_iterator I = begin(), E = end(); I != E; ++I) { OS << " Function: "; if (I->second == Root) OS << "< root >"; else I->second->print(OS); OS << " calls: "; for (CallGraphNode::iterator CI = I->second->begin(), CE = I->second->end(); CI != CE; ++CI) { assert(*CI != Root && "No one can call the root node."); (*CI)->print(OS); OS << " "; } OS << '\n'; } OS.flush(); } void CallGraph::dump() const { print(llvm::errs()); } void CallGraph::viewGraph() const { llvm::ViewGraph(this, "CallGraph"); } StringRef CallGraphNode::getName() const { if (const FunctionDecl *D = dyn_cast_or_null<FunctionDecl>(FD)) if (const IdentifierInfo *II = D->getIdentifier()) return II->getName(); return "< >"; } void CallGraphNode::print(raw_ostream &os) const { os << getName(); } void CallGraphNode::dump() const { print(llvm::errs()); } namespace llvm { template <> struct DOTGraphTraits<const CallGraph*> : public DefaultDOTGraphTraits { DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
}; }
static std::string getNodeLabel(const CallGraphNode *Node, const CallGraph *CG) { if (CG->getRoot() == Node) { return "< root >"; } return Node->getName(); }
function_block-function_prefix_line
[]
C++
source/code/iceshard/iceshard/private/world/iceshard_world.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
#include "iceshard_world.hxx" #include <ice/world/world_trait.hxx> #include <ice/engine_runner.hxx> #include <ice/engine_frame.hxx> #include <ice/engine_shards.hxx> #include <ice/pod/hash.hxx> #include <ice/assert.hxx> #include "iceshard_world_portal.hxx" namespace ice { IceshardWorld::IceshardWorld( ice::Allocator& alloc, ice::ecs::EntityStorage* entity_storage ) noexcept : _allocator{ alloc } , _entity_storage{ entity_storage } , _state{ WorldState::Idle } , _traits{ _allocator } , _portals{ _allocator } { } IceshardWorld::~IceshardWorld() noexcept { ICE_ASSERT( ice::pod::array::empty(_portals._data), "Not all traits where removed from this World before destruction!" ); } auto IceshardWorld::allocator() noexcept -> ice::Allocator& { return _allocator; } auto IceshardWorld::entity_storage() noexcept -> ice::ecs::EntityStorage& { return *_entity_storage; } auto IceshardWorld::state_hint() const noexcept -> ice::WorldState { return _state; } void IceshardWorld::set_state( ice::WorldState state ) noexcept { _state = state; } void IceshardWorld::add_trait( ice::StringID_Arg name, ice::WorldTrait* trait ) noexcept { ice::u64 const name_hash = ice::hash(name); ICE_ASSERT( ice::pod::hash::has(_portals, name_hash) == false, "World already contains a trait of name {}", ice::stringid_hint(name) ); ice::pod::array::push_back( _traits, trait ); ice::pod::hash::set( _portals, name_hash, _allocator.make<IceshardWorldPortal>( _allocator, *this, trait, *_entity_storage ) ); } void IceshardWorld::remove_trait( ice::StringID_Arg name ) noexcept { ice::u64 const name_hash = ice::hash(name); ICE_ASSERT( ice::pod::hash::has(_portals, name_hash) == true, "World does not contain a trait with name {}", ice::stringid_hint(name) ); ice::IceshardWorldPortal* const portal = ice::pod::hash::get(_portals, name_hash, nullptr); auto* it = ice::pod::array::begin(_traits); auto* const end = ice::pod::array::end(_traits); while (it != end && (*it) != portal->trait()) { it += 1; } ICE_ASSERT(it != end, "Couldnt find location of the world trait to be removed!"); *it = ice::pod::array::back(_traits); ice::pod::array::pop_back(_traits); ice::pod::hash::remove( _portals, ice::hash(name_hash) ); _allocator.destroy(portal); } void IceshardWorld::activate( ice::Engine& engine, ice::EngineRunner& runner ) noexcept { for (auto& entry : _portals) { entry.value->trait()->on_activate( engine, runner, *entry.value ); } } void IceshardWorld::deactivate( ice::Engine& engine, ice::EngineRunner& runner ) noexcept { for (auto& entry : _portals) { entry.value->trait()->on_deactivate( engine, runner, *entry.value ); } } void IceshardWorld::update( ice::EngineRunner& runner ) noexcept { ice::EngineFrame& current_frame = runner.current_frame(); _entity_storage->execute_operations( runner.previous_frame().entity_operations(), current_frame.shards() ); for (auto& entry : _portals) { entry.value->remove_finished_tasks(); entry.value->trait()->on_update( runner.current_frame(), runner, *entry.value ); } } auto IceshardWorld::traits() noexcept -> ice::pod::Array<ice::WorldTrait*>& { return _traits; } }
#include "iceshard_world.hxx" #include <ice/world/world_trait.hxx> #include <ice/engine_runner.hxx> #include <ice/engine_frame.hxx> #include <ice/engine_shards.hxx> #include <ice/pod/hash.hxx> #include <ice/assert.hxx> #include "iceshard_world_portal.hxx" namespace ice { IceshardWorld::IceshardWorld( ice::Allocator& alloc, ice::ecs::EntityStorage* entity_storage ) noexcept : _allocator{ alloc } , _entity_storage{ entity_storage } , _state{ WorldState::Idle } , _traits{ _allocator } , _portals{ _allocator } { } IceshardWorld::~IceshardWorld() noexcept { ICE_ASSERT( ice::pod::array::empty(_portals._data), "Not all traits where removed from this World before destruction!" ); } auto IceshardWorld::allocator() noexcept -> ice::Allocator& { return _allocator; } auto IceshardWorld::entity_storage() noexcept -> ice::ecs::EntityStorage& { return *_entity_storage; } auto IceshardWorld::state_hint() const noexcept -> ice::WorldState { return _state; } void IceshardWorld::set_state( ice::WorldState state ) noexcept { _state = state; } void IceshardWorld::add_trait( ice::StringID_Arg name, ice::WorldTrait* trait ) noexcept { ice::u64 const name_hash = ice::hash(name); ICE_ASSERT( ice::pod::hash::has(_portals, name_hash) == false, "World already contains a trait of name {}", ice::stringid_hint(name) ); ice::pod::array::push_back( _traits, trait ); ice::pod::hash::set( _portals, name_hash, _allocator.make<IceshardWorldPortal>( _allocator, *this, trait, *_entity_storage ) ); } void IceshardWorld::remove_trait( ice::StringID_Arg name ) noexcept { ice::u64 const name_hash = ice::hash(name); ICE_ASSERT( ice::pod::hash::has(_portals, name_hash) == true, "World does not contain a trait with name {}", ice::stringid_hint(name) ); ice::IceshardWorldPortal* const portal = ice::pod::hash::get(_portals, name_hash, nullptr); auto* it = ice::pod::array::begin(_traits); auto* const end = ice::pod::array::end(_traits); while (it != end && (*it) != portal->trait()) { it += 1; } ICE_ASSERT(it != end, "Couldnt find location of the world trait to be removed!"); *it = ice::pod::array::back(_traits); ice::pod::array::pop_back(_traits); ice::pod::hash::remove( _portals, ice::hash(name_hash) ); _allocator.destroy(portal); } void IceshardWorld::activate( ice::Engine& engine, ice::EngineRunner& runner ) noexcept { for (auto& entry : _portals) { entry.value->trait()->on_activate( engine, runner, *entry.value ); } } void IceshardWorld::deactivate( ice::Engine& engine, ice::EngineRunner& runner ) noexcept { for (auto& entry : _portals) { entry.value->trait()->on_deactivate( engine, runner, *entry.value ); } } void IceshardWorld::update( ice::EngineRunner& runner ) noexcept { ice::EngineFrame& current_frame = runner.current_frame(); _entity_storage->execute_operations( runner.previous_frame().entity_operations(), current_frame.shards() ); for (auto& entry : _portals) { entry.value->remove_finished_tasks();
; } } auto IceshardWorld::traits() noexcept -> ice::pod::Array<ice::WorldTrait*>& { return _traits; } }
entry.value->trait()->on_update( runner.current_frame(), runner, *entry.value )
call_expression
[ { "content": "inline void* b2Alloc(void* alloc, ice::i32 size)\n\n{\n\n return reinterpret_cast<ice::Allocator*>(alloc)->allocate(static_cast<ice::u32>(size));\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 0, "score": 39755.43515219723 }, { "content": "inline void* b2Alloc(void* alloc, ice::i32 size)\n\n{\n\n return reinterpret_cast<ice::Allocator*>(alloc)->allocate(static_cast<ice::u32>(size));\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 1, "score": 28287.862421675192 }, { "content": "inline void b2Free(void* alloc, void* memory)\n\n{\n\n reinterpret_cast<ice::Allocator*>(alloc)->deallocate(memory);\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 2, "score": 25298.416925978232 }, { "content": "inline void b2Log(const char* string, ...)\n\n{\n\n char final_message[512];\n\n\n\n va_list args;\n\n va_start(args, string);\n\n vsnprintf_s(final_message, _TRUNCATE, string, args);\n\n va_end(args);\n\n\n\n ICE_LOG(\n\n ice::LogSeverity::Debug, ice::LogTag::Engine,\n\n \"<Box2D> {}\", final_message\n\n );\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 3, "score": 25298.416925978232 }, { "content": "#define b2_maxPolygonVertices 8\n\n\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 4, "score": 24358.152945173835 }, { "content": "struct B2_API b2JointUserData\n\n{\n\n ice::uptr userdata = 0;\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 5, "score": 24356.23842594329 }, { "content": "struct B2_API b2BodyUserData\n\n{\n\n ice::ecs::EntityHandle entity;\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 6, "score": 24356.23842594329 }, { "content": "struct B2_API b2FixtureUserData\n\n{\n\n ice::uptr userdata = 0;\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 7, "score": 24356.23842594329 }, { "content": "#define b2_lengthUnitsPerMeter 1.0f\n\n\n", "file_path": "source/code/framework/framework_base/private/traits/physics/b2_user_settings.h", "rank": 8, "score": 23911.764908872516 }, { "content": "IF \"%1\" == \"--conan_profile\" (\n\n CALL SET CONAN_PROFILE=\"%2\"\n\n) ELSE (\n\n SHIFT\n\n GOTO :_find_profile_arg\n\n)\n\nGOTO :_exit\n\n\n\n:: Initialize the project environment\n\n:_initialize\n\nPUSHD build\\tools\n\nconan install ..\\..\\tools --build=missing --profile %CONAN_PROFILE%\n\nPOPD\n\nECHO Workspace initialized...\n\nGOTO :_exit\n\n\n\n:: Application runtime\n\n:_run\n\nCALL build\\tools\\activate.bat\n\nCALL \"%ICE_SCRIPT%\" workspace.moon %*\n", "file_path": "ice.bat", "rank": 9, "score": 21344.397985130887 }, { "content": " ECHO Rebuilding enviroment...\n\n CALL :_initialize\n\n)\n\n\n\n:: Check specific args before running\n\nIF \"%1\" == \"init\" (\n\n SHIFT\n\n CALL :_initialize\n\n GOTO :_exit\n\n)\n\n\n\n:: Move to the application\n\nGOTO :_run\n\n\n\n:: Find the value of the --conan_profile argument\n\n:_find_profile_arg\n\nIF [%1] EQU [] (\n\n CALL SET CONAN_PROFILE=\"default\"\n\n GOTO :_exit\n\n)\n", "file_path": "ice.bat", "rank": 10, "score": 21344.071914555367 }, { "content": "@ECHO off\n\nSETLOCAL\n\nPUSHD %~dp0\n\n\n\n:: Cretae the build directory\n\nIF NOT EXIST build\\ (\n\n ECHO Preparing the workspace...\n\n MKDIR build\n\n)\n\n\n\nCALL :_find_profile_arg %*\n\n\n\n:: Create the build\\tools directory\n\nIF NOT EXIST build\\tools\\ (\n\n ECHO Preparing tools...\n\n MKDIR build\\tools\\\n\n CALL :_initialize\n\n)\n\n\n\nIF NOT EXIST build\\tools\\activate.bat (\n", "file_path": "ice.bat", "rank": 11, "score": 21343.529668803403 }, { "content": "\n\n:: Save this value as it so the call to 'deactivate' wont erase it in some caes\n\nset ERROR_CODE=%ERRORLEVEL%\n\n\n\nCALL build\\tools\\deactivate.bat\n\n\n\n:: Check the command return code\n\nIF \"%ERROR_CODE%\" == \"0\" (\n\n GOTO :_exit\n\n)\n\nGOTO :_error\n\n\n\nPOPD\n\n\n\n:_exit\n\nexit /B 0\n\n\n\n:_error\n\nexit /B 1\n", "file_path": "ice.bat", "rank": 12, "score": 21342.42115448448 }, { "content": "# IceShard\n\n\n\nThe project is a game engine with heavy focus on finding the best solution for a given problem, by using different design approaches.\n\nMore info about the development approach can be found in our [wiki](https://github.com/iceshard-engine/engine/wiki).\n\n\n\n## Features\n\n\n\nCurrent list of features:\n\n* Allocator oriented memory access.\n\n * Only `placement new` operators used.\n\n* Support for **Tracy** profiler.\n\n* Device inputs and events.\n\n* Resource and asset access.\n\n * Runtime building of some assets.\n\n* Abstracted API for rendering.\n\n * With a working implementation for Vulkan.\n\n* An extensive engine API.\n\n * Heavily data-oriented ECS implementation.\n\n * **World** design with user **Traits** as extension points.\n\n * Graphics layer build on top of the Render API and world traits.\n\n * Fully removable DevUI API.\n\n* ...\n\n\n\n## Building the engine\n\n\n\nA quick overview how to build the engine on your machine.\n\n\n\n### Prerequisites\n\nTo build this engine you will need the following tools and SDKs installed:\n\n* [Conan Package Manager](https://conan.io/) - Used to manage project dependencies.\n\n * This also requires python3 as a dependency.\n\n* **Windows:**\n\n * Required: Visual Studio 2019 _(16.10 or later)_\n\n * Required: Windows Kit (10.0.19041.0 or later)\n\n * Required: Vulkan SDK _(1.2.170.0 or later)_\n\n * Optional when a DX1* implementation is available.\n\n* **Linux** - _(Under heavy development, currently not available in the repository)_\n\n * Tested On: \n\n * Manjarno Linux (KDE Plasma) (Kernel 5.15.6-2-MANJARNO x64)\n\n * GitHub Runner: Ubuntu-Latest\n\n * Required: GCC-11 C++ compiler or later\n\n * Required: standard library libstdc++ v6 or later\n\n * ~~Required: Vulkan SDK _(1.2.170.0 or later)_~~ - Not implemented yet.\n\n * Optional when a OpenGL implementation is available.\n\n* **MacOS:**\n\n * No support\n\n\n", "file_path": "README.md", "rank": 13, "score": 12775.004046322818 }, { "content": "### Configuring Conan\n\n\n\nTo properly initialize the workspace, you will need to setup Conan with configurations from the [IceShard-Conan-Config](https://github.com/iceshard-engine/conan-config.git) repository.\n\nThis contains the Conan clang profiles and remotes that should be used with this project.\n\n\n\nThe quickest way to setup Conan for this project is to use the following command:\n\n\n\n```\n\nconan config install https://github.com/iceshard-engine/conan-config.git\n\n```\n\n\n\n### Ice Build Tools\n\n\n\nThis project uses its own command line tool named **Ice Build Tools** to provide various utilities that can be used during development.\n\n\n\nIt is a Conan package that will be installed on first use. It can be easily updated at any point or reset by removing the `./build/` directory when something goes wrong.\n\n\n\n---\n\n#### The `build` command\n\n\n\nBuilding the engine is straight forward, all you need to do is to call this command in your terminal and you have built the engine.\n\n\n\n ./ice.sh build\n\n ./ice.bat build\n\n\n\nYou can further specify the target you want to build by using the `-t --target` option.\n\n\n\n ice build -t all-x64-Debug\n\n\n\n---\n\n#### The `vstudio` command\n\n\n\nThis command allows to generate project files for Visual Studio.\n\n\n\n ./ice.bat vstudio\n\n\n\n---\n\n#### The `run` command\n\n\n\nThis command allows to execute pre-defined lists of other commands or tools in order. These execution `scenarios` are stored in the `scenarios.json` file and currently provide a quick way to run the test application and to build shaders on the Windows platform.\n\n\n\n :: Build all shaders into Vulkan SPIR-V\n\n ./ice.bat run -s shaders\n\n\n\n :: Run the default-built test application executable (all-x64-Develop)\n\n ./ice.bat run\n\n\n\n\n", "file_path": "README.md", "rank": 14, "score": 12774.151952069808 }, { "content": "## Contributing\n\n\n\nContributions are welcome, however they need to follow the\n\n[Coding Style](https://github.com/iceshard-engine/coding-style) of the engine and pass the review process.\n\n\n\nAdditionally, some contributions might also require additional changes if the implementation does not follow the design principles of this project.\n\n\n\nIt is however possible to ask for a separate repository that will and provide new features via modules API. This would only require to follow the aforementioned coding style.\n\n\n\n\n\n## License\n\n\n\nThe engine is licensed under [BSD 3-Clause Clear License](https://github.com/iceshard-engine/engine/blob/master/LICENSE).\n\n\n\n## Acknowledgements\n\n\n\nThis project was heavily influenced by several articles, but mostly by the BitSquid development blog.\n\n\n\nAdditionally, some parts of the engine were based on the **BitSquid Foundation Library** which was discussed here:\n\nhttps://bitsquid.blogspot.com/2012/11/bitsquid-foundation-library.html\n", "file_path": "README.md", "rank": 15, "score": 12771.892295016032 }, { "content": "inline void b2Free(void* alloc, void* memory)\n\n{\n\n reinterpret_cast<ice::Allocator*>(alloc)->deallocate(memory);\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 16, "score": 12770.023747288162 }, { "content": "inline void b2Log(const char* string, ...)\n\n{\n\n char final_message[512];\n\n\n\n va_list args;\n\n va_start(args);\n\n vsnprintf_s(final_message, _TRUNCATE, string, args);\n\n va_end(args);\n\n\n\n ICE_LOG(\n\n ice::LogSeverity::Debug, ice::LogTag::Engine,\n\n \"<Box2D> {}\", final_message\n\n );\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 17, "score": 12770.023747288162 }, { "content": "#define b2_maxPolygonVertices 8\n\n\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 18, "score": 12365.220828180556 }, { "content": "struct B2_API b2BodyUserData\n\n{\n\n ice::uptr userdata = 0;\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 19, "score": 12363.306308950014 }, { "content": "struct B2_API b2JointUserData\n\n{\n\n ice::uptr userdata = 0;\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 20, "score": 12363.306308950014 }, { "content": "struct B2_API b2FixtureUserData\n\n{\n\n ice::uptr userdata = 0;\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 21, "score": 12363.306308950014 }, { "content": "#define b2_lengthUnitsPerMeter 1.0f\n\n\n", "file_path": "source/code/framework/framework_2d/private/b2_user_settings.h", "rank": 22, "score": 12169.510578177145 }, { "content": "#define CATCH_CONFIG_MAIN\n\n#include <catch2/catch.hpp>\n", "file_path": "source/code/core/core/tests/main.cpp", "rank": 23, "score": 2.030282746751103 } ]
C++
Src/main.cpp
KuhakuPixel/TempestPixyEngine
929d2952e2b4a83a85287c3030accade5ae449e2
#include <string.h> #include <iostream> #include <string> #include "board.h" #include "CharHelper.h" #include "math.h" #include "chessLib.h" #include "evaluation.h" #include "search.h" #include "stringHelper.h" void StartEngineUci() { std::string startFenPosition = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; std::string command = ""; #pragma region Initializing Engine parameters Board board = Board(); board.LoadFromFen(startFenPosition); Evaluation evaluation = Evaluation(); evaluation.InitializeKnightPeriphery0(-0.51); evaluation.InitializeKnightPeriphery1(-0.18); evaluation.InitializeKnightPeriphery2(+0.54); evaluation.InitializeKnightPeriphery3(+0.1); #pragma endregion while (true) { std::getline(std::cin, command); if (command == "isready") printf("readyok\n"); else if (command.find("position") == 0) { if (command.find("position fen") == 0) { std::string newFenPos = command.substr(strlen("position fen") + 1); board.LoadFromFen(newFenPos); } else if (command.find("position startpos moves") == 0) { board = Board(); board.LoadFromFen(startFenPosition); std::string movesStr = command.substr(strlen("position startpos moves") + 1); std::vector<std::string> moves = StringHelper::SplitString(movesStr, " "); for (int i = 0; i < moves.size(); i++) board.Move(moves.at(i)); } } else if (command.find("go") == 0) { std::string bestMove = ""; Search::SearchPosition(board, evaluation, 0, 4, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), &bestMove); printf("bestmove %s\n", bestMove.c_str()); } else if (command == "quit") exit(0); } } void PlayAgainstSelf() { Board board = Board(); board.LoadFromFen("rnbqkb1r/pppp1ppp/5n2/4p3/4PP2/2N5/PPPP2PP/R1BQKBNR b KQkq - 0 3"); Evaluation evaluation = Evaluation(); evaluation.InitializeKnightPeriphery0(-0.51); evaluation.InitializeKnightPeriphery1(-0.18); evaluation.InitializeKnightPeriphery2(+0.54); evaluation.InitializeKnightPeriphery3(+0.1); while (true) { std::string colorToMove = board.GetCurrentTurnStr(); std::string bestMove = ""; printf("Side to move %s \n", colorToMove.c_str()); printf("last move is : %s\n", bestMove.c_str()); board.DisplayBoard('w'); Search::SearchPosition(board, evaluation, 0, 4, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), &bestMove); board.Move(bestMove); system("cls"); } } int main(int argc, char *argv[]) { printf("Tempest Pixy engine\n"); while (true) { std::string command = ""; std::cin >> command; if (command == "uci") { printf("id name Tempest-Pixy-Engine 1.0.0\n"); printf("id author Kuhaku Pixel\n"); printf("uciok\n"); StartEngineUci(); } else if (command == "isready") { printf("readyok\n"); } else if (command == "quit") exit(0); } return 0; }
#include <string.h> #include <iostream> #include <string> #include "board.h" #include "CharHelper.h" #include "math.h" #include "chessLib.h" #include "evaluation.h" #include "search.h" #include "stringHelper.h" void StartEngineUci() { std::string startFenPosition = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; std::string command = ""; #pragma region Initializing Engine parameters Board board = Board(); board.LoadFromFen(startFenPosition); Evaluation evaluation = Evaluation(); evaluation.InitializeKnightPeriphery0(-0.51); evaluation.InitializeKnightPeriphery1(-0.18); evaluation.InitializeKnightPeriphery2(+0.54); evaluation.InitializeKnightPeriphery3(+0.1); #pragma endregion while (true) { std::getline(std::cin, command); if (command == "isready") printf("readyok\n"); else if (command.find("position") == 0) { if (command.find("position fen") == 0) { std::string newFenPos = command.substr(strlen("position fen") + 1); board.LoadFromFen(newFenPos); } else if (command.find("position startpos moves") == 0) { board = Board(); board.LoadFromFen(startFenPosition); std::string movesStr = command.substr(strlen("position startpos moves") + 1); std::vector<std::string> moves = StringHelper::SplitString(movesStr, " "); for (int i = 0; i < moves.size(); i++) board.Move(moves.at(i)); } } else if (command.find("go") == 0) { std::string bestMove = ""; Search::SearchPosition(board, evaluation, 0, 4, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), &bestMove); printf("bestmove %s\n", bestMove.c_str()); } else if (command == "quit") exit(0); } } void PlayAgainstSelf() { Board board = Board(); board.LoadFromFen("rnbqkb1r/pppp1ppp/5n2/4p3/4PP2/2N5/PPPP2PP/R1BQKBNR b KQkq - 0 3"); Evaluation evaluation = Evaluation(); evaluation.InitializeKnightPeriphery0(-0.5
int main(int argc, char *argv[]) { printf("Tempest Pixy engine\n"); while (true) { std::string command = ""; std::cin >> command; if (command == "uci") { printf("id name Tempest-Pixy-Engine 1.0.0\n"); printf("id author Kuhaku Pixel\n"); printf("uciok\n"); StartEngineUci(); } else if (command == "isready") { printf("readyok\n"); } else if (command == "quit") exit(0); } return 0; }
1); evaluation.InitializeKnightPeriphery1(-0.18); evaluation.InitializeKnightPeriphery2(+0.54); evaluation.InitializeKnightPeriphery3(+0.1); while (true) { std::string colorToMove = board.GetCurrentTurnStr(); std::string bestMove = ""; printf("Side to move %s \n", colorToMove.c_str()); printf("last move is : %s\n", bestMove.c_str()); board.DisplayBoard('w'); Search::SearchPosition(board, evaluation, 0, 4, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), &bestMove); board.Move(bestMove); system("cls"); } }
function_block-function_prefixed
[ { "content": "#pragma once\n\n#include <string>\n\n#include <map>\n\n#include \"CharHelper.h\"\n\n#include <vector>\n\n#include \"chessLib.h\"\n\n#include \"square.h\"\n\nclass Board\n\n{\n\nprivate:\n\n std::vector<MoveFlag> blackCastlingRights = {MoveFlag::shortCastle, MoveFlag::longCastle};\n\n std::vector<MoveFlag> whiteCastlingRights = {MoveFlag::shortCastle, MoveFlag::longCastle};\n\n PieceColors currentTurn = PieceColors::white;\n\n char board[8][8] = {\n\n\n\n {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'},\n\n {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},\n\n {EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE},\n\n {EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE},\n\n {EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE},\n\n {EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE, EMPTYSQUARE},\n\n {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},\n\n {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'},\n\n\n\n };\n\n void ClearBoard();\n\n\n", "file_path": "Src/board.h", "rank": 0, "score": 61622.82286029591 }, { "content": "class Evaluation\n\n{\n\nprivate:\n\n std::map<PieceName, std::map<ESquare, double>> piecesSquaresValue;\n\n\n\npublic:\n\n static const std::map<PieceName, double> pieceNameToValueMap;\n\n Evaluation();\n\n void SetPieceSquareValue(PieceName pieceName, std::string square, double value);\n\n /// initialize knight square value on\n\n /// a1 to a8,a8 to h8,a1 to h1 or h1 to h8.\n\n void InitializeKnightPeriphery0(double value);\n\n /// initialize knight square value on\n\n /// b2 to b7,b7 to g7,b2 to g2 or g2 to g7.\n\n void InitializeKnightPeriphery1(double value);\n\n /// initialize knight square value on\n\n /// c3 to c6,c6 to f6,c3 to f3 or f3 to f6.\n\n void InitializeKnightPeriphery2(double value);\n\n /// initialize knight square value on\n\n /// e4, e5,d4 or d5\n\n void InitializeKnightPeriphery3(double value);\n\n\n\n void EvaluateMaterial(EvaluationVector &evaluationVector, PieceName pieceName, PieceColors pieceColors) const;\n\n double EvaluateHangingPieces(const Board &board, PieceColors sideToEvaluate) const;\n\n double EvaluateDefendedPieces(const Board &board, PieceColors sideToEvaluate) const;\n\n double EvaluateKingSafety(const Board &board, PieceColors sideToEvaluate) const;\n\n void EvaluateKnight(const Board &board, EvaluationVector &evaluationVector, PieceColors pieceColor, int fileNum, int rankNum) const;\n\n double EvaluateGameResult(const Board &board, GameResult gameResult) const;\n\n double Evaluate(const Board &board) const;\n\n};", "file_path": "Src/evaluation.h", "rank": 1, "score": 46860.979491568956 }, { "content": "#pragma once\n\n#include \"board.h\"\n\n#include \"chessLib.h\"\n\n#include <map>\n\nclass EvaluationVector\n\n{\n\nprivate:\n\n std::map<PieceColors, double> pieceColorToEvaluation = {\n\n {PieceColors::white, 0},\n\n {PieceColors::black, 0},\n\n };\n\n\n\npublic:\n\n void IncrementEvaluation(PieceColors side, double value);\n\n double GetStaticEvaluation();\n\n};\n", "file_path": "Src/evaluation.h", "rank": 2, "score": 44303.02987885072 }, { "content": "#pragma once\n\n#include <vector>\n\n#include <string>\n\nclass StringHelper\n\n{\n\npublic:\n\n static std::vector<std::string> SplitString(std::string str,std::string delimiter);\n\n};", "file_path": "Src/stringHelper.h", "rank": 3, "score": 41980.97457847007 }, { "content": "#pragma once\n\n#include \"board.h\"\n\n#include \"chessLib.h\"\n\n#include <map>\n", "file_path": "Src/evaluation.h", "rank": 4, "score": 38541.89978787423 }, { "content": " PieceName GetPieceNameEnum(Square square) const;\n\n\n\n PieceColors GetPieceColor(int fileNum, int rankNum) const;\n\n PieceColors GetPieceColor(Square square) const;\n\n\n\n void LoadPseudoBoard(const Board &board);\n\n void LoadFromFen(std::string fen);\n\n std::string ExportFen();\n\n\n\n ///w for white , b for black\n\n void DisplayBoard(char orientation = 'w');\n\n\n\n ///The move format is in long algebraic notation.\n\n ///A nullmove from the Engine to the GUI should be send as 0000.\n\n ///Examples: e2e4, e7e5, e1g1 (white short castling), e7e8q (for promotion)\n\n void Move(std::string moveNotation, bool psuedoLegalMove = false);\n\n\n\n ///The move format is in long algebraic notation.\n\n ///A nullmove from the Engine to the GUI should be send as 0000.\n\n ///Examples: e2e4, e7e5, e1g1 (white short castling), e7e8q (for promotion)\n\n void Move(Square from, Square to, bool psuedoLegalMove = false, PieceName newPromotedPiece = PieceName::null);\n\n};", "file_path": "Src/board.h", "rank": 5, "score": 38496.55209241813 }, { "content": "public:\n\n //getter are const to tell the compiler that this function will not change\n\n //the property of this instance\n\n //ref:\n\n //https://stackoverflow.com/questions/26963510/error-passing-const-as-this-argument-of-discards-qualifiers/26963552\n\n //https://stackoverflow.com/questions/13103755/intellisense-the-object-has-type-qualifiers-that-are-not-compatible-with-the-me/13103791\n\n //https://stackoverflow.com/questions/28987916/cannot-call-a-method-of-const-reference-parameter-in-c\n\n PieceColors GetCurrentTurn() const;\n\n std::string GetCurrentTurnStr() const;\n\n std::vector<MoveFlag> GetCastlingRights(PieceColors color) const;\n\n bool IsSquareEmpty(int fileNum, int rankNum) const;\n\n bool IsSquareEmpty(Square square) const;\n\n void PlacePiece(char piece, int fileNum, int rankNum);\n\n void PlacePiece(char piece, Square square);\n\n void PlacePiece(PieceName pieceName, PieceColors pieceColor, int fileNum, int rankNum);\n\n void PlacePiece(PieceName pieceName, PieceColors pieceColor, Square square);\n\n char GetPieceName(int fileNum, int rankNum) const;\n\n char GetPieceName(Square square) const;\n\n\n\n PieceName GetPieceNameEnum(int fileNum, int rankNum) const;\n", "file_path": "Src/board.h", "rank": 6, "score": 38482.35333567193 }, { "content": "#pragma once\n\n#include <string>\n\n#include <map>\n\n#include \"CharHelper.h\"\n\n#include <vector>\n\n#include \"chessLib.h\"\n\n#include \"square.h\"\n", "file_path": "Src/board.h", "rank": 7, "score": 38482.00089630062 }, { "content": "#include \"evaluation.h\"\n\n#include \"analyzer.h\"\n\n#include \"search.h\"\n\n#include <limits>\n\nvoid EvaluationVector::IncrementEvaluation(PieceColors side, double value)\n\n{\n\n this->pieceColorToEvaluation[side] += value;\n\n}\n\ndouble EvaluationVector::GetStaticEvaluation()\n\n{\n\n return this->pieceColorToEvaluation[PieceColors::white] - this->pieceColorToEvaluation[PieceColors::black];\n\n}\n\nEvaluation::Evaluation()\n\n{\n\n // initialize piecesSquaresValue\n\n for (int i = (int)PieceName::pawn; i <= (int)PieceName::king; i++)\n\n {\n\n PieceName piece = static_cast<PieceName>(i);\n\n for (int i = (int)ESquare::A1; i <= (int)ESquare::H8; i++)\n\n {\n", "file_path": "Src/evaluation.cpp", "rank": 8, "score": 35188.30395714364 }, { "content": "\n\nconst std::map<PieceName, double> Evaluation::pieceNameToValueMap = {\n\n {PieceName::pawn, 1},\n\n {PieceName::bishop, 3},\n\n {PieceName::knight, 3},\n\n {PieceName::rook, 5},\n\n {PieceName::queen, 9},\n\n {PieceName::king, 0},\n\n};\n\nvoid Evaluation::EvaluateMaterial(\n\n EvaluationVector &evaluationVector, PieceName pieceName, PieceColors pieceColor) const\n\n{\n\n evaluationVector.IncrementEvaluation(pieceColor, Evaluation::pieceNameToValueMap.at(pieceName));\n\n}\n\nvoid Evaluation::EvaluateKnight(\n\n const Board &board, EvaluationVector &evaluationVector, PieceColors pieceColor, int fileNum, int rankNum) const\n\n{\n\n ESquare eSquare = ChessLib::ToESquare(fileNum, rankNum);\n\n double squareValue = this->piecesSquaresValue.at(PieceName::knight).at(eSquare);\n\n evaluationVector.IncrementEvaluation(pieceColor, squareValue);\n", "file_path": "Src/evaluation.cpp", "rank": 9, "score": 35182.44453137197 }, { "content": "}\n\ndouble Evaluation::EvaluateGameResult(const Board &board, GameResult gameResult) const\n\n{\n\n if (gameResult == GameResult::whiteWins)\n\n return std::numeric_limits<double>::infinity();\n\n else if (gameResult == GameResult::blackWins)\n\n return -std::numeric_limits<double>::infinity();\n\n else\n\n return 0.0;\n\n}\n\ndouble Evaluation::Evaluate(const Board &board) const\n\n{\n\n EvaluationVector evalVector = EvaluationVector();\n\n // check for possible checkmates\n\n GameResult gameResult = Analyzer::GetGameResult(board, board.GetCurrentTurn());\n\n if (gameResult != GameResult::ongoing)\n\n return EvaluateGameResult(board, gameResult);\n\n for (int rankItr = 1; rankItr <= 8; rankItr++)\n\n {\n\n for (int fileItr = 1; fileItr <= 8; fileItr++)\n", "file_path": "Src/evaluation.cpp", "rank": 10, "score": 35180.97334367318 }, { "content": " ESquare eSquare = static_cast<ESquare>(i);\n\n this->piecesSquaresValue[piece][eSquare] = 0;\n\n }\n\n }\n\n}\n\nvoid Evaluation::SetPieceSquareValue(PieceName pieceName, std::string squareStr, double value)\n\n{\n\n ESquare eSquare = ChessLib::ToESquare(squareStr);\n\n this->piecesSquaresValue[pieceName][eSquare] = value;\n\n}\n\nvoid Evaluation::InitializeKnightPeriphery0(double value)\n\n{\n\n for (int i = 0; i < 7; i++)\n\n {\n\n // a1 to h1\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(i)] = value;\n\n // a8 to h8\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(56 + i)] = value;\n\n // a1 to a8\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(i * 8)] = value;\n", "file_path": "Src/evaluation.cpp", "rank": 11, "score": 35180.828714580464 }, { "content": " // h1 to h8\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>((i * 8) + 7)] = value;\n\n }\n\n}\n\nvoid Evaluation::InitializeKnightPeriphery1(double value)\n\n{\n\n for (int i = 0; i < 6; i++)\n\n {\n\n // b2 to g2\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(9 + i)] = value;\n\n // b7 to g7\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(49 + i)] = value;\n\n // b2 to b7\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(i * 8 + 9)] = value;\n\n // g2 to g7\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(i * 8 + 14)] = value;\n\n }\n\n}\n\nvoid Evaluation::InitializeKnightPeriphery2(double value)\n\n{\n", "file_path": "Src/evaluation.cpp", "rank": 12, "score": 35180.307432105605 }, { "content": " for (int i = 0; i < 4; i++)\n\n {\n\n // c3 to f3\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(18 + i)] = value;\n\n // c6 to f6\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(42 + i)] = value;\n\n // c3 to c6\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(i * 8 + 18)] = value;\n\n // f3 to f6\n\n this->piecesSquaresValue[PieceName::knight][static_cast<ESquare>(i * 8 + 21)] = value;\n\n }\n\n}\n\nvoid Evaluation::InitializeKnightPeriphery3(double value)\n\n{\n\n // center\n\n this->piecesSquaresValue[PieceName::knight][ESquare::E4] = value;\n\n this->piecesSquaresValue[PieceName::knight][ESquare::D4] = value;\n\n this->piecesSquaresValue[PieceName::knight][ESquare::E5] = value;\n\n this->piecesSquaresValue[PieceName::knight][ESquare::D5] = value;\n\n}\n", "file_path": "Src/evaluation.cpp", "rank": 13, "score": 35175.53066179367 }, { "content": " {\n\n if (!board.IsSquareEmpty(fileItr, rankItr))\n\n {\n\n\n\n PieceName pieceName = board.GetPieceNameEnum(fileItr, rankItr);\n\n PieceColors pieceColor = board.GetPieceColor(fileItr, rankItr);\n\n EvaluateMaterial(evalVector, pieceName, pieceColor);\n\n switch (pieceName)\n\n {\n\n case PieceName::pawn:\n\n {\n\n }\n\n case PieceName::knight:\n\n {\n\n EvaluateKnight(board, evalVector, pieceColor, fileItr, rankItr);\n\n }\n\n case PieceName::bishop:\n\n {\n\n }\n\n case PieceName::rook:\n", "file_path": "Src/evaluation.cpp", "rank": 14, "score": 35175.14966701028 }, { "content": " {\n\n }\n\n case PieceName::queen:\n\n {\n\n }\n\n case PieceName::king:\n\n {\n\n }\n\n }\n\n }\n\n }\n\n }\n\n return evalVector.GetStaticEvaluation();\n\n}\n", "file_path": "Src/evaluation.cpp", "rank": 15, "score": 35170.49555904735 }, { "content": "#pragma once\n\n#include <vector>\n\n#include <string>\n", "file_path": "Src/stringHelper.h", "rank": 16, "score": 35167.888737307585 }, { "content": " if (sideToMoveColor == \"b\")\n\n this->currentTurn = PieceColors::black;\n\n else if (sideToMoveColor == \"w\")\n\n this->currentTurn = PieceColors::white;\n\n else\n\n throw std::invalid_argument(\"Invalid fen when trying to load a board from fen\");\n\n}\n\nstd::string Board::ExportFen()\n\n{\n\n std::string fen = \"\";\n\n std::string fenPos = \"\";\n\n for (int i = 0; i++; i < 8)\n\n {\n\n fenPos += std::string(this->board[i]);\n\n if (i < 7)\n\n fenPos += \"/\";\n\n }\n\n return \"\";\n\n}\n\nvoid Board::DisplayBoard(char orientation)\n", "file_path": "Src/board.cpp", "rank": 17, "score": 35139.616365819544 }, { "content": "#include \"board.h\"\n\n#include <string>\n\n#include <iostream>\n\n#include <ctype.h>\n\n#include <stdexcept>\n\n#include \"CharHelper.h\"\n\n#include \"math.h\"\n\n#include <cmath>\n\n#include <map>\n\n#include <string.h>\n\n#include \"analyzer.h\"\n\n#include \"stringHelper.h\"\n\n#include \"chessLib.h\"\n\n#include <algorithm>\n\nvoid Board::ClearBoard()\n\n{\n\n for (int rankItr = 1; rankItr <= 8; rankItr++)\n\n {\n\n for (int fileItr = 1; fileItr <= 8; fileItr++)\n\n {\n", "file_path": "Src/board.cpp", "rank": 18, "score": 35139.29295417531 }, { "content": " {\n\n printf(\"%d \", i + 1);\n\n for (int j = 0; j < 8; j++)\n\n {\n\n printf(\" %c \", board[7 - i][j]);\n\n }\n\n\n\n printf(\"\\n\");\n\n }\n\n }\n\n printf(\"===========================\");\n\n printf(\"\\n A B C D E F G H\\n\");\n\n printf(\"===========================\\n\");\n\n}\n\n\n\nvoid Board::Move(std::string moveNotation, bool psuedoLegalMove)\n\n{\n\n if (moveNotation.size() < 4)\n\n {\n\n throw std::invalid_argument(\"move size must be at least 4\");\n", "file_path": "Src/board.cpp", "rank": 19, "score": 35137.15439625173 }, { "content": " std::vector<std::string> fenSplitted = StringHelper::SplitString(fen, \" \");\n\n\n\n std::string fenPos = ChessLib::ExpandFenPosition(fenSplitted[0], EMPTYSQUARE);\n\n std::vector<std::string> fenPositions = StringHelper::SplitString(fenPos, \"/\");\n\n std::string sideToMoveColor = fenSplitted[1];\n\n std::string castlingRightsStrings = fenSplitted[2];\n\n\n\n //load board\n\n this->ClearBoard();\n\n for (int rankItr = 1; rankItr <= 8; rankItr++)\n\n {\n\n for (int fileItr = 1; fileItr <= 8; fileItr++)\n\n {\n\n //need to inverse because the fen pos will start with the black pieces\n\n //and the black pieces start on the 8th rank\n\n char piece = fenPositions[rankItr - 1][fileItr - 1];\n\n this->PlacePiece(piece, fileItr, 8 - rankItr + 1);\n\n }\n\n }\n\n //load side to move\n", "file_path": "Src/board.cpp", "rank": 20, "score": 35134.149246195615 }, { "content": "PieceColors Board::GetPieceColor(Square square) const\n\n{\n\n return this->GetPieceColor(square.fileNum, square.rankNum);\n\n}\n\n\n\nPieceName Board::GetPieceNameEnum(int fileNum, int rankNum) const\n\n{\n\n return ChessLib::ToPieceNameEnum(this->GetPieceName(fileNum, rankNum));\n\n}\n\nPieceName Board::GetPieceNameEnum(Square square) const\n\n{\n\n return ChessLib::ToPieceNameEnum(this->GetPieceName(square));\n\n}\n\nvoid Board::LoadPseudoBoard(const Board &board)\n\n{\n\n memcpy(this->board, board.board, sizeof(char) * 8 * 8);\n\n}\n\nvoid Board::LoadFromFen(std::string fen)\n\n{\n\n //example of a fen : \"r1bqkbnr/pp2ppp1/2np3p/2p5/2B1P3/3PBN2/PPP2PPP/RN1QK2R b KQkq - 1 5\"\n", "file_path": "Src/board.cpp", "rank": 21, "score": 35131.879808241676 }, { "content": " return this->GetPieceName(square) == EMPTYSQUARE;\n\n}\n\n\n\nvoid Board::PlacePiece(char piece, int fileNum, int rankNum)\n\n{\n\n board[8 - rankNum][fileNum - 1] = piece;\n\n}\n\nvoid Board::PlacePiece(char piece, Square square)\n\n{\n\n this->PlacePiece(piece, square.fileNum, square.rankNum);\n\n}\n\nvoid Board::PlacePiece(PieceName pieceName, PieceColors pieceColor, int fileNum, int rankNum)\n\n{\n\n this->PlacePiece(\n\n ChessLib::ToPieceNameChar(pieceName, pieceColor),\n\n fileNum,\n\n rankNum);\n\n}\n\nvoid Board::PlacePiece(PieceName pieceName, PieceColors pieceColor, Square square)\n\n{\n", "file_path": "Src/board.cpp", "rank": 22, "score": 35126.645523816514 }, { "content": "{\n\n printf(\"===========================\\n\");\n\n printf(\" A B C D E F G H\\n\");\n\n printf(\"===========================\\n\");\n\n if (orientation == 'w')\n\n {\n\n for (int i = 0; i < 8; i++)\n\n {\n\n printf(\"%d \", 8 - i);\n\n for (int j = 0; j < 8; j++)\n\n {\n\n printf(\" %c \", board[i][j]);\n\n }\n\n\n\n printf(\"\\n\");\n\n }\n\n }\n\n else if (orientation == 'b')\n\n {\n\n for (int i = 0; i < 8; i++)\n", "file_path": "Src/board.cpp", "rank": 23, "score": 35126.26003262169 }, { "content": " std::string errorMsg = std::string(\"invalid color : \") + ChessLib::GetPieceColorStr(color);\n\n throw std::invalid_argument(errorMsg);\n\n }\n\n}\n\n\n\nbool Board::IsSquareEmpty(int fileNum, int rankNum) const\n\n{\n\n if (fileNum > 8 || fileNum < 1 || rankNum > 8 || rankNum < 1)\n\n {\n\n std::string errorMsg = std::string(\"invalid Square position\\n\") +\n\n \"fileNum:\" + std::to_string(fileNum) + \"\\n\" +\n\n \"rankNum:\" + std::to_string(rankNum) + \"\\n\";\n\n throw std::invalid_argument(errorMsg);\n\n }\n\n\n\n return this->GetPieceName(fileNum, rankNum) == EMPTYSQUARE;\n\n}\n\n\n\nbool Board::IsSquareEmpty(Square square) const\n\n{\n", "file_path": "Src/board.cpp", "rank": 24, "score": 35124.871517422565 }, { "content": " this->PlacePiece(EMPTYSQUARE, fileItr, rankItr);\n\n }\n\n }\n\n}\n\nPieceColors Board::GetCurrentTurn() const\n\n{\n\n return this->currentTurn;\n\n}\n\nstd::string Board::GetCurrentTurnStr() const\n\n{\n\n return ChessLib::GetPieceColorStr(this->GetCurrentTurn());\n\n}\n\nstd::vector<MoveFlag> Board::GetCastlingRights(PieceColors color) const\n\n{\n\n if (color == PieceColors::white)\n\n return this->whiteCastlingRights;\n\n else if (color == PieceColors::black)\n\n return this->blackCastlingRights;\n\n else\n\n {\n", "file_path": "Src/board.cpp", "rank": 25, "score": 35122.99335140059 }, { "content": " }\n\n if (isdigit(moveNotation[0]) || !isdigit(moveNotation[1]) ||\n\n isdigit(moveNotation[2]) || !isdigit(moveNotation[3]))\n\n {\n\n throw std::invalid_argument(\"invalid move notation \" + moveNotation);\n\n }\n\n Square from = Square(moveNotation[0], moveNotation[1]);\n\n Square to = Square(moveNotation[2], moveNotation[3]);\n\n\n\n PieceName newPromotedPiece = PieceName::null;\n\n //last char of a long algebraic notation is the piece to promote to\n\n if (moveNotation.size() == 5)\n\n newPromotedPiece = ChessLib::ToPieceNameEnum(moveNotation[4]);\n\n\n\n this->Move(from, to, psuedoLegalMove, newPromotedPiece);\n\n}\n\n//todo : Fix bug where pawn is not promoting to queen if pawn is capturing\n\nvoid Board::Move(Square from, Square to, bool psuedoLegalMove, PieceName newPromotedPiece)\n\n{\n\n PieceName pieceName = this->GetPieceNameEnum(from);\n", "file_path": "Src/board.cpp", "rank": 26, "score": 35122.88140485423 }, { "content": " PieceColors sideToMove = this->GetPieceColor(from);\n\n\n\n bool isMoveLegal = false;\n\n if (!psuedoLegalMove)\n\n isMoveLegal = Analyzer::IsMoveLegal(*this, from, to, true, newPromotedPiece);\n\n else\n\n isMoveLegal = true;\n\n if (isMoveLegal)\n\n {\n\n MoveFlag moveFlag = Analyzer::GetMoveFlag(*this, from, to);\n\n switch (moveFlag)\n\n {\n\n case MoveFlag::normal:\n\n {\n\n this->PlacePiece(EMPTYSQUARE, from);\n\n if (newPromotedPiece == PieceName::null)\n\n this->PlacePiece(pieceName, sideToMove, to);\n\n else\n\n this->PlacePiece(newPromotedPiece, sideToMove, to);\n\n //remove castling right\n", "file_path": "Src/board.cpp", "rank": 27, "score": 35122.20056880195 }, { "content": " this->PlacePiece(\n\n ChessLib::ToPieceNameChar(pieceName, pieceColor),\n\n square);\n\n}\n\nchar Board::GetPieceName(int fileNum, int rankNum) const\n\n{\n\n return board[8 - rankNum][fileNum - 1];\n\n}\n\n\n\nchar Board::GetPieceName(Square square) const\n\n{\n\n return this->GetPieceName(square.fileNum, square.rankNum);\n\n}\n\n\n\nPieceColors Board::GetPieceColor(int fileNum, int rankNum) const\n\n{\n\n char piece = this->GetPieceName(fileNum, rankNum);\n\n\n\n return ChessLib::ToPieceColorEnum(piece);\n\n}\n", "file_path": "Src/board.cpp", "rank": 28, "score": 35122.01402981412 }, { "content": "\n\n if (from.file == 'a' && from.rank == '8')\n\n {\n\n std::vector<MoveFlag>::iterator pos = std::find(this->blackCastlingRights.begin(), this->blackCastlingRights.end(), MoveFlag::longCastle);\n\n if (pos != this->blackCastlingRights.end())\n\n this->blackCastlingRights.erase(pos);\n\n }\n\n }\n\n }\n\n break;\n\n }\n\n case MoveFlag::pawnDiagonalMove:\n\n {\n\n this->PlacePiece(EMPTYSQUARE, from);\n\n if (newPromotedPiece == PieceName::null)\n\n this->PlacePiece(pieceName, sideToMove, to);\n\n else\n\n this->PlacePiece(newPromotedPiece, sideToMove, to);\n\n break;\n\n }\n", "file_path": "Src/board.cpp", "rank": 29, "score": 35117.49879806012 }, { "content": " std::vector<MoveFlag>::iterator pos = std::find(this->whiteCastlingRights.begin(), this->whiteCastlingRights.end(), MoveFlag::shortCastle);\n\n if (pos != this->whiteCastlingRights.end())\n\n this->whiteCastlingRights.erase(pos);\n\n }\n\n\n\n if (from.file == 'a' && from.rank == '1')\n\n {\n\n std::vector<MoveFlag>::iterator pos = std::find(this->whiteCastlingRights.begin(), this->whiteCastlingRights.end(), MoveFlag::longCastle);\n\n if (pos != this->whiteCastlingRights.end())\n\n this->whiteCastlingRights.erase(pos);\n\n }\n\n }\n\n else if (sideToMove == PieceColors::black)\n\n {\n\n if (from.file == 'h' && from.rank == '8')\n\n {\n\n std::vector<MoveFlag>::iterator pos = std::find(this->blackCastlingRights.begin(), this->blackCastlingRights.end(), MoveFlag::shortCastle);\n\n if (pos != this->blackCastlingRights.end())\n\n this->blackCastlingRights.erase(pos);\n\n }\n", "file_path": "Src/board.cpp", "rank": 30, "score": 35117.30183368699 }, { "content": " if (pieceName == PieceName::king)\n\n {\n\n if (sideToMove == PieceColors::white)\n\n {\n\n if (this->whiteCastlingRights.size() > 0)\n\n this->whiteCastlingRights.clear();\n\n }\n\n else if (sideToMove == PieceColors::black)\n\n {\n\n if (this->blackCastlingRights.size() > 0)\n\n this->blackCastlingRights.clear();\n\n }\n\n }\n\n else if (pieceName == PieceName::rook)\n\n {\n\n //a rook or king move will remove the castling rights\n\n if (sideToMove == PieceColors::white)\n\n {\n\n if (from.file == 'h' && from.rank == '1')\n\n {\n", "file_path": "Src/board.cpp", "rank": 31, "score": 35117.21372207165 }, { "content": " case MoveFlag::longCastle:\n\n {\n\n if (sideToMove == PieceColors::white)\n\n {\n\n this->PlacePiece(EMPTYSQUARE, from);\n\n this->PlacePiece('K', to);\n\n this->PlacePiece(EMPTYSQUARE, Square('a', '1'));\n\n this->PlacePiece('R', Square('d', '1'));\n\n this->whiteCastlingRights.clear();\n\n }\n\n else if (sideToMove == PieceColors::black)\n\n {\n\n this->PlacePiece(EMPTYSQUARE, from);\n\n this->PlacePiece('k', to);\n\n this->PlacePiece(EMPTYSQUARE, Square('a', '8'));\n\n this->PlacePiece('r', Square('d', '8'));\n\n this->blackCastlingRights.clear();\n\n }\n\n break;\n\n }\n", "file_path": "Src/board.cpp", "rank": 32, "score": 35116.85868279177 }, { "content": " case MoveFlag::shortCastle:\n\n {\n\n if (sideToMove == PieceColors::white)\n\n {\n\n this->PlacePiece(EMPTYSQUARE, from);\n\n this->PlacePiece('K', to);\n\n this->PlacePiece(EMPTYSQUARE, Square('h', '1'));\n\n this->PlacePiece('R', Square('f', '1'));\n\n this->whiteCastlingRights.clear();\n\n }\n\n else if (sideToMove == PieceColors::black)\n\n {\n\n this->PlacePiece(EMPTYSQUARE, from);\n\n this->PlacePiece('k', to);\n\n this->PlacePiece(EMPTYSQUARE, Square('h', '8'));\n\n this->PlacePiece('r', Square('f', '8'));\n\n this->blackCastlingRights.clear();\n\n }\n\n break;\n\n }\n", "file_path": "Src/board.cpp", "rank": 33, "score": 35116.85868279177 }, { "content": "\n\n default:\n\n {\n\n throw std::invalid_argument(\"Invalid Moveflags\");\n\n }\n\n }\n\n\n\n if (currentTurn == PieceColors::white)\n\n {\n\n this->currentTurn = PieceColors::black;\n\n }\n\n else\n\n {\n\n this->currentTurn = PieceColors::white;\n\n }\n\n }\n\n else\n\n {\n\n throw std::invalid_argument(\"move is not legal,try again\\n\");\n\n }\n\n}\n", "file_path": "Src/board.cpp", "rank": 34, "score": 35115.8338671916 }, { "content": "#include \"stringHelper.h\"\n\n#include <iostream>\n\nstd::vector<std::string> StringHelper::SplitString(\n\n std::string str,\n\n std::string delimeter)\n\n{\n\n std::vector<std::string> splittedStrings = {};\n\n size_t pos = 0;\n\n\n\n while ((pos = str.find(delimeter)) != std::string::npos)\n\n {\n\n std::string token = str.substr(0, pos);\n\n if (token.length() > 0)\n\n splittedStrings.push_back(token);\n\n str.erase(0, pos + delimeter.length());\n\n }\n\n\n\n if (str.length() > 0)\n\n splittedStrings.push_back(str);\n\n return splittedStrings;\n\n}", "file_path": "Src/stringHelper.cpp", "rank": 35, "score": 32345.603353605897 }, { "content": "#include \"catch.hpp\"\n\n#include \"../Src/board.h\"\n\nTEST_CASE(\"Test Load fen to board\", \"[LoadFen]\")\n\n{\n\n Board board = Board();\n\n\n\n SECTION(\"TestLoad1\")\n\n {\n\n board.LoadFromFen(\"B4r1k/p1p1Nppp/1p1q2b1/8/3P2P1/PQP3nP/5P2/3RR1K1 b - - 0 26\");\n\n //board.DisplayBoard();\n\n }\n\n}\n", "file_path": "tests/TestBoard.cpp", "rank": 36, "score": 32311.5263414185 }, { "content": " /// A non-owning string class (similar to the forthcoming std::string_view)\n\n /// Note that, because a StringRef may be a substring of another string,\n\n /// it may not be null terminated.\n\n class StringRef {\n\n public:\n\n using size_type = std::size_t;\n\n using const_iterator = const char*;\n\n\n\n private:\n\n static constexpr char const* const s_empty = \"\";\n\n\n\n char const* m_start = s_empty;\n\n size_type m_size = 0;\n\n\n\n public: // construction\n\n constexpr StringRef() noexcept = default;\n\n\n\n StringRef( char const* rawChars ) noexcept;\n\n\n\n constexpr StringRef( char const* rawChars, size_type size ) noexcept\n\n : m_start( rawChars ),\n\n m_size( size )\n\n {}\n", "file_path": "tests/catch.hpp", "rank": 37, "score": 29936.75095053789 }, { "content": "struct ratio_string {\n\n static std::string symbol();\n\n};\n\n\n\ntemplate <class Ratio>\n\nstd::string ratio_string<Ratio>::symbol() {\n\n Catch::ReusableStringStream rss;\n\n rss << '[' << Ratio::num << '/'\n\n << Ratio::den << ']';\n\n return rss.str();\n\n}\n\ntemplate <>\n", "file_path": "tests/catch.hpp", "rank": 38, "score": 29931.098867858644 }, { "content": " class StringRef;\n\n\n\n struct IStream {\n\n virtual ~IStream();\n\n virtual std::ostream& stream() const = 0;\n\n };\n\n\n\n auto makeStream( StringRef const &filename ) -> IStream const*;\n\n\n", "file_path": "tests/catch.hpp", "rank": 39, "score": 29931.098867858644 }, { "content": " class ResultValueBase<void> : public ResultBase {\n\n protected:\n\n using ResultBase::ResultBase;\n\n };\n\n\n\n template<typename T = void>\n", "file_path": "tests/catch.hpp", "rank": 40, "score": 28979.058303114558 }, { "content": "enum class MoveFlag\n\n{\n\n normal,\n\n pawnDiagonalMove,\n\n shortCastle,\n\n longCastle,\n\n null,\n\n};\n", "file_path": "Src/chessLib.h", "rank": 41, "score": 27908.887406832964 }, { "content": "struct ratio_string<std::micro> {\n\n static std::string symbol();\n\n};\n\ntemplate <>\n", "file_path": "tests/catch.hpp", "rank": 42, "score": 26060.304418645483 }, { "content": "struct ratio_string<std::milli> {\n\n static std::string symbol();\n\n};\n\n\n\n ////////////\n\n // std::chrono::duration specializations\n\n template<typename Value, typename Ratio>\n\n struct StringMaker<std::chrono::duration<Value, Ratio>> {\n\n static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {\n\n ReusableStringStream rss;\n\n rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';\n\n return rss.str();\n\n }\n\n };\n\n template<typename Value>\n\n struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {\n\n static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {\n\n ReusableStringStream rss;\n\n rss << duration.count() << \" s\";\n\n return rss.str();\n", "file_path": "tests/catch.hpp", "rank": 43, "score": 26060.304418645483 }, { "content": "struct ratio_string<std::femto> {\n\n static std::string symbol();\n\n};\n\ntemplate <>\n", "file_path": "tests/catch.hpp", "rank": 44, "score": 26060.304418645483 }, { "content": "struct ratio_string<std::pico> {\n\n static std::string symbol();\n\n};\n\ntemplate <>\n", "file_path": "tests/catch.hpp", "rank": 45, "score": 26060.304418645483 }, { "content": "struct ratio_string<std::atto> {\n\n static std::string symbol();\n\n};\n\ntemplate <>\n", "file_path": "tests/catch.hpp", "rank": 46, "score": 26060.304418645483 }, { "content": "struct ratio_string<std::nano> {\n\n static std::string symbol();\n\n};\n\ntemplate <>\n", "file_path": "tests/catch.hpp", "rank": 47, "score": 26060.304418645483 }, { "content": " class ReusableStringStream : NonCopyable {\n\n std::size_t m_index;\n\n std::ostream* m_oss;\n\n public:\n\n ReusableStringStream();\n\n ~ReusableStringStream();\n\n\n\n auto str() const -> std::string;\n\n\n\n template<typename T>\n\n auto operator << ( T const& value ) -> ReusableStringStream& {\n\n *m_oss << value;\n\n return *this;\n\n }\n\n auto get() -> std::ostream& { return *m_oss; }\n\n };\n\n}\n\n\n\n// end catch_stream.h\n\n// start catch_interfaces_enum_values_registry.h\n", "file_path": "tests/catch.hpp", "rank": 48, "score": 24477.543618779117 }, { "content": "struct StringMaker<Catch::Detail::Approx> {\n\n static std::string convert(Catch::Detail::Approx const& value);\n\n};\n\n\n\n} // end namespace Catch\n\n\n\n// end catch_approx.h\n\n// start catch_string_manip.h\n\n\n\n#include <string>\n\n#include <iosfwd>\n\n#include <vector>\n\n\n\nnamespace Catch {\n\n\n\n bool startsWith( std::string const& s, std::string const& prefix );\n\n bool startsWith( std::string const& s, char prefix );\n\n bool endsWith( std::string const& s, std::string const& suffix );\n\n bool endsWith( std::string const& s, char suffix );\n\n bool contains( std::string const& s, std::string const& infix );\n", "file_path": "tests/catch.hpp", "rank": 49, "score": 24477.543618779117 }, { "content": " static std::pair<Square, Square> GetMoveFromStr(std::string move);\n", "file_path": "Src/square.h", "rank": 50, "score": 24465.009031173115 }, { "content": " int y;\n", "file_path": "Src/math.h", "rank": 51, "score": 24465.009031173115 }, { "content": " Vector2(int x,int y);\n", "file_path": "Src/math.h", "rank": 52, "score": 24465.009031173115 }, { "content": "from typing import List\n\nimport subprocess\n\nimport sys\n\nimport os\n\n\n\n\n\npythonVersion = sys.version_info\n\n# print(\"version of python {0}\".format(pythonVersion))\n\n\n\n\n\nif pythonVersion.major < 3 and pythonVersion.minor < 5:\n\n print(\"version is not compatable\")\n\n print(\n\n \"version of python :\"\n\n + str(pythonVersion.major)\n\n + \".\"\n\n + str(pythonVersion.minor)\n\n + \".\"\n\n + str(pythonVersion.micro)\n\n )\n\n print(\"version must at least be 3.5 or greater\")\n\n exit()\n\n\n\n\n\ndef compile_cpp_codes(\n\n source_folders: List[str],\n\n build_path: str,\n\n file_name: str,\n\n debug: bool = False,\n\n optimized: bool = False,\n\n exclude_cpp_files: List[str] = [],\n\n object_files: List[str] = [],\n\n):\n\n codesFiles = []\n\n codesFiles.extend(object_files)\n\n for folder in source_folders:\n\n for file in os.listdir(folder):\n\n if file in exclude_cpp_files:\n\n continue\n\n filePath = os.path.join(folder, file)\n\n file_extension = os.path.splitext(filePath)[1]\n\n if os.path.isfile(filePath) and file_extension == \".cpp\":\n\n codesFiles.append(filePath)\n\n\n\n commands = [\"g++\"]\n\n if debug:\n\n commands.append(\"-g\")\n\n if optimized:\n\n commands.append(\"-Ofast\")\n\n commands.extend(codesFiles)\n\n commands.extend([\"-o\", os.path.join(build_path, file_name)])\n\n print(\"Running : \" + \" \".join(commands))\n\n subprocess.run(commands)\n\n\n\n\n\nargs = sys.argv\n\ndel args[0]\n\nif len(args) == 0:\n\n compile_cpp_codes(\n\n [\"Src\"], \"build\", \"TempestPixyEngine\", debug=False, optimized=True\n\n )\n\n subprocess.run([\"./build/TempestPixyEngine\"])\n\nelse:\n\n if args[0] == \"debug\":\n\n compile_cpp_codes([\"Src\"], \"build\", \"TempestPixyEngine\", debug=True)\n\n subprocess.run([\"gdb\", \"build/TempestPixyEngine\"])\n\n\n\n elif args[0] == \"test\":\n\n if not (\"TestMain.o\" in os.listdir(\"tests\")):\n\n print(\"compiling catch2 's library\")\n\n subprocess.run(\n\n [\"g++\", \"tests/TestMain.cpp\", \"-c\", \"-o\", \"tests/TestMain.o\"]\n\n )\n\n\n\n compile_cpp_codes(\n\n [\"Src\", \"tests\"],\n\n \"build\",\n\n \"test\",\n\n debug=False,\n\n exclude_cpp_files=[\"TestMain.cpp\", \"main.cpp\"],\n\n object_files=[\"tests/TestMain.o\"],\n\n )\n\n subprocess.run([\"./build/test\"])\n\n\n\n elif args[0] == \"debugtest\":\n\n if not (\"TestMain.o\" in os.listdir(\"tests\")):\n\n print(\"compiling catch2 's library\")\n\n subprocess.run(\n\n [\"g++\", \"tests/TestMain.cpp\", \"-c\", \"-o\", \"tests/TestMain.o\"]\n\n )\n\n\n\n compile_cpp_codes(\n\n [\"Src\", \"tests\"],\n\n \"build\",\n\n \"test\",\n\n debug=True,\n\n exclude_cpp_files=[\"TestMain.cpp\", \"main.cpp\"],\n\n object_files=[\"tests/TestMain.o\"],\n\n )\n\n subprocess.run([\"gdb\", \"build/test\"])\n\n else:\n\n print(\"unknown command\")\n", "file_path": "build.py", "rank": 53, "score": 24465.009031173115 }, { "content": "struct Vector2\n\n{\n\n int x;\n\n int y;\n\n Vector2(int x,int y);\n\n\n\n static Vector2 Direction(Vector2 a,Vector2 b);\n", "file_path": "Src/math.h", "rank": 54, "score": 23064.214403051108 }, { "content": " char rank;\n", "file_path": "Src/square.h", "rank": 55, "score": 23064.214403051108 }, { "content": " static Vector2 Direction(Vector2 a,Vector2 b);\n", "file_path": "Src/math.h", "rank": 56, "score": 23064.214403051108 }, { "content": " Square(char file, char rank);\n", "file_path": "Src/square.h", "rank": 57, "score": 23064.214403051108 }, { "content": "struct Square\n\n{\n\n char file;\n\n char rank;\n\n int fileNum;\n\n int rankNum;\n\n Square(char file, char rank);\n\n Square(int fileNum, int rankNum);\n\n /// square size must be exactly 2\n\n /// for example :e2 ,h3 and ect\n\n Square(std::string square);\n\n std::string GetNotation();\n\n\n\n /// the first element of the tuple is the original square\n\n /// the second element of the tuple is the destination square\n\n static std::pair<Square, Square> GetMoveFromStr(std::string move);\n", "file_path": "Src/square.h", "rank": 58, "score": 23064.214403051108 }, { "content": " Square(int fileNum, int rankNum);\n", "file_path": "Src/square.h", "rank": 59, "score": 21815.14331045284 }, { "content": " int rankNum;\n", "file_path": "Src/square.h", "rank": 60, "score": 21815.14331045284 }, { "content": "def compile_cpp_codes(\n\n source_folders: List[str],\n\n build_path: str,\n\n file_name: str,\n\n debug: bool = False,\n\n optimized: bool = False,\n\n exclude_cpp_files: List[str] = [],\n\n object_files: List[str] = [],\n\n):\n\n codesFiles = []\n\n codesFiles.extend(object_files)\n\n for folder in source_folders:\n\n for file in os.listdir(folder):\n\n if file in exclude_cpp_files:\n\n continue\n\n filePath = os.path.join(folder, file)\n\n file_extension = os.path.splitext(filePath)[1]\n\n if os.path.isfile(filePath) and file_extension == \".cpp\":\n\n codesFiles.append(filePath)\n\n\n\n commands = [\"g++\"]\n\n if debug:\n\n commands.append(\"-g\")\n\n if optimized:\n\n commands.append(\"-Ofast\")\n\n commands.extend(codesFiles)\n\n commands.extend([\"-o\", os.path.join(build_path, file_name)])\n\n print(\"Running : \" + \" \".join(commands))\n", "file_path": "build.py", "rank": 61, "score": 20694.411811830367 }, { "content": "\n\n# TempestPixyEngine\n\n- A simple chess engine (under 3000 lines ) written in c++ which is easy and simple to read / understand\n\n- Uses Minimax and alphabeta pruning to search and evaluate the current position\n\n\n\n# Playing with TempestPixyEngine\n\n this engine can be played [here](https://lichess.org/@/TempestPixyEngine) (Make sure that you are signed in)\n\n\n\n# Compiling\n\nBuild the project using python (at least version 3.0)\n\n```sh\n\n python3 build.py\n\n```\n\nRun unit tests with\n\n```sh\n\npython3 build.py test\n\n```\n\n# TODO:\n\n- use cmake to build the project\n\n- use google benchmark to test performance\n\n- Improve performance\n\n- planning to make this into a simple machine learning framework for board and zero sum games \n\n\n\n# Deploying Engine to lichess.org\n\n- https://lichess.org/forum/general-chess-discussion/how-to-create-a-httpslichessorg-bot\n\n- https://github.com/ShailChoksi/lichess-bot\n\n- https://github.com/ShailChoksi/lichess-bot/issues/312 (some issues)\n\n\n\n# Credits\n\n- https://www.chessprogramming.org/Main_Page\n\n- https://www.youtube.com/watch?v=STjW3eH0Cik&t=1735s&ab_channel=MITOpenCourseWare (For understanding about minimax and alphabeta pruning algorithm)\n", "file_path": "README.md", "rank": 62, "score": 16474.216365200868 }, { "content": "#include \"catch.hpp\"\n\n#include \"../Src/board.h\"\n\n#include \"../Src/stringHelper.h\"\n\n#include \"../Src/analyzer.h\"\n\n#include \"../Src/chessLib.h\"\n\n#include \"../Src/search.h\"\n\n#include <vector>\n\n#include <string>\n\n#include <algorithm>\n\n#include <exception>\n\n// reference : https://github.com/catchorg/Catch2/issues/850\n\n// https://stackoverflow.com/questions/43762651/how-does-stdtie-work\n\n// https://stackoverflow.com/questions/20705702/stl-pair-like-triplet-class-do-i-roll-my-own\n\n\n\nvoid TestGeneratePieceLegalMoves(std::string fenPosition, int fileNum, int rankNum, int expect)\n\n{\n\n\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n std::vector<std::string> generatedPieceMoves = Search::GeneratePieceLegalMoves(board, fileNum, rankNum);\n", "file_path": "tests/TestSearch.cpp", "rank": 67, "score": 31.394974375365052 }, { "content": " for (int i = 0; i < generatedPieceMoves.size(); i++)\n\n {\n\n printf(\"move : %s\\n\", generatedPieceMoves.at(i).c_str());\n\n }\n\n }\n\n\n\n REQUIRE(generatedPieceMoves.size() == expect);\n\n}\n\n\n\nvoid TestGenerateMoves(std::string fenPosition, PieceColors sideToMove, int expect)\n\n{\n\n\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n std::vector<std::string> generatedMoves = Search::GenerateMoves(board, sideToMove);\n\n std::vector<std::string> generatedMovesNoDuplicate = {};\n\n for (int i = 0; i < generatedMoves.size(); i++)\n\n {\n\n if (std::find(generatedMovesNoDuplicate.begin(), generatedMovesNoDuplicate.end(), generatedMoves.at(i)) == generatedMovesNoDuplicate.end())\n\n {\n", "file_path": "tests/TestSearch.cpp", "rank": 68, "score": 28.016835583472826 }, { "content": " */\n\n printf(\"move : %s\\n\", generatedMoves.at(i).c_str());\n\n // movedBoard.DisplayBoard();\n\n }\n\n }\n\n\n\n REQUIRE(generatedMoves.size() == expect);\n\n}\n\n\n\nvoid TestGenerateMoves(std::string fenPosition, PieceColors sideToMove, std::vector<std::string> expectedMoves)\n\n{\n\n\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n std::vector<std::string> generatedMoves = Search::GenerateMoves(board, sideToMove);\n\n std::vector<std::string> generatedMovesNoDuplicate = {};\n\n for (int i = 0; i < generatedMoves.size(); i++)\n\n {\n\n if (std::find(generatedMovesNoDuplicate.begin(), generatedMovesNoDuplicate.end(), generatedMoves.at(i)) == generatedMovesNoDuplicate.end())\n\n {\n", "file_path": "tests/TestSearch.cpp", "rank": 69, "score": 26.9113750514085 }, { "content": " printf(\"fenPosition : %s \\n side : %s\\n actual:%d \\n expect:%d\",\n\n fenPosition.c_str(),\n\n ChessLib::GetPieceColorStr(side).c_str(),\n\n actual,\n\n expect);\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\n\n\nvoid TestGetPieceCountAfterPromotion(std::string fenPosition, std::string move, PieceName pieceName, PieceColors side, int expect)\n\n{\n\n\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n board.Move(move);\n\n int actual = Analyzer::GetPieceCount(board, pieceName, side);\n\n if (actual != expect)\n\n {\n\n printf(\"TestGetPieceCountAfterPromotion test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n side : %s\\n Move : %s\\n actual:%d \\n expect:%d\",\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 70, "score": 26.056218329020997 }, { "content": "void TestGetGameResult(std::string fenPosition, PieceColors sideToMove, GameResult expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n GameResult actual = Analyzer::GetGameResult(board, sideToMove);\n\n if (actual != expect)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n sideToMove: %s\\n actual:%s \\n expect:%s\",\n\n fenPosition.c_str(),\n\n ChessLib::GetPieceColorStr(sideToMove).c_str(),\n\n ChessLib::GetGameResultStr(actual).c_str(),\n\n ChessLib::GetGameResultStr(expect).c_str());\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\nvoid TestGetDefendedPiecesCount(std::string fenPosition, PieceColors side, int expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 71, "score": 25.41204464931859 }, { "content": "TEST_CASE(\"Test Promotion\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::string move;\n\n bool isMoveLegal;\n\n\n\n std::tie(fenPosition, move, isMoveLegal) = GENERATE(\n\n table<std::string, std::string, bool>({\n\n //normal promotion\n\n {\"8/5P2/1k6/8/8/2K5/8/8 w - - 0 1\", \"f7f8q\", true},\n\n {\"8/5P2/1k6/8/8/2K5/8/8 w - - 0 1\", \"f7f8N\", true},\n\n {\"8/5P2/1k6/8/8/2K5/8/8 w - - 0 1\", \"f7f8B\", true},\n\n {\"8/5P2/1k6/8/8/2K5/8/8 w - - 0 1\", \"f7f8R\", true},\n\n {\"8/1P6/8/3K4/8/8/8/3k4 w - - 43 23\", \"b7b8q\", true},\n\n\n\n {\"8/8/1k3P2/8/8/2K5/6p1/8 b - - 0 1\", \"g2g1q\", true},\n\n {\"8/8/1k3P2/8/8/2K5/6p1/8 b - - 0 1\", \"g2g1r\", true},\n\n {\"8/8/1k3P2/8/8/2K5/6p1/8 b - - 0 1\", \"g2g1b\", true},\n\n {\"8/8/1k3P2/8/8/2K5/6p1/8 b - - 0 1\", \"g2g1n\", true},\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 72, "score": 24.963940733550665 }, { "content": "std::vector<std::string> Search::GenerateMoves(const Board &board, PieceColors sideToMove)\n\n{\n\n std::vector<std::string> moves = {};\n\n for (int rankItr = 1; rankItr <= 8; rankItr++)\n\n {\n\n for (int fileItr = 1; fileItr <= 8; fileItr++)\n\n {\n\n if (board.GetPieceColor(fileItr, rankItr) == sideToMove &&\n\n !board.IsSquareEmpty(fileItr, rankItr))\n\n {\n\n std::vector<std::string> pieceLegalMoves = Search::GeneratePieceLegalMoves(board, fileItr, rankItr);\n\n moves.insert(moves.end(), pieceLegalMoves.begin(), pieceLegalMoves.end());\n\n }\n\n }\n\n }\n\n return moves;\n\n}\n\ndouble Search::SearchPosition(const Board &board, const Evaluation &evaluation, int currentDepth, int maxDepth, double alpha, double beta, std::string *bestMove)\n\n{\n\n std::string currentBestMove = \"\";\n", "file_path": "Src/search.cpp", "rank": 73, "score": 24.42877425167155 }, { "content": "#pragma once\n\n#include \"board.h\"\n\n#include \"math.h\"\n\n#include \"chessLib.h\"\n\n#include \"evaluation.h\"\n\n#include <vector>\n\n#include <map>\n\n#include <string>\n\n#include <limits>\n\nclass Search\n\n{\n\npublic:\n\n /// Get the number of legal moves that a piece standing on the specified squares\n\n /// returns 0 if empty square\n\n static std::vector<std::string> GeneratePieceLegalMoves(const Board &board, int fileNum, int rankNum);\n\n /// search for all possible moves on a given position for a certain side\n\n static std::vector<std::string> GenerateMoves(const Board &board, PieceColors sideToMove);\n\n\n\n static const std::map<PieceName, std::vector<Vector2>> pieceToMoveVectorMap;\n\n static double SearchPosition(const Board &board,\n\n const Evaluation &evaluation,\n\n int currentDepth,\n\n int maxDepth,\n\n double alpha = -std::numeric_limits<double>::infinity(),\n\n double beta = std::numeric_limits<double>::infinity(),\n\n std::string *bestMove = nullptr);\n\n};", "file_path": "Src/search.h", "rank": 74, "score": 23.774125135756755 }, { "content": "#pragma once\n\n#include \"board.h\"\n\n#include \"math.h\"\n\n#include \"chessLib.h\"\n\n#include \"evaluation.h\"\n\n#include <vector>\n\n#include <map>\n\n#include <string>\n\n#include <limits>\n", "file_path": "Src/search.h", "rank": 75, "score": 23.774125135756755 }, { "content": " {\n\n actual = Analyzer::IsMoveLegal(board, move);\n\n }\n\n //ref: https://stackoverflow.com/questions/6755991/catching-stdexception-by-reference/6756040#6756040\n\n catch (const std::exception &e)\n\n {\n\n printf(\"%s \\n\", e.what());\n\n }\n\n if (actual != expect)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n move: %s\\n\", fenPosition.c_str(), move.c_str());\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\n///Testing a sequence of move and test whether the last move is legal or not\n\nvoid TestIsLastMoveLegal(std::string fenPosition, std::vector<std::string> moves, bool expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 76, "score": 23.688855784281664 }, { "content": " generatedMovesNoDuplicate.push_back(generatedMoves.at(i));\n\n }\n\n else\n\n {\n\n std::string errorMsg = std::string(\"duplicate moves when testing GenerateMoves function : \") + \"\\n\" +\n\n generatedMoves.at(i);\n\n throw std::invalid_argument(errorMsg);\n\n }\n\n }\n\n if (generatedMoves.size() != expect)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n side To Move : %s\\n generated moves count: %zu \\n\", fenPosition.c_str(), ChessLib::GetPieceColorStr(sideToMove).c_str(), generatedMoves.size());\n\n printf(\"Generated moves : \\n\");\n\n for (int i = 0; i < generatedMoves.size(); i++)\n\n {\n\n /*\n\n Board movedBoard = Board();\n\n movedBoard.LoadFromFen(fenPosition);\n\n movedBoard.Move(generatedMoves.at(i));\n", "file_path": "tests/TestSearch.cpp", "rank": 77, "score": 23.07573846928001 }, { "content": " PieceColors sideToMove = board.GetCurrentTurn();\n\n // initialize the best value (will always be initialized to the worst depending on the side to move)\n\n double bestValue = (sideToMove == PieceColors::white)\n\n ? -std::numeric_limits<double>::infinity()\n\n : std::numeric_limits<double>::infinity();\n\n // if the current depth hasn't reached the maxDepth yet then continue recursively\n\n if (currentDepth < maxDepth)\n\n {\n\n std::vector<std::string> generatedMoves = Search::GenerateMoves(board, sideToMove);\n\n // In case the evaluation of all the generated Moves are the same\n\n if (generatedMoves.size() > 0)\n\n currentBestMove = generatedMoves[0];\n\n for (int i = 0; i < generatedMoves.size(); i++)\n\n {\n\n // move newBoard\n\n Board newBoard = Board(board);\n\n newBoard.Move(generatedMoves.at(i), false);\n\n double newPositionValue = SearchPosition(newBoard, evaluation, currentDepth + 1, maxDepth, alpha, beta);\n\n // choose the best value and best move according to the sideToMove\n\n if (sideToMove == PieceColors::white)\n", "file_path": "Src/search.cpp", "rank": 79, "score": 22.8124752953372 }, { "content": " {\"rnbqkbnr/1pppp2p/p4pp1/8/8/1P3N2/PBPPPPPP/RN1QKB1R w KQkq - 0 4\", \"b2f6\", true},\n\n {\"rn1qkbnr/pbpppppp/1p6/8/3PP3/8/PPP1NPPP/RNBQKB1R b KQkq - 2 3\", \"b7e4\", true},\n\n {\"rnbqk1nr/ppppppbp/6p1/8/2P1P3/1P6/P2P1PPP/RNBQKBNR b KQkq - 0 3\", \"g7a1\", true},\n\n }));\n\n\n\n SECTION(\"Test Bishops moves\")\n\n {\n\n TestIsMoveLegal(fenPosition, move, isMoveLegal);\n\n }\n\n}\n\nTEST_CASE(\"Test rook legal moves\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::string move;\n\n bool isMoveLegal;\n\n\n\n std::tie(fenPosition, move, isMoveLegal) = GENERATE(\n\n table<std::string, std::string, bool>({\n\n //test rook movements\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 80, "score": 22.428811701387417 }, { "content": " fenPosition.c_str(),\n\n ChessLib::GetPieceColorStr(side).c_str(),\n\n move.c_str(),\n\n actual,\n\n expect);\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\n\n\n//reference : https://github.com/catchorg/Catch2/issues/850\n\n//https://stackoverflow.com/questions/43762651/how-does-stdtie-work\n\n//https://stackoverflow.com/questions/20705702/stl-pair-like-triplet-class-do-i-roll-my-own\n\n\n\nvoid TestIsMoveLegal(std::string fenPosition, std::string move, bool expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n\n\n bool actual;\n\n try\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 81, "score": 22.27045436967406 }, { "content": " {\n\n printf(\"test cases failed \\n\");\n\n printf(\"pieceName:%s , pieceColor:%s , move:%s ,\",\n\n ChessLib::GetPieceNameStr(pieceName).c_str(),\n\n ChessLib::GetPieceColorStr(pieceColor).c_str(),\n\n move.c_str());\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\n\n\nvoid TestIsPieceMovementBlocked(std::string fenPosition, std::string move, bool expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n Square from = Square(1, 1);\n\n Square to = Square(1, 1);\n\n std::tie(from, to) = Square::GetMoveFromStr(move);\n\n\n\n bool actual = Analyzer::IsPieceMovementBlocked(board, from, to);\n\n if (actual != expect)\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 82, "score": 21.932584307585863 }, { "content": " PieceName::king,\n\n {\n\n Vector2(0, 1),\n\n Vector2(0, -1),\n\n Vector2(1, 0),\n\n Vector2(-1, 0),\n\n Vector2(1, 1),\n\n Vector2(1, -1),\n\n Vector2(-1, 1),\n\n Vector2(-1, -1),\n\n\n\n },\n\n },\n\n};\n\n/// This function has no PieceColors parameter because it it will know for certain what piece color at the given square\n\nstd::vector<std::string> Search::GeneratePieceLegalMoves(const Board &board, int fileNum, int rankNum)\n\n{\n\n std::vector<std::string> moves = {};\n\n if (!board.IsSquareEmpty(fileNum, rankNum))\n\n {\n", "file_path": "Src/search.cpp", "rank": 84, "score": 21.608274891174737 }, { "content": " {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n move: %s\\n\", fenPosition.c_str(), move.c_str());\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\n\n\nvoid TestIsSquareUnderAttack(std::string fenPosition, std::string square, PieceColors attackingColor, bool expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n bool actual = Analyzer::IsSquareAttacked(board, attackingColor, Square(square));\n\n if (actual != expect)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n square: %s\\n attackingColor: %s\\n\", fenPosition.c_str(), square.c_str(), ChessLib::GetPieceColorStr(attackingColor).c_str());\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\n\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 85, "score": 21.295267660577014 }, { "content": " generatedMovesNoDuplicate.push_back(generatedMoves.at(i));\n\n }\n\n else\n\n {\n\n std::string errorMsg = std::string(\"duplicate moves when testing GenerateMoves function : \") + \"\\n\" +\n\n generatedMoves.at(i);\n\n throw std::invalid_argument(errorMsg);\n\n }\n\n }\n\n /*\n\n if (generatedMoves.size() != expectedMovebres)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n side To Move : %s\\n generated moves count: %zu \\n\", fenPosition.c_str(), ChessLib::GetPieceColorStr(sideToMove).c_str(), generatedMoves.size());\n\n printf(\"Generated moves : \\n\");\n\n for (int i = 0; i < generatedMoves.size(); i++)\n\n {\n\n\n\n printf(\"move : %s\\n\", generatedMoves.at(i).c_str());\n\n // movedBoard.DisplayBoard();\n", "file_path": "tests/TestSearch.cpp", "rank": 86, "score": 20.91310444001708 }, { "content": "#include \"catch.hpp\"\n\n#include \"../Src/board.h\"\n\n#include \"../Src/stringHelper.h\"\n\n#include \"../Src/chessLib.h\"\n\n#include <vector>\n\n#include <string>\n\n\n\nvoid TestToESquare(int fileNum, int rankNum, ESquare expect)\n\n{\n\n ESquare actual = ChessLib::ToESquare(fileNum, rankNum);\n\n if (actual != expect)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fileNum : %d \\nrankNum : %d \\nactual : %d \\nexpect : %d\", fileNum, rankNum, actual, (int)expect);\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\nvoid TestToESquare(Square square, ESquare expect)\n\n{\n\n\n", "file_path": "tests/TestChessLib.cpp", "rank": 87, "score": 20.805729068400748 }, { "content": "#include \"catch.hpp\"\n\n#include \"../Src/board.h\"\n\n#include \"../Src/stringHelper.h\"\n\n#include \"../Src/analyzer.h\"\n\n#include \"../Src/chessLib.h\"\n\n#include <vector>\n\n#include <string>\n\n\n\n//reference : https://github.com/catchorg/Catch2/issues/850\n\n//https://stackoverflow.com/questions/43762651/how-does-stdtie-work\n\n//https://stackoverflow.com/questions/20705702/stl-pair-like-triplet-class-do-i-roll-my-own\n\n\n\nvoid TestDoesPieceMoveCorrectly(PieceName pieceName, PieceColors pieceColor, std::string move, bool expect)\n\n{\n\n Square from = Square(1, 1);\n\n Square to = Square(1, 1);\n\n std::tie(from, to) = Square::GetMoveFromStr(move);\n\n\n\n bool actual = Analyzer::DoesPieceMoveCorrectly(pieceName, pieceColor, from, to);\n\n if (actual != expect)\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 88, "score": 20.35396197977728 }, { "content": " int actual = Analyzer::GetDefendedPiecesCount(board, side);\n\n if (actual != expect)\n\n {\n\n printf(\"TestGetDefendedPiecesCount test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n side : %s\\n actual:%d \\n expect:%d\",\n\n fenPosition.c_str(),\n\n ChessLib::GetPieceColorStr(side).c_str(),\n\n actual,\n\n expect);\n\n }\n\n REQUIRE(actual == expect);\n\n}\n\nvoid TestGetHangingPiecesCount(std::string fenPosition, PieceColors side, int expect)\n\n{\n\n Board board = Board();\n\n board.LoadFromFen(fenPosition);\n\n int actual = Analyzer::GetHangingPiecesCount(board, side);\n\n if (actual != expect)\n\n {\n\n printf(\"TestGetHangingPiecesCount test cases failed \\n\");\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 89, "score": 20.303320248630037 }, { "content": " TestIsMoveLegal(fenPosition, move, isMoveLegal);\n\n }\n\n}\n\n\n\nTEST_CASE(\"Test bishop legal moves\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::string move;\n\n bool isMoveLegal;\n\n\n\n std::tie(fenPosition, move, isMoveLegal) = GENERATE(\n\n table<std::string, std::string, bool>({\n\n //test if bishop is blocked\n\n {\"rnbqkbnr/ppp1pppp/8/8/3pP3/3P4/PPP2PPP/RNBQKBNR w KQkq - 0 3\", \"f1c4\", false},\n\n {\"rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2\", \"f1h3\", false},\n\n {\"rnbqkbnr/ppp1pppp/8/3p4/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2\", \"f8c5\", false},\n\n {\"rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2\", \"c8e6\", false},\n\n //test capture\n\n {\"rnbqkbnr/p1p1pppp/8/1p1p4/4P3/7P/PPPP1PP1/RNBQKBNR w KQkq - 0 3\", \"f1b5\", true},\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 91, "score": 19.587559413146188 }, { "content": "\n\n for (int i = 0; i < moves.size(); i++)\n\n {\n\n bool isMoveLegal = Analyzer::IsMoveLegal(board, moves[i]);\n\n if (i < moves.size() - 1)\n\n {\n\n if (isMoveLegal)\n\n board.Move(moves[i]);\n\n else\n\n {\n\n throw std::invalid_argument(\"move is invalid\\n\");\n\n }\n\n }\n\n else if (i == moves.size() - 1)\n\n {\n\n if (isMoveLegal != expect)\n\n {\n\n printf(\"test cases failed \\n\");\n\n printf(\"fenPosition : %s \\n move: %s\\n\", fenPosition.c_str(), moves[i].c_str());\n\n }\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 92, "score": 19.472832104883512 }, { "content": " {\"rnbqkb1r/pp1p1ppp/2p4n/4p3/3PP2P/8/PPP1QPP1/RNB1KBNR w KQkq - 3 6\", \"e2e4\", false},\n\n\n\n {\"rnbqkb1r/pp1p1ppp/2p4n/4p3/3PP2P/N7/PPP1QPP1/R1B1KBNR b KQkq - 4 6\", \"d8h4\", true},\n\n {\"rnbqkb1r/1p3ppp/2pN3n/p2pp3/3PP2P/8/PPP1QPP1/R1B1KBNR b KQkq - 1 8\", \"d8d6\", true},\n\n {\"rnb1kb1r/1p3ppp/2pq3n/p2pp3/3PP2P/P7/1PP1QPP1/R1B1KBNR b KQkq - 0 9\", \"d6f8\", false},\n\n {\"rnb1kb1r/1p3ppp/2pq3n/p2pp3/3PP2P/P7/1PP1QPP1/R1B1KBNR b KQkq - 0 9\", \"d6d5\", false},\n\n }));\n\n\n\n SECTION(\"Test queen moves\")\n\n {\n\n TestIsMoveLegal(fenPosition, move, isMoveLegal);\n\n }\n\n}\n\nTEST_CASE(\"Test knight legal moves\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::string move;\n\n bool isMoveLegal;\n\n\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 93, "score": 18.9011298287089 }, { "content": "TEST_CASE(\"Test Illegal king moves by check\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::string move;\n\n bool isMoveLegal;\n\n\n\n std::tie(fenPosition, move, isMoveLegal) = GENERATE(\n\n table<std::string, std::string, bool>({\n\n\n\n {\"rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2\", \"e1e2\", true},\n\n {\"rnbqk1nr/pppp1ppp/8/2b1p3/4P3/2N5/PPPPKPPP/R1BQ1BNR w kq - 4 4\", \"e2e3\", false},\n\n {\"rnb1k1nr/pppq1ppp/3p4/4p3/1K2P3/2N5/PPPP1PPP/R1BQ1BNR w kq - 1 7\", \"b4b5\", false},\n\n {\"rnb1k1nr/pppq1ppp/3p4/4p3/1K2P3/2N5/PPPP1PPP/R1BQ1BNR w kq - 1 7\", \"b4a4\", false},\n\n {\"r1b1k1nr/pppq1ppp/2np4/4p3/2K1P3/2N5/PPPP1PPP/R1BQ1BNR w kq - 3 8\", \"c4b4\", false},\n\n\n\n //test moving other piece when king is in check\n\n {\"8/8/1P6/KP6/Pr6/8/3b4/Q3k3 b - - 0 1\", \"d2e3\", false},\n\n {\"2R3k1/5ppp/8/8/1b6/8/5PPP/6K1 b - - 0 1\", \"b4f8\", true},\n\n\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 94, "score": 18.838975986219573 }, { "content": " }\n\n }\n\n */\n\n REQUIRE_THAT(generatedMoves, Catch::Matchers::UnorderedEquals(expectedMoves));\n\n}\n\nTEST_CASE(\"Test Generate Pieces Moves\", \"[TestGenerateMoves]\")\n\n{\n\n std::string fenPosition;\n\n int fileNum;\n\n int rankNum;\n\n int expect;\n\n\n\n std::tie(fenPosition, fileNum, rankNum, expect) = GENERATE(\n\n table<std::string, int, int, int>({\n\n // pawn endgame\n\n {\"8/2p4p/2Pk2p1/6P1/5P2/8/6KP/8 w - - 1 2\", 7, 2, 7}, // king legal moves\n\n {\"8/2p4p/2Pk2p1/6P1/5P2/8/6KP/8 w - - 1 2\", 8, 2, 2}, // pawn legal moves\n\n // queen vs pawn\n\n {\"8/8/8/8/6K1/6Q1/2p5/3k4 w - - 0 1\", 7, 3, 18}, // queen legal moves\n\n // knight pawn vs knight pawn\n", "file_path": "tests/TestSearch.cpp", "rank": 95, "score": 18.80565698700248 }, { "content": " }));\n\n\n\n SECTION(\"Test king moves illegal\")\n\n {\n\n TestIsMoveLegal(fenPosition, move, isMoveLegal);\n\n }\n\n}\n\n\n\nTEST_CASE(\"Test Absolute Pin move\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::string move;\n\n bool isMoveLegal;\n\n\n\n std::tie(fenPosition, move, isMoveLegal) = GENERATE(\n\n table<std::string, std::string, bool>({\n\n //knight pinned\n\n {\"rnbqk2r/ppp2ppp/8/3pP3/1b1Pnp2/2NB1N2/PPP3PP/R1BQK2R w KQkq - 3 8\", \"c3b5\", false},\n\n {\"rnbqk2r/ppp2ppp/8/3pP3/1b1P1p2/2NB1NnP/PPP3P1/R1BQK2R w KQkq - 1 9\", \"c3b5\", false},\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 96, "score": 18.259181554786444 }, { "content": "}\n\n\n\nTEST_CASE(\"Test Loosing castling rights\", \"[BoardLegalMoves]\")\n\n{\n\n std::string fenPosition;\n\n\n\n std::vector<std::string> moves;\n\n bool isMoveLegal;\n\n\n\n std::tie(fenPosition, moves, isMoveLegal) = GENERATE(\n\n table<std::string, std::vector<std::string>, bool>({\n\n //white loose castling rights because of a rook(a1) move\n\n {\n\n \"r1bqkb1r/ppp1ppp1/2np1n1p/8/2B1P2P/5N2/PPPP1PP1/RNBQK2R w KQkq - 0 5\",\n\n\n\n {\n\n \"h1h2\",\n\n \"a7a6\",\n\n \"h2h1\",\n\n \"a6a5\",\n", "file_path": "tests/TestAnalyzer.cpp", "rank": 97, "score": 18.22562390538378 }, { "content": "#include \"analyzer.h\"\n\n#include \"math.h\"\n\n#include \"board.h\"\n\n#include \"chessLib.h\"\n\n#include \"search.h\"\n\n#include <cmath>\n\n#include <stdexcept>\n\n#include <sstream>\n\n#include <algorithm>\n\nbool Analyzer::IsPieceMovementBlocked(const Board &board, Square from, Square to, bool canGoToSamePieceColor)\n\n{\n\n\n\n bool pieceMovementIsBlocked = false;\n\n PieceName pieceName = board.GetPieceNameEnum(from);\n\n PieceColors pieceColor = board.GetPieceColor(from);\n\n if (!DoesPieceMoveCorrectly(pieceName, pieceColor, from, to))\n\n {\n\n\n\n std::string errorMsg = std::string(\"Piece movement is not correct / according to rules\\n \") +\n\n \"pieceName:\" + ChessLib::GetPieceNameStr(pieceName) + \"\\n\" + \"pieceColor:\" + ChessLib::GetPieceColorStr(pieceColor) + \"\\n\" +\n", "file_path": "Src/analyzer.cpp", "rank": 98, "score": 16.934737452900357 }, { "content": " for (int i = 0; i <= abs(moveDir.x) - 2; i++)\n\n {\n\n\n\n if (!board.IsSquareEmpty(fileNumIterator, rankNumIterator))\n\n {\n\n pieceMovementIsBlocked = true;\n\n break;\n\n }\n\n rankNumIterator += unitDir.y;\n\n fileNumIterator += unitDir.x;\n\n }\n\n break;\n\n }\n\n case PieceName::rook:\n\n {\n\n int unitDirX = moveDir.x == 0 ? 0 : (moveDir.x / abs(moveDir.x));\n\n int unitDirY = moveDir.y == 0 ? 0 : (moveDir.y / abs(moveDir.y));\n\n Vector2 unitDir = Vector2(unitDirX, unitDirY);\n\n\n\n int distanceSquare = 0;\n", "file_path": "Src/analyzer.cpp", "rank": 99, "score": 16.83012763184584 } ]
C++
RedeNeural.cpp
AndreSFND/evolutive-agario
cb974d89d413e5db56fda06d6eb18a43aecf1658
#include <iostream> #include <vector> #include <list> #include <cstdlib> #include <math.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include "RedeNeural.h" using namespace std; RedeNeural::RedeNeural(double _input[], double _biasNeuron, double _biasOutput) { for(int i = 0; i < N_INPUTS; i++) { input[i] = _input[i]; } biasNeuron = _biasNeuron; biasOutput = _biasOutput; populateAxons(); } double* RedeNeural::getInput() { return input; } double* RedeNeural::getOutput() { return output; } RedeNeural::structAxons RedeNeural::getAxons() { return axons; } double* RedeNeural::getNeuron() { return neuron; } double RedeNeural::getBiasNeuron() { return biasNeuron; } double RedeNeural::getBiasOutput() { return biasOutput; } void RedeNeural::setInput(double _input[]) { for(int i = 0; i < N_INPUTS; i++) { input[i] = _input[i]; } } void RedeNeural::setOutput(double _output[]) { for(int i = 0; i < N_OUTPUTS; i++) { output[i] = _output[i]; } } void RedeNeural::setAxonsIn(double _axonsIn[][N_NEURONS]) { for(int i = 0; i < N_INPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { axons.axonsIn[i][j] = _axonsIn[i][j]; } } } void RedeNeural::setAxonsOut(double _axonsOut[][N_OUTPUTS]) { for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_OUTPUTS; j++) { axons.axonsOut[i][j] = _axonsOut[i][j]; } } } void RedeNeural::setNeuron(double _neuron[]) { for(int i = 0; i < N_NEURONS; i++) { neuron[i] = _neuron[i]; } } void RedeNeural::setBiasNeuron(double _biasNeuron) { biasNeuron = _biasNeuron; } void RedeNeural::setBiasOutput(double _biasOutput) { biasOutput = _biasOutput; } void RedeNeural::populateAxons() { for(int i = 0; i < N_INPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { axons.axonsIn[i][j] = ( ((double) rand() / (double) RAND_MAX) * (MAX_AXON - MIN_AXON) ) + MIN_AXON ; } } for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_OUTPUTS; j++) { axons.axonsOut[i][j] = ( ((double) rand() / (double) RAND_MAX) * (MAX_AXON - MIN_AXON) ) + MIN_AXON ; } } } double RedeNeural::sigmoid(double x) { return 1 / (1 + exp(-x)); } void RedeNeural::activatingFunction(double source[], int size) { for(int i = 0; i < size; i++) { source[i] = sigmoid(source[i]); } } double RedeNeural::feedForward() { for(int i = 0; i < N_NEURONS; i++) { neuron[i] = 0; } for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_INPUTS; j++) { neuron[i] += input[j] * axons.axonsIn[j][i]; } neuron[i] += biasNeuron; } activatingFunction(neuron, N_NEURONS); for(int i = 0; i < N_OUTPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { output[i] += neuron[j] * axons.axonsOut[j][i]; } output[i] += biasOutput; } activatingFunction(output, N_OUTPUTS); return 0; } void RedeNeural::printExample() { double _inputs[] = {1, 2}; double _biasNeuron = 0; double _biasOutput = 0; RedeNeural n(_inputs, _biasNeuron, _biasOutput); n.feedForward(); printf("\n\n\tRESUMINDO\n\n"); for(int i = 0; i < N_INPUTS; i++) printf("Input[%d]: %.2f\n", i, n.getInput()[i]); printf("----\n"); for(int i = 0; i < N_INPUTS; i++) for(int j = 0; j < N_NEURONS; j++) printf("AxonIn[%d][%d]: %.2f\n", i, j, n.getAxons().axonsIn[i][j]); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) printf("Neuron[%d]: %.2f\n", i, n.getNeuron()[i]); printf("----\n"); printf("Bias Neuronio (adicionado no neuronio antes da sigmoid): %.2f\n", n.getBiasNeuron()); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) for(int j = 0; j < N_OUTPUTS; j++) printf("AxonOut[%d][%d]: %.2f\n", i, j, n.getAxons().axonsOut[i][j]); printf("----\n"); for(int i = 0; i < N_OUTPUTS; i++) printf("Output[%d]: %.2f\n", i, n.getOutput()[i]); printf("----\n"); printf("Bias Output (adicionado no output antes da sigmoid): %.2f\n", n.getBiasOutput()); printf("----\n"); }
#include <iostream> #include <vector> #include <list> #include <cstdlib> #include <math.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include "RedeNeural.h" using namespace std; RedeNeural::RedeNeural(double _input[], double _biasNeuron, double _biasOutput) { for(int i = 0; i < N_INPUTS; i++) { input[i] = _input[i]; } biasNeuron = _biasNeuron; biasOutput = _biasOutput; populateAxons(); } double* RedeNeural::getInput() { return input; } double* RedeNeural::getOutput() { return output; } RedeNeural::structAxons RedeNeural::getAxons() { return axons; } double* RedeNeural::getNeuron() { return neuron; } double RedeNeural::getBiasNeuron() { return biasNeuron; } double RedeNeural::getBiasOutput() { return biasOutput; } void RedeNeural::setInput(double _input[]) { for(int i = 0; i < N_INPUTS; i++) { input[i] = _input[i]; } } void RedeNeural::setOutput(double _output[]) { for(int i = 0; i < N_OUTPUTS; i++) { output[i] = _output[i]; } }
void RedeNeural::setAxonsOut(double _axonsOut[][N_OUTPUTS]) { for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_OUTPUTS; j++) { axons.axonsOut[i][j] = _axonsOut[i][j]; } } } void RedeNeural::setNeuron(double _neuron[]) { for(int i = 0; i < N_NEURONS; i++) { neuron[i] = _neuron[i]; } } void RedeNeural::setBiasNeuron(double _biasNeuron) { biasNeuron = _biasNeuron; } void RedeNeural::setBiasOutput(double _biasOutput) { biasOutput = _biasOutput; } void RedeNeural::populateAxons() { for(int i = 0; i < N_INPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { axons.axonsIn[i][j] = ( ((double) rand() / (double) RAND_MAX) * (MAX_AXON - MIN_AXON) ) + MIN_AXON ; } } for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_OUTPUTS; j++) { axons.axonsOut[i][j] = ( ((double) rand() / (double) RAND_MAX) * (MAX_AXON - MIN_AXON) ) + MIN_AXON ; } } } double RedeNeural::sigmoid(double x) { return 1 / (1 + exp(-x)); } void RedeNeural::activatingFunction(double source[], int size) { for(int i = 0; i < size; i++) { source[i] = sigmoid(source[i]); } } double RedeNeural::feedForward() { for(int i = 0; i < N_NEURONS; i++) { neuron[i] = 0; } for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_INPUTS; j++) { neuron[i] += input[j] * axons.axonsIn[j][i]; } neuron[i] += biasNeuron; } activatingFunction(neuron, N_NEURONS); for(int i = 0; i < N_OUTPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { output[i] += neuron[j] * axons.axonsOut[j][i]; } output[i] += biasOutput; } activatingFunction(output, N_OUTPUTS); return 0; } void RedeNeural::printExample() { double _inputs[] = {1, 2}; double _biasNeuron = 0; double _biasOutput = 0; RedeNeural n(_inputs, _biasNeuron, _biasOutput); n.feedForward(); printf("\n\n\tRESUMINDO\n\n"); for(int i = 0; i < N_INPUTS; i++) printf("Input[%d]: %.2f\n", i, n.getInput()[i]); printf("----\n"); for(int i = 0; i < N_INPUTS; i++) for(int j = 0; j < N_NEURONS; j++) printf("AxonIn[%d][%d]: %.2f\n", i, j, n.getAxons().axonsIn[i][j]); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) printf("Neuron[%d]: %.2f\n", i, n.getNeuron()[i]); printf("----\n"); printf("Bias Neuronio (adicionado no neuronio antes da sigmoid): %.2f\n", n.getBiasNeuron()); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) for(int j = 0; j < N_OUTPUTS; j++) printf("AxonOut[%d][%d]: %.2f\n", i, j, n.getAxons().axonsOut[i][j]); printf("----\n"); for(int i = 0; i < N_OUTPUTS; i++) printf("Output[%d]: %.2f\n", i, n.getOutput()[i]); printf("----\n"); printf("Bias Output (adicionado no output antes da sigmoid): %.2f\n", n.getBiasOutput()); printf("----\n"); }
void RedeNeural::setAxonsIn(double _axonsIn[][N_NEURONS]) { for(int i = 0; i < N_INPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { axons.axonsIn[i][j] = _axonsIn[i][j]; } } }
function_block-full_function
[ { "content": "// Leonardo Antonetti da Motta - ICMC USP 11275338\n\n\n\n#include <iostream> \n\n#include <vector>\n\n#include <list>\n\n#include <cstdlib>\n\n#include <math.h>\n\n#include <time.h>\n\n#include <stdlib.h>\n\n#include <stdio.h>\n\n\n\nusing namespace std;\n\n\n\n#define MIN_AXON -1\n\n#define MAX_AXON 1\n\n//#define ESCOPO_DECIMAL_AXON 100\n\n\n\n#define N_INPUTS 6\n\n#define N_NEURONS 4\n\n#define N_OUTPUTS 2\n\n\n", "file_path": "RedeNeural.h", "rank": 0, "score": 25.63773469645616 }, { "content": " #endif\n\n\n\n #include <iostream>\n\n #include <vector>\n\n #include <math.h>\n\n #include \"Comida.h\"\n\n #include \"RedeNeural.h\"\n\n\n\n using namespace std;\n\n\n", "file_path": "Bolinha.h", "rank": 2, "score": 16.659971718371526 }, { "content": "\n\n#include <algorithm>\n\n#include <iostream>\n\n#include <vector>\n\n#include <time.h>\n\n#include \"Comida.h\"\n\n#include \"Bolinha.h\"\n\n\n\nusing namespace std;\n\n\n\n#define windowWidth 600\n\n#define windowHeight 600\n\n#define windowPositionX 383\n\n#define windowPositionY 84\n\n#define fps 60\n\n\n\n#define nPlayers 10\n\n#define timeLimit 2000\n\n\n\nvoid initialize();\n", "file_path": "main.cpp", "rank": 3, "score": 15.660859454386575 }, { "content": "\t\tstructAxons getAxons();\n\n\t\tdouble* getNeuron();\n\n\t\tdouble getBiasNeuron();\n\n\t\tdouble getBiasOutput();\n\n\t\t\n\n\t\tvoid setInput(double _input[]);\n\n\t\tvoid setOutput(double _output[]);\n\n\t\tvoid setAxonsIn(double _axonsIn[][N_NEURONS]);\n\n\t\tvoid setAxonsOut(double _axonsOut[][N_OUTPUTS]);\n\n\t\tvoid setNeuron(double _neuron[]);\n\n\t\tvoid setBiasNeuron(double _biasNeuron);\n\n\t\tvoid setBiasOutput(double _biasOutput);\n\n\t\t\n\n\t\tvoid populateAxons();\n\n\t\tdouble sigmoid(double x);\n\n\t\t\n\n\t\tvoid activatingFunction(double source[], int size);\n\n\t\tdouble feedForward();\n\n\t\tvoid printExample();\n\n\n\n};", "file_path": "RedeNeural.h", "rank": 4, "score": 14.47619371537154 }, { "content": "/**\n\n * USP Sao Carlos, ICMC\n\n * Agario Evolutivo\n\n * \n\n * Classe da comida\n\n * \n\n * @author Andre Santana Fernandes <11208537>\n\n * @author Diogo Castanho Emídio <11297274>\n\n * @author Leonardo Antonetti da Motta <11275338>\n\n * @author Marcus Vinicius Santos Rodrigues <11218862>\n\n * @author Olavo Morais Borges Pereira <11297792>\n\n * \n\n*/\n\n#ifndef COMIDA_H\n\n#define COMIDA_H\n\n\n\n #ifdef __APPLE__\n\n #include <GLUT/glut.h>\n\n #else\n\n #include <GL/glut.h>\n\n #endif\n\n\n\n #include <iostream>\n\n #include <vector>\n\n #include <math.h>\n\n\n\n using namespace std;\n\n\n", "file_path": "Comida.h", "rank": 7, "score": 12.145916711332767 }, { "content": "\n\n // Inicializa os axons da rede neural\n\n double axonsIn[N_INPUTS][N_NEURONS];\n\n double axonsOut[N_NEURONS][N_OUTPUTS];\n\n\n\n // Se nao houverem vencedores, inicializa a partida com axons aleatorios\n\n if( winners.size() <= 0 ) {\n\n\n\n int counter = 0;\n\n\n\n for(int i=0; i<nPlayers; i++) {\n\n\n\n for( int j=0; j<N_INPUTS; j++ ) {\n\n\n\n for( int k=0; k<N_NEURONS; k++ ) {\n\n\n\n axonsIn[j][k] = fRand(MIN_AXON, MAX_AXON);\n\n\n\n }\n\n\n", "file_path": "main.cpp", "rank": 14, "score": 10.378342764045945 }, { "content": " \n\n mass = _mass;\n\n x = _x;\n\n y = _y;\n\n r = _r; g = _g; b = _b;\n\n horizontal = _horizontal;\n\n vertical = _vertical;\n\n active = true;\n\n\n\n closestFood = NULL;\n\n closestEnemy = NULL;\n\n\n\n // Cria a rede neural\n\n double _inputs[] = {0, 0, 0, 0, 0, 0};\n\n\tdouble _biasNeuron = 0;\n\n\tdouble _biasOutput = -0;\n\n\n\n redeNeural = new RedeNeural(_inputs, _biasNeuron, _biasOutput);\n\n redeNeural->setAxonsIn(_axonsIn);\n\n redeNeural->setAxonsOut(_axonsOut);\n", "file_path": "Bolinha.cpp", "rank": 15, "score": 10.377419079833807 }, { "content": " }\n\n\n\n for( int j=0; j<N_NEURONS; j++ ) {\n\n\n\n for( int k=0; k<N_OUTPUTS; k++ ) {\n\n\n\n axonsOut[j][k] = fRand(MIN_AXON, MAX_AXON);\n\n\n\n }\n\n\n\n }\n\n \n\n new Bolinha(axonsIn, axonsOut, 0.001, (0.1 * i)-0.5, (0.1 * i)-0.5, 1, 0, 1, 1, 0, players);\n\n\n\n }\n\n \n\n } else { // Se houverem vencedores da ultima partida, faz o cruzamento (elitismo)\n\n\n\n // Move os jogadores atuais para outro vetor \n\n vector<Bolinha> oldGen(players);\n", "file_path": "main.cpp", "rank": 18, "score": 9.061526613169704 }, { "content": "// Desenha um poligono de n pontos\n\nvoid DrawCircle(double cx, double cy, double r, int num_segments) {\n\n\n\n glBegin(GL_LINE_LOOP);\n\n\n\n for (int i = 0; i < num_segments; i++) {\n\n\n\n double theta = 2.0f * PI * double(i) / double(num_segments); //get the current angle \n\n double x = r * cosf(theta); //calculate the x component \n\n double y = r * sinf(theta); //calculate the y component \n\n glVertex2f(x + cx, y + cy); //output vertex \n\n\n\n }\n\n\n\n glEnd();\n\n\n\n}\n\n\n\n// Construtor\n\nBolinha::Bolinha(double _axonsIn[][N_NEURONS], double _axonsOut[][N_OUTPUTS], double _mass, double _x, double _y, double _r, double _g, double _b, double _horizontal, double _vertical, vector<Bolinha>& players) {\n", "file_path": "Bolinha.cpp", "rank": 19, "score": 8.526138557855651 }, { "content": "\n\n double _inputs[] = { DistanceToClosestEnemy(), AngleToClosestEnemy() / 180, ClosestEnemyMass(), Mass(), DistanceToClosestFood(), AngleToClosestFood() / 180 }; \n\n redeNeural->setInput(_inputs);\n\n redeNeural->feedForward();\n\n\n\n double *_outputs = redeNeural->getOutput();\n\n\n\n horizontal = ( _outputs[0] * 2 ) - 1;\n\n vertical = ( _outputs[1] * 2 ) - 1;\n\n\n\n RedeNeural::structAxons playerAxons = redeNeural->getAxons();\n\n\n\n // Move o personagem\n\n x += horizontal * Speed() / 500;\n\n y += vertical * Speed() / 500;\n\n\n\n // Impede que o personagem saia da tela\n\n x = x > 1 || x < -1 ? x*-1 : x;\n\n y = y > 1 || y < -1 ? y*-1 : y;\n\n\n", "file_path": "Bolinha.cpp", "rank": 20, "score": 8.128375277595627 }, { "content": " axonsIn[j][k] = axon;\n\n\n\n }\n\n\n\n }\n\n\n\n for( int j=0; j<N_NEURONS; j++ ) {\n\n\n\n for( int k=0; k<N_OUTPUTS; k++ ) {\n\n\n\n // Cruza o vencedor com o jogador da ultima geracao\n\n double axon = ( ( playerAxons.axonsOut[j][k] + winnerAxons.axonsOut[j][k] ) / 2 ) + fRand(-1, 1);\n\n if( playerAxons.axonsOut[j][k] == winnerAxons.axonsOut[j][k] ) axon = winnerAxons.axonsOut[j][k];\n\n\n\n axonsOut[j][k] = axon;\n\n\n\n }\n\n\n\n }\n\n \n", "file_path": "main.cpp", "rank": 22, "score": 7.514065146877769 }, { "content": "/**\n\n * USP Sao Carlos, ICMC\n\n * Agario Evolutivo\n\n * \n\n * Classe da comida\n\n * \n\n * @author Andre Santana Fernandes <11208537>\n\n * @author Diogo Castanho Emídio <11297274>\n\n * @author Leonardo Antonetti da Motta <11275338>\n\n * @author Marcus Vinicius Santos Rodrigues <11218862>\n\n * @author Olavo Morais Borges Pereira <11297792>\n\n * \n\n*/\n\n\n\n#include \"Comida.h\"\n\n#define CIRCLE_SEGMENTS 8 // Quantos pontos a comida tem\n\n#define MASS 0.00005 // Massa da comida\n\n\n\nusing namespace std;\n\n\n", "file_path": "Comida.cpp", "rank": 23, "score": 7.496045356138193 }, { "content": "/**\n\n * USP Sao Carlos, ICMC\n\n * Agario Evolutivo\n\n * \n\n * Classe dos personagens, que sao capazes de se mover e absorver outros personagens e comidas\n\n * \n\n * @author Andre Santana Fernandes <11208537>\n\n * @author Diogo Castanho Emídio <11297274>\n\n * @author Leonardo Antonetti da Motta <11275338>\n\n * @author Marcus Vinicius Santos Rodrigues <11218862>\n\n * @author Olavo Morais Borges Pereira <11297792>\n\n * \n\n*/\n\n\n\n#include \"Bolinha.h\"\n\n#define CIRCLE_SEGMENTS 8\n\n#define PI 3.1415\n\n\n\nusing namespace std;\n\n\n", "file_path": "Bolinha.cpp", "rank": 24, "score": 7.377337994858735 }, { "content": "\n\n // Limpa o vetor de jogadores atuais\n\n players.clear();\n\n\n\n // Pega os axons do vencedor\n\n RedeNeural::structAxons winnerAxons = winners[0].redeNeural->getAxons();\n\n\n\n for(int i=0; i<nPlayers; i++) {\n\n\n\n // Pega os axons do jogador da ultima geracao\n\n RedeNeural::structAxons playerAxons = oldGen[i].redeNeural->getAxons();\n\n\n\n for( int j=0; j<N_INPUTS; j++ ) {\n\n\n\n for( int k=0; k<N_NEURONS; k++ ) {\n\n\n\n // Cruza o vencedor com o jogador da ultima geracao\n\n double axon = ( ( playerAxons.axonsIn[j][k] + winnerAxons.axonsIn[j][k] ) / 2 ) + fRand(-1, 1);\n\n if( playerAxons.axonsIn[j][k] == winnerAxons.axonsIn[j][k] ) axon = winnerAxons.axonsIn[j][k];\n\n\n", "file_path": "main.cpp", "rank": 25, "score": 6.514237901723968 }, { "content": "// Calcula a velocidade com base na massa\n\ndouble Bolinha::Speed() {\n\n\n\n double speed = pow(Radius(), -0.439) * 2.2;\n\n\n\n return isnan(speed) ? 0 : speed;\n\n\n\n}\n\n\n\n// Desenha o poligono\n\nvoid Bolinha::Draw() {\n\n\n\n glColor3f(r, g, b);\n\n DrawCircle(x, y, Radius(), CIRCLE_SEGMENTS);\n\n glEnd();\n\n\n\n}\n\n\n\n// Joga os inputs na rede neural e move o personagem segundo o output\n\nvoid Bolinha::Move() {\n", "file_path": "Bolinha.cpp", "rank": 26, "score": 6.166191168275196 }, { "content": "// Desenha um poligono de n pontos\n\nvoid DrawCircle_(double cx, double cy, double r, int num_segments) {\n\n\n\n glBegin(GL_LINE_LOOP);\n\n\n\n for (int i = 0; i < num_segments; i++) {\n\n\n\n double theta = 2.0f * 3.1415926f * double(i) / double(num_segments); //get the current angle \n\n double x = r * cosf(theta); //calculate the x component \n\n double y = r * sinf(theta); //calculate the y component \n\n glVertex2f(x + cx, y + cy); //output vertex \n\n\n\n }\n\n\n\n glEnd();\n\n\n\n}\n\n\n\n// Construtor\n\nComida::Comida(double _x, double _y, double _r, double _g, double _b, vector<Comida>& comidas) {\n", "file_path": "Comida.cpp", "rank": 27, "score": 4.820933738152759 }, { "content": " double Radius(); // Calcula o raio com base na massa\n\n double Speed(); // Calcula a velocidade com base na massa\n\n\n\n void Draw(); // Desenha\n\n void Move(); // Move o jogador\n\n void Collide(vector<Bolinha>& players); // Calcula a colisao com outros jogadores\n\n void Collide(vector<Comida>& comidas); // Calcula a colisao com outras comidas\n\n\n\n double DistanceToClosestFood(); // Calcula a distancia ate a comida mais proxima\n\n double AngleToClosestFood(); // Calcula o angulo ate a comida mais proxima\n\n\n\n double DistanceToClosestEnemy(); // Calcula a distancia ate o inimigo mais proximo\n\n double AngleToClosestEnemy(); // Calcula o angulo ate o inimigo mais proximo\n\n double ClosestEnemyMass(); // Retorna a massa do inimigo mais proximo\n\n\n\n bool isActive(); // Verifica se esta vivo\n\n void setActive(bool active); // Define se esta vivo\n\n\n\n };\n\n\n\n#endif", "file_path": "Bolinha.h", "rank": 28, "score": 4.5373136139001735 }, { "content": "void draw();\n\nvoid timer(int);\n\n\n\n/**\n\n * TODO:\n\n * Cruzamento in game\n\n * - Duas bolinhas cruzam na hora\n\n * \n\n * Variaveis a serem adicionadas (distribuir pontos entre elas):\n\n * - Velocidade\n\n * - Taxa de conversao de comida em massa\n\n * \n\n * Variaveis input rede neural:\n\n * - Distancia do inimigo mais proximo\n\n * - Angulo entre personagem e inimigo mais proximo\n\n * - Massa do inimigo mais proximo\n\n * - Massa do personagem\n\n * - Distancia da comida mais proxima\n\n * - Angulo entre personagem e comida mais proxima\n\n * \n", "file_path": "main.cpp", "rank": 29, "score": 3.9184987002867935 }, { "content": " // x = x + Radius() > 1 ? 1 - Radius() : x;\n\n // x = x - Radius() < -1 ? -1 + Radius() : x;\n\n\n\n // y = y + Radius() > 1 ? 1 - Radius() : y;\n\n // y = y - Radius() < -1 ? -1 + Radius() : y;\n\n\n\n}\n\n\n\n// Calcula a colisao do personagem com outros personagens\n\n// Define o inimigo mais proximo\n\nvoid Bolinha::Collide(vector<Bolinha>& players) {\n\n\n\n int playersLength = players.size();\n\n double currentDistance = -1;\n\n\n\n if( playersLength > 0 ) {\n\n\n\n for(int i=0; i<playersLength; i++) {\n\n\n\n if( &(players[i]) != this && players[i].isActive() ) {\n", "file_path": "Bolinha.cpp", "rank": 30, "score": 3.8750483922137775 }, { "content": "// Calcula a colisao do personagem com comidas\n\n// Define a comida mais proxima\n\nvoid Bolinha::Collide(vector<Comida>& comidas) {\n\n\n\n int comidasLength = comidas.size();\n\n double currentDistance = -1;\n\n\n\n if( comidasLength > 0 ) {\n\n\n\n for(int i=0; i<comidasLength; i++) {\n\n\n\n if( comidas[i].isActive() ) {\n\n\n\n double distance = sqrt(pow(comidas[i].x - x, 2) + pow(comidas[i].y - y, 2) * 1.0);\n\n\n\n if( currentDistance == -1 ) {\n\n\n\n closestFood = &comidas[i];\n\n currentDistance = distance;\n\n\n", "file_path": "Bolinha.cpp", "rank": 31, "score": 3.7139833667482667 }, { "content": " * \n\n*/\n\n\n\n// Vetores que salval as comidas, players e vencedores da partida\n\nvector<Comida> comidas;\n\nvector<Bolinha> players;\n\nvector<Bolinha> winners;\n\n\n\n// Tick e geracao atual\n\nint ticks = 0;\n\nint geracao = 1;\n\n\n\n// Conta a quantidade de jogadores vivos\n\nint countActivePlayers() {\n\n\n\n int activePlayers = 0;\n\n\n\n for(int i=0; i<nPlayers; i++) {\n\n\n\n if(players[i].isActive())\n", "file_path": "main.cpp", "rank": 33, "score": 2.9709755412892354 }, { "content": " new Bolinha(axonsIn, axonsOut, 0.001, (0.1 * i)-0.5, (0.1 * i)-0.5, 1, 0, 1, 1, 0, players);\n\n\n\n }\n\n\n\n oldGen.clear();\n\n winners.clear();\n\n winners.reserve(0);\n\n\n\n }\n\n\n\n // Cria as comidas em locais aleatorios\n\n for(int i=0; i<nPlayers*5; i++) {\n\n\n\n double x = ((rand() % 200) / 100.0) - 1;\n\n double y = ((rand() % 200) / 100.0) - 1;\n\n\n\n new Comida(x, y, 0.8, 0, 0.8, comidas);\n\n\n\n }\n\n\n", "file_path": "main.cpp", "rank": 34, "score": 2.770000289910013 }, { "content": "\n\n// Desenha o poligono\n\nvoid Comida::Draw() {\n\n\n\n glColor3f(r, g, b);\n\n DrawCircle_(x, y, Radius(), CIRCLE_SEGMENTS);\n\n glEnd();\n\n\n\n}\n\n\n\nbool Comida::isActive() {\n\n\n\n return this->active;\n\n\n\n}\n\n\n\nvoid Comida::setActive(bool active) {\n\n\n\n this->active = active;\n\n\n\n}", "file_path": "Comida.cpp", "rank": 35, "score": 2.7369024957378665 }, { "content": "\n\n return this->active;\n\n\n\n}\n\n\n\nvoid Bolinha::setActive(bool active) {\n\n\n\n this->active = active;\n\n\n\n}", "file_path": "Bolinha.cpp", "rank": 36, "score": 2.584696473483002 }, { "content": "/**\n\n * USP Sao Carlos, ICMC\n\n * Agario Evolutivo\n\n * \n\n * Classe dos personagens, que sao capazes de se mover e absorver outros personagens e comidas\n\n * \n\n * @author Andre Santana Fernandes <11208537>\n\n * @author Diogo Castanho Emídio <11297274>\n\n * @author Leonardo Antonetti da Motta <11275338>\n\n * @author Marcus Vinicius Santos Rodrigues <11218862>\n\n * @author Olavo Morais Borges Pereira <11297792>\n\n * \n\n*/\n\n#ifndef BOLINHA_H\n\n#define BOLINHA_H\n\n\n\n #ifdef __APPLE__\n\n #include <GLUT/glut.h>\n\n #else\n\n #include <GL/glut.h>\n", "file_path": "Bolinha.h", "rank": 37, "score": 2.4669402740642026 }, { "content": "/**\n\n * USP Sao Carlos, ICMC\n\n * Agario Evolutivo\n\n * \n\n * O jogo, que utiliza OpenGL, simula varias partidas do jogo Agar.io, cruzando os individuos que sobrevivem por mais tempo e \n\n * gerando um que sempre consiga vencer. \n\n * \n\n * @author Andre Santana Fernandes <11208537>\n\n * @author Diogo Castanho Emídio <11297274>\n\n * @author Leonardo Antonetti da Motta <11275338>\n\n * @author Marcus Vinicius Santos Rodrigues <11218862>\n\n * @author Olavo Morais Borges Pereira <11297792>\n\n * \n\n*/\n\n\n\n#ifdef __APPLE__\n\n #include <GLUT/glut.h>\n\n#else\n\n #include <GL/glut.h>\n\n#endif\n", "file_path": "main.cpp", "rank": 38, "score": 2.3663583474361096 }, { "content": " }\n\n\n\n // Desenha os jogadores ativos/vivos\n\n for(int i=0; i<players.size(); i++) {\n\n \n\n if( players[i].isActive() ) players[i].Draw();\n\n \n\n }\n\n\n\n glutSwapBuffers();\n\n\n\n}\n\n\n\nvoid timer(int) {\n\n\n\n for(int i=0; i<players.size(); i++) {\n\n \n\n if( players[i].isActive() ) {\n\n \n\n // Calcula a colisao do jogador com as comidas e outros jogadores\n", "file_path": "main.cpp", "rank": 39, "score": 2.0692031749375244 }, { "content": " activePlayers++;\n\n\n\n }\n\n\n\n return activePlayers;\n\n\n\n}\n\n\n\n// Gera um numero aleatorio\n\ndouble fRand(double fMin, double fMax)\n\n{\n\n double f = (double)rand() / RAND_MAX;\n\n return fMin + f * (fMax - fMin);\n\n}\n\n\n\n// Roda ao iniciar a partida\n\nvoid initialize() {\n\n\n\n // Imprime a geracao atual\n\n printf(\"GERACAO %d\\n\", geracao++);\n", "file_path": "main.cpp", "rank": 40, "score": 1.9934737445557542 }, { "content": "}\n\n\n\n// Roda ao acabar a partida\n\nvoid destroy() {\n\n\n\n int playersLength = players.size();\n\n double maxMass = 0;\n\n Bolinha *winner;\n\n\n\n // Busca pelo vencedor\n\n for(int i=0; i<playersLength; i++) {\n\n\n\n if( players[i].isActive() && players[i].Mass() > maxMass ) {\n\n\n\n winner = &players[i];\n\n maxMass = players[i].Mass();\n\n\n\n }\n\n\n\n }\n", "file_path": "main.cpp", "rank": 41, "score": 1.9934737445557542 }, { "content": " glutInitWindowPosition(windowPositionX, windowPositionY);\n\n glutCreateWindow(\"Evolutive Agario\");\n\n glClearColor(1.0, 1.0, 1.0, 1.0);\n\n glutDisplayFunc(draw);\n\n glutTimerFunc(0, timer, 0);\n\n glutMainLoop();\n\n\n\n return 0;\n\n\n\n}\n\n\n\nvoid draw() {\n\n \n\n glClear(GL_COLOR_BUFFER_BIT);\n\n\n\n // Desenha as comidas ativas\n\n for(int i=0; i<comidas.size(); i++) {\n\n \n\n if( comidas[i].isActive() ) comidas[i].Draw();\n\n \n", "file_path": "main.cpp", "rank": 42, "score": 1.7815659991941284 }, { "content": "## 2.2 Rede Neural Artificial (RNA)\n\n\n\nUma Rede Neural Artificial (RNA), com quatro neurônios em uma única camada, está presente em cada uma das células. Ela foi feita de forma que suas entradas sejam geradas inicialmente de forma aleatória e suas saídas ditem para onde o indivíduo irá.\n\n\n\nOs seis _inputs_ são:\n\n- Distância até o inimigo mais próximo;\n\n- Ângulo em relação ao inimigo mais próximo;\n\n- Massa do inimigo mais próximo;\n\n- Sua própria massa;\n\n- Distância até a comida mais próxima;\n\n- Ângulo em relação à comida mais próxima.\n\n\n\nA partir da segunda geração, esses valores são calculados através do produto entre a média aritmética dos de seus pais (o vencedor e um perdedor ainda sem filho) e um valor aleatório pertencente ao intervalo [-2, 2]. É válido ainda ressaltar que o peso de cada entrada é aleatório, independentemente da geração, e que a massa da célula é diretamente proporcional ao seu raio e inversamente à sua velocidade.\n\n\n\nOs _outputs_, por sua vez, são somente dois:\n\n- Movimento na horizontal;\n\n- Movimento na vertical.\n\n\n\nA função sigmoide foi a escolhida para ser a função de ativação da RNA, uma vez que é a mais utilizada para essa função e por não haver necessidades de uma mais complexa. Portanto, os valores das saídas pertencem ao intervalo [0,1], fazendo com que o indivíduo ande para a direita, para cima ou para qualquer outro sentido compreendido entre esses dois. Por fim, é necessário destacar que a RNA implementada não possui limiar de ativação, devido à simplicidade da natureza de sua aplicação.\n\n\n", "file_path": "README.md", "rank": 43, "score": 1.494727100096946 } ]
C++
network/gameserver/proto.hpp
hbccdf/network-core
37cbf03829bffd9c0903a1e755ce1f96f46e3dfa
#pragma once #include "network/net/tcp_connect.hpp" #include "msg_pack.hpp" namespace cytx { namespace gameserver { namespace detail { using namespace cytx; using namespace cytx::gameserver; class Proto; class game_server; using game_server_t = game_server; using msg_t = net::server_msg<net::msg_body>; using header_t = typename msg_t::header_t; using connection_t = net::tcp_connection<msg_t>; using connection_ptr = std::shared_ptr<connection_t>; using context_t = typename connection_t::context_t; using msg_ptr = typename connection_t::msg_ptr; using proto_t = Proto; using proto_ptr_t = std::shared_ptr<proto_t>; using proto_map_t = std::map<uint32_t, proto_ptr_t>; template <typename T> struct has_ctx_process_func { private: template <typename P, typename = decltype(std::declval<P>().process(*(msg_ptr)nullptr, *(connection_ptr*)nullptr, *(game_server_t*)nullptr, *(context_t*)nullptr))> static std::true_type test(int); template <typename P> static std::false_type test(...); using result_type = decltype(test<T>(0)); public: static constexpr bool value = result_type::value; }; template<typename T> constexpr bool has_ctx_process_func_v = has_ctx_process_func<T>::value; class Proto : public std::enable_shared_from_this<Proto>, public custom_msg { public: Proto() : protocol_id_(0) , has_ctx_process_(false) {} Proto(const Proto& rhs) : protocol_id_(rhs.protocol_id_) , has_ctx_process_(rhs.has_ctx_process_) { } uint32_t get_protocol_id() const { return protocol_id_; } void set_has_ctx_process(bool has_ctx_process) { has_ctx_process_ = has_ctx_process; } public: virtual proto_ptr_t clone() { return nullptr; } virtual void unpack(msg_ptr& msgp) = 0; void do_process(msg_ptr& msgp, connection_ptr& conn_ptr, game_server_t& server) { if (!has_ctx_process_) { process(msgp, conn_ptr, server); } else { auto& ios = net::get_current_ios(); boost::asio::spawn(ios, [&] (context_t ctx) { this->process(msgp, conn_ptr, server, ctx); }); } } private: virtual void process(msg_ptr& msgp, connection_ptr& conn_ptr, game_server_t& server) { } virtual void process(msg_ptr& msgp, connection_ptr& conn_ptr, game_server_t& server, context_t ctx) { } public: static proto_map_t& GetMap() { static proto_map_t protocols; return protocols; } static proto_ptr_t GetProto(uint32_t protocol_id) { auto& proto_map = GetMap(); auto it = proto_map.find(protocol_id); if (it != proto_map.end()) { return it->second; } return nullptr; } static proto_ptr_t Decode(msg_ptr& msgp) { uint32_t protocol_id = msgp->header().protocol_id; proto_ptr_t proto = Create(protocol_id); if (proto) { proto->unpack(msgp); } return proto; } static proto_ptr_t Create(uint32_t protocol_id) { proto_ptr_t proto = GetProto(protocol_id); return proto ? proto->clone() : nullptr; } static void RegisterProto(proto_ptr_t proto) { uint32_t proto_id = proto->get_protocol_id(); if (!GetProto(proto_id)) { auto& proto_map = GetMap(); proto_map.emplace(proto_id, proto); } } protected: Proto(uint32_t id) : protocol_id_(id) , has_ctx_process_(false) {} uint32_t protocol_id_; bool has_ctx_process_; }; template<typename T> auto make_proto_ptr(uint32_t proto_id) { bool has_ctx_process = has_ctx_process_func_v<T>; std::shared_ptr<T> ptr = std::make_shared<T>(); ptr->set_has_ctx_process(has_ctx_process); proto_t::RegisterProto(ptr); return ptr; } } using Proto = detail::Proto; using proto_t = Proto; using proto_ptr_t = std::shared_ptr<proto_t>; using msg_t = net::server_msg<net::msg_body>; using header_t = typename msg_t::header_t; using connection_t = net::tcp_connection<msg_t>; using context_t = typename connection_t::context_t; using connection_ptr = std::shared_ptr<connection_t>; using msg_ptr = typename connection_t::msg_ptr; } } #define REGISTER_PROTOCOL(type) \ namespace MACRO_CONCAT(___reg_proto_helper_value___ ## type, __LINE__) \ { \ static auto type ## _ptr = cytx::gameserver::detail::make_proto_ptr<type>(type::ProtoId()); \ }
#pragma once #include "network/net/tcp_connect.hpp" #include "msg_pack.hpp" namespace cytx { namespace gameserver { namespace detail { using namespace cytx; using namespace cytx::gameserver; class Proto; class game_server; using game_server_t = game_server; using msg_t = net::server_msg<net::msg_body>; using header_t = typename msg_t::header_t; using connection_t = net::tcp_connection<msg_t>; using connection_ptr = std::shared_ptr<connection_t>; using context_t = typename connection_t::context_t; using msg_ptr = typename connection_t::msg_ptr; using proto_t = Proto; using proto_ptr_t = std::shared_ptr<proto_t>; using proto_map_t = std::map<uint32_t, proto_ptr_t>; template <typename T> struct has_ctx_process_func { private: template <typename P, typename = decltype(std::declval<P>().process(*(msg_ptr)nullptr, *(connection_ptr*)nullptr, *(game_server_t*)nullptr, *(context_t*)nullptr))> static std::true_type test(int); template <typename P> static std::false_type test(...); using result_type = decltype(test<T>(0)); public: static constexpr bool value = result_type::value; }; template<typename T> constexpr bool has_ctx_process_func_v = has_ctx_process_func<T>::value; class Proto : public std::enable_shared_from_this<Proto>, public custom_msg { public: Proto() : protocol_id_(0) , has_ctx_process_(false) {} Proto(const Proto& rhs) : protocol_id_(rhs.protocol_id_) , has_ctx_process_(rhs.has_ctx_process_) { } uint32_t get_protocol_id() const { return protocol_id_; } void set_has_ctx_process(bool has_ctx_process) { has_ctx_process_ = has_ctx_process; } public: virtual proto_ptr_t clone() { return nullptr; } virtual void unpack(msg_ptr& msgp) = 0; void do_process(msg_ptr& msgp, connection_ptr& conn_ptr, game_server_t& server) { if (!has_ctx_process_) { process(msgp, conn_ptr, server); } else { auto& ios = net::get_current_ios(); boost::asio::spawn(ios, [&] (context_t ctx) { this->process(msgp, conn_ptr, server, ctx); }); } } private: virtual void process(msg_ptr& msgp, connection_ptr& conn_ptr, game_server_t& server) { } virtual void process(msg_ptr& msgp, connection_ptr& conn_ptr, game_server_t& server, context_t ctx) { } public: static proto_map_t& GetMap() { static proto_map_t protocols; return protocols; } static proto_ptr_t GetProto(uint32_t protocol_id) { auto& proto_map = GetMap(); auto it = proto_map.find(protocol_id); if (it != proto_map.end()) { return it->second; } return nullptr; } static proto_ptr_t Decode(msg_ptr& msgp) { uint32_t protocol_id = msgp->header().protocol_id; proto_ptr_t proto = Create(protocol_id); if (proto) { proto->unpack(msgp); } return proto; } static proto_ptr_t Create(uint32_t protocol_id) { proto_ptr_t proto = GetProto(protocol_id); return proto ? proto->clone() : nullptr; }
protected: Proto(uint32_t id) : protocol_id_(id) , has_ctx_process_(false) {} uint32_t protocol_id_; bool has_ctx_process_; }; template<typename T> auto make_proto_ptr(uint32_t proto_id) { bool has_ctx_process = has_ctx_process_func_v<T>; std::shared_ptr<T> ptr = std::make_shared<T>(); ptr->set_has_ctx_process(has_ctx_process); proto_t::RegisterProto(ptr); return ptr; } } using Proto = detail::Proto; using proto_t = Proto; using proto_ptr_t = std::shared_ptr<proto_t>; using msg_t = net::server_msg<net::msg_body>; using header_t = typename msg_t::header_t; using connection_t = net::tcp_connection<msg_t>; using context_t = typename connection_t::context_t; using connection_ptr = std::shared_ptr<connection_t>; using msg_ptr = typename connection_t::msg_ptr; } } #define REGISTER_PROTOCOL(type) \ namespace MACRO_CONCAT(___reg_proto_helper_value___ ## type, __LINE__) \ { \ static auto type ## _ptr = cytx::gameserver::detail::make_proto_ptr<type>(type::ProtoId()); \ }
static void RegisterProto(proto_ptr_t proto) { uint32_t proto_id = proto->get_protocol_id(); if (!GetProto(proto_id)) { auto& proto_map = GetMap(); proto_map.emplace(proto_id, proto); } }
function_block-full_function
[ { "content": "class UseSkill : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UseSkill(const UseSkill&);\n\n UseSkill& operator=(const UseSkill&);\n\n UseSkill() : skillId(0) {\n\n }\n\n\n\n virtual ~UseSkill() throw();\n\n int32_t skillId;\n\n std::vector<int32_t> targetIds;\n\n\n\n _UseSkill__isset __isset;\n\n\n\n void __set_skillId(const int32_t val);\n\n\n\n void __set_targetIds(const std::vector<int32_t> & val);\n\n\n\n bool operator == (const UseSkill & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 0, "score": 407535.16665541474 }, { "content": "class UseUltSkillTrigger : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UseUltSkillTrigger(const UseUltSkillTrigger&);\n\n UseUltSkillTrigger& operator=(const UseUltSkillTrigger&);\n\n UseUltSkillTrigger() : id(0), stage(0) {\n\n }\n\n\n\n virtual ~UseUltSkillTrigger() throw();\n\n int32_t id;\n\n int32_t stage;\n\n\n\n _UseUltSkillTrigger__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n void __set_stage(const int32_t val);\n\n\n\n bool operator == (const UseUltSkillTrigger & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 1, "score": 394697.2752940505 }, { "content": "class UseUltSkillCancel : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UseUltSkillCancel(const UseUltSkillCancel&);\n\n UseUltSkillCancel& operator=(const UseUltSkillCancel&);\n\n UseUltSkillCancel() : id(0) {\n\n }\n\n\n\n virtual ~UseUltSkillCancel() throw();\n\n int32_t id;\n\n\n\n _UseUltSkillCancel__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n bool operator == (const UseUltSkillCancel & rhs) const\n\n {\n\n if (!(id == rhs.id))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 2, "score": 394697.2752940506 }, { "content": "class UseUltSkillFailed : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UseUltSkillFailed(const UseUltSkillFailed&);\n\n UseUltSkillFailed& operator=(const UseUltSkillFailed&);\n\n UseUltSkillFailed() : id(0) {\n\n }\n\n\n\n virtual ~UseUltSkillFailed() throw();\n\n int32_t id;\n\n\n\n _UseUltSkillFailed__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n bool operator == (const UseUltSkillFailed & rhs) const\n\n {\n\n if (!(id == rhs.id))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 3, "score": 394697.2752940506 }, { "content": "class UseUltSkillStart : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UseUltSkillStart(const UseUltSkillStart&);\n\n UseUltSkillStart& operator=(const UseUltSkillStart&);\n\n UseUltSkillStart() : id(0) {\n\n }\n\n\n\n virtual ~UseUltSkillStart() throw();\n\n int32_t id;\n\n\n\n _UseUltSkillStart__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n bool operator == (const UseUltSkillStart & rhs) const\n\n {\n\n if (!(id == rhs.id))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 4, "score": 394697.2752940505 }, { "content": "class UseUltSkillSuccess : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UseUltSkillSuccess(const UseUltSkillSuccess&);\n\n UseUltSkillSuccess& operator=(const UseUltSkillSuccess&);\n\n UseUltSkillSuccess() : id(0), power(0) {\n\n }\n\n\n\n virtual ~UseUltSkillSuccess() throw();\n\n int32_t id;\n\n int32_t power;\n\n TRotation rot;\n\n\n\n _UseUltSkillSuccess__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n void __set_power(const int32_t val);\n\n\n\n void __set_rot(const TRotation& val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 5, "score": 394697.2752940506 }, { "content": " class auto_handler : public detail::handler_detector, public \n\n boost::conditional< \n\n boost::is_convertible<context&, Application>::value, \n\n detail::handler_auto_set_c<Application, auto_handler<Application> >, \n\n detail::handler_auto_set_u<Application, auto_handler<Application> > \n\n >::type\n\n {\n\n \n\n template <typename , typename >\n\n friend struct detail::handler_auto_set_u;\n\n\n\n template <typename , typename >\n\n friend struct detail::handler_auto_set_c;\n\n\n\n public:\n\n \n\n typedef typename boost::conditional< \n\n boost::is_convertible<context&, Application>::value, \n\n detail::handler_auto_set_c<Application, auto_handler<Application> >, \n\n detail::handler_auto_set_u<Application, auto_handler<Application> > \n", "file_path": "third_party/Boost.Application/include/boost/application/auto_handler.hpp", "rank": 7, "score": 388168.52710283606 }, { "content": " class battle_manager : public cytx::gameserver::service_base\n\n {\n\n using this_t = battle_manager;\n\n public:\n\n bool init();\n\n void stop();\n\n public:\n\n void update(float delta);\n\n bool create_battle(SCRoomInfo& room_info);\n\n arena_battle* get_battle(int32_t user_id);\n\n private:\n\n static int get_battle_id();\n\n\n\n private:\n\n //std::map<int32_t, arena_battle*> battle_map_;\n\n std::vector<arena_battle*> battles_;\n\n };\n\n\n\n REG_SERVICE(battle_manager);\n\n}", "file_path": "example/battle_server/service/battle_manager.h", "rank": 8, "score": 362538.21892334684 }, { "content": " class update_timer : public cytx::gameserver::service_base\n\n {\n\n using this_t = update_timer;\n\n using timer_t = cytx::timer_proxy;\n\n public:\n\n bool init();\n\n bool start();\n\n\n\n public:\n\n using func_t = std::function<void(float)>;\n\n void set_update_func(func_t&& func);\n\n private:\n\n void update();\n\n private:\n\n timer_t timer_;\n\n date_time last_time_;\n\n func_t func_;\n\n timer_config config_;\n\n };\n\n\n\n REG_SERVICE(update_timer);\n\n}", "file_path": "example/battle_server/service/update_timer.h", "rank": 9, "score": 362538.21892334684 }, { "content": " class battle_config : public cytx::gameserver::service_base\n\n {\n\n public:\n\n bool init();\n\n\n\n public:\n\n battle_server_info& get_config() { return config_info_; }\n\n const battle_server_info& get_config() const { return config_info_; }\n\n private:\n\n battle_server_info config_info_;\n\n };\n\n\n\n REG_SERVICE(battle_config);\n\n}", "file_path": "example/battle_server/service/battle_config.h", "rank": 10, "score": 362538.21892334695 }, { "content": " class room_service : public cytx::gameserver::service_base\n\n {\n\n public:\n\n bool init();\n\n\n\n room_ptr_t create_room(player_ptr_t& master, size_t max_size, room_mode mode);\n\n room_ptr_t find_room(int room_id);\n\n void exit_room(player_ptr_t& player);\n\n void destroy_room(room_ptr_t& room);\n\n void deal_destroy_room(room_ptr_t& room);\n\n std::vector<room_ptr_t> get_room_list(room_mode mode, bool all_mode);\n\n\n\n public:\n\n template<typename T>\n\n void broadcast_msg(room_ptr_t& room, T& msg)\n\n {\n\n for (const auto& p : room->players())\n\n {\n\n server_->send_client_msg(p.first, msg);\n\n }\n\n }\n\n private:\n\n room_map_t rooms_;\n\n };\n\n\n\n REG_SERVICE(room_service);\n\n}", "file_path": "example/room_server/service/room_service.h", "rank": 11, "score": 362538.2189233469 }, { "content": " class room_config : public cytx::gameserver::service_base\n\n {\n\n public:\n\n bool init();\n\n\n\n public:\n\n room_config_info& get_config() { return config_info_; }\n\n const room_config_info& get_config() const { return config_info_; }\n\n private:\n\n room_config_info config_info_;\n\n };\n\n\n\n REG_SERVICE(room_config);\n\n}", "file_path": "example/room_server/service/room_config.h", "rank": 12, "score": 362538.21892334684 }, { "content": " class player_service : public cytx::gameserver::service_base\n\n {\n\n public:\n\n bool init();\n\n void reset();\n\n\n\n player_ptr_t find_player(int user_id, bool is_login = true);\n\n player_ptr_t get_player(int user_id);\n\n void handle_player_disconnect(int user_id);\n\n private:\n\n player_map_t players_;\n\n };\n\n\n\n REG_SERVICE(player_service);\n\n}", "file_path": "example/room_server/service/player_service.h", "rank": 13, "score": 362538.2189233469 }, { "content": "struct Mocker<I(R(C::*)(const void*, P ...) constness)> : MockerBase<R(const void*, P ...)> { \\\n\n typedef I IntegrateType(R(C::*)(const void*, P ...) constness); \\\n\n typedef I EntryPointType(R(C::*)(P ...) constness); \\\n\n typedef R (C::*FunctionType)(P ...) constness; \\\n\n typedef R StubFunctionType(const void*, P ...); \\\n\n Mocker(FunctionType function, const std::string& functionName): \\\n\n MockerBase<StubFunctionType>(functionName), \\\n\n originFunction(function) { \\\n\n SimpleSingleton<decltype(this)>::getInstance() = this; \\\n\n RuntimePatcher::GraftFunction(originFunction, \\\n\n &MockerEntryPoint<EntryPointType>::EntryPoint, \\\n\n MockerBase<StubFunctionType>::binaryBackup); \\\n\n } \\\n\n virtual ~Mocker() { \\\n\n RestoreToReal(); \\\n\n } \\\n\n virtual void RestoreToReal() { \\\n\n RuntimePatcher::RevertGraft(originFunction, MockerBase<StubFunctionType>::binaryBackup); \\\n\n SimpleSingleton<decltype(this)>::getInstance() = nullptr; \\\n\n } \\\n\n FunctionType originFunction; \\\n\n}\n\n\n\nMOCKER_WITH_THIS_POINTER_CHECK(const);\n\nMOCKER_WITH_THIS_POINTER_CHECK();\n\n\n\n#undef MOCKER_WITH_THIS_POINTER_CHECK\n\n\n\ntemplate < typename T >\n", "file_path": "third_party/CppFreeMock/cpp11/impl.h", "rank": 14, "score": 362285.64867171587 }, { "content": "class Move : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n Move(const Move&);\n\n Move& operator=(const Move&);\n\n Move() {\n\n }\n\n\n\n virtual ~Move() throw();\n\n TVector3 pos;\n\n TVector3 dir;\n\n TRotation rot;\n\n\n\n _Move__isset __isset;\n\n\n\n void __set_pos(const TVector3& val);\n\n\n\n void __set_dir(const TVector3& val);\n\n\n\n void __set_rot(const TRotation& val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 15, "score": 360204.1422631059 }, { "content": "class Cage : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n Cage(const Cage&);\n\n Cage& operator=(const Cage&);\n\n Cage() : uid(0), radius(0), captureTime(0) {\n\n }\n\n\n\n virtual ~Cage() throw();\n\n int32_t uid;\n\n TVector3 center;\n\n int32_t radius;\n\n int32_t captureTime;\n\n\n\n _Cage__isset __isset;\n\n\n\n void __set_uid(const int32_t val);\n\n\n\n void __set_center(const TVector3& val);\n\n\n", "file_path": "example/common/proto/struct_types.h", "rank": 16, "score": 360204.14226310584 }, { "content": "class Revive : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n Revive(const Revive&);\n\n Revive& operator=(const Revive&);\n\n Revive() : bornId(0) {\n\n }\n\n\n\n virtual ~Revive() throw();\n\n int32_t bornId;\n\n TVector3 bornPos;\n\n\n\n _Revive__isset __isset;\n\n\n\n void __set_bornId(const int32_t val);\n\n\n\n void __set_bornPos(const TVector3& val);\n\n\n\n bool operator == (const Revive & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 17, "score": 360204.1422631059 }, { "content": "class Line : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n Line(const Line&);\n\n Line& operator=(const Line&);\n\n Line() : uid(0), casterId(0), isEnd(0), lineType((LineType::type)0) {\n\n }\n\n\n\n virtual ~Line() throw();\n\n int32_t uid;\n\n int32_t casterId;\n\n std::vector<TVector3> points;\n\n bool isEnd;\n\n LineType::type lineType;\n\n\n\n _Line__isset __isset;\n\n\n\n void __set_uid(const int32_t val);\n\n\n\n void __set_casterId(const int32_t val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 18, "score": 360204.1422631059 }, { "content": "class Bullet : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n Bullet(const Bullet&);\n\n Bullet& operator=(const Bullet&);\n\n Bullet() : uid(0), casterId(0) {\n\n }\n\n\n\n virtual ~Bullet() throw();\n\n int32_t uid;\n\n int32_t casterId;\n\n TVector3 pos;\n\n TVector3 dir;\n\n\n\n _Bullet__isset __isset;\n\n\n\n void __set_uid(const int32_t val);\n\n\n\n void __set_casterId(const int32_t val);\n\n\n", "file_path": "example/common/proto/struct_types.h", "rank": 19, "score": 360204.1422631059 }, { "content": "class Bounds : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n Bounds(const Bounds&);\n\n Bounds& operator=(const Bounds&);\n\n Bounds() {\n\n }\n\n\n\n virtual ~Bounds() throw();\n\n TVector3 center;\n\n TVector3 size;\n\n\n\n _Bounds__isset __isset;\n\n\n\n void __set_center(const TVector3& val);\n\n\n\n void __set_size(const TVector3& val);\n\n\n\n bool operator == (const Bounds & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 20, "score": 360204.14226310584 }, { "content": "class FooTest : public ::testing::TestWithParam<const char*> {\n\n // You can implement all the usual class fixture members here.\n\n};\n\n\n\n// Then, use the TEST_P macro to define as many parameterized tests\n\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n\n// or \"pattern\", whichever you prefer to think.\n\n\n\nTEST_P(FooTest, DoesBlah) {\n\n // Inside a test, access the test parameter with the GetParam() method\n\n // of the TestWithParam<T> class:\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n ...\n\n}\n\n\n\nTEST_P(FooTest, HasBlahBlah) {\n\n ...\n\n}\n\n\n\n// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test\n", "file_path": "third_party/googletest-release-1.8.0/googletest/include/gtest/gtest-param-test.h", "rank": 21, "score": 354929.3783043404 }, { "content": "class DelBuff : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n DelBuff(const DelBuff&);\n\n DelBuff& operator=(const DelBuff&);\n\n DelBuff() : id(0) {\n\n }\n\n\n\n virtual ~DelBuff() throw();\n\n int32_t id;\n\n\n\n _DelBuff__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n bool operator == (const DelBuff & rhs) const\n\n {\n\n if (!(id == rhs.id))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 22, "score": 354514.8002913601 }, { "content": "class AccountData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n AccountData(const AccountData&);\n\n AccountData& operator=(const AccountData&);\n\n AccountData() : id(0), sessionKey(), channel(), openId(), lastLoginTime(0) {\n\n }\n\n\n\n virtual ~AccountData() throw();\n\n int32_t id;\n\n std::string sessionKey;\n\n std::string channel;\n\n std::string openId;\n\n int64_t lastLoginTime;\n\n\n\n _AccountData__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n void __set_sessionKey(const std::string& val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 23, "score": 354514.8002913601 }, { "content": "class TagSuccess : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n TagSuccess(const TagSuccess&);\n\n TagSuccess& operator=(const TagSuccess&);\n\n TagSuccess() : type(0) {\n\n }\n\n\n\n virtual ~TagSuccess() throw();\n\n int32_t type;\n\n TVector3 pos;\n\n\n\n _TagSuccess__isset __isset;\n\n\n\n void __set_type(const int32_t val);\n\n\n\n void __set_pos(const TVector3& val);\n\n\n\n bool operator == (const TagSuccess & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 24, "score": 354514.8002913601 }, { "content": "class TVector3 : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n TVector3(const TVector3&);\n\n TVector3& operator=(const TVector3&);\n\n TVector3() : x(0), y(0), z(0) {\n\n }\n\n\n\n virtual ~TVector3() throw();\n\n int32_t x;\n\n int32_t y;\n\n int32_t z;\n\n\n\n _TVector3__isset __isset;\n\n\n\n void __set_x(const int32_t val);\n\n\n\n void __set_y(const int32_t val);\n\n\n\n void __set_z(const int32_t val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 25, "score": 354514.8002913601 }, { "content": "class StateMaps : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n StateMaps(const StateMaps&);\n\n StateMaps& operator=(const StateMaps&);\n\n StateMaps() {\n\n }\n\n\n\n virtual ~StateMaps() throw();\n\n std::map<int32_t, bool> bools;\n\n std::map<int32_t, int32_t> ints;\n\n std::map<int32_t, double> decimals;\n\n std::map<int32_t, TVector3> vectors;\n\n\n\n _StateMaps__isset __isset;\n\n\n\n void __set_bools(const std::map<int32_t, bool> & val);\n\n\n\n void __set_ints(const std::map<int32_t, int32_t> & val);\n\n\n", "file_path": "example/common/proto/struct_types.h", "rank": 26, "score": 354514.8002913601 }, { "content": "class TRotation : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n TRotation(const TRotation&);\n\n TRotation& operator=(const TRotation&);\n\n TRotation() : x(0), y(0), z(0), w(0) {\n\n }\n\n\n\n virtual ~TRotation() throw();\n\n int32_t x;\n\n int32_t y;\n\n int32_t z;\n\n int32_t w;\n\n\n\n _TRotation__isset __isset;\n\n\n\n void __set_x(const int32_t val);\n\n\n\n void __set_y(const int32_t val);\n\n\n", "file_path": "example/common/proto/struct_types.h", "rank": 27, "score": 354514.8002913601 }, { "content": "class RoleData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n RoleData(const RoleData&);\n\n RoleData& operator=(const RoleData&);\n\n RoleData() : shipId(0), shipConfigId(0) {\n\n }\n\n\n\n virtual ~RoleData() throw();\n\n int32_t shipId;\n\n int32_t shipConfigId;\n\n\n\n _RoleData__isset __isset;\n\n\n\n void __set_shipId(const int32_t val);\n\n\n\n void __set_shipConfigId(const int32_t val);\n\n\n\n bool operator == (const RoleData & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 28, "score": 354514.8002913601 }, { "content": "class MoveStop : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n MoveStop(const MoveStop&);\n\n MoveStop& operator=(const MoveStop&);\n\n MoveStop() {\n\n }\n\n\n\n virtual ~MoveStop() throw();\n\n TVector3 pos;\n\n TRotation rot;\n\n\n\n _MoveStop__isset __isset;\n\n\n\n void __set_pos(const TVector3& val);\n\n\n\n void __set_rot(const TRotation& val);\n\n\n\n bool operator == (const MoveStop & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 29, "score": 354514.8002913601 }, { "content": "class SyncLine : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SyncLine(const SyncLine&);\n\n SyncLine& operator=(const SyncLine&);\n\n SyncLine() {\n\n }\n\n\n\n virtual ~SyncLine() throw();\n\n std::vector<Line> lineList;\n\n\n\n _SyncLine__isset __isset;\n\n\n\n void __set_lineList(const std::vector<Line> & val);\n\n\n\n bool operator == (const SyncLine & rhs) const\n\n {\n\n if (!(lineList == rhs.lineList))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 30, "score": 354514.8002913601 }, { "content": "class RoomData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n RoomData(const RoomData&);\n\n RoomData& operator=(const RoomData&);\n\n RoomData() : id(0), name(), pattern(0), playerCount(0), playerMaxCount(0) {\n\n }\n\n\n\n virtual ~RoomData() throw();\n\n int32_t id;\n\n std::string name;\n\n int32_t pattern;\n\n int32_t playerCount;\n\n int32_t playerMaxCount;\n\n\n\n _RoomData__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n void __set_name(const std::string& val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 31, "score": 354514.8002913601 }, { "content": "class UserData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UserData(const UserData&);\n\n UserData& operator=(const UserData&);\n\n UserData() : userId(0), userAccount(), userPassword() {\n\n }\n\n\n\n virtual ~UserData() throw();\n\n int32_t userId;\n\n std::string userAccount;\n\n std::string userPassword;\n\n RoleData roleData;\n\n\n\n _UserData__isset __isset;\n\n\n\n void __set_userId(const int32_t val);\n\n\n\n void __set_userAccount(const std::string& val);\n\n\n", "file_path": "example/common/proto/struct_types.h", "rank": 32, "score": 354514.8002913601 }, { "content": "class KillDead : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n KillDead(const KillDead&);\n\n KillDead& operator=(const KillDead&);\n\n KillDead() : killerId(0) {\n\n }\n\n\n\n virtual ~KillDead() throw();\n\n int32_t killerId;\n\n\n\n _KillDead__isset __isset;\n\n\n\n void __set_killerId(const int32_t val);\n\n\n\n bool operator == (const KillDead & rhs) const\n\n {\n\n if (!(killerId == rhs.killerId))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 33, "score": 354514.8002913601 }, { "content": "class DropSkill : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n DropSkill(const DropSkill&);\n\n DropSkill& operator=(const DropSkill&);\n\n DropSkill() : skillId(0), isA(0) {\n\n }\n\n\n\n virtual ~DropSkill() throw();\n\n int32_t skillId;\n\n bool isA;\n\n\n\n _DropSkill__isset __isset;\n\n\n\n void __set_skillId(const int32_t val);\n\n\n\n void __set_isA(const bool val);\n\n\n\n bool operator == (const DropSkill & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 34, "score": 354514.8002913601 }, { "content": "class SyncBullet : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SyncBullet(const SyncBullet&);\n\n SyncBullet& operator=(const SyncBullet&);\n\n SyncBullet() {\n\n }\n\n\n\n virtual ~SyncBullet() throw();\n\n std::vector<Bullet> bulletList;\n\n\n\n _SyncBullet__isset __isset;\n\n\n\n void __set_bulletList(const std::vector<Bullet> & val);\n\n\n\n bool operator == (const SyncBullet & rhs) const\n\n {\n\n if (!(bulletList == rhs.bulletList))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 35, "score": 354514.8002913601 }, { "content": "class SyncData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SyncData(const SyncData&);\n\n SyncData& operator=(const SyncData&);\n\n SyncData() : uid(0), syncType((SyncDataType::type)0) {\n\n }\n\n\n\n virtual ~SyncData() throw();\n\n int32_t uid;\n\n SyncDataType::type syncType;\n\n UnitSyncData unitStatus;\n\n Move move;\n\n MoveStop moveStop;\n\n UseSkill userSkill;\n\n KillDead killDead;\n\n SyncBullet bullet;\n\n SyncLine line;\n\n Cage cage;\n\n Revive revive;\n", "file_path": "example/common/proto/struct_types.h", "rank": 36, "score": 354514.8002913601 }, { "content": "class InstantiateData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n InstantiateData(const InstantiateData&);\n\n InstantiateData& operator=(const InstantiateData&);\n\n InstantiateData() : uid(0), creator(0), type((ObjType::type)0) {\n\n }\n\n\n\n virtual ~InstantiateData() throw();\n\n int32_t uid;\n\n int32_t creator;\n\n ObjType::type type;\n\n TVector3 pos;\n\n TRotation rot;\n\n std::vector<int32_t> argvs;\n\n TVector3 casterPos;\n\n\n\n _InstantiateData__isset __isset;\n\n\n\n void __set_uid(const int32_t val);\n", "file_path": "example/common/proto/struct_types.h", "rank": 37, "score": 354514.8002913601 }, { "content": "class TriggerMagic : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n TriggerMagic(const TriggerMagic&);\n\n TriggerMagic& operator=(const TriggerMagic&);\n\n TriggerMagic() : magicId(0) {\n\n }\n\n\n\n virtual ~TriggerMagic() throw();\n\n int32_t magicId;\n\n\n\n _TriggerMagic__isset __isset;\n\n\n\n void __set_magicId(const int32_t val);\n\n\n\n bool operator == (const TriggerMagic & rhs) const\n\n {\n\n if (!(magicId == rhs.magicId))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 38, "score": 354514.8002913601 }, { "content": "class PlayerData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n PlayerData(const PlayerData&);\n\n PlayerData& operator=(const PlayerData&);\n\n PlayerData() : userId(0), nickname(), faction(0), classType((ClassType::type)0), shipId(0), position(0), playerId(0), shipLevel(0), skillSlotCount(0), bulletCount(0) {\n\n }\n\n\n\n virtual ~PlayerData() throw();\n\n int32_t userId;\n\n std::string nickname;\n\n int32_t faction;\n\n ClassType::type classType;\n\n int32_t shipId;\n\n int32_t position;\n\n int32_t playerId;\n\n int32_t shipLevel;\n\n int32_t skillSlotCount;\n\n std::vector<int32_t> uniqueSkills;\n\n int32_t bulletCount;\n", "file_path": "example/common/proto/struct_types.h", "rank": 39, "score": 354514.8002913601 }, { "content": "class AddBuff : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n AddBuff(const AddBuff&);\n\n AddBuff& operator=(const AddBuff&);\n\n AddBuff() : id(0) {\n\n }\n\n\n\n virtual ~AddBuff() throw();\n\n int32_t id;\n\n\n\n _AddBuff__isset __isset;\n\n\n\n void __set_id(const int32_t val);\n\n\n\n bool operator == (const AddBuff & rhs) const\n\n {\n\n if (!(id == rhs.id))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 40, "score": 354514.8002913601 }, { "content": "class MovementData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n MovementData(const MovementData&);\n\n MovementData& operator=(const MovementData&);\n\n MovementData() {\n\n }\n\n\n\n virtual ~MovementData() throw();\n\n TVector3 moveDir;\n\n TVector3 facingDir;\n\n\n\n _MovementData__isset __isset;\n\n\n\n void __set_moveDir(const TVector3& val);\n\n\n\n void __set_facingDir(const TVector3& val);\n\n\n\n bool operator == (const MovementData & rhs) const\n\n {\n", "file_path": "example/common/proto/struct_types.h", "rank": 41, "score": 354514.8002913601 }, { "content": "class GetItem : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n GetItem(const GetItem&);\n\n GetItem& operator=(const GetItem&);\n\n GetItem() : itemUid(0) {\n\n }\n\n\n\n virtual ~GetItem() throw();\n\n int32_t itemUid;\n\n\n\n _GetItem__isset __isset;\n\n\n\n void __set_itemUid(const int32_t val);\n\n\n\n bool operator == (const GetItem & rhs) const\n\n {\n\n if (!(itemUid == rhs.itemUid))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 42, "score": 354514.8002913601 }, { "content": "class SCServerInfo : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SCServerInfo(const SCServerInfo&);\n\n SCServerInfo& operator=(const SCServerInfo&);\n\n SCServerInfo() : currentServerTime(0) {\n\n }\n\n\n\n virtual ~SCServerInfo() throw();\n\n int64_t currentServerTime;\n\n\n\n _SCServerInfo__isset __isset;\n\n\n\n void __set_currentServerTime(const int64_t val);\n\n\n\n bool operator == (const SCServerInfo & rhs) const\n\n {\n\n if (!(currentServerTime == rhs.currentServerTime))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/message_types.h", "rank": 43, "score": 349307.2244941768 }, { "content": "class UnitSyncData : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n UnitSyncData(const UnitSyncData&);\n\n UnitSyncData& operator=(const UnitSyncData&);\n\n UnitSyncData() {\n\n }\n\n\n\n virtual ~UnitSyncData() throw();\n\n StateMaps states;\n\n\n\n _UnitSyncData__isset __isset;\n\n\n\n void __set_states(const StateMaps& val);\n\n\n\n bool operator == (const UnitSyncData & rhs) const\n\n {\n\n if (!(states == rhs.states))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/struct_types.h", "rank": 44, "score": 349061.1563594712 }, { "content": "class PlayerOperateCommand : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n PlayerOperateCommand(const PlayerOperateCommand&);\n\n PlayerOperateCommand& operator=(const PlayerOperateCommand&);\n\n PlayerOperateCommand() : uid(0), type((OperateCmdType::type)0), argv1(0), argv2(0), argv3(0) {\n\n }\n\n\n\n virtual ~PlayerOperateCommand() throw();\n\n int32_t uid;\n\n OperateCmdType::type type;\n\n TVector3 moveDir;\n\n int32_t argv1;\n\n int32_t argv2;\n\n int32_t argv3;\n\n\n\n _PlayerOperateCommand__isset __isset;\n\n\n\n void __set_uid(const int32_t val);\n\n\n", "file_path": "example/common/proto/struct_types.h", "rank": 45, "score": 349061.1563594712 }, { "content": " class SCServerInfo_Msg : public Proto\n\n {\n\n using this_t = SCServerInfo_Msg;\n\n using base_t = Proto;\n\n public:\n\n SCServerInfo_Msg()\n\n : base_t(ProtoId())\n\n {\n\n }\n\n msg_ptr pack() const\n\n {\n\n return pack_msg(scServerInfo);\n\n }\n\n void pack(stream_t& gos) const\n\n {\n\n pack_msg(gos, scServerInfo);\n\n }\n\n void unpack(msg_ptr& msgp) override\n\n {\n\n scServerInfo = unpack_msg<SCServerInfo>(msgp);\n", "file_path": "example/common/proto/message_actions.hpp", "rank": 46, "score": 348628.86616567423 }, { "content": "class TypedTestP : public Test {\n\n};\n\n\n\nTYPED_TEST_CASE_P(TypedTestP);\n\n\n\nTYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {\n\n FAIL() << \"Unexpected failure: \"\n\n << \"Disabled type-parameterized test should not run.\";\n\n}\n\n\n\nREGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun);\n\n\n\nINSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes);\n\n\n\ntemplate <typename T>\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest_unittest.cc", "rank": 47, "score": 344386.6947664041 }, { "content": "struct TestStaticMemberFunction : public ::testing::Test {\n\n TestStaticMemberFunction():\n\n boolValue(false),\n\n charValue('0'),\n\n intValue(0),\n\n stringValue(\"\"),\n\n stringConstValue(\"HELLO\") { }\n\n virtual void SetUp() { }\n\n virtual void TearDown() {\n\n CLEAR_MOCKER();\n\n }\n\n\n\n static string func0Parameter() {\n\n return \"Non mocked.\";\n\n }\n\n\n\n static string func0Parameter2() {\n\n return \"Non mocked.\";\n\n }\n\n\n", "file_path": "third_party/CppFreeMock/example/test_static_member_function.cpp", "rank": 48, "score": 342757.5777305533 }, { "content": "class DISABLED_TypedTestP : public Test {\n\n};\n\n\n\nTYPED_TEST_CASE_P(DISABLED_TypedTestP);\n\n\n\nTYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {\n\n FAIL() << \"Unexpected failure: \"\n\n << \"Disabled type-parameterized test should not run.\";\n\n}\n\n\n\nREGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun);\n\n\n\nINSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes);\n\n\n\n#endif // GTEST_HAS_TYPED_TEST_P\n\n\n\n// Tests that assertion macros evaluate their arguments exactly once.\n\n\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest_unittest.cc", "rank": 49, "score": 340533.4770954326 }, { "content": " class VirtualDerived : public virtual Base {};\n", "file_path": "third_party/googletest-release-1.8.0/googlemock/test/gmock-matchers_test.cc", "rank": 50, "score": 338637.5576506632 }, { "content": "class TypedTestCasePStateTest : public Test {\n\n protected:\n\n virtual void SetUp() {\n\n state_.AddTestName(\"foo.cc\", 0, \"FooTest\", \"A\");\n\n state_.AddTestName(\"foo.cc\", 0, \"FooTest\", \"B\");\n\n state_.AddTestName(\"foo.cc\", 0, \"FooTest\", \"C\");\n\n }\n\n\n\n TypedTestCasePState state_;\n\n};\n\n\n\nTEST_F(TypedTestCasePStateTest, SucceedsForMatchingList) {\n\n const char* tests = \"A, B, C\";\n\n EXPECT_EQ(tests,\n\n state_.VerifyRegisteredTestNames(\"foo.cc\", 1, tests));\n\n}\n\n\n\n// Makes sure that the order of the tests and spaces around the names\n\n// don't matter.\n\nTEST_F(TypedTestCasePStateTest, IgnoresOrderAndSpaces) {\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest-typed-test_test.cc", "rank": 51, "score": 336878.68943140446 }, { "content": "class TypedTestP : public testing::Test {\n\n};\n\n\n\nTYPED_TEST_CASE_P(TypedTestP);\n\n\n\nTYPED_TEST_P(TypedTestP, Success) {\n\n EXPECT_EQ(0U, TypeParam());\n\n}\n\n\n\nTYPED_TEST_P(TypedTestP, Failure) {\n\n EXPECT_EQ(1U, TypeParam()) << \"Expected failure\";\n\n}\n\n\n\nREGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure);\n\n\n\ntypedef testing::Types<unsigned char, unsigned int> UnsignedTypes;\n\nINSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes);\n\n\n\n#endif // GTEST_HAS_TYPED_TEST_P\n\n\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest_output_test_.cc", "rank": 52, "score": 333906.765521004 }, { "content": "class FooTest : public testing::Test {\n\n ...\n\n};\n\n\n\n// Next, declare that you will define a type-parameterized test case\n\n// (the _P suffix is for \"parameterized\" or \"pattern\", whichever you\n\n// prefer):\n\nTYPED_TEST_CASE_P(FooTest);\n\n\n\n// Then, use TYPED_TEST_P() to define as many type-parameterized tests\n\n// for this type-parameterized test case as you want.\n\nTYPED_TEST_P(FooTest, DoesBlah) {\n\n // Inside a test, refer to TypeParam to get the type parameter.\n\n TypeParam n = 0;\n\n ...\n\n}\n\n\n\nTYPED_TEST_P(FooTest, HasPropertyA) { ... }\n\n\n\n// Now the tricky part: you need to register all test patterns before\n", "file_path": "third_party/googletest-release-1.8.0/googletest/include/gtest/gtest-typed-test.h", "rank": 53, "score": 333532.57163358014 }, { "content": "class BaseTest : public ::testing::Test {\n\n // You can inherit all the usual members for a non-parameterized test\n\n // fixture here.\n\n};\n\n\n", "file_path": "third_party/googletest-release-1.8.0/googletest/include/gtest/gtest-param-test.h", "rank": 54, "score": 333532.57163358014 }, { "content": "class TestWithParam : public Test, public WithParamInterface<T> {\n\n};\n\n\n\n#endif // GTEST_HAS_PARAM_TEST\n\n\n\n// Macros for indicating success/failure in test code.\n\n\n\n// ADD_FAILURE unconditionally adds a failure to the current test.\n\n// SUCCEED generates a success - it doesn't automatically make the\n\n// current test successful, as a test is only successful when it has\n\n// no failure.\n\n//\n\n// EXPECT_* verifies that a certain condition is satisfied. If not,\n\n// it behaves like ADD_FAILURE. In particular:\n\n//\n\n// EXPECT_TRUE verifies that a Boolean condition is true.\n\n// EXPECT_FALSE verifies that a Boolean condition is false.\n\n//\n\n// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except\n\n// that they will also abort the current function on failure. People\n", "file_path": "third_party/googletest-release-1.8.0/googletest/include/gtest/gtest.h", "rank": 55, "score": 332010.08763729705 }, { "content": "struct TypeHelper<ValueType, const typename ValueType::Ch*> {\n\n typedef const typename ValueType::Ch* StringType;\n\n static bool Is(const ValueType& v) { return v.IsString(); }\n\n static StringType Get(const ValueType& v) { return v.GetString(); }\n\n static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); }\n\n static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }\n\n};\n\n\n\n#if RAPIDJSON_HAS_STDSTRING\n\ntemplate<typename ValueType> \n", "file_path": "third_party/rapidjson/include/rapidjson/document.h", "rank": 56, "score": 331207.49429411173 }, { "content": "class SetErrnoAndReturnTest : public testing::Test {\n\n protected:\n\n virtual void SetUp() { errno = 0; }\n\n virtual void TearDown() { errno = 0; }\n\n};\n\n\n\nTEST_F(SetErrnoAndReturnTest, Int) {\n\n Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);\n\n EXPECT_EQ(-5, a.Perform(make_tuple()));\n\n EXPECT_EQ(ENOTTY, errno);\n\n}\n\n\n\nTEST_F(SetErrnoAndReturnTest, Ptr) {\n\n int x;\n\n Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);\n\n EXPECT_EQ(&x, a.Perform(make_tuple()));\n\n EXPECT_EQ(ENOTTY, errno);\n\n}\n\n\n\nTEST_F(SetErrnoAndReturnTest, CompatibleTypes) {\n", "file_path": "third_party/googletest-release-1.8.0/googlemock/test/gmock-actions_test.cc", "rank": 57, "score": 330497.37560824014 }, { "content": " class server_application_impl_ : public application_impl\n\n {\n\n public:\n\n\n\n // callback for app code\n\n typedef csbl::function< int (void) > mainop;\n\n\n\n // string types to be used internaly to handle unicode on windows\n\n typedef CharType char_type;\n\n typedef std::basic_string<char_type> string_type;\n\n\n\n server_application_impl_(const mainop &main, signal_binder &sb,\n\n application::context &context, boost::system::error_code& ec)\n\n : application_impl(context)\n\n , main_(main)\n\n {\n\n // ver 1\n\n#if defined( USE_DAEMONIZE_VER_1 )\n\n process_id_ = daemonize(ec);\n\n#else \n", "file_path": "third_party/Boost.Application/include/boost/application/detail/posix/server_application_impl.hpp", "rank": 58, "score": 327121.9810982404 }, { "content": " class server_application_impl_ : public application_impl\n\n {\n\n public:\n\n\n\n // callback for app code\n\n typedef csbl::function< int (void) > mainop;\n\n\n\n // string types to be used internaly to handle unicode on windows\n\n typedef CharType char_type;\n\n typedef std::basic_string<char_type> string_type;\n\n\n\n server_application_impl_(const mainop &main_op, signal_binder &sb,\n\n application::context &context, boost::system::error_code& ec)\n\n : application_impl(context)\n\n , main_(main_op)\n\n , launch_thread_(0)\n\n , result_code_(0)\n\n , terminate_event_(0)\n\n , terminate_code_(0)\n\n {\n", "file_path": "third_party/Boost.Application/include/boost/application/detail/windows/server_application_impl.hpp", "rank": 59, "score": 327121.9810982405 }, { "content": "class TVirtualProtocol : public Super_ {\n\npublic:\n\n /**\n\n * Writing functions.\n\n */\n\n\n\n virtual uint32_t writeMessageBegin_virt(const std::string& name,\n\n const TMessageType messageType,\n\n const int32_t seqid) {\n\n return static_cast<Protocol_*>(this)->writeMessageBegin(name, messageType, seqid);\n\n }\n\n\n\n virtual uint32_t writeMessageEnd_virt() {\n\n return static_cast<Protocol_*>(this)->writeMessageEnd();\n\n }\n\n\n\n virtual uint32_t writeStructBegin_virt(const char* name) {\n\n return static_cast<Protocol_*>(this)->writeStructBegin(name);\n\n }\n\n\n", "file_path": "third_party/thrift-0.10.0_linux/thrift/protocol/TVirtualProtocol.h", "rank": 60, "score": 323507.60577637935 }, { "content": "class FooTest : public ::testing::TestWithParam<const char*> {\n\n // You can implement all the usual class fixture members here.\n\n};\n\n\n\n// Then, use the TEST_P macro to define as many parameterized tests\n\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n\n// or \"pattern\", whichever you prefer to think.\n\n\n\nTEST_P(FooTest, DoesBlah) {\n\n // Inside a test, access the test parameter with the GetParam() method\n\n // of the TestWithParam<T> class:\n\n EXPECT_TRUE(foo.Blah(GetParam()));\n\n ...\n\n}\n\n\n\nTEST_P(FooTest, HasBlahBlah) {\n\n ...\n\n}\n\n\n\n// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test\n", "file_path": "third_party/fmt/test/gtest/gtest.h", "rank": 61, "score": 322067.10657038615 }, { "content": "", "file_path": "network/gameserver/server_manager.hpp", "rank": 62, "score": 320123.1647521908 }, { "content": "", "file_path": "network/gameserver/game_server.hpp", "rank": 63, "score": 320123.1647521908 }, { "content": "class DefaultValue<void> {\n\n public:\n\n static bool Exists() { return true; }\n\n static void Get() {}\n\n};\n\n\n\n// Points to the user-set default value for type T.\n\ntemplate <typename T>\n\nconst T* DefaultValue<T>::value_ = NULL;\n\n\n\n// Points to the user-set default value for type T&.\n\ntemplate <typename T>\n\nT* DefaultValue<T&>::address_ = NULL;\n\n\n\n// Implement this interface to define an action for function type F.\n\ntemplate <typename F>\n", "file_path": "third_party/fmt/test/gmock/gmock.h", "rank": 64, "score": 314642.04400779895 }, { "content": " class game_server_base : public irouter_t\n\n {\n\n using this_t = game_server_base;\n\n public:\n\n game_server_base(server_unique_id unique_id)\n\n : unique_id_(unique_id)\n\n {\n\n\n\n }\n\n void init(const std::string& config_file_name = \"server_config.xml\")\n\n {\n\n world_[\"game_server\"] = this;\n\n world_[\"svc_manager\"] = &service_mgr_;\n\n\n\n //初始化内存池\n\n memory_pool::ins().init();\n\n\n\n //读取配置文件\n\n config_mgr_.init(config_file_name);\n\n config_mgr_.parse_real_ip(cytx::util::domain2ip);\n", "file_path": "network/gameserver/game_server_base.hpp", "rank": 65, "score": 312925.72655909095 }, { "content": "class EnableConstPtrType : public cytx::meta::MetaProperty { };\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n\n\n/** @brief Explicitly enables generation of the array type for this type.\n\n*/\n", "file_path": "network/reflect/MetaProperty.h", "rank": 66, "score": 309656.9839239806 }, { "content": " class battle_server_t : public game_server_t\n\n {\n\n using base_t = game_server_t;\n\n public:\n\n battle_server_t()\n\n : game_server_t(server_unique_id::battle_server)\n\n {}\n\n protected:\n\n void on_receive(connection_ptr& conn_ptr, const msg_ptr& msgp) override\n\n {\n\n base_t::on_receive(conn_ptr, msgp);\n\n }\n\n };\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char* argv[])\n\n{\n\n CytxGame::battle_server_t server;\n\n server.init();\n\n server.start();\n\n}", "file_path": "example/battle_server/battle_server.cpp", "rank": 67, "score": 309517.8325743972 }, { "content": " class center_server_t : public game_server_t\n\n {\n\n using base_t = game_server_t;\n\n public:\n\n center_server_t()\n\n : game_server_t(server_unique_id::center_server)\n\n {}\n\n protected:\n\n void on_receive(connection_ptr& conn_ptr, const msg_ptr& msgp) override\n\n {\n\n base_t::on_receive(conn_ptr, msgp);\n\n }\n\n };\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char* argv[])\n\n{\n\n CytxGame::center_server_t server;\n\n server.init();\n\n server.start();\n\n}", "file_path": "example/center_server/center_server.cpp", "rank": 68, "score": 309517.8325743972 }, { "content": " class room_server_t : public game_server_t\n\n {\n\n using base_t = game_server_t;\n\n public:\n\n room_server_t()\n\n : game_server_t(server_unique_id::room_server)\n\n {}\n\n protected:\n\n void on_receive(connection_ptr& conn_ptr, const msg_ptr& msgp) override\n\n {\n\n base_t::on_receive(conn_ptr, msgp);\n\n }\n\n };\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char* argv[])\n\n{\n\n CytxGame::room_server_t server;\n\n server.init();\n\n server.start();\n\n}", "file_path": "example/room_server/room_server.cpp", "rank": 69, "score": 309517.8325743972 }, { "content": "class TProtocolDefaults : public TProtocol {\n\npublic:\n\n uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid) {\n\n (void)name;\n\n (void)messageType;\n\n (void)seqid;\n\n throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,\n\n \"this protocol does not support reading (yet).\");\n\n }\n\n\n\n uint32_t readMessageEnd() {\n\n throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,\n\n \"this protocol does not support reading (yet).\");\n\n }\n\n\n\n uint32_t readStructBegin(std::string& name) {\n\n (void)name;\n\n throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,\n\n \"this protocol does not support reading (yet).\");\n\n }\n", "file_path": "third_party/thrift-0.10.0_linux/thrift/protocol/TVirtualProtocol.h", "rank": 70, "score": 308369.43187609955 }, { "content": "class SubClassOfTest : public Test {};\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest_unittest.cc", "rank": 71, "score": 308146.1272643873 }, { "content": "class AnotherSubClassOfTest : public Test {};\n\n\n\nTEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {\n\n EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());\n\n EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());\n\n EXPECT_NE(GetTypeId<int>(), GetTestTypeId());\n\n EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());\n\n EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());\n\n EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());\n\n}\n\n\n\n// Verifies that GetTestTypeId() returns the same value, no matter it\n\n// is called from inside Google Test or outside of it.\n\nTEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {\n\n EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());\n\n}\n\n\n\n// Tests FormatTimeInMillisAsSeconds().\n\n\n\nTEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest_unittest.cc", "rank": 72, "score": 305491.6578398917 }, { "content": "class ActionResultHolder<void> : public UntypedActionResultHolderBase {\n\n public:\n\n void GetValueAndDelete() const { delete this; }\n\n\n\n virtual void PrintAsActionResult(::std::ostream* /* os */) const {}\n\n\n\n // Performs the given mock function's default action and returns NULL;\n\n template <typename F>\n\n static ActionResultHolder* PerformDefaultAction(\n\n const FunctionMockerBase<F>* func_mocker,\n\n const typename Function<F>::ArgumentTuple& args,\n\n const string& call_description) {\n\n func_mocker->PerformDefaultAction(args, call_description);\n\n return NULL;\n\n }\n\n\n\n // Performs the given action and returns NULL.\n\n template <typename F>\n\n static ActionResultHolder* PerformAction(\n\n const Action<F>& action,\n\n const typename Function<F>::ArgumentTuple& args) {\n\n action.Perform(args);\n\n return NULL;\n\n }\n\n};\n\n\n\n// The base of the function mocker class for the given function type.\n\n// We put the methods in this class instead of its child to avoid code\n\n// bloat.\n\ntemplate <typename F>\n", "file_path": "third_party/fmt/test/gmock/gmock.h", "rank": 73, "score": 303388.92815098655 }, { "content": "struct TypeHelper<ValueType, typename ValueType::ConstObject> {\n\n typedef typename ValueType::ConstObject ObjectType;\n\n static bool Is(const ValueType& v) { return v.IsObject(); }\n\n static ObjectType Get(const ValueType& v) { return v.GetObject(); }\n\n};\n\n\n\n} // namespace internal\n\n\n\n// Forward declarations\n\ntemplate <bool, typename> class GenericArray;\n\ntemplate <bool, typename> class GenericObject;\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n// GenericValue\n\n\n\n//! Represents a JSON value. Use Value for UTF8 encoding and default allocator.\n\n/*!\n\n A JSON value can be one of 7 types. This class is a variant type supporting\n\n these types.\n\n\n\n Use the Value if UTF8 and default allocator\n\n\n\n \\tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)\n\n \\tparam Allocator Allocator type for allocating memory of object, array and string.\n\n*/\n\ntemplate <typename Encoding, typename Allocator = MemoryPoolAllocator<> > \n", "file_path": "third_party/rapidjson/include/rapidjson/document.h", "rank": 74, "score": 302381.6978443134 }, { "content": "struct TypeHelper<ValueType, typename ValueType::ConstArray> {\n\n typedef typename ValueType::ConstArray ArrayType;\n\n static bool Is(const ValueType& v) { return v.IsArray(); }\n\n static ArrayType Get(const ValueType& v) { return v.GetArray(); }\n\n};\n\n\n\ntemplate<typename ValueType> \n", "file_path": "third_party/rapidjson/include/rapidjson/document.h", "rank": 75, "score": 302381.69784431334 }, { "content": "class CSPing : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n CSPing(const CSPing&);\n\n CSPing& operator=(const CSPing&);\n\n CSPing() {\n\n }\n\n\n\n virtual ~CSPing() throw();\n\n\n\n bool operator == (const CSPing & /* rhs */) const\n\n {\n\n return true;\n\n }\n\n bool operator != (const CSPing &rhs) const {\n\n return !(*this == rhs);\n\n }\n\n\n\n bool operator < (const CSPing & ) const;\n\n\n", "file_path": "example/common/proto/message_types.h", "rank": 76, "score": 301871.79718695313 }, { "content": "class SCPing : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SCPing(const SCPing&);\n\n SCPing& operator=(const SCPing&);\n\n SCPing() : result(0) {\n\n }\n\n\n\n virtual ~SCPing() throw();\n\n int32_t result;\n\n\n\n _SCPing__isset __isset;\n\n\n\n void __set_result(const int32_t val);\n\n\n\n bool operator == (const SCPing & rhs) const\n\n {\n\n if (!(result == rhs.result))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/message_types.h", "rank": 77, "score": 301871.79718695313 }, { "content": "class SCInstantiate : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SCInstantiate(const SCInstantiate&);\n\n SCInstantiate& operator=(const SCInstantiate&);\n\n SCInstantiate() {\n\n }\n\n\n\n virtual ~SCInstantiate() throw();\n\n std::vector< ::InstantiateData> objList;\n\n\n\n _SCInstantiate__isset __isset;\n\n\n\n void __set_objList(const std::vector< ::InstantiateData> & val);\n\n\n\n bool operator == (const SCInstantiate & rhs) const\n\n {\n\n if (!(objList == rhs.objList))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/message_types.h", "rank": 78, "score": 301871.79718695313 }, { "content": "class DefaultValue<void> {\n\n public:\n\n static bool Exists() { return true; }\n\n static void Get() {}\n\n};\n\n\n\n// Points to the user-set default value for type T.\n\ntemplate <typename T>\n\ntypename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;\n\n\n\n// Points to the user-set default value for type T&.\n\ntemplate <typename T>\n\nT* DefaultValue<T&>::address_ = NULL;\n\n\n\n// Implement this interface to define an action for function type F.\n\ntemplate <typename F>\n", "file_path": "third_party/googletest-release-1.8.0/googlemock/include/gmock/gmock-actions.h", "rank": 79, "score": 301565.41020378156 }, { "content": "class TJSONProtocol : public TVirtualProtocol<TJSONProtocol> {\n\npublic:\n\n TJSONProtocol(boost::shared_ptr<TTransport> ptrans);\n\n\n\n ~TJSONProtocol();\n\n\n\nprivate:\n\n void pushContext(boost::shared_ptr<TJSONContext> c);\n\n\n\n void popContext();\n\n\n\n uint32_t writeJSONEscapeChar(uint8_t ch);\n\n\n\n uint32_t writeJSONChar(uint8_t ch);\n\n\n\n uint32_t writeJSONString(const std::string& str);\n\n\n\n uint32_t writeJSONBase64(const std::string& str);\n\n\n\n template <typename NumberType>\n", "file_path": "third_party/thrift-0.10.0_linux/thrift/protocol/TJSONProtocol.h", "rank": 80, "score": 301015.0140505 }, { "content": "struct TypeHelper<ValueType, bool> {\n\n static bool Is(const ValueType& v) { return v.IsBool(); }\n\n static bool Get(const ValueType& v) { return v.GetBool(); }\n\n static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); }\n\n static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); }\n\n};\n\n\n\ntemplate<typename ValueType> \n", "file_path": "third_party/rapidjson/include/rapidjson/document.h", "rank": 82, "score": 300362.8992771861 }, { "content": "class CustomStructNamingTest : public TestWithParam<CustomStruct> {};\n\n\n\nTEST_P(CustomStructNamingTest, TestsReportCorrectNames) {\n\n const ::testing::TestInfo* const test_info =\n\n ::testing::UnitTest::GetInstance()->current_test_info();\n\n Message test_name_stream;\n\n test_name_stream << \"TestsReportCorrectNames/\" << GetParam();\n\n EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());\n\n}\n\n\n\nINSTANTIATE_TEST_CASE_P(PrintToString,\n\n CustomStructNamingTest,\n\n Values(CustomStruct(0), CustomStruct(1)),\n\n ::testing::PrintToStringParamName());\n\n\n\n// Test that using a stateful parameter naming function works as expected.\n\n\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest-param-test_test.cc", "rank": 83, "score": 300280.8068136527 }, { "content": "class ContainerTest : public Test {\n\n};\n\n\n\nTYPED_TEST_CASE_P(ContainerTest);\n\n\n\nTYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) {\n\n TypeParam container;\n\n}\n\n\n\nTYPED_TEST_P(ContainerTest, InitialSizeIsZero) {\n\n TypeParam container;\n\n EXPECT_EQ(0U, container.size());\n\n}\n\n\n\nREGISTER_TYPED_TEST_CASE_P(ContainerTest,\n\n CanBeDefaultConstructed, InitialSizeIsZero);\n\n\n\n#endif // GTEST_HAS_TYPED_TEST_P\n\n\n\n#endif // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest-typed-test_test.h", "rank": 84, "score": 299668.59715552116 }, { "content": "class IsNotZero : public ActionInterface<bool(int)> { // NOLINT\n\n public:\n\n virtual bool Perform(const tuple<int>& arg) {\n\n return get<0>(arg) != 0;\n\n }\n\n};\n\n\n\n#if !GTEST_OS_SYMBIAN\n\n// Compiling this test on Nokia's Symbian compiler fails with:\n\n// 'Result' is not a member of class 'testing::internal::Function<int>'\n\n// (point of instantiation: '@unnamed@gmock_actions_test_cc@::\n\n// ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')\n\n// with no obvious fix.\n\nTEST(ActionTest, CanBeConvertedToOtherActionType) {\n\n const Action<bool(int)> a1(new IsNotZero); // NOLINT\n\n const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT\n\n EXPECT_EQ(1, a2.Perform(make_tuple('a')));\n\n EXPECT_EQ(0, a2.Perform(make_tuple('\\0')));\n\n}\n\n#endif // !GTEST_OS_SYMBIAN\n\n\n\n// The following two classes are for testing MakePolymorphicAction().\n\n\n", "file_path": "third_party/googletest-release-1.8.0/googlemock/test/gmock-actions_test.cc", "rank": 85, "score": 298826.821424276 }, { "content": "class A : public Test {};\n\nTEST_F(A, A) {}\n\nTEST_F(A, B) {}\n\n\n\nTEST(ADeathTest, A) {}\n\nTEST(ADeathTest, B) {}\n\nTEST(ADeathTest, C) {}\n\n\n\nTEST(B, A) {}\n\nTEST(B, B) {}\n\nTEST(B, C) {}\n\nTEST(B, DISABLED_D) {}\n\nTEST(B, DISABLED_E) {}\n\n\n\nTEST(BDeathTest, A) {}\n\nTEST(BDeathTest, B) {}\n\n\n\nTEST(C, A) {}\n\nTEST(C, B) {}\n\nTEST(C, C) {}\n\nTEST(C, DISABLED_D) {}\n\n\n\nTEST(CDeathTest, A) {}\n\n\n\nTEST(DISABLED_D, A) {}\n\nTEST(DISABLED_D, DISABLED_B) {}\n\n\n", "file_path": "third_party/googletest-release-1.8.0/googletest/test/gtest_shuffle_test_.cc", "rank": 86, "score": 298373.92096708284 }, { "content": " class SCPing_Msg : public Proto\n\n {\n\n using this_t = SCPing_Msg;\n\n using base_t = Proto;\n\n public:\n\n SCPing_Msg()\n\n : base_t(ProtoId())\n\n {\n\n }\n\n msg_ptr pack() const\n\n {\n\n return pack_msg(scPing);\n\n }\n\n void pack(stream_t& gos) const\n\n {\n\n pack_msg(gos, scPing);\n\n }\n\n void unpack(msg_ptr& msgp) override\n\n {\n\n scPing = unpack_msg<SCPing>(msgp);\n", "file_path": "example/common/proto/message_actions.hpp", "rank": 87, "score": 297937.7839268918 }, { "content": " class CSPing_Msg : public Proto\n\n {\n\n using this_t = CSPing_Msg;\n\n using base_t = Proto;\n\n public:\n\n CSPing_Msg()\n\n : base_t(ProtoId())\n\n {\n\n }\n\n msg_ptr pack() const\n\n {\n\n return pack_msg(csPing);\n\n }\n\n void pack(stream_t& gos) const\n\n {\n\n pack_msg(gos, csPing);\n\n }\n\n void unpack(msg_ptr& msgp) override\n\n {\n\n csPing = unpack_msg<CSPing>(msgp);\n", "file_path": "example/common/proto/message_actions.hpp", "rank": 88, "score": 297937.7839268918 }, { "content": " class SCInstantiate_Msg : public Proto\n\n {\n\n using this_t = SCInstantiate_Msg;\n\n using base_t = Proto;\n\n public:\n\n SCInstantiate_Msg()\n\n : base_t(ProtoId())\n\n {\n\n }\n\n msg_ptr pack() const\n\n {\n\n return pack_msg(scInstantiate);\n\n }\n\n void pack(stream_t& gos) const\n\n {\n\n pack_msg(gos, scInstantiate);\n\n }\n\n void unpack(msg_ptr& msgp) override\n\n {\n\n scInstantiate = unpack_msg<SCInstantiate>(msgp);\n", "file_path": "example/common/proto/message_actions.hpp", "rank": 89, "score": 297937.7839268918 }, { "content": " class SCConnect_Msg : public Proto\n\n {\n\n using this_t = SCConnect_Msg;\n\n using base_t = Proto;\n\n public:\n\n SCConnect_Msg()\n\n : base_t(ProtoId())\n\n {\n\n }\n\n msg_ptr pack() const\n\n {\n\n return pack_msg();\n\n }\n\n void pack(stream_t& gos) const\n\n {\n\n }\n\n void unpack(msg_ptr& msgp) override\n\n {\n\n }\n\n\n\n public:\n\n static uint32_t ProtoId()\n\n {\n\n return ::MessageId::SC_Connect;\n\n }\n\n\n\n };\n\n\n", "file_path": "example/common/proto/message_actions.hpp", "rank": 90, "score": 297937.7839268918 }, { "content": "class SCRoomInfo : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SCRoomInfo(const SCRoomInfo&);\n\n SCRoomInfo& operator=(const SCRoomInfo&);\n\n SCRoomInfo() : roomId(0), masterId(0), roomSize(0), mathPattern(0) {\n\n }\n\n\n\n virtual ~SCRoomInfo() throw();\n\n int32_t roomId;\n\n int32_t masterId;\n\n std::vector< ::PlayerData> playerList;\n\n int32_t roomSize;\n\n int32_t mathPattern;\n\n\n\n _SCRoomInfo__isset __isset;\n\n\n\n void __set_roomId(const int32_t val);\n\n\n\n void __set_masterId(const int32_t val);\n", "file_path": "example/common/proto/message_types.h", "rank": 91, "score": 297508.6003318535 }, { "content": "class SLoginGame : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SLoginGame(const SLoginGame&);\n\n SLoginGame& operator=(const SLoginGame&);\n\n SLoginGame() : state(0), error() {\n\n }\n\n\n\n virtual ~SLoginGame() throw();\n\n bool state;\n\n std::string error;\n\n ::AccountData account;\n\n\n\n _SLoginGame__isset __isset;\n\n\n\n void __set_state(const bool val);\n\n\n\n void __set_error(const std::string& val);\n\n\n\n void __set_account(const ::AccountData& val);\n", "file_path": "example/common/proto/message_types.h", "rank": 92, "score": 297508.6003318535 }, { "content": "class CSCreateRoom : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n CSCreateRoom(const CSCreateRoom&);\n\n CSCreateRoom& operator=(const CSCreateRoom&);\n\n CSCreateRoom() : playerCount(0), matchPattern(0) {\n\n }\n\n\n\n virtual ~CSCreateRoom() throw();\n\n int32_t playerCount;\n\n int32_t matchPattern;\n\n\n\n _CSCreateRoom__isset __isset;\n\n\n\n void __set_playerCount(const int32_t val);\n\n\n\n void __set_matchPattern(const int32_t val);\n\n\n\n bool operator == (const CSCreateRoom & rhs) const\n\n {\n", "file_path": "example/common/proto/message_types.h", "rank": 93, "score": 297508.6003318535 }, { "content": "class CSJoinRoom : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n CSJoinRoom(const CSJoinRoom&);\n\n CSJoinRoom& operator=(const CSJoinRoom&);\n\n CSJoinRoom() : roomId(0) {\n\n }\n\n\n\n virtual ~CSJoinRoom() throw();\n\n int32_t roomId;\n\n\n\n _CSJoinRoom__isset __isset;\n\n\n\n void __set_roomId(const int32_t val);\n\n\n\n bool operator == (const CSJoinRoom & rhs) const\n\n {\n\n if (!(roomId == rhs.roomId))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/message_types.h", "rank": 94, "score": 297508.6003318535 }, { "content": "class SCJoinRoom : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SCJoinRoom(const SCJoinRoom&);\n\n SCJoinRoom& operator=(const SCJoinRoom&);\n\n SCJoinRoom() : result(0) {\n\n }\n\n\n\n virtual ~SCJoinRoom() throw();\n\n int32_t result;\n\n\n\n _SCJoinRoom__isset __isset;\n\n\n\n void __set_result(const int32_t val);\n\n\n\n bool operator == (const SCJoinRoom & rhs) const\n\n {\n\n if (!(result == rhs.result))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/message_types.h", "rank": 95, "score": 297508.6003318535 }, { "content": "class CSSwitchSeat : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n CSSwitchSeat(const CSSwitchSeat&);\n\n CSSwitchSeat& operator=(const CSSwitchSeat&);\n\n CSSwitchSeat() : playerId(0), targetPos(0) {\n\n }\n\n\n\n virtual ~CSSwitchSeat() throw();\n\n int32_t playerId;\n\n int32_t targetPos;\n\n\n\n _CSSwitchSeat__isset __isset;\n\n\n\n void __set_playerId(const int32_t val);\n\n\n\n void __set_targetPos(const int32_t val);\n\n\n\n bool operator == (const CSSwitchSeat & rhs) const\n\n {\n", "file_path": "example/common/proto/message_types.h", "rank": 96, "score": 297508.6003318535 }, { "content": "class CLoginGame : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n CLoginGame(const CLoginGame&);\n\n CLoginGame& operator=(const CLoginGame&);\n\n CLoginGame() : accountId(0), sessionKey() {\n\n }\n\n\n\n virtual ~CLoginGame() throw();\n\n int32_t accountId;\n\n std::string sessionKey;\n\n\n\n _CLoginGame__isset __isset;\n\n\n\n void __set_accountId(const int32_t val);\n\n\n\n void __set_sessionKey(const std::string& val);\n\n\n\n bool operator == (const CLoginGame & rhs) const\n\n {\n", "file_path": "example/common/proto/message_types.h", "rank": 97, "score": 297508.6003318535 }, { "content": "class SCCreateRoom : public virtual ::apache::thrift::TBase {\n\n public:\n\n\n\n SCCreateRoom(const SCCreateRoom&);\n\n SCCreateRoom& operator=(const SCCreateRoom&);\n\n SCCreateRoom() : result(0) {\n\n }\n\n\n\n virtual ~SCCreateRoom() throw();\n\n int32_t result;\n\n\n\n _SCCreateRoom__isset __isset;\n\n\n\n void __set_result(const int32_t val);\n\n\n\n bool operator == (const SCCreateRoom & rhs) const\n\n {\n\n if (!(result == rhs.result))\n\n return false;\n\n return true;\n", "file_path": "example/common/proto/message_types.h", "rank": 98, "score": 297508.6003318535 } ]
C++
ModuleObstacle.cpp
BravoXavi/Space-Harrier-MVJ-
cfc3d6f392b926faa0b88a2acb8c89db24a626d7
#include <math.h> #include "ModuleObstacle.h" #include "Application.h" #include "ModuleAudio.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleCollision.h" #include "ModuleParticles.h" #include "ModuleShadows.h" #include "ModulePlayer.h" #include "SDL/include/SDL_timer.h" ModuleObstacle::ModuleObstacle(bool active) : Module(active) {} ModuleObstacle::~ModuleObstacle() {} bool ModuleObstacle::Start() { LOG("Loading Obstacles"); graphics = App->textures->Load("assets/enemiesobstacles.png"); tree.anim.frames.push_back({ 206, 378, 40, 158 }); tree.worldPosition.z = MAX_Z; tree.colType = D_OBSTACLE; rock.anim.frames.push_back({ 192, 72, 59, 37 }); rock.worldPosition.z = MAX_Z; rock.colType = D_OBSTACLE; rock.shadowCast = true; bush.anim.frames.push_back({ 193, 8, 59, 41 }); bush.worldPosition.z = MAX_Z; bush.colType = NOLETHAL_D_OBSTACLE; return true; } bool ModuleObstacle::CleanUp() { LOG("Unloading particles"); App->textures->Unload(graphics); for (list<Obstacle*>::iterator it = active.begin(); it != active.end(); ++it) RELEASE(*it); active.clear(); return true; } update_status ModuleObstacle::PreUpdate() { for (list<Obstacle*>::iterator it = active.begin(); it != active.end();) { if ((*it)->to_delete == true) { RELEASE(*it); it = active.erase(it); } else ++it; } return UPDATE_CONTINUE; } update_status ModuleObstacle::Update() { for (list<Obstacle*>::iterator it = active.begin(); it != active.end(); ++it) { Obstacle* o = *it; if(!App->renderer->stopUpdating) o->Update(); if (o->shadowCast) App->shadows->DrawShadow(o->screenPosition.x, o->screenPosition.y, o->screenPosition.z, o->dataToBlit->newWidth); App->renderer->depthBuffer[(int)o->dataToBlit->z].push_back(*o->dataToBlit); } return UPDATE_CONTINUE; } void ModuleObstacle::AddObstacle(const Obstacle& obstacle, const float& x, const float& xOffset, const float& y, collisionType type) { Obstacle* o = new Obstacle(obstacle); o->worldPosition = { x, y, (float)MAX_Z}; o->xOffset = xOffset; o->colType = type; o->collider = App->collision->AddCollider({ 0, 0, 0, 0 }, o->colType, (int)o->worldPosition.z, App->obstacles); o->lineToFollow = App->renderer->nextTopLine; active.push_back(o); } const bool ModuleObstacle::onCollision(Collider* moduleOwner, Collider* otherCollider) { bool ret = true; for (std::list<Obstacle*>::iterator it = active.begin(); it != active.end(); ++it) { if ((*it)->collider == moduleOwner) { if (otherCollider->colType != PLAYER) { App->player->playerScore += 1000.0f; (*it)->to_delete = true; (*it)->collider->to_delete = true; if (otherCollider->colType != PLAYER) App->particles->AddParticle(App->particles->explosion, (*it)->screenPosition.x, (*it)->screenPosition.y + (*it)->dataToBlit->newHeight, (*it)->screenPosition.z, EXPLOSION); } } } return ret; } Obstacle::Obstacle() {} Obstacle::Obstacle(const Obstacle& o) : anim(o.anim), worldPosition(o.worldPosition), shadowCast(o.shadowCast) {} Obstacle::~Obstacle() { delete dataToBlit; } void Obstacle::Update() { if (worldPosition.z <= MIN_Z + 1) { collider->to_delete = true; to_delete = true; } float tempY = ((App->renderer->renderLineValues[lineToFollow]) / (float)SCREEN_SIZE); float scaleValue = calculateScaleValue(tempY); float newWidth = (float)anim.GetCurrentFrame().w * scaleValue; float newHeight = (float)anim.GetCurrentFrame().h * scaleValue; if (newHeight < 2.0f) newHeight = 2.0f; if (newWidth < 1.0f) newWidth = 1.0f; worldPosition.z = ((float)SCREEN_HEIGHT - tempY) / (App->renderer->horizonY / (float)MAX_Z); xOffset -= App->renderer->playerSpeed; screenPosition.x = worldPosition.x - (newWidth / 2.0f) + (xOffset * scaleValue); screenPosition.y = tempY - newHeight - (worldPosition.y * scaleValue); screenPosition.z = worldPosition.z; setRect(App->obstacles->graphics, screenPosition.x, screenPosition.y, screenPosition.z, newWidth, newHeight, &(anim.GetCurrentFrame())); collider->SetPos((int)screenPosition.x, (int)screenPosition.y, (int)worldPosition.z, (int)newWidth, (int)newHeight); } const float Obstacle::calculateScaleValue(float yRender) const { float min = (float)SCREEN_HEIGHT - App->renderer->horizonY; float max = (float)SCREEN_HEIGHT; float toReturn = (yRender - min) / (max - min); if (toReturn < 0.0f) toReturn = 0.0f; return toReturn; } void Obstacle::setRect(SDL_Texture* texture, const float& x, const float& y, const float& z, const float& newWidth, const float& newHeight, SDL_Rect* section) const { dataToBlit->x = x; dataToBlit->y = y; dataToBlit->z = z; dataToBlit->newWidth = newWidth; dataToBlit->newHeight = newHeight; dataToBlit->texture = texture; dataToBlit->section = section; }
#include <math.h> #include "ModuleObstacle.h" #include "Application.h" #include "ModuleAudio.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleCollision.h" #include "ModuleParticles.h" #include "ModuleShadows.h" #include "ModulePlayer.h" #include "SDL/include/SDL_timer.h" ModuleObstacle::ModuleObstacle(bool active) : Module(active) {} ModuleObstacle::~ModuleObstacle() {} bool ModuleObstacle::Start() { LOG("Loading Obstacles"); graphics = App->textures->Load("assets/enemiesobstacles.png"); tree.anim.frames.push_back({ 206, 378, 40, 158 }); tree.worldPosition.z = MAX_Z; tree.colType = D_OBSTACLE; rock.anim.frames.push_back({ 192, 72, 59, 37 }); rock.worldPosition.z = MAX_Z; rock.colType = D_OBSTACLE; rock.shadowCast = true; bush.anim.frames.push_back({ 193, 8, 59, 41 }); bush.worldPosition.z = MAX_Z; bush.colType = NOLETHAL_D_OBSTACLE; return true; } bool ModuleObstacle::CleanUp() { LOG("Unloading particles"); App->textures->Unload(graphics); for (list<Obstacle*>::iterat
oat)anim.GetCurrentFrame().w * scaleValue; float newHeight = (float)anim.GetCurrentFrame().h * scaleValue; if (newHeight < 2.0f) newHeight = 2.0f; if (newWidth < 1.0f) newWidth = 1.0f; worldPosition.z = ((float)SCREEN_HEIGHT - tempY) / (App->renderer->horizonY / (float)MAX_Z); xOffset -= App->renderer->playerSpeed; screenPosition.x = worldPosition.x - (newWidth / 2.0f) + (xOffset * scaleValue); screenPosition.y = tempY - newHeight - (worldPosition.y * scaleValue); screenPosition.z = worldPosition.z; setRect(App->obstacles->graphics, screenPosition.x, screenPosition.y, screenPosition.z, newWidth, newHeight, &(anim.GetCurrentFrame())); collider->SetPos((int)screenPosition.x, (int)screenPosition.y, (int)worldPosition.z, (int)newWidth, (int)newHeight); } const float Obstacle::calculateScaleValue(float yRender) const { float min = (float)SCREEN_HEIGHT - App->renderer->horizonY; float max = (float)SCREEN_HEIGHT; float toReturn = (yRender - min) / (max - min); if (toReturn < 0.0f) toReturn = 0.0f; return toReturn; } void Obstacle::setRect(SDL_Texture* texture, const float& x, const float& y, const float& z, const float& newWidth, const float& newHeight, SDL_Rect* section) const { dataToBlit->x = x; dataToBlit->y = y; dataToBlit->z = z; dataToBlit->newWidth = newWidth; dataToBlit->newHeight = newHeight; dataToBlit->texture = texture; dataToBlit->section = section; }
or it = active.begin(); it != active.end(); ++it) RELEASE(*it); active.clear(); return true; } update_status ModuleObstacle::PreUpdate() { for (list<Obstacle*>::iterator it = active.begin(); it != active.end();) { if ((*it)->to_delete == true) { RELEASE(*it); it = active.erase(it); } else ++it; } return UPDATE_CONTINUE; } update_status ModuleObstacle::Update() { for (list<Obstacle*>::iterator it = active.begin(); it != active.end(); ++it) { Obstacle* o = *it; if(!App->renderer->stopUpdating) o->Update(); if (o->shadowCast) App->shadows->DrawShadow(o->screenPosition.x, o->screenPosition.y, o->screenPosition.z, o->dataToBlit->newWidth); App->renderer->depthBuffer[(int)o->dataToBlit->z].push_back(*o->dataToBlit); } return UPDATE_CONTINUE; } void ModuleObstacle::AddObstacle(const Obstacle& obstacle, const float& x, const float& xOffset, const float& y, collisionType type) { Obstacle* o = new Obstacle(obstacle); o->worldPosition = { x, y, (float)MAX_Z}; o->xOffset = xOffset; o->colType = type; o->collider = App->collision->AddCollider({ 0, 0, 0, 0 }, o->colType, (int)o->worldPosition.z, App->obstacles); o->lineToFollow = App->renderer->nextTopLine; active.push_back(o); } const bool ModuleObstacle::onCollision(Collider* moduleOwner, Collider* otherCollider) { bool ret = true; for (std::list<Obstacle*>::iterator it = active.begin(); it != active.end(); ++it) { if ((*it)->collider == moduleOwner) { if (otherCollider->colType != PLAYER) { App->player->playerScore += 1000.0f; (*it)->to_delete = true; (*it)->collider->to_delete = true; if (otherCollider->colType != PLAYER) App->particles->AddParticle(App->particles->explosion, (*it)->screenPosition.x, (*it)->screenPosition.y + (*it)->dataToBlit->newHeight, (*it)->screenPosition.z, EXPLOSION); } } } return ret; } Obstacle::Obstacle() {} Obstacle::Obstacle(const Obstacle& o) : anim(o.anim), worldPosition(o.worldPosition), shadowCast(o.shadowCast) {} Obstacle::~Obstacle() { delete dataToBlit; } void Obstacle::Update() { if (worldPosition.z <= MIN_Z + 1) { collider->to_delete = true; to_delete = true; } float tempY = ((App->renderer->renderLineValues[lineToFollow]) / (float)SCREEN_SIZE); float scaleValue = calculateScaleValue(tempY); float newWidth = (fl
random
[ { "content": "struct Obstacle\n\n{\n\n\tObstacle();\n\n\tObstacle(const Obstacle& p);\n\n\t~Obstacle();\n\n\n\n\tvoid Update();\n\n\n\n\tconst float calculateScaleValue(float yRender) const;\n\n\tvoid setRect(SDL_Texture* texture, const float& x, const float& y, const float& z, const float& newWidth, const float& newHeight, SDL_Rect* section) const;\n\n\n\n\tint lineToFollow = 0;\n\n\tbool to_delete = false;\n\n\tbool shadowCast = false;\n\n\tfloat xOffset = 0.0f;\n\n\n\n\tfPoint screenPosition = { 0.0f, 0.0f, 0.0f };\n\n\tfPoint worldPosition = { 0.0f, 0.0f, 0.0f };\n\n\tAnimation anim;\n\n\tcollisionType colType;\n\n\tCollider* collider = nullptr;\n\n\tBlitTarget* dataToBlit = new BlitTarget(nullptr, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, nullptr);\n\n};\n\n\n", "file_path": "ModuleObstacle.h", "rank": 0, "score": 55942.46697624411 }, { "content": "struct Particle\n\n{\n\n\tParticle();\n\n\tParticle(const Particle& p);\n\n\t~Particle();\n\n\n\n\tvoid Update(const int& updateSelector);\n\n\tconst void setDataToBlit(SDL_Texture* texture, const float& x, const float& y, const float& z, const float& newWidth, const float& newHeight, SDL_Rect* section) const;\n\n\n\n\tbool to_delete = false;\n\n\tbool repelled = false;\n\n\tfloat speed = 0;\n\n\tunsigned int fxIndex = 0;\n\n\t\t\n\n\tfPoint position = { 0.0f, 0.0f, 0.0f };\n\n\tfPoint targetOffset = { 0.0f, 0.0f, 0.0f };\n\n\tAnimation anim;\n\n\tcollisionType colType;\n\n\tCollider* collider = nullptr;\n\n\tBlitTarget* dataToBlit = new BlitTarget(nullptr, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, nullptr);\n\n};\n\n\n", "file_path": "ModuleParticles.h", "rank": 1, "score": 55909.60291040084 }, { "content": "class ModuleObstacle : public Module\n\n{\n\npublic:\n\n\tModuleObstacle(bool active = false);\n\n\t~ModuleObstacle();\n\n\n\n\tbool Start();\n\n\tupdate_status PreUpdate();\n\n\tupdate_status Update();\n\n\tbool CleanUp();\n\n\n\n\tconst bool onCollision(Collider* c1, Collider* c2);\n\n\tvoid AddObstacle(const Obstacle& particle, const float& x, const float& xOffset, const float& y, collisionType type);\n\n\n\npublic:\n\n\tSDL_Texture* graphics = nullptr;\n\n\tObstacle tree;\n\n\tObstacle rock;\n\n\tObstacle bush;\n\n\n\nprivate:\n\n\tstd::list<Obstacle*> active;\n\n\n\n};\n\n\n\n#endif // __MODULEOBSTACLE_H__", "file_path": "ModuleObstacle.h", "rank": 2, "score": 54621.57140619223 }, { "content": "class ModuleParticles : public Module\n\n{\n\npublic:\n\n\tModuleParticles();\n\n\t~ModuleParticles();\n\n\n\n\tbool Start();\n\n\tupdate_status PreUpdate();\n\n\tupdate_status Update();\n\n\tbool CleanUp();\n\n\tvoid AddParticle(const Particle& particle, const float& x, const float& y, const float& z, collisionType colType);\n\n\n\nprivate:\n\n\tconst bool onCollision(Collider* c1, Collider* c2);\n\n\t\n\npublic:\n\n\tSDL_Texture * graphics = nullptr;\n\n\tParticle p_laser;\n\n\tParticle e_laser;\n\n\tParticle explosion;\n\n\tParticle fireBall;\n\n\n\nprivate:\n\n\tuint repelledShotSFX = 0;\n\n\tstd::list<Particle*> active;\n\n\n\n};\n\n\n\n#endif // __MODULEPARTICLES_H__", "file_path": "ModuleParticles.h", "rank": 3, "score": 54589.483316120735 }, { "content": "#ifndef __MODULEOBSTACLE_H__\n\n#define __MODULEOBSTACLE_H__\n\n\n\n#include<list>\n\n#include \"Globals.h\"\n\n#include \"Module.h\"\n\n#include \"Animation.h\"\n\n#include \"Point.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModuleRender.h\"\n\n\n", "file_path": "ModuleObstacle.h", "rank": 4, "score": 48976.341840145884 }, { "content": "#ifndef __MODULEPARTICLES_H__\n\n#define __MODULEPARTICLES_H__\n\n\n\n#include <list>\n\n#include \"Globals.h\"\n\n#include \"Module.h\"\n\n#include \"Animation.h\"\n\n#include \"Point.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModuleRender.h\"\n\n\n", "file_path": "ModuleParticles.h", "rank": 5, "score": 48947.5730385816 }, { "content": "class ModuleObstacle;\n\n\n\n\n", "file_path": "Application.h", "rank": 16, "score": 48289.846388821425 }, { "content": "\n\n// Unload assets\n\nbool ModuleParticles::CleanUp()\n\n{\n\n\tLOG(\"Unloading particles\");\n\n\tApp->textures->Unload(graphics);\n\n\t\n\n\tfor (list<Particle*>::iterator it = active.begin(); it != active.end(); ++it)\n\n\t\tRELEASE(*it);\n\n\n\n\tactive.clear();\n\n\t\n\n\treturn true;\n\n}\n\n\n\n// PreUpdate to clear up all dirty particles\n\nupdate_status ModuleParticles::PreUpdate()\n\n{\n\n\tfor (list<Particle*>::iterator it = active.begin(); it != active.end();)\n\n\t{\n", "file_path": "ModuleParticles.cpp", "rank": 17, "score": 48275.18622477381 }, { "content": "#include <math.h>\n\n#include \"ModuleParticles.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModulePlayer.h\"\n\n#include \"SDL/include/SDL_timer.h\"\n\n\n\nModuleParticles::ModuleParticles()\n\n{}\n\n\n\nModuleParticles::~ModuleParticles()\n\n{}\n\n\n\n// Load assets\n\nbool ModuleParticles::Start()\n\n{\n\n\tLOG(\"Loading particles\");\n", "file_path": "ModuleParticles.cpp", "rank": 18, "score": 48272.318421384756 }, { "content": "\t\tif ((*it)->to_delete == true)\n\n\t\t{\n\n\t\t\tRELEASE(*it);\n\n\t\t\tit = active.erase(it);\n\n\t\t}\n\n\t\telse\n\n\t\t\t++it;\n\n\t}\n\n\n\n\treturn UPDATE_CONTINUE;\n\n}\n\n\n\n// Update all particle logic and draw them\n\nupdate_status ModuleParticles::Update()\n\n{\n\n\tfor (list<Particle*>::iterator it = active.begin(); it != active.end(); ++it)\n\n\t{\n\n\t\tParticle* p = *it;\n\n\n\n\t\tif (p->colType == P_LASER) \n", "file_path": "ModuleParticles.cpp", "rank": 19, "score": 48271.76141602298 }, { "content": "// -------------------------------------------------------------\n\n\n\nParticle::Particle()\n\n{}\n\n\n\nParticle::Particle(const Particle& p) : anim(p.anim), position(p.position), fxIndex(p.fxIndex), speed(p.speed)\n\n{}\n\n\n\nParticle::~Particle()\n\n{\n\n\tdelete dataToBlit;\n\n}\n\n\n\nvoid Particle::Update(const int& updateSelector)\n\n{\n\n\tif (position.z >= MAX_Z || position.z <= MIN_Z || anim.animationWithoutLoopEnded)\n\n\t{\n\n\t\tto_delete = true;\n\n\t\tif(collider != nullptr)\n\n\t\t\tcollider->to_delete = true;\n", "file_path": "ModuleParticles.cpp", "rank": 20, "score": 48268.6242756378 }, { "content": "\t\t{\n\n\t\t\tif (otherCollider->colType == D_OBSTACLE || otherCollider->colType == NOLETHAL_D_OBSTACLE || otherCollider->colType == ENEMY)\n\n\t\t\t{\n\n\t\t\t\t//Bullet gets destroyed with the other object\n\n\t\t\t\t(*it)->to_delete = true;\n\n\t\t\t\t(*it)->collider->to_delete = true;\n\n\t\t\t}\n\n\t\t\telse if (otherCollider->colType == ND_ENEMY)\n\n\t\t\t{\n\n\t\t\t\t//Bullet gets repelled and the enemy remains unmodified\n\n\t\t\t\tApp->audio->PlayFx(repelledShotSFX);\n\n\t\t\t\t(*it)->repelled = true;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\treturn true;\n\n}\n\n\n\n// -------------------------------------------------------------\n", "file_path": "ModuleParticles.cpp", "rank": 21, "score": 48267.69928138219 }, { "content": "\t\tp->position.y += (-App->renderer->horizonY + (float)FLOOR_Y_MIN);\n\n\t\tp->targetOffset.x = (App->player->position.x + (float)App->player->current_animation->GetCurrentFrame().w/2.0f) - p->position.x;\n\n\t\tp->targetOffset.y = (App->player->position.y + (float)App->player->current_animation->GetCurrentFrame().h/2.0f) - p->position.y;\n\n\t\tp->targetOffset.z = z;\n\n\t}\n\n\n\n\tif (colType == P_LASER || colType == E_LASER)\n\n\t{\n\n\t\tp->collider = App->collision->AddCollider({ 0, 0, 0, 0 }, colType, (int)z, App->particles);\n\n\t\tApp->audio->PlayFx(p->fxIndex, 0);\n\n\t}\n\n\n\n\tactive.push_back(p);\n\n}\n\n\n\nconst bool ModuleParticles::onCollision(Collider* moduleOwner, Collider* otherCollider)\n\n{\n\n\tfor (std::list<Particle*>::iterator it = active.begin(); it != active.end(); ++it)\n\n\t{\n\n\t\tif ((*it)->collider == moduleOwner || (*it)->collider == otherCollider)\n", "file_path": "ModuleParticles.cpp", "rank": 22, "score": 48267.1789395846 }, { "content": "\t\t\tp->Update(1);\n\n\t\telse if (p->colType == E_LASER) \n\n\t\t\tp->Update(2);\n\n\t\telse if (p->colType == EXPLOSION) \n\n\t\t\tp->Update(3);\n\n\n\n\t\tApp->renderer->depthBuffer[(int)p->dataToBlit->z].push_back(*p->dataToBlit);\n\n\t}\n\n\n\n\treturn UPDATE_CONTINUE;\n\n}\n\n\n\nvoid ModuleParticles::AddParticle(const Particle& particle, const float& x, const float& y, const float& z, collisionType colType)\n\n{\n\n\tParticle* p = new Particle(particle);\n\n\tp->position = { x, y, z };\n\n\tp->colType = colType;\n\n\n\n\tif (colType == E_LASER)\n\n\t{\n", "file_path": "ModuleParticles.cpp", "rank": 23, "score": 48265.751405938456 }, { "content": "\t\t{\n\n\t\t\tcollider->to_delete = true;\n\n\t\t\tcollider = nullptr;\n\n\t\t}\n\n\n\n\t\tposition.x += 3.0f;\n\n\t\tposition.y -= 3.0f;\n\n\t\tnewX = position.x - newWidth / 2.0f;\n\n\t\tnewY = position.y - newHeight / 4.0f;\n\n\t}\n\n\n\n\tposition.z += speed;\n\n\n\n\tsetDataToBlit(App->particles->graphics, newX, newY, position.z, newWidth, newHeight, &(anim.GetCurrentFrame()));\n\n\n\n\tif( collider != nullptr )\n\n\t\tcollider->SetPos((int)newX, (int)newY, (int)position.z, (int)newWidth, (int)newHeight);\t\n\n}\n\n\n\nconst void Particle::setDataToBlit(SDL_Texture* texture, const float& x, const float& y, const float& z, const float& newWidth, const float& newHeight, SDL_Rect* section) const\n\n{\n\n\tdataToBlit->x = x;\n\n\tdataToBlit->y = y;\n\n\tdataToBlit->z = z;\n\n\tdataToBlit->newWidth = newWidth;\n\n\tdataToBlit->newHeight = newHeight;\n\n\tdataToBlit->texture = texture;\n\n\tdataToBlit->section = section;\t\n\n}", "file_path": "ModuleParticles.cpp", "rank": 24, "score": 48264.82447454983 }, { "content": "\t//Texture\n\n\tgraphics = App->textures->Load(\"assets/particle_models.png\");\n\n\n\n\t//Sounds\n\n\trepelledShotSFX = App->audio->LoadFx(\"assets/sfx/SFX_RepelledBullet.wav\");\n\n\n\n\t//PlayerLaser particle (Main attack)\n\n\tp_laser.fxIndex = App->audio->LoadFx(\"assets/sfx/PLAYER_Shot.wav\");\n\n\tp_laser.anim.frames.push_back({ 1, 1, 91, 61 });\n\n\tp_laser.anim.frames.push_back({ 95, 0, 91, 61 });\n\n\tp_laser.anim.frames.push_back({ 188, 1, 91, 61 });\n\n\tp_laser.anim.frames.push_back({ 284, 0, 91, 61 });\n\n\tp_laser.anim.speed = 8.0f;\n\n\tp_laser.position.z = 1.0f;\n\n\tp_laser.speed = 1.0f;\n\n\tp_laser.colType = P_LASER;\n\n\n\n\t//EnemyLaser particle. The behaviour is the same as PlayerLaser but reversed and with a certain target\n\n\tfireBall.fxIndex = App->audio->LoadFx(\"assets/sfx/BOSS_FireBall.wav\");\n\n\te_laser.anim.frames.push_back({ 34, 105, 68, 45});\n", "file_path": "ModuleParticles.cpp", "rank": 25, "score": 48264.517835471284 }, { "content": "\tfireBall.colType = E_LASER;\n\n\n\n\t//Explosion particle works completely different from other particles (is not an attack)\n\n\texplosion.anim.frames.push_back({ 400, 5, 89, 65 });\n\n\texplosion.anim.frames.push_back({ 497, 6, 88, 64 });\n\n\texplosion.anim.frames.push_back({ 595, 6, 90, 70 });\n\n\texplosion.anim.frames.push_back({ 690, 5, 97, 75 });\n\n\texplosion.anim.frames.push_back({ 794, 9, 93, 68 });\n\n\texplosion.anim.frames.push_back({ 895, 13, 93, 65 });\n\n\texplosion.anim.frames.push_back({ 399, 85, 96, 83 });\n\n\texplosion.anim.frames.push_back({ 504, 86, 90, 82 });\n\n\texplosion.anim.frames.push_back({ 599, 92, 95, 77 });\n\n\texplosion.anim.speed = 10.0f;\n\n\texplosion.position.z = MAX_Z;\n\n\texplosion.speed = -0.5f;\n\n\texplosion.anim.loop = false;\n\n\texplosion.colType = EXPLOSION;\n\n\n\n\treturn true;\n\n}\n", "file_path": "ModuleParticles.cpp", "rank": 26, "score": 48264.51368023417 }, { "content": "\te_laser.anim.frames.push_back({ 117, 101, 62, 53 });\n\n\te_laser.anim.frames.push_back({ 201, 97, 54, 61 });\n\n\te_laser.anim.frames.push_back({ 285, 94, 46, 68 });\n\n\te_laser.anim.frames.push_back({ 45, 174, 46, 68 });\n\n\te_laser.anim.frames.push_back({ 121, 177, 54, 61 });\n\n\te_laser.anim.frames.push_back({ 197, 182, 62, 53 });\n\n\te_laser.anim.frames.push_back({ 274, 185, 68, 45 });\n\n\te_laser.anim.speed = 8.0f;\n\n\te_laser.position.z = MAX_Z;\n\n\te_laser.speed = -0.4f;\n\n\te_laser.colType = E_LASER;\n\n\n\n\t//FireBall particle has the same behaviour as EnemyLaser particle\n\n\tfireBall.fxIndex = App->audio->LoadFx(\"assets/sfx/BOSS_FireBall.wav\");\n\n\tfireBall.anim.frames.push_back({ 6, 280, 75, 69 });\n\n\tfireBall.anim.frames.push_back({ 90, 282, 71, 64 });\n\n\tfireBall.anim.frames.push_back({ 172, 278, 74, 71 });\n\n\tfireBall.anim.speed = 8.0f;\n\n\tfireBall.position.z = MAX_Z;\n\n\tfireBall.speed = -0.2f;\n", "file_path": "ModuleParticles.cpp", "rank": 27, "score": 48263.07411880971 }, { "content": "\t}\n\n\n\n\tfloat zModifier = 1.0f - (position.z / (float)MAX_Z);\n\n\tfloat newWidth = (float)anim.GetCurrentFrame().w * zModifier;\n\n\tfloat newHeight = (float)anim.GetCurrentFrame().h * zModifier;\n\n\tfloat newX = 0.0f;\n\n\tfloat newY = 0.0f;\n\n\n\n\tnewWidth *= 0.6f;\n\n\tnewHeight *= 0.6f;\n\n\n\n\tif (!repelled)\n\n\t{\n\n\t\t//The movement behaviour is slightly different in each of the three particles, so we use a switch to choose between them\n\n\t\tswitch (updateSelector)\n\n\t\t{\n\n\t\t\tcase 1: //Player bullet\n\n\t\t\t{\n\n\t\t\t\tnewX = position.x - (newWidth / 2.0f);\n\n\t\t\t\tnewY = position.y - (newHeight / 4.0f);\n", "file_path": "ModuleParticles.cpp", "rank": 28, "score": 48262.83178483883 }, { "content": "\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tcase 2: //Enemy bullet\n\n\t\t\t{\n\n\t\t\t\tfloat posModifier = 1.0f - (position.z / targetOffset.z);\n\n\t\t\t\tnewX = position.x - (newWidth / 2.0f) + (targetOffset.x * posModifier);\n\n\t\t\t\tnewY = position.y - (newHeight / 2.0f) + (targetOffset.y * posModifier);\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tcase 3: //Explosion\n\n\t\t\t{\n\n\t\t\t\tnewX = position.x - (newWidth / 2.0f);\n\n\t\t\t\tnewY = position.y - newHeight;\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\telse\n\n\t{\n\n\t\tif (collider != nullptr)\n", "file_path": "ModuleParticles.cpp", "rank": 29, "score": 48261.477945721526 }, { "content": "class ModuleParticles;\n", "file_path": "Application.h", "rank": 30, "score": 48261.477945721526 }, { "content": "struct SDL_Texture;\n\n\n", "file_path": "ModuleObstacle.h", "rank": 31, "score": 47627.04880647965 }, { "content": "struct SDL_Texture;\n\n\n", "file_path": "ModuleParticles.h", "rank": 32, "score": 47599.069731681935 }, { "content": " Sint64 (SDLCALL * size) (struct SDL_RWops * context);\n", "file_path": "SDL/include/SDL_rwops.h", "rank": 33, "score": 37780.959615686275 }, { "content": " Uint8 r, g, b;\n", "file_path": "SDL/include/SDL_messagebox.h", "rank": 34, "score": 37777.056753572455 }, { "content": " int h; /**< height, in screen coordinates */\n", "file_path": "SDL/include/SDL_video.h", "rank": 35, "score": 37777.056753572455 }, { "content": " int w; /**< width, in screen coordinates */\n", "file_path": "SDL/include/SDL_video.h", "rank": 36, "score": 37777.056753572455 }, { "content": " int w, h; /**< Read-only */\n", "file_path": "SDL/include/SDL_surface.h", "rank": 37, "score": 37777.056753572455 }, { "content": " float y;\n", "file_path": "SDL/include/SDL_touch.h", "rank": 38, "score": 37777.056753572455 }, { "content": " int w, h;\n", "file_path": "SDL/include/SDL_rect.h", "rank": 39, "score": 37777.056753572455 }, { "content": " Uint8 r;\n", "file_path": "SDL/include/SDL_pixels.h", "rank": 40, "score": 37777.056753572455 }, { "content": " Uint32 which; /**< The audio device index for the ADDED event (valid until next SDL_GetNumAudioDevices() call), SDL_AudioDeviceID for the REMOVED event */\n", "file_path": "SDL/include/SDL_events.h", "rank": 41, "score": 37777.056753572455 }, { "content": " Uint32 a, b;\n", "file_path": "SDL/include/SDL_endian.h", "rank": 42, "score": 37777.056753572455 }, { "content": " float x; /**< Normalized center of gesture */\n", "file_path": "SDL/include/SDL_events.h", "rank": 43, "score": 37777.056753572455 }, { "content": " Uint8 *here;\n", "file_path": "SDL/include/SDL_rwops.h", "rank": 44, "score": 37777.056753572455 }, { "content": " float y; /**< Normalized center of gesture */\n", "file_path": "SDL/include/SDL_events.h", "rank": 45, "score": 37777.056753572455 }, { "content": " int x, y;\n", "file_path": "SDL/include/SDL_rect.h", "rank": 46, "score": 37777.056753572455 }, { "content": " float x;\n", "file_path": "SDL/include/SDL_touch.h", "rank": 47, "score": 37777.056753572455 }, { "content": " void *h;\n", "file_path": "SDL/include/SDL_rwops.h", "rank": 48, "score": 37777.056753572455 }, { "content": " Uint8 b;\n", "file_path": "SDL/include/SDL_pixels.h", "rank": 49, "score": 37777.056753572455 }, { "content": " int y;\n", "file_path": "SDL/include/SDL_rect.h", "rank": 50, "score": 37777.056753572455 }, { "content": " Uint8 g;\n", "file_path": "SDL/include/SDL_pixels.h", "rank": 51, "score": 37777.056753572455 }, { "content": " Uint8 a;\n", "file_path": "SDL/include/SDL_pixels.h", "rank": 52, "score": 37777.056753572455 }, { "content": " const char * text; /**< The UTF-8 button text */\n", "file_path": "SDL/include/SDL_messagebox.h", "rank": 53, "score": 37307.243742295956 }, { "content": " SDL_AudioFormat format; /**< Audio data format */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 54, "score": 37304.001552765665 }, { "content": " void *driverdata; /**< driver-specific data, initialize to 0 */\n", "file_path": "SDL/include/SDL_video.h", "rank": 55, "score": 37304.001552765665 }, { "content": " Uint8 minor; /**< minor version */\n", "file_path": "SDL/include/SDL_version.h", "rank": 56, "score": 37304.001552765665 }, { "content": " SDL_AudioCallback callback; /**< Callback that feeds the audio device (NULL to use SDL_QueueAudio()). */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 57, "score": 37304.001552765665 }, { "content": " int len; /**< Length of original audio buffer */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 58, "score": 37304.001552765665 }, { "content": " Uint16 padding; /**< Necessary for some compile environments */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 59, "score": 37304.001552765665 }, { "content": " void *userdata; /**< Userdata passed to callback (ignored for NULL callbacks). */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 60, "score": 37304.001552765665 }, { "content": " SDL_AudioFilter filters[10]; /**< Filter list */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 61, "score": 37304.001552765665 }, { "content": " Uint8 major; /**< major version */\n", "file_path": "SDL/include/SDL_version.h", "rank": 62, "score": 37304.001552765665 }, { "content": " Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 63, "score": 37304.001552765665 }, { "content": " Uint8 silence; /**< Audio buffer silence value (calculated) */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 64, "score": 37304.001552765665 }, { "content": " Uint8 patch; /**< update version */\n", "file_path": "SDL/include/SDL_version.h", "rank": 65, "score": 37304.001552765665 }, { "content": " float pressure;\n", "file_path": "SDL/include/SDL_touch.h", "rank": 66, "score": 37304.001552765665 }, { "content": " Uint16 samples; /**< Audio buffer size in samples (power of 2) */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 67, "score": 37304.001552765665 }, { "content": " int freq; /**< DSP frequency -- samples per second */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 68, "score": 37304.001552765665 }, { "content": " Uint8 *buf; /**< Buffer to hold entire audio data */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 69, "score": 37304.001552765665 }, { "content": " SDL_FingerID id;\n", "file_path": "SDL/include/SDL_touch.h", "rank": 70, "score": 37304.001552765665 }, { "content": " Uint32 format; /**< pixel format */\n", "file_path": "SDL/include/SDL_video.h", "rank": 71, "score": 37304.001552765665 }, { "content": " int needed; /**< Set to 1 if conversion possible */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 72, "score": 37304.001552765665 }, { "content": " Uint32 size; /**< Audio buffer size in bytes (calculated) */\n", "file_path": "SDL/include/SDL_audio.h", "rank": 73, "score": 37304.001552765665 }, { "content": "\t\treturn true;\n\n\t}\n\n\n\n\t bool Disable()\n\n\t {\n\n\t\t if(active == true)\n\n\t\t\t return active = !CleanUp();\n\n\n\n\t\t return true;\n\n\t }\n\n\n\n\tvirtual bool Init() \n\n\t{\n\n\t\treturn true; \n\n\t}\n\n\n\n\tvirtual bool Start()\n\n\t{\n\n\t\treturn true;\n\n\t}\n", "file_path": "Module.h", "rank": 74, "score": 13.061331160661236 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModulePlayer.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModuleInput.h\"\n\n#include \"ModuleParticles.h\"\n\n#include \"ModuleStage.h\"\n\n#include \"ModuleObstacle.h\"\n\n#include \"ModuleShadows.h\"\n\n#include \"ModuleFadeToBlack.h\"\n\n#include \"ModuleEnemy.h\"\n\n#include \"FontManager.h\"\n\n\n\nModuleStage::ModuleStage(bool active) : Module(active)\n\n{\n\n\tscores[\"ZELLERYON\"] = 170000;\n\n\tscores[\"NEIKAR\"] = 120000;\n", "file_path": "ModuleStage.cpp", "rank": 75, "score": 11.510165169306816 }, { "content": "\n\n\t// Callbacks ---\n\n\tvirtual const bool onCollision(Collider* moduleOwner, Collider* otherCollider)\n\n\t{\n\n\t\treturn true;\n\n\t}\n\n\n\nprivate:\n\n\tbool active = true;\n\n};\n\n\n\n#endif // __MODULE_H__", "file_path": "Module.h", "rank": 76, "score": 10.847122138069755 }, { "content": "#include <math.h>\n\n#include \"Enemy.h\"\n\n#include \"ModuleEnemy.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleParticles.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModuleTime.h\"\n\n#include \"ModuleShadows.h\"\n\n#include \"ModulePlayer.h\"\n\n#include \"SDL/include/SDL_timer.h\"\n\n\n\nModuleEnemy::ModuleEnemy(bool active) : Module(active)\n\n{}\n\n\n\nModuleEnemy::~ModuleEnemy()\n\n{}\n\n\n", "file_path": "ModuleEnemy.cpp", "rank": 77, "score": 10.493490105374681 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleInput.h\"\n\n#include \"ModuleParticles.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModuleFadeToBlack.h\"\n\n#include \"ModulePlayer.h\"\n\n#include \"ModuleEnemy.h\"\n\n#include \"ModuleTime.h\"\n\n#include \"ModuleShadows.h\"\n\n#include \"ModuleAudio.h\"\n\n\n\nconst float ModulePlayer::playerDepth = 0.0f;\n\n\n\nModulePlayer::ModulePlayer(bool active) : Module(active)\n\n{\n\n\trun.frames.push_back({ 4, 4, 20, 47 });\n\n\trun.frames.push_back({ 25, 4, 20, 47 });\n", "file_path": "ModulePlayer.cpp", "rank": 78, "score": 9.738816036083286 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleShadows.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"SDL/include/SDL.h\"\n\n\n\nusing namespace std;\n\n\n\nModuleShadows::ModuleShadows(bool start_enabled) : Module(start_enabled)\n\n{}\n\n\n\n// Destructor\n\nModuleShadows::~ModuleShadows()\n\n{}\n\n\n\nbool ModuleShadows::Start()\n\n{\n\n\tbool ret = true;\n\n\n", "file_path": "ModuleShadows.cpp", "rank": 79, "score": 9.377449921805376 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleWindow.h\"\n\n#include \"SDL/include/SDL.h\"\n\n\n\nModuleWindow::ModuleWindow()\n\n{\n\n}\n\n\n\n// Destructor\n\nModuleWindow::~ModuleWindow()\n\n{\n\n}\n\n\n\n// Called before render is available\n\nbool ModuleWindow::Init()\n\n{\n\n\tLOG(\"Init SDL window & surface\");\n\n\tbool ret = true;\n\n\n", "file_path": "ModuleWindow.cpp", "rank": 80, "score": 8.989599058886782 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleFadeToBlack.h\"\n\n#include \"ModuleSegaIntro.h\"\n\n\n\nModuleSegaIntro::ModuleSegaIntro(bool active) : Module(active)\n\n{}\n\n\n\nModuleSegaIntro::~ModuleSegaIntro()\n\n{}\n\n\n\nbool ModuleSegaIntro::Start()\n\n{\n\n\tsegaTimer = SDL_GetTicks();\n\n\tlogo = App->textures->Load(\"assets/segalogo.png\");\n\n\n\n\tif (fx == 0)\n", "file_path": "ModuleSegaIntro.cpp", "rank": 81, "score": 8.763204671517054 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleInput.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleCollision.h\"\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nModuleCollision::ModuleCollision()\n\n{\n\n\t//Create the matrix that will decide if a collision is possible (true) or won't affect to the gameplay (false)\n\n\tcollisionMatrix[PLAYER][PLAYER] = false;\n\n\tcollisionMatrix[PLAYER][ENEMY] = true;\n\n\tcollisionMatrix[PLAYER][P_LASER] = false;\n\n\tcollisionMatrix[PLAYER][E_LASER] = true;\n\n\tcollisionMatrix[PLAYER][D_OBSTACLE] = true;\n\n\tcollisionMatrix[PLAYER][NOLETHAL_D_OBSTACLE] = true;\n\n\tcollisionMatrix[PLAYER][ND_ENEMY] = true;\n\n\tcollisionMatrix[PLAYER][EXPLOSION] = false;\n", "file_path": "ModuleCollision.cpp", "rank": 82, "score": 8.734721636528747 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleTime.h\"\n\n#include \"SDL/include/SDL.h\"\n\n\n\nusing namespace std;\n\n\n\nModuleTime::ModuleTime(bool start_enabled) : Module(start_enabled)\n\n{}\n\n\n\n// Destructor\n\nModuleTime::~ModuleTime()\n\n{}\n\n\n\nbool ModuleTime::Init()\n\n{\n\n\tdeltaTime = 0.0f;\n\n\tlastDeltaTime = 0.0f;\n\n\n\n\treturn true;\n", "file_path": "ModuleTime.cpp", "rank": 83, "score": 8.60857475618923 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"ModuleInput.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleFadeToBlack.h\"\n\n#include \"ModuleSceneIntro.h\"\n\n#include \"FontManager.h\"\n\n\n\nModuleSceneIntro::ModuleSceneIntro(bool active) : Module(active)\n\n{\n\n\tbackgroundRect.x = 1943;\n\n\tbackgroundRect.y = 57;\n\n\tbackgroundRect.w = 320;\n\n\tbackgroundRect.h = 224;\n\n\n\n\twavingGuy.frames.push_back({ 17, 5, 51, 35 });\n\n\twavingGuy.frames.push_back({ 69, 5, 51, 35 });\n\n\twavingGuy.frames.push_back({ 17, 40, 51, 35 });\n", "file_path": "ModuleSceneIntro.cpp", "rank": 84, "score": 7.9063273687378235 }, { "content": "#include \"Application.h\"\n\n#include \"ModuleWindow.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"ModuleTextures.h\"\n\n#include \"ModuleInput.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"ModuleFadeToBlack.h\"\n\n#include \"ModuleCollision.h\"\n\n#include \"ModuleParticles.h\"\n\n#include \"ModuleTime.h\"\n\n#include \"ModuleSegaIntro.h\"\n\n#include \"ModuleSceneIntro.h\"\n\n#include \"ModuleStage.h\"\n\n#include \"ModulePlayer.h\"\n\n#include \"ModuleEnemy.h\"\n\n#include \"ModuleObstacle.h\"\n\n#include \"ModuleShadows.h\"\n\n#include \"FontManager.h\"\n\n#include \"Font.h\"\n\n\n", "file_path": "Application.cpp", "rank": 85, "score": 7.899369378887029 }, { "content": "\tactive.clear();\n\n\n\n\treturn true;\n\n}\n\n\n\nupdate_status ModuleEnemy::PreUpdate()\n\n{\n\n\tfor (list<Enemy*>::iterator it = active.begin(); it != active.end();)\n\n\t{\n\n\t\tif ((*it)->to_delete == true)\n\n\t\t{\n\n\t\t\tRELEASE(*it);\n\n\t\t\tit = active.erase(it);\n\n\t\t}\n\n\t\telse\n\n\t\t\t++it;\n\n\t}\n\n\n\n\treturn UPDATE_CONTINUE;\n\n}\n", "file_path": "ModuleEnemy.cpp", "rank": 86, "score": 7.899151181277308 }, { "content": "#include <math.h>\n\n#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleFadeToBlack.h\"\n\n#include \"ModuleRender.h\"\n\n#include \"SDL/include/SDL.h\"\n\n\n\nModuleFadeToBlack::ModuleFadeToBlack(bool start_enabled) : Module(start_enabled)\n\n{}\n\n\n\nModuleFadeToBlack::~ModuleFadeToBlack()\n\n{}\n\n\n\n// Load assets\n\nbool ModuleFadeToBlack::Start()\n\n{\n\n\tLOG(\"Preparing Fade Screen\");\n\n\tSDL_SetRenderDrawBlendMode(App->renderer->renderer, SDL_BLENDMODE_BLEND);\n\n\treturn true;\n\n}\n", "file_path": "ModuleFadeToBlack.cpp", "rank": 87, "score": 7.602755308835158 }, { "content": "\n\n\treturn ret;\n\n}\n\n\n\nbool Application::CleanUp()\n\n{\n\n\tbool ret = true;\n\n\n\n\tfor(list<Module*>::reverse_iterator it = modules.rbegin(); it != modules.rend() && ret; ++it)\n\n\t\tif((*it)->IsEnabled() == true) \n\n\t\t\tret = (*it)->CleanUp();\n\n\n\n\tfontManager->CleanUp();\n\n\n\n\treturn ret;\n\n}\n\n\n", "file_path": "Application.cpp", "rank": 88, "score": 6.902167155874981 }, { "content": "// Play WAV\n\nbool ModuleAudio::PlayFx(unsigned int id, int repeat)\n\n{\n\n\tbool ret = false;\n\n\n\n\tif(id < fx.size())\n\n\t{\n\n\t\tMix_PlayChannel(-1, fx[id], repeat);\n\n\t\tret = true;\n\n\t}\n\n\n\n\treturn ret;\n\n}\n\n\n\n//Stop the currently playing music\n\nconst void ModuleAudio::StopMusic() const\n\n{\n\n\tMix_HaltMusic();\n\n}\n\n\n\n//Return true if any music is beeing played\n\nconst bool ModuleAudio::isMusicPlaying() const\n\n{\n\n\treturn (Mix_PlayingMusic() == 1);\n\n}", "file_path": "ModuleAudio.cpp", "rank": 89, "score": 6.830271272578832 }, { "content": "\tint randX = 0;\n\n\tint randY = 0;\n\n\n\n\tif (!bossActive)\n\n\t{\n\n\t\tif (obstacleTimer1 < 15) \n\n\t\t\tobstacleTimer1++;\n\n\t\telse\n\n\t\t{\n\n\t\t\tobstacleTimer1 = 0;\n\n\t\t\trandX = rand() % (350 - (-350) + 1) + (-350);\n\n\n\n\t\t\tApp->obstacles->AddObstacle(App->obstacles->bush, ((float)SCREEN_WIDTH / 2.0f), (float)randX, 0.0f, NOLETHAL_D_OBSTACLE);\n\n\t\t}\n\n\n\n\t\tif (obstacleTimer2 < 25)\n\n\t\t\tobstacleTimer2++;\n\n\t\telse\n\n\t\t{\n\n\t\t\tobstacleTimer2 = 0;\n", "file_path": "ModuleStage.cpp", "rank": 90, "score": 6.7231598400371375 }, { "content": "\twaveNum = 0;\n\n\ttriggerEnemies = false;\n\n\tbossEncounter = false;\n\n\taliveEnemy = false;\n\n\n\n\tspaceshipSFX = App->audio->LoadFx(\"assets/sfx/ENEMY_Alienship.wav\");\n\n\ttomosSFX = App->audio->LoadFx(\"assets/sfx/ENEMY_Tomos.wav\");\n\n\n\n\treturn true;\n\n}\n\n\n\n// Unload assets\n\nbool ModuleEnemy::CleanUp()\n\n{\n\n\tLOG(\"Unloading enemies\");\n\n\tApp->textures->Unload(graphics);\n\n\n\n\tfor (list<Enemy*>::iterator it = active.begin(); it != active.end(); ++it)\n\n\t\tRELEASE(*it);\n\n\n", "file_path": "ModuleEnemy.cpp", "rank": 91, "score": 6.69193686154983 }, { "content": "#include \"Globals.h\"\n\n#include \"Application.h\"\n\n#include \"ModuleAudio.h\"\n\n#include \"SDL/include/SDL.h\"\n\n\n\n#include \"SDL_mixer/include/SDL_mixer.h\"\n\n#pragma comment( lib, \"SDL_mixer/libx86/SDL2_mixer.lib\" )\n\n\n\nusing namespace std;\n\n\n\nModuleAudio::ModuleAudio( bool start_enabled) : Module( start_enabled)\n\n{}\n\n\n\n// Destructor\n\nModuleAudio::~ModuleAudio()\n\n{}\n\n\n\n// Called before render is available\n\nbool ModuleAudio::Init()\n\n{\n", "file_path": "ModuleAudio.cpp", "rank": 92, "score": 6.616041062521473 }, { "content": "\tmodules.push_back(player = new ModulePlayer(false));\n\n\t\n\n\t// Modules to draw on top of game logic\n\n\tmodules.push_back(collision = new ModuleCollision());\n\n\tmodules.push_back(particles = new ModuleParticles());\n\n\tmodules.push_back(fade = new ModuleFadeToBlack());\n\n}\n\n\n\nApplication::~Application()\n\n{\n\n\tfor(list<Module*>::iterator it = modules.begin(); it != modules.end(); ++it)\n\n\t\tRELEASE(*it);\n\n\n\n\tRELEASE(fontManager);\n\n}\n\n\n\nbool Application::Init()\n\n{\n\n\tbool ret = true;\n\n\n", "file_path": "Application.cpp", "rank": 93, "score": 6.606641919129701 }, { "content": "\n\n\treturn true;\n\n}\n\n\n\n// Unload assets\n\nbool ModulePlayer::CleanUp()\n\n{\n\n\tLOG(\"Unloading player\");\n\n\n\n\tApp->textures->Unload(graphics);\n\n\n\n\treturn true;\n\n}\n\n\n\n// Update: draw background\n\nupdate_status ModulePlayer::Update()\n\n{\n\n\tUint32 tickCheck = SDL_GetTicks();\n\n\n\n\tfloat speed = 150.0f * App->time->getDeltaTime();\n", "file_path": "ModulePlayer.cpp", "rank": 94, "score": 6.60303372955397 }, { "content": "\t\t{\n\n\t\t\tif (otherCollider->colType == P_LASER)\n\n\t\t\t{\n\n\t\t\t\tif (moduleOwner->colType != ND_ENEMY)\n\n\t\t\t\t{\n\n\t\t\t\t\t(*it)->lifePoints -= 1;\n\n\t\t\t\t\tif ((*it)->lifePoints <= 0)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tApp->player->playerScore += 2000.0f;\n\n\t\t\t\t\t\t(*it)->collider->to_delete = true;\n\n\t\t\t\t\t\t(*it)->to_delete = true;\n\n\t\t\t\t\t\tApp->particles->AddParticle(App->particles->explosion, (*it)->screenPosition.x, (*it)->screenPosition.y + (*it)->dataToBlit->newHeight, (*it)->screenPosition.z, EXPLOSION);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\t\t\t\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\treturn true;\n\n}\n", "file_path": "ModuleEnemy.cpp", "rank": 95, "score": 6.534831989356962 }, { "content": "\t\t\trandX = rand() % (350 - (-350) + 1) + (-350);\n\n\t\t\trandY = rand() % (150 - 80 + 1) + 80;\n\n\n\n\t\t\tif (App->enemies->waveNum < 4) \n\n\t\t\t\tApp->obstacles->AddObstacle(App->obstacles->rock, ((float)SCREEN_WIDTH / 2.0f), (float)randX, (float)randY, D_OBSTACLE);\n\n\t\t\telse \n\n\t\t\t\tApp->obstacles->AddObstacle(App->obstacles->tree, ((float)SCREEN_WIDTH / 2.0f), (float)randX, 0.0f, D_OBSTACLE);\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid ModuleStage::EndingAndScoreBoard()\n\n{\n\n\tif (!Ending)\n\n\t{\n\n\t\tApp->audio->StopMusic();\n\n\t\tApp->renderer->stopUpdating = true;\n\n\t\tEnding = true;\n\n\t}\n\n\n", "file_path": "ModuleStage.cpp", "rank": 96, "score": 6.371579617000506 }, { "content": "\tcollisionMatrix[E_LASER][ENEMY] = false;\n\n\tcollisionMatrix[E_LASER][P_LASER] = false;\n\n\tcollisionMatrix[E_LASER][E_LASER] = false;\n\n\tcollisionMatrix[E_LASER][D_OBSTACLE] = false;\n\n\tcollisionMatrix[E_LASER][NOLETHAL_D_OBSTACLE] = false;\n\n\tcollisionMatrix[E_LASER][ND_ENEMY] = false;\n\n\tcollisionMatrix[E_LASER][EXPLOSION] = false;\n\n\t\n\n\tcollisionMatrix[D_OBSTACLE][PLAYER] = true;\n\n\tcollisionMatrix[D_OBSTACLE][ENEMY] = false;\n\n\tcollisionMatrix[D_OBSTACLE][P_LASER] = true;\n\n\tcollisionMatrix[D_OBSTACLE][E_LASER] = false;\n\n\tcollisionMatrix[D_OBSTACLE][D_OBSTACLE] = false;\n\n\tcollisionMatrix[D_OBSTACLE][NOLETHAL_D_OBSTACLE] = false;\n\n\tcollisionMatrix[D_OBSTACLE][ND_ENEMY] = false;\n\n\tcollisionMatrix[D_OBSTACLE][EXPLOSION] = false;\n\n\t\n\n\tcollisionMatrix[NOLETHAL_D_OBSTACLE][PLAYER] = true;\n\n\tcollisionMatrix[NOLETHAL_D_OBSTACLE][ENEMY] = false;\n\n\tcollisionMatrix[NOLETHAL_D_OBSTACLE][P_LASER] = true;\n", "file_path": "ModuleCollision.cpp", "rank": 97, "score": 6.361856559185281 }, { "content": "\tgraphics = App->textures->Load(\"assets/shadow.png\");\n\n\tshadowPosition = { 2, 3, 43, 20 };\n\n\n\n\treturn ret;\n\n}\n\n\n\n// Called before quitting\n\nbool ModuleShadows::CleanUp()\n\n{\n\n\tbool ret = true;\n\n\treturn ret;\n\n}\n\n\n\nconst void ModuleShadows::DrawShadow(const float&x, const float& y, const float& z, const float& ownerWidth)\n\n{\n\n\tfloat scaleValue = 1.0f - (z / (float)MAX_Z);\n\n\n\n\tif (scaleValue < 0.0f) \n\n\t\tscaleValue = 0.0f;\n\n\n", "file_path": "ModuleShadows.cpp", "rank": 98, "score": 6.151288883542996 }, { "content": "\t\tb->lifePoints = h->lifePoints;\n\n\t\tactive.push_back(b);\n\n\n\n\t\tprevious = b;\n\n\t}\n\n\n\n\tpos.z = z + (bodySize + 3);\n\n\tEnemy* t = tail.createEnemyInstance(tail, pos, ND_ENEMY, moveSet+1, previous->oscillationAngle - 0.1f);\n\n\tt->superiorBodyPart = previous;\n\n\tt->lifePoints = h->lifePoints;\n\n\tactive.push_back(t);\n\n\n\n\taliveEnemy = true;\n\n}\n\n\n\nconst bool ModuleEnemy::onCollision(Collider* moduleOwner, Collider* otherCollider)\n\n{\n\n\tfor (std::list<Enemy*>::iterator it = active.begin(); it != active.end(); ++it)\n\n\t{\n\n\t\tif ((*it)->collider == moduleOwner)\n", "file_path": "ModuleEnemy.cpp", "rank": 99, "score": 6.14812211684784 } ]
C++
Sources/Modules/Core/Logger.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
#include <Core/Logger.h> #include <Core/IO/FileStream.h> #include <Core/System/Files.h> namespace Core { using namespace Core::System; LoggerMessage::LoggerMessage() : _msg(new Core::BufferStream()) { } LoggerMessage::~LoggerMessage() { } String LoggerMessage::getLastLine() { String8 string8; char oneChar; int32 readBytes = _msg->readUpTo(&oneChar, sizeof(char)); bool isEndLine = (oneChar == '\n'); while(readBytes == sizeof(char) && !isEndLine) { if(oneChar != '\r') { string8.push_back(oneChar); } readBytes = _msg->readUpTo(&oneChar, sizeof(char)); isEndLine = (oneChar == '\n'); } return String(string8); } String LoggerMessage::computeMessage (const String& loggerTag) { String str; String line; do { line = getLastLine(); str << loggerTag << _tagContainer << line << L"\n"; } while(!_msg->eof()); _tagContainer = L""; return str; } Logger::Logger(Ptr<OutputStream> stream, String name) { Ptr<TextOutputStream > tos = Ptr<TextOutputStream > (new TextOutputStream (stream, true)); addStream(tos, LOGGER_DEFAULT_STREAM_NAME); _name = name; _nbMsg = 0; _logMsgLevel = Core::L_DEBUG; setDefaultMsgLevel(L_INFO); _showTagIdMsg = true; _showTagAppTime = true; _showTagLocalTime = false; _showTagThreadId = false; _showTagMsgLevel = true; _DBGtoStdOut = true; } Logger::~Logger() { } void Logger::destroyStream(const String& name) { _streamMap.erase(name); } void Logger::addStream(Ptr<TextOutputStream > tos, const String& name) { _streamMap[name] = tos; } String Logger::getLoggerTag() { String str; if (_showTagIdMsg) { str += Core::toString(_nbMsg, 6); str += LOGGER_TAG_SEPARATOR; } if (_showTagAppTime) { str += Clock::applicationTime().toString(false, TD_PRINT_HOURS); str += LOGGER_TAG_SEPARATOR; #ifdef _WIN32 str += Clock::applicationTime().toString(false, TD_PRINT_COUNTER); str += LOGGER_TAG_SEPARATOR; #endif } if (_showTagLocalTime) { String time(Core::Clock::localTime().toString().slice(0, 22)); time[10] = L'_'; str += time; str += LOGGER_TAG_SEPARATOR; } if (_showTagThreadId) { str += Core::toStringHex(Thread::getCurrentThreadID(), 4); str += LOGGER_TAG_SEPARATOR; } if (_showTagMsgLevel) { switch(_msgLevel) { case L_ERROR: str += L"ERR"; break; case L_WARNING: str += L"WAR"; break; case L_INFO: str += L"INF"; break; case L_DEBUG: str += L"DBG"; break; } str += LOGGER_TAG_SEPARATOR; } return str; } void Logger::operator= (LoggerMessage& lm) { String loggerTag = getLoggerTag(); String msg = lm.computeMessage (loggerTag); #if defined _MSC_VER OutputDebugStringW(msg.c_str()); #endif if (_DBGtoStdOut == true && _msgLevel == L_DEBUG) { LM_COUT<<msg; } for(Map<String, Ptr<TextOutputStream > >::iterator it = _streamMap.begin(); it != _streamMap.end(); ++it) { (*it->second)<<msg; it->second->flush(); } _nbMsg++; } Logger& Logger::configMessage(ELogMsgLevel eLevel) { setMsgLevel(eLevel); return *this; } LoggerManager::LoggerManager() { _defautLogger = getFileName(getFileBaseName(getExecutableName())); String defaultFileName = _defautLogger; String ext = L".log"; String pathFile = getUserLocalAppDir() + L"/AnimaGames/"; createDirectory(pathFile); String pathAndFileName = pathFile + defaultFileName; Ptr<Core::FileOutputStream> defaultStreamLog (new Core::FileOutputStream(pathAndFileName + ext)); int32 idLog = 0; while (defaultStreamLog->isOpened() == false) { idLog++; defaultStreamLog->open(pathAndFileName + L"_" + Core::toString(idLog) + ext); } Ptr<Logger > defaultLog = (Ptr<Logger >)new Logger (defaultStreamLog, _defautLogger); defaultLog->setShowTagIdMsg(LOGGER_DEFAULT_TAG_ID_MSG); defaultLog->setShowTagAppTime(LOGGER_DEFAULT_TAG_APP_TIME); defaultLog->setShowTagLocalTime(LOGGER_DEFAULT_TAG_LOCAL_TIME); defaultLog->setShowTagThreadId(LOGGER_DEFAULT_TAG_THREAD_ID); defaultLog->setShowTagMsgLevel(LOGGER_DEFAULT_TAG_MSG_LEVEL); defaultLog->setLogMsgLevel(LM_LOGGER_DEFAULT_MSG_LEVEL); addLogger(defaultLog); defaultLog->addStream(Ptr<TextOutputStream > (new TextOutputStream (LM_COUT_PTR, true)), STDCOUT_STREAM_NAME); defaultLog->setDBGtoStdOut(false); } LoggerManager::~LoggerManager() { } void LoggerManager::destroyLogger(const String& name) { _loggerMap.erase(name); } void LoggerManager::addLogger(Ptr<Logger > log) { _loggerMap[log->getName()] = log; } Ptr<Logger > LoggerManager::getLogger(const String& name) { return _loggerMap[name]; } LoggerManager& LoggerManager::getInstance() { static LoggerManager sInstance; return sInstance; } }
#include <Core/Logger.h> #include <Core/IO/FileStream.h> #include <Core/System/Files.h> namespace Core { using namespace Core::System; LoggerMessage::LoggerMessage() : _msg(new Core::BufferStream()) { } LoggerMessage::~LoggerMessage() { } String LoggerMessage::getLastLine() { String8 string8; char oneChar; int32 readBytes = _msg->readUpTo(&oneChar, sizeof(char)); bool isEndLine = (oneChar == '\n'); while(readBytes == sizeof(char) && !isEndLine) { if(oneChar != '\r') { string8.push_back(oneChar); } readBytes = _msg->readUpTo(&oneChar, sizeof(char)); isEndLine = (oneChar == '\n'); } return String(string8); } String LoggerMessage::computeMessage (const String& loggerTag) { String str; String line; do { line = getLastLine(); str << loggerTag << _tagContainer << line << L"\n"; } while(!_msg->eof()); _tagContainer = L""; return str; } Logger::Logger(Ptr<OutputStream> stream, String name) { Ptr<TextOutputStream > tos = Ptr<TextOutputStream > (new TextOutputStream (stream, true)); addStream(tos, LOGGER_DEFAULT_STREAM_NAME); _name = name; _nbMsg = 0; _logMsgLevel = Core::L_DEBUG; setDefaultMsgLevel(L_INFO); _showTagIdMsg = true; _showTagAppTime = true; _showTagLocalTime = false; _showTagThreadId = false; _showTagMsgLevel = true; _DBGtoStdOut = true; } Logger::~Logger() { } void Logger::destroyStream(const String& name) { _streamMap.erase(name); } void Logger::addStream(Ptr<TextOutputStream > tos, const String& name) { _streamMap[name] = tos; } String Logger::getLoggerTag() { String str; if (_showTagIdMsg) { str += Core::toString(_nbMsg, 6); str += LOGGER_TAG_SEPARATOR; } if (_showTagAppTime) { str += Clock::applicationTime().toString(false, TD_PRINT_HOURS); str += LOGGER_TAG_SEPARATOR; #ifdef _WIN32 str += Clock::applicationTime().toString(false, TD_PRINT_COUNTER); str += LOGGER_TAG_SEPARATOR; #endif } if (_showTagLocalTime) { String time(Core::Clock::localTime().toString().slice(0, 22)); time[10] = L'_'; str += time; str += LOGGER_TAG_SEPARATOR; }
if (_showTagMsgLevel) { switch(_msgLevel) { case L_ERROR: str += L"ERR"; break; case L_WARNING: str += L"WAR"; break; case L_INFO: str += L"INF"; break; case L_DEBUG: str += L"DBG"; break; } str += LOGGER_TAG_SEPARATOR; } return str; } void Logger::operator= (LoggerMessage& lm) { String loggerTag = getLoggerTag(); String msg = lm.computeMessage (loggerTag); #if defined _MSC_VER OutputDebugStringW(msg.c_str()); #endif if (_DBGtoStdOut == true && _msgLevel == L_DEBUG) { LM_COUT<<msg; } for(Map<String, Ptr<TextOutputStream > >::iterator it = _streamMap.begin(); it != _streamMap.end(); ++it) { (*it->second)<<msg; it->second->flush(); } _nbMsg++; } Logger& Logger::configMessage(ELogMsgLevel eLevel) { setMsgLevel(eLevel); return *this; } LoggerManager::LoggerManager() { _defautLogger = getFileName(getFileBaseName(getExecutableName())); String defaultFileName = _defautLogger; String ext = L".log"; String pathFile = getUserLocalAppDir() + L"/AnimaGames/"; createDirectory(pathFile); String pathAndFileName = pathFile + defaultFileName; Ptr<Core::FileOutputStream> defaultStreamLog (new Core::FileOutputStream(pathAndFileName + ext)); int32 idLog = 0; while (defaultStreamLog->isOpened() == false) { idLog++; defaultStreamLog->open(pathAndFileName + L"_" + Core::toString(idLog) + ext); } Ptr<Logger > defaultLog = (Ptr<Logger >)new Logger (defaultStreamLog, _defautLogger); defaultLog->setShowTagIdMsg(LOGGER_DEFAULT_TAG_ID_MSG); defaultLog->setShowTagAppTime(LOGGER_DEFAULT_TAG_APP_TIME); defaultLog->setShowTagLocalTime(LOGGER_DEFAULT_TAG_LOCAL_TIME); defaultLog->setShowTagThreadId(LOGGER_DEFAULT_TAG_THREAD_ID); defaultLog->setShowTagMsgLevel(LOGGER_DEFAULT_TAG_MSG_LEVEL); defaultLog->setLogMsgLevel(LM_LOGGER_DEFAULT_MSG_LEVEL); addLogger(defaultLog); defaultLog->addStream(Ptr<TextOutputStream > (new TextOutputStream (LM_COUT_PTR, true)), STDCOUT_STREAM_NAME); defaultLog->setDBGtoStdOut(false); } LoggerManager::~LoggerManager() { } void LoggerManager::destroyLogger(const String& name) { _loggerMap.erase(name); } void LoggerManager::addLogger(Ptr<Logger > log) { _loggerMap[log->getName()] = log; } Ptr<Logger > LoggerManager::getLogger(const String& name) { return _loggerMap[name]; } LoggerManager& LoggerManager::getInstance() { static LoggerManager sInstance; return sInstance; } }
if (_showTagThreadId) { str += Core::toStringHex(Thread::getCurrentThreadID(), 4); str += LOGGER_TAG_SEPARATOR; }
if_condition
[]
C++
problem/Tree/Shortest distance between two nodes.cpp
mechusatveer/coding-questions
a86b41f753ffd70001357ab059ee0cb63c7914ff
#include<iostream> #include<list> using namespace std; struct Node { int val; Node *plft; Node *prgt; Node(int v) : val(v), plft(NULL), prgt(NULL) {} }; bool GetNodePath(Node *root, Node *node, list<Node*>& path) { if (root == node) return true; path.push_back(root); bool found = false; if (root->plft != NULL) found = getNodePath(root->plft, node, path); if (!found && root->prgt) found = getNodePath(root->prgt, node, path); if (!found) path.pop_back(); return found; } Node* LastCommonNode(const list<Node*>& path1, const list<Node*>& path2) { list<Node*>::const_iterator iterator1 = path1.begin(); list<Node*>::const_iterator iterator2 = path2.begin(); Node *last = NULL; while (iterator1 != path1.end() && iterator2 != path2.end()) { if (*iterator1 == *iterator2) last = *iterator1; iterator1++; iterator2++; } return last; } Node *LastCommonAncestor(Node* root, Node* node1, Node* node2) { if(root == NULL || node1 == NULL || node2 == NULL) return NULL; list<Node*> path1; GetNodePath(root, node1, path1); list<Node*> path2; GetNodePath(root, node2, path2); return LastCommonNode(path1, path2); } int Height(Node *lca, Node *node,bool &found) { int lheight = 0, rheight = 0; if (lca) { if (found == false && lca == node) { found = true; return 0; } else if (found == false) { lheight = Height(lca->plft, node, found); rheight = 0; if(found == false) { rheight = Height(lca->prgt, node, found); } if(found == true) { return lheight > rheight? 1+lheight : 1+rheight; } else { return 0; } } else { return 0; } } else { return 0; } } int ShortestDistance(Node *node1, Node* node2, Node *lca) { if (lca) { bool found = false; int dist1 = Height(lca, node1, found); cout<<"Distance of "<<node1->val<<": "<<dist1<<endl; found = false; int dist2 = Height(lca,node2,found); cout<<"Distance of "<<node2->val<<": "<<dist2<<endl; return dist1 + dist2; } else { return 0; } } int main() { Node *root = new Node(1); root->plft = new Node(2); root->prgt = new Node(3); root->plft->plft = new Node(4); root->plft->prgt = new Node(5); root->prgt->plft = new Node(6); root->prgt->prgt = new Node(7); root->prgt->prgt->plft = new Node(8); root->prgt->prgt->prgt = new Node(9); Node *node1 = root->prgt->prgt->plft; Node *node2 = root->prgt->plft; Node *lca = LastCommonAncestor(root, node1, node2); if (lca) { cout<<"Least Common Ancestor: "<<lca->val<<endl; } cout<<"Total distance: "<<ShortestDistance(node1, node2, lca)<<endl; return 0; }
#include<iostream> #include<list> using namespace std; struct Node { int val; Node *plft; Node *prgt; Node(int v) : val(v), plft(NULL), prgt(NULL) {} }; bool GetNodePath(Node *root, Node *node, list<Node*>& path) { if (root == node) return true; path.push_back(root); bool found = false; if (root->plft != NULL) found = getNodePath(root->plft, node, path); if (!found && root->prgt) found = getNodePath(root->prgt, node, path); if (!found) path.pop_back(); return found; } Node* LastCommonNode(const list<Node*>& path1, const list<Node*>& path2) { list<Node*>::const_iterator iterator1 = path1.begin(); list<Node*>::const_iterator iterator2 = path2.begin(); Node *last = NULL; while (iterator1 != path1.end() && iterator2 != path2.end()) { if (*iterator1 == *iterator2) last = *iterator1; iterator1++; iterator2++; } return last; } Node *LastCommonAncestor(Node* root, Node* node1, Node* node2) { if(root == NULL || node1 == NULL || node2 == NULL) return NULL; list<Node*> path1; GetNodePath(root, node1, path1); list<Node*> path2; GetNodePath(root, node2, path2); return LastCommonNode(path1, path2); } int Height(Node *lca, Node *node,bool &found) { int lheight = 0, rheight = 0; if (lca) { if (found == false && lca == node) { found = true; return 0; } else if (found == false) { lheight = Height(lca->plft, node, found); rheight = 0; if(found == false) { rheight = Height(lca->prgt, node, found); } if(found == true) { return lheight > rheight? 1+lheight : 1+rheight; } else { return 0; } } else { return 0; } } else { return 0; } } int ShortestDistance(Node *node1, Node* node2, Node *lca) {
} int main() { Node *root = new Node(1); root->plft = new Node(2); root->prgt = new Node(3); root->plft->plft = new Node(4); root->plft->prgt = new Node(5); root->prgt->plft = new Node(6); root->prgt->prgt = new Node(7); root->prgt->prgt->plft = new Node(8); root->prgt->prgt->prgt = new Node(9); Node *node1 = root->prgt->prgt->plft; Node *node2 = root->prgt->plft; Node *lca = LastCommonAncestor(root, node1, node2); if (lca) { cout<<"Least Common Ancestor: "<<lca->val<<endl; } cout<<"Total distance: "<<ShortestDistance(node1, node2, lca)<<endl; return 0; }
if (lca) { bool found = false; int dist1 = Height(lca, node1, found); cout<<"Distance of "<<node1->val<<": "<<dist1<<endl; found = false; int dist2 = Height(lca,node2,found); cout<<"Distance of "<<node2->val<<": "<<dist2<<endl; return dist1 + dist2; } else { return 0; }
if_condition
[ { "content": "struct Node {\n\n int val;\n\n Node* plft;\n\n Node* prgt;\n\n\n\n\tNode(int v) : val(v), plft(NULL), prgt(NULL) {}\n\n};\n\n\n\n\n\n//need finish this version\n\n\n\nint main() {\n\n\n\n\t/*\n\n\tNode *root = new Node(1);\n\n\troot->plft = new Node(2);\n\n\troot->prgt = new Node(3);\n\n\troot->plft->plft = new Node(4);\n\n\troot->plft->prgt = new Node(5);\n\n\troot->prgt->plft = new Node(6);\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 0, "score": 115952.27447917088 }, { "content": "struct Node {\n\n int val;\n\n Node *plft;\n\n Node *prgt;\n\n \n\n Node(int v) : val(v), plft(NULL), prgt(NULL) {}\n\n};\n\n\n\n\n\n\n\n\n\nNode *SecondLargestNode(NODE *root) {\n\n\n\n\n\n if (root == NULL || root->plft == NULL && root->prgt == NULL) return NULL;\n\n\n\n NODE *iter = root;\n\n NODE *parent = NULL;\n\n \n\n while (iter->prgt != NULL) {\n", "file_path": "problem/Tree/Second largest node in BST.cpp", "rank": 1, "score": 112531.14414397393 }, { "content": "struct Node {\n\n\n\n int val\n\n Node *plft;\n\n TreeNode *prgt;\n\n \n\n Node(int v) : val(v), plft(NULL), prgt(NULL) {}\n\n\n\n};\n\n\n\nint Height(Node* root) {\n\n\n\n if (root == NULL) {\n\n return 0;\n\n }\n\n\n\n int leftheight = Height(root->plft);\n\n int rightheight = Height(root->prgt);\n\n\n\n if (leftheight > rightheight) {\n", "file_path": "problem/Tree/Longest distance between two nodes.cpp", "rank": 2, "score": 112531.14414397393 }, { "content": "struct NODE {\n\n int val;\n\n NODE* pLft;\n\n NODE* pRgt;\n\n \n\n NODE(int n) : val(n), pLft(NULL), pRgt(NULL) {}\n\n};\n\n\n\nvoid GetRightMostBTInner(NODE* Node, vector<NODE*> &vec, int Lev) {\n\n\n\n if (Node == NULL) return;\n\n \n\n if (Lev >= vec.size()) {\n\n \n\n vec.push_back(Node);\n\n cout<<Node->val;\n\n }\n\n\t\n\n \n\n GetRightMostBTInnerNode->pRgt, vec, Lev+1);\n", "file_path": "problem/Tree/Find the right most node in each level of a binary tree.cpp", "rank": 4, "score": 109383.88740781978 }, { "content": "struct NODE {\n\n int val;\n\n vector<NODE*> vec;\n\n \n\n NODE(int n) : val(n), vec() {}\n\n};\n\n \n\nvoid SerialInner(NODE* node, char*& p) {\n\n\n\n\t\n\n itoa(node->val, p, 10);\n\n p += strlen(p);\t\n\n int num = node->vec.size();\n\n itoa(num, p, 10);\n\n p += strlen(p);\n\n\t\n\n if (node->vec.size() == 0) return;\n\n \n\n for (vector<NODE*>::iterator it = node->vec.begin(); it != pNode->vec.end(); it++) {\n\n \n", "file_path": "problem/Tree/SerializeDeSerialize an arbitrary nodes tree.cpp", "rank": 5, "score": 109383.88740781978 }, { "content": "struct node {\n\n double _x, _y;\n\n node(double x, double y): _x(x), _y(y){}\n\n node(): _x(0.0), _y(0.0){}\n\n};\n\n\n\ndouble Distance(node x, node target) {\n\n\treturn pow(x._x - target._x, 2) + pow(x._y - target._y,2);\n\n}\n\n\n\nnode target(0,0);\n\n\n", "file_path": "problem/Heap/TwoDtopk.cpp", "rank": 6, "score": 107116.52377831328 }, { "content": "struct Node {\n\n int val;\n\n Node *left;\n\n Node *right;\n\n Node *parent;\n\n \n\n Node(int v) : val(v), left(NULL), right(NULL), parent(NULL) {}\n\n};\n\n\n\n\n\nNode *FindNeighbor( Node *node, int level ) {\n\n\n\n if( node == NULL ) return NULL;\n\n if( level == 0 ) return node;\n\n\n\n Node *left = FindNeighbor(node->left,level+1);\n\n //always return left child at first such that this node is the immediate right neighbor\n\n if( left ) { \n\n\t\treturn left;\n\n\t} else { \n", "file_path": "problem/Tree/Immediate right neighbor.cpp", "rank": 7, "score": 105134.336527965 }, { "content": "struct NODE {\n\n int val;\n\n NODE* plft;\n\n NODE* prgt;\n\n \n\n NODE(int n) : val(n), plft(NULL), prgt(NULL) {}\n\n};\n\n\n\nvoid ShiftUp(NODE *node) {\n\n\n\n if(!node) return; \n\n \n\n NODE *largest = node;\n\n\n\n\t //find the largest node\n\n if (node->plft != NULL && largest->val < node->plft->val) { \n\n\n\n largest = node->plft; \n\n\n\n }\n", "file_path": "problem/Tree/Heapify a binary tree.cpp", "rank": 8, "score": 105134.336527965 }, { "content": "struct NODE {\n\n int val;\n\n NODE* pLft;\n\n NODE* pRgt;\n\n \n\n NODE(int n) : val(n), pLft(NULL), pRgt(NULL) {}\n\n};\n\n\n\n/*\n\nHere is the inorder iterator.\n\n*/\n\n\n", "file_path": "problem/Tree/Iterator for binary tree.cpp", "rank": 9, "score": 105134.336527965 }, { "content": "struct NODE {\n\n int val;\n\n NODE* pLft;\n\n NODE* pRgt;\n\n int size; //the size of the subtree rooted at that node\n\n NODE* pParent;\n\n \n\n NODE(int n, int sz = 1) : val(n), size(sz), pLft(NULL), pRgt(NULL), pParent(NULL) {}\n\n \n\n void setLeft(NODE* node) {\n\n if (node==NULL) return;\n\n pLft = node;\n\n node->pParent = this;\n\n }\n\n \n\n void setRight(NODE* node) {\n\n if (node==NULL) return;\n\n pRgt = node;\n\n node->pParent = this;\n\n }\n", "file_path": "problem/Tree/Statistical binary search tree.cpp", "rank": 10, "score": 103250.96983060292 }, { "content": "struct Node {\n\n int val;\n\n Node *plft;\n\n Node *prgt;\n\n \n\n Node(int v) : val(v), plft(NULL), prgt(NULL) {}\n\n};\n\n\n\n\n\nvoid GetHorizontalDistance(Node *root, int hd, unordered_map<int, int> &hdmp) { \n\n\n\n \n\n if (root == NULL) return;\n\n \n\n \n\n GetHorizontalDistance(root->plft, hd - 1, hdmp);\n\n \n\n \n\n int prevsum = (hdmp.find(hd) == hdmp.end()) ? 0 : hdmp.find(hd)->second;\n\n\n", "file_path": "problem/Tree/Vertical sum in a binary tree.cpp", "rank": 11, "score": 103250.96983060292 }, { "content": "struct NODE {\n\n int val;\n\n NODE* pLft;\n\n NODE* pRgt;\n\n \n\n NODE(int n) : val(n), pLft(NULL), pRgt(NULL) {}\n\n};\n\n\n\n//postorder\n\nvoid PostOrderTravel(NODE* root) {\n\n assert(root);\n\n \n\n stack<NODE*> stk;\n\n NODE* cur = root;\n\n while (cur != NULL) {\n\n \n\n stk.push(cur);\n\n cur = cur->pLft;\n\n }\n\n \n", "file_path": "problem/Tree/PreInPostorder travel of bT with stack.cpp", "rank": 12, "score": 101459.21347241984 }, { "content": "struct NODE {\n\n int val;\n\n NODE* pLft;\n\n NODE* pRgt;\n\n \n\n NODE(int n) : val(n), pLft(NULL), pRgt(NULL) {}\n\n};\n\n \n\nvoid SerializeInner(char * &p, NODE* node) {\n\n if (node == NULL) {\n\n *p++ = '#';\n\n *p++ = ' ';\n\n return;\n\n }\n\n //char * itoa ( int value, char * str, int base );\n\n //Converts an integer value to a null-terminated string using \n\n //the specified base and stores the result in the array given\n\n //by str parameter.\n\n\t\n\n itoa(node->val, p, 10);\n", "file_path": "problem/Tree/SerializeDeSerialize a binary tree.cpp", "rank": 13, "score": 101459.21347241984 }, { "content": "struct NODE {\n\n int val;\n\n NODE* next;\n\n \n\n NODE(int x) : val(x), next(NULL) {}\n\n};\n\n\n\n//insert x after p\n\nvoid Insert(NODE* p, int x) {\n\n NODE* tmp = p->next;\n\n NODE* newnode = new NODE(x);\n\n p->next = newnode;\n\n newnode->next = tmp;\n\n}\n\n \n\nvoid InsertToCycleLink(NODE* node, int x) {\n\n assert(node != NULL);\n\n \n\n NODE* iter = node;\n\n NODE* big = iter; \n", "file_path": "problem/LinkedList/Insert into a Cyclic Sorted List.cpp", "rank": 14, "score": 101459.21347241984 }, { "content": "struct NODE {\n\n int val;\n\n NODE* Lft;\n\n NODE* Rgt;\n\n \n\n NODE(int n) : val(n), Lft(NULL), Rgt(NULL) {}\n\n};\n\n \n\nbool BinTreeSwitchEqualInner(NODE* node1, NODE* node2, int& switch) {\n\n switch = 0;\n\n\t\n\n if (node1 == NULL || node2 == NULL) return node1 == NULL && node2 == NULL;\n\n \n\n if (node1->val != node2->val) return false;\n\n \n\n int leftswitch, rightswitch;\n\n \n\n if (BinTreeSwitchEqualInner(node1->Lft, node2->Lft, leftswitch) && \n\n BinTreeSwitchEqualInner(node1->Rgt, node2->Rgt, rightswitch)) {\n\n \n", "file_path": "problem/Tree/Switch binary tree to make equal.cpp", "rank": 15, "score": 101459.21347241984 }, { "content": "struct NODE {\n\n int val;\n\n NODE* pLft;\n\n NODE* pRgt;\n\n \n\n NODE(int n) : val(n), pLft(NULL), pRgt(NULL) {}\n\n};\n\n\n\n \n\nint GetLargestBSTInner(NODE* Node, int& minbound, int& maxbound, NODE*& maxbstroot, int& maxbstnum) {\n\n \n\n assert(Node);\n\n \n\n minbound = Node->val;\n\n maxbound = Node->val;\n\n \n\n int result = 1; //count root\n\n bool bivalid = false;\n\n if (Node->pLft != NULL) {\n\n \n", "file_path": "problem/Tree/Find the largest BST sub tree in BT.cpp", "rank": 16, "score": 99752.5420206213 }, { "content": "struct node {\n\n int a,b,val; //element index and their value sum\n\n node(int _a,int _b,int v): a(_a),b(_b),val(v) {}\n\n\t\n\n};\n\n\n", "file_path": "problem/Heap/Kth maximal element of sum of two arrays.cpp", "rank": 17, "score": 99752.5420206213 }, { "content": "struct TNode {\n\n int val;\n\n TNode* plft;\n\n TNode* prgt;\n\n TNode* parent;\n\n\n\n TNode(int v) : val(v), plft(NULL), prgt(NULL), parent(NULL) {}\n\n};\n\n\n\n//print node below given node \n\nvoid PrintDown(TNode * node, int k) {\n\n\n\n if (node == NULL || k < 0) return;\n\n\n\n if (k == 0) {\n\n cout<<node->val<<endl;\n\n } else {\n\n PrintDown(node->plft, k -1);\n\n PrintDown(node->prgt, k -1);\t\n\n }\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 18, "score": 97779.65219680007 }, { "content": "", "file_path": "problem/Quadtree.cpp", "rank": 19, "score": 92779.9945778869 }, { "content": "struct TreeNode {\n\n int val;\n\n vector<TreeNode*> children; \n\n TreeNode(int n) : val(n), children() {}\n\n};\n\n\n\nint MaxPathSumInner(TreeNode *node, int &maxSoFar) {\n\n if (node == NULL) return 0;\n\n\tint maxPath = node->val;\n\n\tint tempPath = INT_MIN;\n\n\tvector<TreeNode*>::iterator it = node->children.begin();\n\n\tfor (; it != node->children.end(); it++) {\n\n\t\tint maxchild = MaxPathSumInner(*it, maxSoFar);\n\n\t\t\n\n\t\tif (maxchild > 0) maxPath += maxchild;\n\n\t\tif (maxchild > tempPath) tempPath = maxchild;\n\n\t}\n\n\tif (maxPath > maxSoFar) maxSoFar = maxPath;\n\n\tint res = node->val;\n\n\treturn max(res, res + tempPath); //note path definition\n", "file_path": "problem/Tree/Maximalpathsum.cpp", "rank": 20, "score": 90690.99953321335 }, { "content": "struct Racer {\n\n\n\n\n\n Racer(int ide, int starte, int ende) {\n\n id = ide;\n\n start = starte;\n\n end = ende;\n\n startrank = 0;\n\n score = 0;\n\n }\n\n Racer() {\n\n id = -1;\n\n start = -1;\n\n end = -1;\n\n startrank = 0;\n\n score = 0;\n\n }\n\n\n\n int id, start, end, score, startrank;\n\n};\n", "file_path": "problem/Racescore.cpp", "rank": 21, "score": 54179.822181620446 }, { "content": "struct Event {\n\n Event(int _h, int _x, int _type) \n\n : height(_h), x(_x), type(_type) {}\n\n enum Type{START, END};\n\n int height;\n\n int x;\n\n int type;\n\n};\n\n/*\n\nsort the event from begin to end by the following order:\n\nthe event with smaller x axis value, with smaller type,\n\nif both event are START, with larger height, or if both\n\nevent are END, with smaller height. \n\n\n\n*/\n\nbool CmpEvent(const Event* lhs, const Event* rhs) {\n\n if (lhs->x == rhs->x) {\n\n if (lhs->type == rhs->type) {\n\n if (lhs->type == Event::START) {\n\n return lhs->height > rhs->height;\n", "file_path": "problem/Skyline.cpp", "rank": 22, "score": 54179.822181620446 }, { "content": "", "file_path": "problem/Onlineuser.cpp", "rank": 23, "score": 54179.822181620446 }, { "content": "", "file_path": "problem/Groupcontact.cpp", "rank": 24, "score": 54179.822181620446 }, { "content": "", "file_path": "problem/Onlineuser.cpp", "rank": 25, "score": 54179.822181620446 }, { "content": "struct Compareto {\n\n bool operator() (const Cell *a, const Cell *b) {\n\n return a->height > b->height;\n\n }\n\n};\n\n\n\nconst int m = 3;\n\nconst int n = 3;\n\npriority_queue<Cell*, vector<Cell*>, Compareto> minheap; \n\nvector<vector<bool> > visited(m, vector<bool>(n, false));\n\nvector<vector<int> > mat(m, vector<int>(n, 0));\n\n\n\n\n\n\n\nvoid Check(int x, int y, int lowest, int &result) {\n\n\n\n if(x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) return;\n\n if(mat[x][y] < lowest) result += lowest - mat[x][y];\n\n visited[x][y] = true;\n\n minheap.push(new Cell(x,y, max(lowest, mat[x][y])));\n", "file_path": "problem/Heap/Waterin2dhistogram.cpp", "rank": 26, "score": 53074.507745440525 }, { "content": "struct Cell {\n\n\n\n int x;\n\n int y;\n\n int height;\n\n\tCell(): x(0), y(0), height(0) {}\n\n Cell(int _x,int _y,int _height): x(_x), y(_y), height(_height) {}\n\n\n\n};\n\n\n", "file_path": "problem/Heap/Waterin2dhistogram.cpp", "rank": 27, "score": 53074.507745440525 }, { "content": "struct GreaterNote {\n\n\n\n bool operator() (const node a, const node b) {\n\n return Distance(a, target) < Distance(b, target);\n\n }\n\n};\n\n\n\n\n\n\n\nvector<node> GetKClosestNode(vector<node> nodes, int k) {\n\n priority_queue<node, vector<node>, GreaterNote > q; //build the max heap\n\n size_t size = nodes.size();\n\n if (size <= k) return nodes;\n\n for (size_t i = 0; i < k; i++ ){\n\n q.push(nodes[i]);\n\n }\n\n size_t num = k;\n\n\t\n\n while (num < size) {\n\n node top = q.top();\n", "file_path": "problem/Heap/TwoDtopk.cpp", "rank": 28, "score": 51033.41905068699 }, { "content": "/////////////////////////////////////////// \n\nstruct TOKEN {\n\n bool bnull;\n\n int val;\n\n TOKEN(bool b, int n) : bnull(b), val(n) {}\n\n};\n\n \n\nTOKEN GetToken(const char* &p) {\n\n while(*p == ' ') p++;\n\n \n\n if (*p < '0' || *p > '9') {\n\n \n\n p++;\n\n return TOKEN(true, 0);\n\n }\n\n \n\n int val = 0;\n\n while (*p >= '0' && *p <= '9') {\n\n \n\n val = 10*val + *p++ - '0';\n\n \n", "file_path": "problem/Tree/SerializeDeSerialize a binary tree.cpp", "rank": 29, "score": 49190.89479681765 }, { "content": "struct GreaterNote {\n\n\n\n bool operator() (const node a, const node b) {\n\n return a.val < b.val;\n\n }\n\n};\n\n\n\nint FindKthSum1(int A[],int m,int B[],int n,int k) {\n\n\n\n\tpriority_queue<node, vector<node>, GreaterNote > q; //build the max heap\n\n\tq.push(node(0,0,A[0]+B[0]));\n\n\tset<pair<int,int> > visited;\n\n\tvisited.insert(pair<int,int>(0,0));\n\n\twhile(!q.empty()) {\n\n\t\n\n\t\tnode t = q.top();\n\n\t\tq.pop();\n\n\t\tk--;\n\n\t\tif(k == 0) return t.val;\n\n\t\t\n", "file_path": "problem/Heap/Kth maximal element of sum of two arrays.cpp", "rank": 30, "score": 47519.303438591596 }, { "content": "using namespace std;\n\n\n\nbool Prob() {\n\n\n\n int i = rand();\n\n if (i % 2 == 0) {\n\n\n\n return true;\n\n\n\n } else {\n\n\n\n return false;\n\n\n\n }\n\n}\n\n\n\nbool ProbAny(double probability, bool value ) {\n\n\n\n if (probability < 0.5) {\n\n\t\n", "file_path": "problem/Tree/Output true.cpp", "rank": 31, "score": 40305.559503098884 }, { "content": "/*\n\n\n\nCalculate the last digit of a^b, where a,b are positive. Use map to store the last digit.\n\nO(logb) time, O(10) space\n\n\n\n*/\n\n\n\n#include<iostream>\n\n#include<map>\n\n#include<math.h>\n\nusing namespace std;\n\n\n\nunsigned int LastDigit(unsigned int a, unsigned int b, map<unsigned int, unsigned int> &mp){\n\n\n\n if (a == 1) return 1;\n\n unsigned int digit = a %10;\n\n digit = mp[a]; //a^2;\n\n\n\n unsigned int time = 2;\n\n for (; time * 2 <= b; time = time * 2){\n", "file_path": "problem/Math/Last digit of a^b.cpp", "rank": 32, "score": 40300.40422053819 }, { "content": " return ProbAny(1.0 - probability,!value);\n\n\n\n } else if (Prob() == value) {\n\n\n\n return value;\n\n\n\n } else {\n\n\n\n return ProbAny((probability - 0.5) * 2, value);\n\n\n\n }\n\n\n\n}\n\n\n\nint main() {\n\n\n\n srand (time(NULL));\n\n\t\n\n for (int i = 0; i< 20; ++i) {\n\n\n\n cout<<ProbAny(0.3, true)<<endl;\n\n }\n\n return 0;\n\n\n\n}\n", "file_path": "problem/Tree/Output true.cpp", "rank": 33, "score": 40293.48422962657 }, { "content": "/*\n\n\n\nGiven a function which can return true with probability 0.5, write a function which can return ture with any probability.\n\n\n\nsolution: from peking2 at mitbbs\n\n\n\n*/\n\n\n\n/*\n\n\n\nsolution: suppose you want to the function return true with probability 0.4, which means it returns false with 0.6\n\nIf you get false from prob(), you can return false because 0.5 is smaller than 0.6. If get true from prob(), you have\n\nto subtract 0.5 from to 0.6, you need to a function return false with probability 0.2 next time.\n\nIt is similar when we want to return true with probability larger than 0.5\n\n\n\n\n\n*/\n\n\n\n#include<iostream>\n\n#include<time.h>\n", "file_path": "problem/Tree/Output true.cpp", "rank": 34, "score": 40286.71174120319 }, { "content": "\n\n digit = mp[digit];\n\n }\n\n \n\n time = time / 2;\n\n\n\n unsigned int extratime = b - time * 2;\n\n\n\n digit = (digit * (int)pow((double)a, (int)extratime)) % 10;\n\n \n\n\n\n return digit;\n\n}\n\n\n\n\n\nint main(){\n\n\t\n\n map<unsigned int, unsigned int> mp;\n\n mp[1]=1;\n\n mp[2]=4;\n", "file_path": "problem/Math/Last digit of a^b.cpp", "rank": 35, "score": 40286.448019464995 }, { "content": " mp[3]=9;\n\n mp[4]=6;\n\n mp[5]=5;\n\n mp[6]=6;\n\n mp[7]=9;\n\n mp[8]=4;\n\n mp[9]=1;\n\n\n\n cout<<LastDigit(2, 35, mp)<<endl;\n\n return 0;\n\n}", "file_path": "problem/Math/Last digit of a^b.cpp", "rank": 36, "score": 40286.011816461876 }, { "content": "/*\n\n\n\nGiven an array with numbers, find the number with most duplicates, and return all the corresponding index with equal probability.\n\n\n\nFor example, int input[]={3,7,4,3,6,1,3,6}, the function should return index 0, 3, 6 each with probability 1/3.\n\n\n\n*/\n\n\n\n/*\n\n\n\nsolution: scan first time to get the number with most duplicates, scan second time to output the num equally.\n\nO(n) time, O(n) space\n\n\n\n*/\n\n\n\n#include<iostream>\n\n#include<unordered_map>\n\nusing namespace std;\n\n\n\nint MaxDupEqual(int arr[], int len) {\n", "file_path": "problem/Math/Return the duplicate.cpp", "rank": 37, "score": 40281.56494835272 }, { "content": "\n\n int maxoccur = 0;\n\n int num = 0 ;\n\n int maxnum = 0;\n\n int result=0;\n\n unordered_map<int , int> occurmap;\n\n unordered_map<int , int> randompickmap;\n\n for (int i = 0 ; i < len ; ++i) {\n\n\n\n num = arr[i];\n\n if (occurmap.count(num)) {\n\n\n\n occurmap[num] += 1;\n\n\n\n } else {\n\n\n\n occurmap[num] = 1;\n\n\n\n }\n\n\n", "file_path": "problem/Math/Return the duplicate.cpp", "rank": 38, "score": 40273.69723677676 }, { "content": " return result;\n\n}\n\n\n\n\n\n\n\nint main() {\n\n\n\n int arr[] = {3,7,4,3,6,1,3,6};\n\n int len = sizeof(arr)/sizeof(arr[0]);\n\n cout<<MaxDupEqual(arr, len)<<endl;\n\n return 0;\n\n}\n\n\n\n\n", "file_path": "problem/Math/Return the duplicate.cpp", "rank": 39, "score": 40273.28351017274 }, { "content": " if (occurmap[num] > maxoccur) {\n\n\n\n maxoccur = occurmap[num];\n\n maxnum = randompickmap[num]; \n\n }\n\n\n\n }\n\n \n\n int occur = 0;\n\n\n\n for (int i = 0 ; i < len ; ++i) {\n\n \n\n if (arr[i] == maxnum) {\n\n\n\n occur++;\n\n\n\n if(rand() % occur == 0) result = i;\n\n }\n\n }\n\n\n", "file_path": "problem/Math/Return the duplicate.cpp", "rank": 40, "score": 40272.922031020746 }, { "content": "}\n\n//print above node from given node \n\nvoid PrintAbove(TNode* node, int k) {\n\n\n\n if(node == NULL || k < 0) return;\n\n\n\n TNode *parent = NULL;\n\n parent = node->parent;\n\n while (parent != NULL) {\n\n k--;\n\n\t\tif(k == 0) {\n\n cout<<parent->val<<endl;\n\n } else if(node == parent->plft) {\n\n\t\t\tPrintDown(parent->prgt, k-1);\n\n } else {\n\n PrintDown(parent->plft,k-1);\n\n }\n\n\t\t\n\n node = parent;\n\n parent = parent->parent;\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 41, "score": 39728.87541440872 }, { "content": "\troot->prgt->prgt = new Node(7);\n\n\tNode *start = root->prgt->prgt;\n\n\t*/\n\n\t\n\n\n\n\tTNode *root1 = new TNode(1);\n\n\troot1->plft = new TNode(2);\n\n\troot1->prgt = new TNode(3);\n\n\troot1->plft->parent = root1;\n\n\troot1->prgt->parent = root1;\n\n\t\n\n\troot1->plft->plft = new TNode(4);\n\n\troot1->plft->plft->parent = root1->plft;\n\n\troot1->plft->prgt = new TNode(5);\n\n\troot1->plft->prgt->parent = root1->plft;\n\n\troot1->prgt->plft = new TNode(6);\n\n\troot1->prgt->prgt = new TNode(7);\n\n\troot1->prgt->plft->parent = root1->prgt;\n\n\troot1->prgt->prgt->parent = root1->prgt;\n\n\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 42, "score": 39724.91757040925 }, { "content": "/*\n\n\n\nPrint all Nodes at a given distance from a starting Node in a binary tree\n\n\n\n*/\n\n\n\n\n\n#include<iostream>\n\n#include<vector>\n\n#include<unordered_set>\n\n#include<queue>\n\nusing namespace std;\n\n\n\n\n\n//The binary tree has parent link.\n\n\n\n/*\n\n\n\nsolution: print nodes in the subtree of the start node is easy. For those nodes as the start node's ancestor, \n\nuse parent link to move up to print nodes, for those nodes as the start node's neighbor and those nodes in another\n\nsubtree of the full tree, call the print down function with proper node and update distance.\n\n\n\nO(n) time, O(1) space\n\n\n\n*/\n\n\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 43, "score": 39719.58574534992 }, { "content": " }\n\n}\n\n\n\n\n\nvoid PrintDistancekNodeP(TNode *start, int k) {\n\n\n\n\tif (start == NULL || k < 0) return;\n\n\n\n\tif (start->parent != NULL) {\n\n PrintAbove(start, k);\n\n\t}\n\n PrintDown(start, k);\n\n\n\n}\n\n\n\n\n\n//The binary tree does not have parent link.\n\n\n\n/*\n\n\n\nsolution:\n\n\n\n*/\n\n\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 44, "score": 39717.48167714881 }, { "content": "\tTNode *start1 = root1->prgt->prgt;\n\n\tTNode *start2 = root1->prgt;\n\n\n\n\tPrintDistancekNodeP(root1, 1);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(root1, 2);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(start1, 1);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(start1, 2);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(start1, 3);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(start2, 1);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(start2, 2);\n\n\tcout<<endl;\n\n\tPrintDistancekNodeP(start2, 3);\n\n\tcout<<endl;\n\n\treturn 0;\n\n\n\n}\n", "file_path": "problem/Tree/Printing all nodes.cpp", "rank": 45, "score": 39715.106137233386 }, { "content": "\n\n return leftheight + 1;\n\n\n\n } else {\n\n\n\n return rightheight + 1;\n\n }\n\n}\n\n\n\nint LongestDistanceTwoNodes(Node *root) {\n\n\n\n if (root == NULL) {\n\n\n\n return 0;\n\n }\n\n\n\n int lheight = Height(root->plft);\n\n int rheight = Height(root->prgt);\n\n\n\n int llength = LongestDistanceTwoNodes(root->plft);\n\n int rlength = LongestDistanceTwoNodes(root->prgt);\n\n\n\n return max(lheight + rheight+ 1, max(llength, rlength));\n\n}\n", "file_path": "problem/Tree/Longest distance between two nodes.cpp", "rank": 52, "score": 37709.14415014129 }, { "content": " \n\n parent = iter;\n\n\n\n iter = iter->prgt;\n\n\n\n }\n\n\n\n if (iter->left == NULL) return parent;\n\n\n\n NODE *leftsub = iter->plft;\n\n\n\n while (leftsub=>prgt != NULL) {\n\n \n\n\n\n leftsub = leftsub=>prgt;\n\n\n\n }\n\n \n\n return leftsub;\n\n\n\n}\n\n\n", "file_path": "problem/Tree/Second largest node in BST.cpp", "rank": 53, "score": 37692.53074604532 }, { "content": "*/\n\n\n\n\n\n/*\n\n\n\nsolution: for a node, if it has child, return first child, otherwise, if it has sibling, return next sibling, \n\notherwise, return its partent sibling\n\n\n\n\n\n*/\n\n\n\n\n\nNode* GetNextNode(Node *node) {\n\n assert(node != NULL);\n\n\n\n Node* next = node->GetFirstChild();\n\n if(next) return next;\n\n\n\n next = node->GetSlibing();\n\n\n", "file_path": "problem/Tree/Implement getNextNode().cpp", "rank": 55, "score": 37684.15825512361 }, { "content": " if(next) return next;\n\n\n\n next = node->GetParent();\n\n\n\n while (next) {\n\n\n\n next = next->GetSlibing();\n\n if(next) return next;\n\n next = next->GetParent();\n\n }\n\n\n\n return NULL;\n\n}\n", "file_path": "problem/Tree/Implement getNextNode().cpp", "rank": 56, "score": 37682.963978951724 }, { "content": "/*\n\n\n\nLongest distance between any two nodes in binary tree\n\n\n\n*/\n\n\n\n/*\n\n\n\nsolution: the longest distance should be in left subtree or in right subtree or it should pass through root. \n\nWe can do it recursively.\n\nO(nlogn) time, O(1) space\n\n\n\n*/\n\n\n\n\n", "file_path": "problem/Tree/Longest distance between two nodes.cpp", "rank": 57, "score": 37682.6856789507 }, { "content": "/*\n\n\n\nSecond largest node in the binary search tree\n\n\n\n*/\n\n\n\n/*\n\n \n\nsolutions: iterate right subtree to find the lastest node. If the node does not have left child, the node's parent is the second largest node, \n\notherwise, find the largest node in its left subtree.\n\nO(n) time, O(1) space \n\n \n\n*/\n\n\n\n\n", "file_path": "problem/Tree/Second largest node in BST.cpp", "rank": 58, "score": 37680.62895952905 }, { "content": "/*\n\n\n\nGive a chapter tree as below:\n\n\n\n 1\n\n / | \\\n\n 1.1 1.2 1.3\n\n / /\n\n 1.1.1 1.2.1 \n\n\n\nand operations getParent(), getNextSibling(), getFirstChild()\n\n\n\nImplement getNextNode(node)\n\n\n\nExample:\n\n\n\n1.1.1's next is 1.2\n\n\n\n1.2.1's next is 1.3\n\n\n", "file_path": "problem/Tree/Implement getNextNode().cpp", "rank": 59, "score": 37679.937898928685 }, { "content": " SerialInner(*it, p);\n\n } \n\n}\n\n \n\nchar* Serialize(NODE* root, char mem[]) {\n\n if (NULL == mem || NULL == root) return NULL;\n\n \n\n char* p = mem;\n\n SerialInner(root, p);\n\n p++;\n\n *p='\\0';\n\n return mem;\n\n}\n\n\n\n\n\nint Proc(const char*& p) {\n\n \n\n int val = 0;\n\n while (*p >= '0' && *p <= '9' && *p!=' ') {\n\n \n", "file_path": "problem/Tree/SerializeDeSerialize an arbitrary nodes tree.cpp", "rank": 60, "score": 35863.630879884964 }, { "content": "/*\n\n\n\nSerializeDeSerialize an arbitrary nodes tree\n\n\n\n*/\n\n\n\n/*\n\n\n\nsolution: preorder traversal\n\nO(n) time\n\n\n\n*/\n\n\n\n\n\n\n\n#include<iostream>\n\n#include<vector>\n\nusing namespace std;\n", "file_path": "problem/Tree/SerializeDeSerialize an arbitrary nodes tree.cpp", "rank": 61, "score": 35857.688820902156 }, { "content": " val = 10 * val + *p++ - '0';\n\n \n\n }\n\n p++;\n\n return val;\n\n}\n\n \n\nNODE *DeserialInner(const char*& p) {\n\n\t\n\n \n\n int val = Proc(p);\n\n \n\n NODE *sresult = new NODE(val);\n\n \n\n val = Proc(p);\n\n\n\n int childnum = val;\n\n \n\n\n\n for (int i = 0; i < childnum; ++i) {\n", "file_path": "problem/Tree/SerializeDeSerialize an arbitrary nodes tree.cpp", "rank": 62, "score": 35857.429845374856 }, { "content": "/*\n\nFind the right most node in each level of a binary tree\n\n*/\n\n\n\n/*\n\nsolution: preorder traversal but with right child at first\n\nO(n) time\n\n*/\n\n\n\n\n\n\n\n#include<iostream>\n\n#include<vector>\n\nusing namespace std;\n\n\n", "file_path": "problem/Tree/Find the right most node in each level of a binary tree.cpp", "rank": 63, "score": 35857.26331592011 }, { "content": " NODE *p3 = new NODE(4);\n\n root1->vec.push_back(p1);\n\n root1->vec.push_back(p2);\n\n root1->vec.push_back(p3);\n\n char str[] = \"\";\n\n Serialize(root1, str);\n\n cout<<str<<endl;\n\n \n\n const char mem1[] = \"3 3 1 0 2 0 4 0\";\n\n NODE *root = DeSerialize(mem1);\n\n cout<<root->val<<endl;\n\n for (vector<NODE*>::iterator it = root->vec.begin(); it != root->vec.end(); it++) {\n\n\t\n\n cout<<(*it)->val<<endl;\n\n\t\t\n\n }\t\n\n return 0;\t\n\n\n\n}\n", "file_path": "problem/Tree/SerializeDeSerialize an arbitrary nodes tree.cpp", "rank": 64, "score": 35856.36569533443 }, { "content": " \n\n result->vec.push_back(DeserialInner(p));\n\n \n\n } \n\n \n\n return result;\n\n}\n\n \n\nNODE *DeSerialize(const char mem[]) {\n\n if (NULL == mem) return NULL;\n\n \n\n const char* p = mem;\n\n return DeserialInner(p);\n\n}\n\n\n\nint main() {\n\n \n\n NODE *root1 = new NODE(3);\n\n NODE *p1 = new NODE(1);\n\n NODE *p2 = new NODE(2);\n", "file_path": "problem/Tree/SerializeDeSerialize an arbitrary nodes tree.cpp", "rank": 65, "score": 35855.20633027471 }, { "content": " GetRightMostBTInner(Node->pLft, vec, Lev+1);\n\n}\n\n \n\nvector<NODE*> GetRightMostBT(NODE* root) {\n\n\n\n vector<NODE*> vec;\n\n GetRightMostBThelp(root, vec, 0);\n\n\n\n return vec;\n\n}\n\n\n\nint main() {\n\n\n\n NODE *head=new NODE(2);\n\n head->pLft=new NODE(3);\n\n head->pRgt=new NODE(5);\n\n head->pRgt->pRgt=new NODE(7);\n\n GetRightMostBT(head);\n\n return 0;\n\n}\n\n\n\n\n", "file_path": "problem/Tree/Find the right most node in each level of a binary tree.cpp", "rank": 66, "score": 35854.5675104419 }, { "content": " if (node->prgt != NULL && largest->val < node->prgt->val) {\n\n\n\n largest = node->prgt;\n\n\n\n }\n\n\n\n\t // if root has the largest value, return\n\n if (largest == node) return;\n\n \n\n\t //if not, swap the node's value with largest value\n\n int tmp = node->val;\n\n node->val = largest->val;\n\n largest->val = tmp; \n\n\n\n ShiftUp(largest);\n\n}\n\n\n\nvoid HeapifyBinaryTree(NODE *root) {\n\n\n\n if (!root) return;\n", "file_path": "problem/Tree/Heapify a binary tree.cpp", "rank": 67, "score": 25.535898596085858 }, { "content": " root->plft = new NODE(2);\n\n root->prgt = new NODE(3);\n\n root->prgt->plft = new NODE(5);\n\n HeapifyBinaryTree(root);\n\n cout<<root->val<<endl;\n\n cout<<root->plft->val<<endl;\n\n cout<<root->prgt->val<<endl;\n\n cout<<root->prgt->plft->val<<endl;\n\n return 0;\n\n\n\n}\n\n\n", "file_path": "problem/Tree/Heapify a binary tree.cpp", "rank": 68, "score": 25.304815329134925 }, { "content": "\n\n for (unordered_map<int, int>::iterator it = hdmp.begin(); it != hdmp.end(); ++it ) {\n\n\n\n cout<< it->second <<\" \"<<endl;\n\n\n\n }\n\n\n\n }\n\n\n\n}\n\n\n\nint main() {\n\n\n\n Node *root = new Node(1);\n\n root->plft = new Node(2);\n\n root->prgt = new Node(3);\n\n root->plft->plft = new Node(4);\n\n root->plft->prgt = new Node(5);\n\n root->prgt->plft = new Node(6);\n\n root->prgt->prgt = new Node(7);\n\n\n\n VerticalSum(root);\n\n\n\n return 0;\n\n\n\n}\n\n\n", "file_path": "problem/Tree/Vertical sum in a binary tree.cpp", "rank": 69, "score": 24.49283136239298 }, { "content": "}\n\n\n\n\n\nint MaxPathSum(TreeNode *root) {\n\n\n\n if (root == NULL) return 0;\n\n int maxSoFar = root->val;\n\n MaxPathSumInner(root, maxSoFar);\n\n return maxSoFar;\n\n}\n\n\n\nint main() {\n\n\n\n TreeNode *root = new TreeNode(-10);\n\n TreeNode *p1 = new TreeNode(2);\n\n TreeNode *p2 = new TreeNode(3);\n\n TreeNode *p3 = new TreeNode(4);\n\n root->children.push_back(p1);\n\n root->children.push_back(p2);\n\n root->children.push_back(p3);\n", "file_path": "problem/Tree/Maximalpathsum.cpp", "rank": 70, "score": 22.91734383565346 }, { "content": " if (hdmp.find(hd) == hdmp.end()) {\n\n\n\n hdmp.insert(make_pair<int,int>(hd, prevsum + root->val));\n\n \n\n } else {\n\n\n\n hdmp[hd] = prevsum + root->val;\n\n }\n\n\n\n GetHorizontalDistance(root->prgt, hd + 1, hdmp);\n\n }\n\n\n\nvoid VerticalSum(Node *root) {\n\n\n\n if (root == NULL) return;\n\n\n\n unordered_map<int, int> hdmp;\n\n GetHorizontalDistance(root, 0, hdmp);\n\n\n\n if (!hdmp.empty()) {\n", "file_path": "problem/Tree/Vertical sum in a binary tree.cpp", "rank": 71, "score": 22.4451248951093 }, { "content": "\n\n if (root->plft) {\n\n HeapifyBinaryTree(root->plft); \n\n } \n\n\n\n if (root->prgt) {\n\n\n\n HeapifyBinaryTree(root->prgt);\n\n \n\n }\n\n\n\n ShiftUp(root);\n\n\n\n}\n\n\n\n\n\n\n\nint main() {\n\n\n\n NODE *root = new NODE(1);\n", "file_path": "problem/Tree/Heapify a binary tree.cpp", "rank": 72, "score": 22.26711575735685 }, { "content": " switch = leftswitch + rightswitch;\n\n return true;\n\n }\n\n \n\n if (BinTreeSwitchEqualInner(node1->Lft, node2->Rgt, leftswitch) && \n\n BinTreeSwitchEqualInner(node1->Rgt, node2->Lft, rightswitch)) {\n\n \n\n switch = leftswitch +rightswitch + 1; //add 1 to count switch left and right part\n\n return true;\n\n }\n\n \n\n return false;\n\n}\n\n \n\nint BinTreeSwitchEqual(NODE* root1, NODE* root2) {\n\n assert(root2 && root1);\n\n \n\n int switch = 0;\n\n bool result = BinTreeSwitchEqualInner(root1, root2, switch);\n\n \n", "file_path": "problem/Tree/Switch binary tree to make equal.cpp", "rank": 73, "score": 20.94375644820505 }, { "content": "#include<vector>\n\n#include<algorithm>\n\n#include<unordered_map>\n\n#include<string>\n\nusing namespace std;\n\n\n\nunordered_map<string, int> mp;\n\n\n\nbool LessThan(string str1, string str2) {\n\n\n\n int order1 = mp[str1];\n\n int order2 = mp[str2];\n\n \n\n if (order1 < order2) {\n\n return true;\n\n } else {\n\n\n\n return false;\n\n \n\n }\n", "file_path": "problem/String/Sortfirstaccordingsecond.cpp", "rank": 74, "score": 20.08211324555336 }, { "content": "/*\n\n\n\nGiven an array and a number k, if there exists an element arr[i] such that its duplicates\n\nlies in arr[i-k] and arr[i+k],return true, else return false\n\n\n\n*/\n\n\n\n/*\n\nsolution: use a set to store and check the duplicates\n\nO(nlogk) time, O(k) space\n\n*/\n\n\n\n#include<iostream>\n\n#include<cassert>\n\n#include<set>\n\nusing namespace std;\n\n\n\nbool HasDupk(int arr[], int len, int k) {\n\n\n\n\tassert(arr && k >= 0 && k < len && len > 0);\n", "file_path": "problem/Given an array and a number k.cpp", "rank": 75, "score": 19.909109844455546 }, { "content": "#include<cassert>\n\nusing namespace std;\n\n\n\nvoid detectLongestCycleInner(int start, int idx, int arr[], vector<bool>& visited, int &len) {\n\n visited[idx] = true;\n\n len++;\n\n \n\n if (!visited[arr[idx]]) {\n\n \n\n detectLongestCycleInner(start, arr[idx], arr, visited, len);\n\n \n\n } else {\n\n \n\n assert(start != idx); //a cycle\n\n }\n\n \n\n}\n\n\n\n\n\n/*\n", "file_path": "problem/Array/Detect the longest cycle in an array.cpp", "rank": 76, "score": 19.32591138332665 }, { "content": "*/\n\n\n\n#include<iostream>\n\nusing namespace std;\n\n\n\n\n\nint FindPartiion(int arr[], int len) {\n\n int sum = 0;\n\n int i, j;\n\n \n\n for (i = 0; i < len; ++i) {\n\n \n\n sum += arr[i];\n\n \n\n } \n\n \n\n bool part[50][8];\n\n \n\n \n\n for (i = 0; i <= len; ++i) {\n", "file_path": "problem/DynamicProgramming/Minimal subset sum.cpp", "rank": 77, "score": 19.067751758837574 }, { "content": " int lftmax, lftmin;\n\n int numnodes = GetLargestBSTInner(Node->pLft, lftmin, lftmax, maxbstroot, maxbstnum);\n\n if (numnodes <= 0 || lftmax > pNode->val) { //check invalid\n\n \n\n bivalid = true; \n\n \n\n } else { //pNode->pLft is a valid BST\n\n \n\n result += numnodes; //count size of left subtree\n\n minbound = lftmin; //update bound\n\n }\n\n }\n\n \n\n if (Node->pRgt != NULL) {\n\n \n\n int rgtmax, rgtmin;\n\n int numnodes = GetLargestBSTInner(Node->pRgt, rgtmin, rgtmax, maxbstroot, maxbstnum);\n\n if (numnodes <= 0 || rgtmin < pNode->val) { //check invalid\n\n \n\n bivalid = true;\n", "file_path": "problem/Tree/Find the largest BST sub tree in BT.cpp", "rank": 78, "score": 18.78339924530132 }, { "content": "NODE *GetLargestBST(NODE *root) {\n\n \n\n if (root == NULL) return NULL;\n\n \n\n NODE *result = NULL;\n\n int maxbstnum = 0;\n\n int minbound, maxbound;\n\n GetLargestBSTInner(root, minbound, maxbound, result, maxbstnum);\n\n \n\n return result;\n\n}\n\n\n\nvoid InOrderTravel(NODE* root) {\n\n assert(root);\n\n \n\n stack<NODE*> stk;\n\n NODE* cur = root;\n\n while (NULL != cur) {\n\n \n\n stk.push(cur);\n", "file_path": "problem/Tree/Find the largest BST sub tree in BT.cpp", "rank": 79, "score": 18.47953280106867 }, { "content": " \n\n if (node->pLft == NULL) {\n\n \n\n node->setLeft(tmp);\n\n \n\n } else {\n\n \n\n Insert(node->pLft, tmp);\n\n } \n\n }\n\n}\n\n\n\n//find the n'th smallest element stored in the tree in O(logn) time\n\n\n\nNODE *Select(NODE *root, int n) {\n\n if (root==NULL || n <= 0) return NULL;\n\n \n\n NODE *cur = root;\n\n \n\n int cursum = 0;\n", "file_path": "problem/Tree/Statistical binary search tree.cpp", "rank": 80, "score": 18.338338178911506 }, { "content": "/*\n\n\n\nGiven a N-way tree, find the maximum path sum. The path may start and end at any node in the tree.\n\n\n\n*/\n\n\n\n/*\n\n\n\nsolution: calculate each path sum for each child, add it to maximal path if it is positve \n\nO(n) time, O(1) space\n\n*/\n\n\n\n#include<iostream>\n\n#include<vector>\n\nusing namespace std;\n\n\n", "file_path": "problem/Tree/Maximalpathsum.cpp", "rank": 81, "score": 18.046225509752027 }, { "content": "}\n\n\n\nint main() {\n\n NODE *root = new NODE(3);\n\n Insert(root, new NODE(1));\n\n Insert(root, new NODE(5));\n\n NODE *p1 = new NODE(4);\n\n Insert(root,p1);\n\n cout<<root->size<<endl;//4\n\n\t\n\n cout<<Select(root,1)->val<<endl;\n\n cout<<Select(root,2)->val<<endl;\n\n cout<<Select(root,3)->val<<endl;\n\n cout<<Select(root,4)->val<<endl;\n\n cout<<GetNum(root, p1)<<endl;\n\n return 0; \n\n\n\n}\n\n\n", "file_path": "problem/Tree/Statistical binary search tree.cpp", "rank": 82, "score": 17.974139495989604 }, { "content": "*/\n\n\n\n#include<iostream>\n\n#include<vector>\n\n#include<queue>\n\nusing namespace std;\n\n\n\nvoid PrintSubTreeSum(vector<vector<int> > &relation, int node) { \n\n int size = relation.size();\n\n if (node == 0 || size == 0) return;\n\n vector<int> outdegree(node, 0);\n\n vector<int> totalweight(node,0);\n\n vector<int> orgweight(node,0);\n\n vector<int> parentindex(node,-1);\n\n\t\n\n for (int i = 0;i < size;i++) {\n\n\n\n outdegree[relation[i][1]]++;\n\n totalweight[relation[i][0]] = relation[i][2];\n\n parentindex[relation[i][0]] = relation[i][1];\n", "file_path": "problem/Tree/Totalweight.cpp", "rank": 83, "score": 17.837139758276738 }, { "content": "\n\n//find the rank of element node in the tree in O(logn) time\n\n\n\nint GetNum(NODE* root, NODE* node) {\n\n if (root == NULL|| node == NULL) return 0;\n\n \n\n if (node == root) return node->pLft == NULL ? 1 : 1 + node->pLft->size;\n\n \n\n NODE* cur = node;\n\n int result = 1;\n\n while (cur->pParent != NULL) {\n\n \n\n if (cur == cur->pParent->pRgt) { // if node is its parent right child\n\n result += 1 + (cur->pParent->pLft == NULL ? 0 : cur->pParent->pLft->size); \n\n }\n\n \n\n cur = cur->pParent;\n\n }\n\n \n\n return result;\n", "file_path": "problem/Tree/Statistical binary search tree.cpp", "rank": 84, "score": 17.804320002015817 }, { "content": " cur = cur->pLft;\n\n }\n\n \n\n while (!stk.empty()) {\n\n \n\n cur = stk.top();\n\n cout<<cur->val<<endl;\n\n stk.pop();\n\n \n\n cur = cur->pRgt;\n\n while (NULL != cur) {\n\n \n\n stk.push(cur);\n\n cur = cur->pLft;\n\n }\n\n }\n\n}\n\n\n\nint main() {\n\n NODE *root = new NODE(5);\n", "file_path": "problem/Tree/Find the largest BST sub tree in BT.cpp", "rank": 85, "score": 17.444583897532635 }, { "content": "/*\n\n\n\nGiven a binary tree with parent link, find a node's immediate right neighbor without the root node.\n\n\n\n\n\n*/\n\n\n\n/*\n\n\n\nsolution: first find the lowest parent that both the node and its immediate neighbor have. Then\n\nrecursively find its immediate neighbor in the parent's left subtree.\n\nO(h) time, O(1) space, h is the height of the node.\n\n*/\n\n\n\n#include<iostream>\n\nusing namespace std;\n\n\n\n\n", "file_path": "problem/Tree/Immediate right neighbor.cpp", "rank": 86, "score": 17.243132807932547 }, { "content": " \n\n const char* p = mem;\n\n return DeSerializeInner(p);\n\n}\n\n\n\nint main() {\n\n\n\n NODE *root = new NODE(3);\n\n root->pLft = new NODE(1);\n\n root->pRgt = new NODE(4);\n\n char str[] = \"\";\n\n Serialize(str, root);\n\n cout<<str<<endl;\n\n const char str1[] = \"3 1 # # 4 # #\";\n\n NODE *r = DeSerialize(str1);\n\n cout<<r->val<<endl;\n\n cout<<r->pLft->val<<endl;\n\n cout<<r->pRgt->val<<endl;\n\n return 0;\n\n}\n", "file_path": "problem/Tree/SerializeDeSerialize a binary tree.cpp", "rank": 87, "score": 17.207804933574288 }, { "content": "/*\n\n\n\n Given an integer array arr, find the maximal a[i] such that a[i]=a[x]+a[y].\n\n \n\n*/\n\n\n\n/*\n\n\n\nsolution: sort&binary search\n\nO(nlogn) time, O(1) space\n\n\n\n*/\n\n\n\n#include<iostream>\n\n#include<cassert>\n\n#include<algorithm>\n\nusing namespace std;\n\n\n\nbool TwoSum(int arr[], int len, int skipindex) {\n\n\n", "file_path": "problem/Array/Find the max item A[i], such that A[i]=A[x]+A[y].cpp", "rank": 88, "score": 17.058967243610713 }, { "content": "*/\n\n#include<iostream>\n\nusing namespace std;\n\n\n\n\n\n\n\nbool IsDuplicate(const string str) {\n\n\n\n int strlen = str.size();\n\n\n\n if(strlen < 4) return false;\n\n\n\n int len = 1; //length of the duplicate substring\n\n int start = 0;\n\n for (int i = 1; i< strlen; ++i) {\n\n\n\n if (str[start] == str[i]) {\n\n\n\n start++;\n\n if(start >= len) start = 0; //reach an end of a duplicate substring, back to beginning\n", "file_path": "problem/String/Kduplicates.cpp", "rank": 89, "score": 16.917550227629544 }, { "content": "\n\nuse two sets, one is to record all visited index in the array, another one is to record the visited index in current possible cycle\n\nO(n) time, O(n) space\n\n\n\n*/\n\n\n\n\n\n#include<iostream>\n\n#include<unordered_set>\n\nusing namespace std;\n\n\n\nbool DetectCycle1(int arr[], int len) {\n\n \n\n int slow = 0;\n\n int fast = 0;\n\n int cur = 0;\n\n \n\n while (cur < len) {\n\n \n\n if (arr[slow] >= 0 && arr[slow] < len) {\n", "file_path": "problem/Array/Detect cycle in an array.cpp", "rank": 90, "score": 16.758783001097143 }, { "content": "\n\n if(local) {\n\n return local;\n\n\t\t} else{\n\n node = parent;\n\n parent = node->parent;\n\n level--;\n\n }\n\n }\n\n return NULL; \n\n}\n\n\n\nint main(){\n\n\n\n Node *root = new Node(0);\n\n root->left = new Node(1);\n\n root->left->parent = root;\n\n root->right = new Node(2);\n\n root->right->parent = root;\n\n root->left->left = new Node(3);\n", "file_path": "problem/Tree/Immediate right neighbor.cpp", "rank": 91, "score": 16.717273349583355 }, { "content": "/*\n\n\n\nsolutuion: calculate horizontal distances from root for all nodes. If two nodes have the same horizontal distance, then they are on same vertical line. \n\nHD for root is 0, a right edge (edge connecting to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1 horizontal distance. \n\n\n\nDo an inorder traversal and calcuate the horizontal distance recursively.\n\n\n\nO(n) time, O(n) space\n\n\n\n*/\n\n\n\n#include<iostream>\n\n#include<unordered_map>\n\nusing namespace std;\n\n\n", "file_path": "problem/Tree/Vertical sum in a binary tree.cpp", "rank": 92, "score": 16.683155915992955 }, { "content": "/*\n\nSieve of Eratosthenes algorithm\n\n*/\n\n\n\n/*\n\n\n\nsolution: start from smallest primer number p, print p and mark 2p, 3p, 4p, ...\n\nprint the first number q greater than p without mark if it exists, then repeat the steps above for q.\n\n\n\n*/\n\n\n\n\n\n#include <iostream>\n\nusing namespace std;\n\n\n\n\n\nvoid FlagMultiples(bool arr[], int a, unsigned int num) {\n\n int i = 2;\n\n int temp = i * a;\n\n while ( temp <= num ) {\n", "file_path": "problem/SieveofEratosthenes.cpp", "rank": 93, "score": 16.682443619178972 }, { "content": "*/\n\n\n\n/*\n\n\n\nsolution: define the vowel checking rule correctly. Then just one scan.\n\nO(n) time, O(1) space\n\n\n\n*/\n\n#include<iostream>\n\n#include<cctype>\n\n#include<string>\n\nusing namespace std;\n\n\n\nbool checkBasicVowel(char c) {\n\n\n\n if (c == 'a' || c =='e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' ||c == 'U') {\n\n return true;\n\n\n\n } else {\n\n\n", "file_path": "problem/String/Vowel product.cpp", "rank": 94, "score": 16.664347476311875 }, { "content": "\n\n#include<iostream>\n\n#include<string>\n\nusing namespace std;\n\n\n\nbool TransformString(string str1, string str2) {\n\n\n\n int len1 = str1.size();\n\n int len2 = str2.size();\n\n\n\n if (abs(len1 - len2) > 1) return false;\n\n\n\n if (len1 > len2) return TransformString(str2, str1);\n\n\n\n\t//replace\t\n\n if (len1 == len2) {\n\n\n\n int countdiff = 0;\n\n\n\n for (int i = 0 ; i < len1; ++i) {\n", "file_path": "problem/String/Edit Distance one.cpp", "rank": 95, "score": 16.567559041272233 }, { "content": "/*\n\nGiven an array of sorted integers where each one is in the range from 0 to m-1 and m > n,\n\nwhere n is the length of this array.\n\nFind the smallest number that is missing from the array.\n\n*/\n\n\n\n/*\n\nsolution: modified binary search. \n\nO(logn) time, O(1) space\n\n*/\n\n\n\n#include<iostream>\n\nusing namespace std;\n\n\n\nint FindFirstMissing(int arr[], int begin, int end) {\n\n \n\n //end+1 is the number larger than the last element of array\n\n if (begin > end)\n\n return end + 1;\n\n \n", "file_path": "problem/SortingSearch/Smallestmissingnumber.cpp", "rank": 96, "score": 16.234300952581133 }, { "content": " stk.pop();\n\n }\n\n }\n\n}\n\n \n\n//preorder\n\nvoid PrevOrderTravel(NODE* root) {\n\n assert(root);\n\n \n\n stack<NODE*> stk;\n\n stk.push(root);\n\n \n\n while (!stk.empty()) {\n\n \n\n NODE* top = stk.top();\n\n stk.pop();\n\n \n\n cout<<top->val<<endl;\n\n \n\n if (top->pRgt != NULL) stk.push(top->pRgt);\n", "file_path": "problem/Tree/PreInPostorder travel of bT with stack.cpp", "rank": 97, "score": 15.901693231718374 }, { "content": "/*\n\nFind the last k digits of m^n, where m, n is positive integer, n may be very large.\n\n*/\n\n\n\n/*\n\n\n\nsolution: big number + recursion\n\nO((log n) * k * k) time, O(k*k) space\n\n*/\n\n\n\n#include<iostream>\n\n#include<cassert>\n\n#include<string>\n\nusing namespace std;\n\n\n\nstring MultiplyArrays(string num1, string num2, int k) {\n\n int N = num1.length(), M = num2.length();\n\n string res(N+M, '0');\n\n for (int i = N - 1; i >= 0; --i) {\n\n int carry = 0;\n", "file_path": "problem/Math/Calculate (m^n)%(10^k).cpp", "rank": 98, "score": 15.607745224466276 }, { "content": "", "file_path": "problem/Quadtree.cpp", "rank": 99, "score": 15.453547276372685 } ]
C++
mindspore/ccsrc/runtime/device/memory_offload_strategy.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
#include "runtime/device/memory_offload_strategy.h" #include <vector> #include <map> #include <memory> #include <utility> #include "utils/log_adapter.h" namespace mindspore { namespace device { constexpr size_t kFirstGetMemEventIndex = 1; constexpr size_t kInitOrMallocMemEventIndex = 0; std::vector<std::shared_ptr<MemEvent>> &MemOffloadStrategy::GetPreComputeEvents(size_t step) { if (pre_compute_events_.size() <= step) { MS_LOG_EXCEPTION << "Index out of pre event range, index:" << step << ", event size:" << pre_compute_events_.size(); } return pre_compute_events_[step]; } std::vector<std::shared_ptr<MemEvent>> &MemOffloadStrategy::GetPostComputeEvents(size_t step) { if (post_compute_events_.size() <= step) { MS_LOG_EXCEPTION << "Index out of post event range, index:" << step << ", event size:" << post_compute_events_.size(); } return post_compute_events_[step]; } void MemOffloadStrategy::Execute() { CountMemUsage(); CheckMemSize(); if (need_swap_) { GenEventSpan(); GenSwapEventSet(); } GenComputeMemEvents(); } void MemOffloadStrategy::CountMemUsage() { if (!min_mem_used_.empty()) { return; } if (mem_events_.empty() || total_step_ == 0) { return; } min_mem_used_.resize(total_step_, 0); std::vector<size_t> total_mem_used(total_step_, 0); size_t high_priority_mem_size = 0; for (auto &item : mem_events_) { auto &mem_events = item.second; if (mem_events.empty()) { continue; } auto first_event = mem_events[kInitOrMallocMemEventIndex]; const bool is_high_priority = IsHighPriorityMem(first_event->key); if (is_high_priority) { high_priority_mem_size += first_event->mem_size; } else { auto last_event = mem_events[mem_events.size() - 1]; for (size_t start_index = first_event->index; start_index <= last_event->index; ++start_index) { total_mem_used[start_index] += first_event->mem_size; } } for (const auto &event : mem_events) { MS_EXCEPTION_IF_NULL(event); if (event->type != kGet) { continue; } min_mem_used_[event->index] += first_event->mem_size; } } min_mem_needed_ = *(std::max_element(min_mem_used_.begin(), min_mem_used_.end())); mem_used_without_swap_ = *(std::max_element(total_mem_used.begin(), total_mem_used.end())) + high_priority_mem_size; if (mem_size_ < min_mem_needed_) { MS_LOG(EXCEPTION) << "Out of memory, as available mem size is " << mem_size_ << " while graph needs at least " << min_mem_needed_; } } bool MemOffloadStrategy::IsHighPriorityMem(const void *key) const { auto iter = mem_priority_.find(key); if (iter != mem_priority_.end()) { return iter->second == kMemPriorityHigh; } return false; } void MemOffloadStrategy::CheckMemSize() { if (mem_size_ < mem_used_without_swap_ || !manual_offload_keys_.empty()) { need_swap_ = true; } MS_LOG(INFO) << "Available mem size: " << mem_size_ << ", graph needs mem size: " << mem_used_without_swap_ << " without swap, and needs at least " << min_mem_needed_ << " with swap."; } void MemOffloadStrategy::GenEventSpan() { if (!event_span_.empty()) { return; } for (auto &item : mem_events_) { auto &tensor_events = item.second; if (tensor_events.size() <= 1) { continue; } const bool is_high_priority = IsHighPriorityMem(tensor_events[kInitOrMallocMemEventIndex]->key); for (size_t i = kFirstGetMemEventIndex; i < tensor_events.size(); ++i) { auto &event = tensor_events[i]; MS_EXCEPTION_IF_NULL(event); if (event->type != kGet) { MS_LOG(EXCEPTION) << "Event should be Get except fist event."; } auto latest_event = tensor_events[i - 1]; if (i == kFirstGetMemEventIndex && is_high_priority) { latest_event = tensor_events[tensor_events.size() - 1]; } auto span = GetSpanBetweenMemEvents(latest_event->index, event->index); if (is_high_priority && span == 0 && latest_event == event) { span = total_step_; } if (span > 1) { const size_t span_mul_size = (span - 1) * event->mem_size; (void)event_span_.emplace(std::make_pair(span_mul_size, std::make_pair(event, span))); } } } } void MemOffloadStrategy::GenSwapEventSet() { swap_events_.clear(); if (!manual_offload_keys_.empty()) { for (const auto &iter : event_span_) { auto &event = iter.second.first; if (manual_offload_keys_.find(event->key) != manual_offload_keys_.end()) { (void)swap_events_.emplace(event); } } return; } std::vector<size_t> cur_mem_used(min_mem_used_.begin(), min_mem_used_.end()); for (const auto &iter : event_span_) { auto span = iter.second.second; auto &event = iter.second.first; auto start_index = ((event->index + total_step_ - span + 1) % total_step_); bool revert = false; size_t cur_index = start_index; while (cur_index != event->index) { cur_mem_used[cur_index] += event->mem_size; if (cur_mem_used[cur_index] > mem_size_) { revert = true; } cur_index += 1; if (cur_index >= total_step_) { cur_index = 0; } } if (revert) { cur_index = start_index; while (cur_index != event->index) { cur_mem_used[cur_index] -= event->mem_size; cur_index += 1; if (cur_index >= total_step_) { cur_index = 0; } } (void)swap_events_.emplace(event); } } } void MemOffloadStrategy::GenComputeMemEvents() { pre_compute_events_.clear(); post_compute_events_.clear(); pre_compute_events_.resize(total_step_); post_compute_events_.resize(total_step_); for (auto &item : mem_events_) { auto &mem_events = item.second; if (mem_events.size() <= 1) { continue; } const bool is_high_priority = IsHighPriorityMem(item.first); auto first_event = mem_events[kInitOrMallocMemEventIndex]; MS_EXCEPTION_IF_NULL(first_event); const auto &first_get_event = mem_events[kFirstGetMemEventIndex]; MS_EXCEPTION_IF_NULL(first_get_event); if (is_high_priority && swap_events_.find(first_get_event) != swap_events_.end()) { first_event->index = first_get_event->index; } if ((first_event->type == kInit || first_event->type == kMalloc) && first_event->index < total_step_) { pre_compute_events_[first_event->index].emplace_back(first_event); } else { MS_LOG_EXCEPTION << "First event should be init or malloc!"; } const auto &last_event = mem_events[mem_events.size() - 1]; size_t pre_index = is_high_priority ? last_event->index : first_event->index; const auto &swap_out_event_index = GetSwapOutEventIndex(item.first, mem_events); for (size_t i = kFirstGetMemEventIndex; i < mem_events.size(); ++i) { auto &event = mem_events[i]; MS_EXCEPTION_IF_NULL(event); if (need_swap_ && swap_events_.find(event) != swap_events_.end()) { MemEventType event_type = kSwapOut; if (is_high_priority && swap_out_event_index.count(i) == 0) { event_type = kFree; } auto free_or_swap_out_event = std::make_shared<MemEvent>(event_type, pre_index); free_or_swap_out_event->key = item.first; free_or_swap_out_event->mem_size = first_event->mem_size; post_compute_events_[pre_index].emplace_back(free_or_swap_out_event); if (i != kFirstGetMemEventIndex || first_event->type != kInit) { auto swap_in_event = std::make_shared<MemEvent>(kSwapIn, event->index); swap_in_event->key = item.first; swap_in_event->mem_size = first_event->mem_size; (void)pre_compute_events_[event->index].emplace_back(swap_in_event); } } if (event->index < pre_compute_events_.size()) { (void)pre_compute_events_[event->index].emplace_back(event); } pre_index = event->index; } if (!is_high_priority) { GenFreeEvent(last_event); } } } void MemOffloadStrategy::GenFreeEvent(const std::shared_ptr<MemEvent> &last_event) { MS_EXCEPTION_IF_NULL(last_event); auto free_event = std::make_shared<MemEvent>(kFree, last_event->index); free_event->key = last_event->key; if (last_event->index < post_compute_events_.size()) { (void)post_compute_events_[last_event->index].emplace_back(free_event); } } std::set<size_t> MemOffloadStrategy::GetSwapOutEventIndex(const void *key, const std::vector<std::shared_ptr<MemEvent>> &mem_events) { const auto &update_step_iter = high_priority_updated_step_.find(key); if (update_step_iter == high_priority_updated_step_.end() || update_step_iter->second.empty()) { return std::set<size_t>(); } const auto &update_steps = update_step_iter->second; size_t update_steps_index = 0; std::set<size_t> swap_out_event_index; size_t min_swap_index_before_update = SIZE_MAX; size_t max_swap_out_step = 0; for (size_t i = 0; i < mem_events.size(); ++i) { const auto &mem_event = mem_events[i]; if (swap_events_.count(mem_event) == 0) { continue; } if (mem_event->index <= update_steps[update_steps_index]) { if (i <= min_swap_index_before_update) { min_swap_index_before_update = i; } } else { swap_out_event_index.insert(i); max_swap_out_step = mem_event->index; while (update_steps_index < update_steps.size() && update_steps[update_steps_index] < mem_event->index) { ++update_steps_index; } } } if (max_swap_out_step <= update_steps[update_steps.size() - 1]) { swap_out_event_index.insert(min_swap_index_before_update); } return swap_out_event_index; } } }
#include "runtime/device/memory_offload_strategy.h" #include <vector> #include <map> #include <memory> #include <utility> #include "utils/log_adapter.h" namespace mindspore { namespace device { constexpr size_t kFirstGetMemEventIndex = 1; constexpr size_t kInitOrMallocMemEventIndex = 0; std::vector<std::shared_ptr<MemEvent>> &MemOffloadStrategy::GetPreComputeEvents(size_t step) { if (pre_compute_events_.size() <= step) { MS_LOG_EXCEPTION << "Index out of pre event range, index:" << step << ", event size:" << pre_compute_events_.size(); } return pre_compute_events_[step]; } std::vector<std::shared_ptr<MemEvent>> &MemOffloadStrategy::GetPostComputeEvents(size_t step) { if (post_compute_events_.size() <= step) { MS_LOG_EXCEPTION << "Index out of post event range, index:" << step << ", event size:" << post_compute_events_.size(); } return post_compute_events_[step]; } void MemOffloadStrategy::Execute() { CountMemUsage(); CheckMemSize(); if (need_swap_) { GenEventSpan(); GenSwapEventSet(); } GenComputeMemEvents(); } void MemOffloadStrategy::CountMemUsage() { if (!min_mem_used_.empty()) { return; } if (mem_events_.empty() || total_step_ == 0) { return; } min_mem_used_.resize(total_step_, 0); std::vector<size_t> total_mem_used(total_step_, 0); size_t high_priority_mem_size = 0; for (auto &item : mem_events_) { auto &mem_events = item.second; if (mem_events.empty()) { continue; } auto first_event = mem_events[kInitOrMallocMemEventIndex]; const bool is_high_priority = IsHighPriorityMem(first_event->key); if (is_high_priority) { high_priority_mem_size += first_event->mem_size; } else { auto last_event = mem_events[mem_events.size() - 1]; for (size_t start_index = first_event->index; start_index <= last_event->index; ++start_index) { total_mem_used[start_index] += first_event->mem_size; } } for (const auto &event : mem_events) { MS_EXCEPTION_IF_NULL(event); if (event->type != kGet) { continue; } min_mem_used_[event->index] += first_event->mem_size; } } min_mem_needed_ = *(std::max_element(min_mem_used_.begin(), min_mem_used_.end())); mem_used_without_swap_ = *(std::max_element(total_mem_used.begin(), total_mem_used.end())) + high_priority_mem_size; if (mem_size_ < min_mem_needed_) { MS_LOG(EXCEPTION) << "Out of memory, as available mem size is " << mem_size_ << " while graph needs at least " << min_mem_needed_; } } bool MemOffloadStrategy::IsHighPriorityMem(const void *key) const { auto iter = mem_priority_.find(key); if (iter != mem_priority_.end()) { return iter->second == kMemPriorityHigh; } return false; } void MemOffloadStrategy::CheckMemSize() { if (mem_size_ < mem_used_without_swap_ || !manual_offload_keys_.empty()) { need_swap_ = true; } MS_LOG(INFO) << "Available mem size: " << mem_size_ << ", graph needs mem size: " << mem_used_without_swap_ << " without swap, and needs at least " << min_mem_needed_ << " with swap."; } void MemOffloadStrategy::GenEventSpan() { if (!event_span_.empty()) { return; } for (auto &item : mem_events_) { auto &tensor_events = item.second; if (tensor_events.size() <= 1) { continue; } const bool is_high_priority = IsHighPriorityMem(tensor_events[kInitOrMallocMemEventIndex]->key); for (size_t i = kFirstGetMemEventIndex; i < tensor_events.size(); ++i) { auto &event = tensor_events[i]; MS_EXCEPTION_IF_NULL(event); if (event->type != kGet) { MS_LOG(EXCEPTION) << "Event should be Get except fist event."; } auto latest_event = tensor_events[i - 1]; if (i == kFirstGetMemEventIndex && is_high_priority) { latest_event = tensor_events[tensor_events.size() - 1]; } auto span = GetSpanBetweenMemEvents(latest_event->index, event->index); if (is_high_priority && span == 0 && latest_event == event) { span = total_step_; } if (span > 1) { const size_t span_mul_size = (span - 1) * event->mem_size; (void)event_span_.emplace(std::make_pair(span_mul_size, std::make_pair(event, span))); } } } } void MemOffloadStrategy::GenSwapEventSet() { swap_events_.clear(); if (!manual_offload_keys_.empty()) { for (const auto &iter : event_span_) { auto &event = iter.second.first; if (manual_offload_keys_.find(event->key) != manual_offload_keys_.end()
rt(min_swap_index_before_update); } return swap_out_event_index; } } }
) { (void)swap_events_.emplace(event); } } return; } std::vector<size_t> cur_mem_used(min_mem_used_.begin(), min_mem_used_.end()); for (const auto &iter : event_span_) { auto span = iter.second.second; auto &event = iter.second.first; auto start_index = ((event->index + total_step_ - span + 1) % total_step_); bool revert = false; size_t cur_index = start_index; while (cur_index != event->index) { cur_mem_used[cur_index] += event->mem_size; if (cur_mem_used[cur_index] > mem_size_) { revert = true; } cur_index += 1; if (cur_index >= total_step_) { cur_index = 0; } } if (revert) { cur_index = start_index; while (cur_index != event->index) { cur_mem_used[cur_index] -= event->mem_size; cur_index += 1; if (cur_index >= total_step_) { cur_index = 0; } } (void)swap_events_.emplace(event); } } } void MemOffloadStrategy::GenComputeMemEvents() { pre_compute_events_.clear(); post_compute_events_.clear(); pre_compute_events_.resize(total_step_); post_compute_events_.resize(total_step_); for (auto &item : mem_events_) { auto &mem_events = item.second; if (mem_events.size() <= 1) { continue; } const bool is_high_priority = IsHighPriorityMem(item.first); auto first_event = mem_events[kInitOrMallocMemEventIndex]; MS_EXCEPTION_IF_NULL(first_event); const auto &first_get_event = mem_events[kFirstGetMemEventIndex]; MS_EXCEPTION_IF_NULL(first_get_event); if (is_high_priority && swap_events_.find(first_get_event) != swap_events_.end()) { first_event->index = first_get_event->index; } if ((first_event->type == kInit || first_event->type == kMalloc) && first_event->index < total_step_) { pre_compute_events_[first_event->index].emplace_back(first_event); } else { MS_LOG_EXCEPTION << "First event should be init or malloc!"; } const auto &last_event = mem_events[mem_events.size() - 1]; size_t pre_index = is_high_priority ? last_event->index : first_event->index; const auto &swap_out_event_index = GetSwapOutEventIndex(item.first, mem_events); for (size_t i = kFirstGetMemEventIndex; i < mem_events.size(); ++i) { auto &event = mem_events[i]; MS_EXCEPTION_IF_NULL(event); if (need_swap_ && swap_events_.find(event) != swap_events_.end()) { MemEventType event_type = kSwapOut; if (is_high_priority && swap_out_event_index.count(i) == 0) { event_type = kFree; } auto free_or_swap_out_event = std::make_shared<MemEvent>(event_type, pre_index); free_or_swap_out_event->key = item.first; free_or_swap_out_event->mem_size = first_event->mem_size; post_compute_events_[pre_index].emplace_back(free_or_swap_out_event); if (i != kFirstGetMemEventIndex || first_event->type != kInit) { auto swap_in_event = std::make_shared<MemEvent>(kSwapIn, event->index); swap_in_event->key = item.first; swap_in_event->mem_size = first_event->mem_size; (void)pre_compute_events_[event->index].emplace_back(swap_in_event); } } if (event->index < pre_compute_events_.size()) { (void)pre_compute_events_[event->index].emplace_back(event); } pre_index = event->index; } if (!is_high_priority) { GenFreeEvent(last_event); } } } void MemOffloadStrategy::GenFreeEvent(const std::shared_ptr<MemEvent> &last_event) { MS_EXCEPTION_IF_NULL(last_event); auto free_event = std::make_shared<MemEvent>(kFree, last_event->index); free_event->key = last_event->key; if (last_event->index < post_compute_events_.size()) { (void)post_compute_events_[last_event->index].emplace_back(free_event); } } std::set<size_t> MemOffloadStrategy::GetSwapOutEventIndex(const void *key, const std::vector<std::shared_ptr<MemEvent>> &mem_events) { const auto &update_step_iter = high_priority_updated_step_.find(key); if (update_step_iter == high_priority_updated_step_.end() || update_step_iter->second.empty()) { return std::set<size_t>(); } const auto &update_steps = update_step_iter->second; size_t update_steps_index = 0; std::set<size_t> swap_out_event_index; size_t min_swap_index_before_update = SIZE_MAX; size_t max_swap_out_step = 0; for (size_t i = 0; i < mem_events.size(); ++i) { const auto &mem_event = mem_events[i]; if (swap_events_.count(mem_event) == 0) { continue; } if (mem_event->index <= update_steps[update_steps_index]) { if (i <= min_swap_index_before_update) { min_swap_index_before_update = i; } } else { swap_out_event_index.insert(i); max_swap_out_step = mem_event->index; while (update_steps_index < update_steps.size() && update_steps[update_steps_index] < mem_event->index) { ++update_steps_index; } } } if (max_swap_out_step <= update_steps[update_steps.size() - 1]) { swap_out_event_index.inse
random
[]
C++
example-ofxDownloadCentral/src/ofApp.cpp
hushstudios/ofxSimpleHttp
5dd8f761381a5abb05913d0a7c50f5611a7aebcf
#include "ofApp.h" void ofApp::setup(){ ofSetFrameRate(60); ofBackground(22); ofSetWindowPosition(20, 20); downloader.setNeedsChecksumMatchToSkipDownload(true); downloader.setIdleTimeAfterEachDownload(0.2); downloader.setVerbose(false); downloader.setMaxConcurrentDownloads(3); } void ofApp::downloadFinished(ofxBatchDownloaderReport &report){ cout << "#################################################" << endl; cout << "#### download finished!!" << endl; cout << "#### [ " << report.attemptedDownloads.size() << " attempted | " ; if(report.wasCanceled){ cout << "#### Download Was CANCELED BY USER!" << endl; } cout << report.failedDownloads.size() << " failed | "; cout << report.successfulDownloads.size() << " ok ]" << endl; for(int i = 0; i < report.responses.size(); i++){ ofxSimpleHttpResponse r = report.responses[i]; r.print(); } bool ok = false; int i = 0; while (!ok && i < report.responses.size()){ if (report.responses[i].ok){ } i++; } } void ofApp::update(){ downloader.update(); } void ofApp::draw(){ ofSetColor(255); drawClock(); downloader.draw(30,30, true, false); string msg = "press 1 to download a file and supply a correct SHA1\n"; msg += "press 2 to download a file and supply an incorrect SHA1\n"; msg += "press 3 to download a few files without supplying a SHA1\n"; msg += "press c to cancel current download\n"; msg += "press C to cancel all downloads\n"; ofDrawBitmapString(msg, 20, ofGetHeight() - 70); } void ofApp::drawClock(){ ofPushMatrix(); ofTranslate(ofGetWidth() - 60,60, 0); ofRotate( ofGetFrameNum() * 3, 0,0,1); ofSetColor(255,255,255); float h = 5; ofRect(-h/2,h/2, h,50); ofPopMatrix(); } void ofApp::keyPressed(int key){ vector<string> allURLS; vector<string> allSha1s; if(key == '1'){ allURLS.push_back("http://farm3.staticflickr.com/2875/9481775605_ea43f5d4f3_o_d.jpg"); allSha1s.push_back("852a7952aabcbf3479974d5350f973b005b23c4a"); } if(key == '2'){ allURLS.push_back("http://farm8.staticflickr.com/7454/9481666291_40f7c00b80_o_d.jpg"); allSha1s.push_back("my_Sha1_Is_Garbage_And_It_Should_Trigger_An_Error"); } if(key == '3'){ allURLS.push_back("http://farm8.staticflickr.com/7420/10032530563_86ff701d19_o.jpg"); allURLS.push_back("http://farm3.staticflickr.com/2877/9481432451_c74c649515_o_d.jpg"); allURLS.push_back("http://farm4.staticflickr.com/3702/9484220536_8f5a866b4d_o_d.jpg"); allURLS.push_back("http://farm4.staticflickr.com/3667/9484488930_2c6527ee35_o_d.jpg"); allURLS.push_back("http://farm3.staticflickr.com/2857/9481682413_5f251ba22d_o_d.jpg"); allURLS.push_back("http://farm8.staticflickr.com/7438/9481688475_e83f92e8b5_o_d.jpg"); } if (key >= '1' && key <= '2'){ downloader.downloadResources(allURLS, allSha1s, this, &ofApp::downloadFinished, "downloads_" ); downloader.startDownloading(); }else if(key == '3'){ for(int i = 0; i < allURLS.size(); i++){ downloader.downloadResources(allURLS[i], this, &ofApp::downloadFinished, "downloads_" ); } downloader.startDownloading(); } if(key == 'c'){ downloader.cancelCurrentDownload(); } if(key == 'C'){ downloader.cancelAllDownloads(); } }
#include "ofApp.h" void ofApp::setup(){ ofSetFrameRate(60); ofBackground(22); ofSetWindowPosition(20, 20); downloader.setNeedsChecksumMatchToSkipDownload(true); downloader.setIdleTimeAfterEachDownload(0.2); downloader.setVerbose(false); downloader.setMaxConcurrentDownloads(3); } void ofApp::downloadFinished(ofxBatchDownloaderReport &report){ cout << "#################################################" << endl; cout << "#### download finished!!" << endl; cout << "#### [ " << report.attemptedDownloads.size() << " attempted | " ; if(report.wasCanceled){ cout << "#### Download Was CANCELED BY USER!" << endl; } cout << report.failedDownloads.size() << " failed | "; cout << report.successfulDownloads.size() << " ok ]" << endl; for(int i = 0; i < report.responses.size(); i++){ ofxSimpleHttpResponse r = report.responses[i]; r.print(); } bool ok = false; int i = 0; while (!ok && i < rep
allURLS, allSha1s, this, &ofApp::downloadFinished, "downloads_" ); downloader.startDownloading(); }else if(key == '3'){ for(int i = 0; i < allURLS.size(); i++){ downloader.downloadResources(allURLS[i], this, &ofApp::downloadFinished, "downloads_" ); } downloader.startDownloading(); } if(key == 'c'){ downloader.cancelCurrentDownload(); } if(key == 'C'){ downloader.cancelAllDownloads(); } }
ort.responses.size()){ if (report.responses[i].ok){ } i++; } } void ofApp::update(){ downloader.update(); } void ofApp::draw(){ ofSetColor(255); drawClock(); downloader.draw(30,30, true, false); string msg = "press 1 to download a file and supply a correct SHA1\n"; msg += "press 2 to download a file and supply an incorrect SHA1\n"; msg += "press 3 to download a few files without supplying a SHA1\n"; msg += "press c to cancel current download\n"; msg += "press C to cancel all downloads\n"; ofDrawBitmapString(msg, 20, ofGetHeight() - 70); } void ofApp::drawClock(){ ofPushMatrix(); ofTranslate(ofGetWidth() - 60,60, 0); ofRotate( ofGetFrameNum() * 3, 0,0,1); ofSetColor(255,255,255); float h = 5; ofRect(-h/2,h/2, h,50); ofPopMatrix(); } void ofApp::keyPressed(int key){ vector<string> allURLS; vector<string> allSha1s; if(key == '1'){ allURLS.push_back("http://farm3.staticflickr.com/2875/9481775605_ea43f5d4f3_o_d.jpg"); allSha1s.push_back("852a7952aabcbf3479974d5350f973b005b23c4a"); } if(key == '2'){ allURLS.push_back("http://farm8.staticflickr.com/7454/9481666291_40f7c00b80_o_d.jpg"); allSha1s.push_back("my_Sha1_Is_Garbage_And_It_Should_Trigger_An_Error"); } if(key == '3'){ allURLS.push_back("http://farm8.staticflickr.com/7420/10032530563_86ff701d19_o.jpg"); allURLS.push_back("http://farm3.staticflickr.com/2877/9481432451_c74c649515_o_d.jpg"); allURLS.push_back("http://farm4.staticflickr.com/3702/9484220536_8f5a866b4d_o_d.jpg"); allURLS.push_back("http://farm4.staticflickr.com/3667/9484488930_2c6527ee35_o_d.jpg"); allURLS.push_back("http://farm3.staticflickr.com/2857/9481682413_5f251ba22d_o_d.jpg"); allURLS.push_back("http://farm8.staticflickr.com/7438/9481688475_e83f92e8b5_o_d.jpg"); } if (key >= '1' && key <= '2'){ downloader.downloadResources(
random
[ { "content": "struct ofxBatchDownloaderReport{\n\n\tstd::string downloadPath;\t\t\t\t\t\t//full path to the directory that holds the downloads\n\n\tofxBatchDownloader* owner;\t\t\t\t\t//pointer to the object in charge of the downloads\n\n\tstd::vector<std::string> attemptedDownloads;\t\t\t//this vector contains all the user supplied urls\n\n\tstd::vector<std::string> successfulDownloads;\t\t\t//this vector contains all the urls that got downloaded correctly\n\n\tstd::vector<std::string> failedDownloads;\t\t\t\t//this vector contains all the urls that failed to download\n\n\tstd::vector<ofxSimpleHttpResponse> responses;\t//this vector contains a list of all url responses, with statuses, filenames, etc\n\n\tbool wasCanceled;\n\n\tofxBatchDownloaderReport(){\n\n\t\twasCanceled = false;\n\n\t}\n\n};\n\n\n\n\n", "file_path": "src/ofxBatchDownloader.h", "rank": 0, "score": 69108.76067937785 }, { "content": "class ofxBatchDownloader;\n\n\n", "file_path": "src/ofxDownloadCentral.h", "rank": 1, "score": 39056.492389340325 }, { "content": "class ofxBatchDownloader;\n\n\n", "file_path": "src/ofxBatchDownloader.h", "rank": 2, "score": 39056.492389340325 }, { "content": "class ofxDownloadCentral{\n\n\n\n\tpublic:\n\n\n\n\t\tofxDownloadCentral();\n\n\t\t~ofxDownloadCentral();\n\n\n\n\t\tvoid update();\n\n\t\tvoid draw(float x, float y, bool drawAllPending = false, bool detailedDownloadInfo = true);\n\n\t\tstd::string getDrawableInfo(bool drawAllPending = false, bool detailedDownloadInfo = true); //draw with a monospaced font!\n\n\n\n\t\tvoid cancelCurrentDownload();\n\n\t\tvoid cancelAllDownloads();\n\n\n\n\t\tbool isBusy();\n\n\t\tint getNumPendingDownloads();\n\n\t\tint getNumActiveDownloads();\n\n\n\n\t\tvoid setVerbose(bool b);\n\n\t\tvoid setNeedsChecksumMatchToSkipDownload(bool needs);\t//if downloaded file is on disk, should I assume its good?\n", "file_path": "src/ofxDownloadCentral.h", "rank": 3, "score": 39056.492389340325 }, { "content": "class ofxBatchDownloader{\n\n\n\npublic:\n\n\n\n\tofxBatchDownloader();\n\n\t~ofxBatchDownloader();\n\n\n\n\tvoid update();\n\n\tvoid draw(float x, float y);\n\n\tstd::string getDrawableString();\n\n\tstd::string getMinimalDrawableString();\n\n\n\n\tvoid setDownloadFolder(std::string f);\n\n\tvoid setSpeedLimit(float KB_per_sec);\n\n\tvoid setTimeOut(float timeOut);\n\n\tvoid setCopyBufferSize(float bufferSizeKb);\n\n\n\n\tvoid setChecksumType(ofxChecksum::Type); //when you supply a checksum to compare a downloaded file against, what type will it be?\n\n\n\n\tvoid addResourcesToDownloadList( std::vector<std::string>urlList );\n", "file_path": "src/ofxBatchDownloader.h", "rank": 4, "score": 39056.492389340325 }, { "content": "\tvoid addResourcesToDownloadList( std::vector<std::string>urlList, std::vector<std::string>checksumList );\n\n\tvoid startDownloading();\n\n\tvoid cancelBatch(bool notify = false);\n\n\n\n\tvoid setVerbose(bool b); //nop\n\n\tvoid setNeedsChecksumMatchToSkipDownload(bool needsChecksum);\n\n\tvoid setIdleTimeAfterEachDownload(float seconds); //wait a bit before notifying once the dowload is over\n\n\n\n\tvoid setProxyConfiguration(const ofxSimpleHttp::ProxyConfig & c);\n\n\tvoid setCredentials(const std::string& user, const std::string& password);\n\n\n\n\tuint64_t getDownloadedBytesSoFar(){ return downloadedSoFar;}\n\n\tint getNumSuppliedUrls();\n\n\tint getNumFailedUrls();\n\n\tint pendingDownloads();\n\n\tbool isBusy();\n\n\tfloat getAverageSpeed(); //bytes/sec\n\n\tstd::vector<std::string> pendingURLs();\n\n\n\n\tofEvent<ofxBatchDownloaderReport>\tresourcesDownloadFinished;\n", "file_path": "src/ofxBatchDownloader.h", "rank": 5, "score": 33956.3409131723 }, { "content": "//\n\n// ofxBatchDownloader.h\n\n// emptyExample\n\n//\n\n// Created by Oriol Ferrer Mesià on 14/03/14.\n\n//\n\n//\n\n\n\n#ifndef emptyExample_ofxBatchDownloader_h\n\n#define emptyExample_ofxBatchDownloader_h\n\n\n\n#include \"ofxSimpleHttp.h\"\n\n\n\n/*\n\n\n\n ####### how to get notifications ############################################\n\n\n\n //create a batch downloader\n\n ofxBatchDownloader dl;\n\n\n\n //sign up for the notification\n\n ofAddListener(dl.resourcesDownloadFinished, this, &myApp::downloadFinished);\n\n\n\n //define the callback in your app\n\n void myApp::downloadFinished(ofxBatchDownloaderReport &report){}\n\n\n\n */\n\n\n", "file_path": "src/ofxBatchDownloader.h", "rank": 6, "score": 33950.96866940381 }, { "content": "\t\tstd::vector<ofxBatchDownloader*>\t\tactiveDownloaders;\n\n\n\n\t\tbool\t\t\t\t\t\t\t\t\tbusy;\n\n\t\tbool\t\t\t\t\t\t\t\t\tverbose;\n\n\t\tbool\t\t\t\t\t\t\t\t\tonlySkipDownloadIfChecksumMatches;\n\n\t\tfloat\t\t\t\t\t\t\t\tidleTimeAfterDownload; //float sec\n\n\t\tfloat\t\t\t\t\t\t\t\tdownloadStartTime;\n\n\t\tstd::streamsize\t\t\t\t\t\tdownloadedSoFar; //bytes\n\n\t\tint\t\t\t\t\t\t\t\t\tdownloadStartJobsNumber;\n\n\n\n\t\tint\t\t\t\t\t\t\t\t\tfailedJobsStartNumber;\n\n\t\tint\t\t\t\t\t\t\t\t\tfailedJobsSoFar;\n\n\n\n\t\tstd::map<int, float>\t\t\t\t\tavgSpeed;\t //bytes/sec\n\n\t\tint\t\t\t\t\t\t\t\t\tmaxURLsToList;\n\n\n\n\t\tint\t\t\t\t\t\t\t\t\tmaxConcurrentDownloads;\n\n\t\tfloat\t\t\t\t\t\t\t\tspeedLimit;\n\n\t\tfloat\t\t\t\t\t\t\t\ttimeOut;\n\n\t\tfloat\t\t\t\t\t\t\t\tcopyBufferSize = 1024.0f; //Kb\n", "file_path": "src/ofxDownloadCentral.h", "rank": 7, "score": 33949.970986501176 }, { "content": "\n\nprivate:\n\n\n\n\tofxSimpleHttp http;\n\n\tbool busy;\n\n\tbool needToStop; //user wants to cancel!\n\n\n\n\tstd::string downloadFolder;\n\n\n\n\tstd::vector<std::string>\toriginalUrlList;\n\n\tstd::vector<std::string>\toriginalChecksumList;\n\n\tstd::vector<std::string>\tfailedList;\n\n\tstd::vector<std::string> okList;\n\n\tstd::vector<ofxSimpleHttpResponse> responses;\n\n\n\n\tvoid httpResult(ofxSimpleHttpResponse &response);\n\n\tvoid reset();\n\n\n\n\tuint64_t downloadedSoFar; //bytes\n\n\n\n\tofxChecksum::Type checksumType = ofxChecksum::Type::SHA1;\n\n\n\n};\n\n\n\n#endif\n\n\n", "file_path": "src/ofxBatchDownloader.h", "rank": 8, "score": 33949.206852253286 }, { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//or only if you provided sha1 checksum and it matches\n\n\n\n\t\tvoid setSpeedLimit(float KB_per_sec);\n\n\t\tvoid setTimeOut(float timeoutSecs);\n\n\t\tvoid setMaxConcurrentDownloads(int numConcurrentDownloads);\n\n\n\n\t\tvoid setChecksumType(ofxChecksum::Type type); //when you supply a checksum to compare a downloaded file against, what type will it be?\n\n\t\tvoid setProxyConfiguration(const ofxSimpleHttp::ProxyConfig & c);\n\n\t\tvoid setCredentials(const std::string& user, const std::string& password);\n\n\n\n\t\tvoid setCopyBufferSize(float bufferInKb);\n\n\n\n\t\tvoid setIdleTimeAfterEachDownload(float seconds);\t\t//wait a bit before notifying once the dowload is over\n\n\t\tvoid setMaxURLsToList(int max);\n\n\n\n\t\tvoid startDownloading();\n\n\n\n\t\t///////////////////////////////////////////////////////////////////////////////\n\n\t\ttemplate <typename ArgumentsType, class ListenerClass>\n\n\t\tvoid downloadResources(\tconst std::string & url,\n", "file_path": "src/ofxDownloadCentral.h", "rank": 9, "score": 33947.55270843547 }, { "content": " will be notified when its downloads are ready.\n\n this is meant mainly to download assets on demand, telling its owner \n\n when the asset is ready to load.\n\n\n\n // HOW IS THIS MEANT TO BE USED ?\n\n\n\n 1 - define a central downloads object\n\n\tofxDownloadCentral dlc;\n\n\n\n 2 - implement a notification callback\n\n\tvoid downloadsFinished(ofxBatchDownloaderReport &report){}\n\n\n\n 3 - fill in a list of url with assets you need downloaded\n\n\tstd::vector<std::string> urlList;\n\n \n\n 4 - supply a list the download\n\n \n\n\tdlc.downloadResources( urlList, this, &myClass::downloadsFinished, destinationFolder );\n\n\n\n\tit will all be downloaded in a bg thread\n", "file_path": "src/ofxDownloadCentral.h", "rank": 10, "score": 33947.01195177293 }, { "content": "//\n\n// ofxDownloadCentral.h\n\n// emptyExample\n\n//\n\n// Created by Oriol Ferrer Mesià on 14/03/14.\n\n//\n\n//\n\n\n\n#pragma once\n\n#include \"ofMain.h\"\n\n#include \"ofxBatchDownloader.h\"\n\n#include \"ofxSimpleHttp.h\"\n\n#include \"ofEvents.h\"\n\n#include \"ofEventUtils.h\"\n\n\n\n/*\n\n// WHAT IS THIS?\n\n\n\n Centralised downloads from any number of objects.\n\n creates a download queue, each object that requests a download list \n", "file_path": "src/ofxDownloadCentral.h", "rank": 11, "score": 33944.43366055997 }, { "content": "\t\t\t}\n\n\t\t}\n\n\n\n\t\t///////////////////////////////////////////////////////////////////////////////\n\n\t\ttemplate <typename ArgumentsType, class ListenerClass>\n\n\t\tvoid downloadResources(const std::vector<std::string> & urlList,\n\n\t\t\t\t\t\t\t ListenerClass * listener,\n\n\t\t\t\t\t\t\t void (ListenerClass::*listenerMethod)(ArgumentsType&),\n\n\t\t\t\t\t\t\t const std::string & destinationFolder = \"ofxDownloadCentral_downloads\"\n\n\t\t\t\t\t\t\t ){\n\n\n\n\t\t\tstd::vector<std::string> shas;\n\n\t\t\tdownloadResources(urlList, shas, listener, listenerMethod, destinationFolder);\n\n\t\t}\n\n\n\n\tprivate:\n\n\n\n\t\tvoid startQueue();\n\n\n\n\t\tstd::vector<ofxBatchDownloader*>\t\tdownloaders;\n", "file_path": "src/ofxDownloadCentral.h", "rank": 12, "score": 33943.38243457822 }, { "content": "\t\t\t\t\t\t\t ListenerClass * listener,\n\n\t\t\t\t\t\t\t void (ListenerClass::*listenerMethod)(ArgumentsType&),\n\n\t\t\t\t\t\t\t const std::string & destinationFolder = \"ofxDownloadCentral_downloads\"\n\n\t\t\t\t\t\t\t ){\n\n\n\n\t\t\tstd::vector<std::string> list;\n\n\t\t\tlist.push_back(url);\n\n\t\t\tdownloadResources(list, listener, listenerMethod, destinationFolder);\n\n\t\t}\n\n\n\n\t\t///////////////////////////////////////////////////////////////////////////////\n\n\t\ttemplate <typename ArgumentsType, class ListenerClass>\n\n\t\tvoid downloadResources( const std::string & url,\n\n\t\t\t\t\t\t\t\tconst std::string & sha1String,\n\n\t\t\t\t\t\t\t ListenerClass * listener,\n\n\t\t\t\t\t\t\t void (ListenerClass::*listenerMethod)(ArgumentsType&),\n\n\t\t\t\t\t\t\t const std::string & destinationFolder = \"ofxDownloadCentral_downloads\"\n\n\t\t\t\t\t\t\t ){\n\n\n\n\t\t\tstd::vector<std::string> list;\n", "file_path": "src/ofxDownloadCentral.h", "rank": 13, "score": 33943.2175345058 }, { "content": "\tyou will be notified from the main thread when they are done\n\n\tyou will get a report\n\n \n\n 6 - start the download\n\n\t\n\n\tstartDownloading();\n\n \n\n 7 - update the dlc object\n\n\t\n\n\tdlc.update();\n\n\t\n\n\tand wait for the notification to arrive\n\n\n\n */\n\n\n", "file_path": "src/ofxDownloadCentral.h", "rank": 14, "score": 33942.849446336804 }, { "content": "\t\t\tstd::vector<std::string> shas;\n\n\t\t\tlist.push_back(url);\n\n\t\t\tshas.push_back(sha1String);\n\n\t\t\tdownloadResources(list, shas, listener, listenerMethod, destinationFolder);\n\n\t\t}\n\n\n\n\n\n\t\t///////////////////////////////////////////////////////////////////////////////\n\n\t\ttemplate <typename ArgumentsType, class ListenerClass>\n\n\t\tvoid downloadResources(\tconst std::vector<std::string> & urlList,\n\n\t\t\t\t\t\t\t\tconst std::vector<std::string> & sha1List,\n\n\t\t\t\t\t\t\t\tListenerClass * listener,\n\n\t\t\t\t\t\t\t\tvoid (ListenerClass::*listenerMethod)(ArgumentsType&),\n\n\t\t\t\t\t\t\t\tconst std::string & destinationFolder = \"ofxDownloadCentral_downloads\"\n\n\t\t\t\t\t\t\t ){\n\n\n\n\t\t\tif (urlList.size() > 0 ){\n\n\t\t\t\tofxBatchDownloader * d = new ofxBatchDownloader();\n\n\t\t\t\td->setProxyConfiguration(proxyConfig);\n\n\t\t\t\tif(credentials.first.size() || credentials.second.size()){\n", "file_path": "src/ofxDownloadCentral.h", "rank": 15, "score": 33942.52243560439 }, { "content": "\t\t\t\t\td->setCredentials(credentials.first, credentials.second);\n\n\t\t\t\t}\n\n\t\t\t\tif(timeOut > 0.0f) d->setTimeOut(timeOut);\n\n\t\t\t\tif(speedLimit > 0.0f) d->setSpeedLimit(speedLimit);\n\n\n\n\t\t\t\td->setDownloadFolder(destinationFolder);\n\n\t\t\t\td->setVerbose(verbose);\n\n\t\t\t\td->setNeedsChecksumMatchToSkipDownload(onlySkipDownloadIfChecksumMatches);\n\n\t\t\t\td->setChecksumType(checksumType);\n\n\t\t\t\td->setCopyBufferSize(copyBufferSize);\n\n\t\t\t\td->setIdleTimeAfterEachDownload(idleTimeAfterDownload);\n\n\t\t\t\td->addResourcesToDownloadList(urlList, sha1List);\n\n\t\t\t\tofAddListener(d->resourcesDownloadFinished, listener, listenerMethod); //set the notification to hit our original caller\n\n\t\t\t\tif(downloaders.size() == 0){\n\n\t\t\t\t\tdownloadStartTime = ofGetElapsedTimef();\n\n\t\t\t\t\tdownloadedSoFar = 0;\n\n\t\t\t\t}else{\n\n\t\t\t\t\tdownloadStartJobsNumber++;\n\n\t\t\t\t}\n\n\t\t\t\tdownloaders.push_back(d);\n", "file_path": "src/ofxDownloadCentral.h", "rank": 16, "score": 33942.22431468315 }, { "content": "\t\tofxChecksum::Type \t\t\t\t\tchecksumType = ofxChecksum::Type::SHA1;\n\n\n\n\t\tofxSimpleHttp::ProxyConfig\t\t\tproxyConfig;\n\n\t\tstd::pair<std::string,std::string> \tcredentials;\n\n\n\n\n\n};\n\n\n\n\n", "file_path": "src/ofxDownloadCentral.h", "rank": 17, "score": 33937.17532460588 }, { "content": "\t\treport.attemptedDownloads = originalUrlList;\n\n\t\treport.successfulDownloads = okList;\n\n\t\treport.failedDownloads = failedList;\n\n\t\treport.responses = responses;\n\n\t\treport.wasCanceled = true;\n\n\t\tofNotifyEvent( resourcesDownloadFinished, report, this );\n\n\t}\n\n\tbusy = false;\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::setDownloadFolder(std::string f){\n\n\tdownloadFolder = f;\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::draw(float x, float y){\n\n\thttp.draw(x, y);\n\n}\n\n\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 18, "score": 32745.904722093117 }, { "content": "\t\treport.attemptedDownloads = originalUrlList;\n\n\t\treport.successfulDownloads = okList;\n\n\t\treport.failedDownloads = failedList;\n\n\t\treport.responses = responses;\n\n\t\tofNotifyEvent( resourcesDownloadFinished, report, this );\n\n\t\tbusy = false;\n\n\t}\n\n}\n\n\n\n\n\nfloat ofxBatchDownloader::getAverageSpeed(){\n\n\treturn http.getAvgDownloadSpeed();\n\n}\n\n\n\n\n\nstd::vector<std::string> ofxBatchDownloader::pendingURLs(){\n\n\n\n\tstd::vector<std::string> res;\n\n\tfor (int i = 0; i < originalUrlList.size(); i++){\n\n\t\tbool found = false;\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 19, "score": 32743.425745430774 }, { "content": "\tbool checkedOK = r.checksumOK || (!r.checksumOK && r.expectedChecksum.size() == 0);\n\n\tif(r.ok && checkedOK){\n\n\t\tokList.push_back( r.url );\n\n\t\tofLogNotice(\"ofxBatchDownloader\") << \"downloaded OK [\" << r.url << \"]\";\n\n\t}else{\n\n\t\tfailedList.push_back( r.url );\n\n\t\tif (!r.checksumOK){\n\n\t\t\tofLogError(\"ofxBatchDownloader\") << \"checksum mismatch! [\" << r.url << \"] expectedChecksum: \" << r.expectedChecksum << \")\";\n\n\t\t}else{\n\n\t\t\tofLogError(\"ofxBatchDownloader\") << \"FAILED TO download [\" << r.url << \"]\";\n\n\t\t}\n\n\t}\n\n\n\n\tdownloadedSoFar += r.downloadedBytes;\n\n\n\n\tif (originalUrlList.size() == failedList.size() + okList.size()){\n\n\t\t//we are done!\n\n\t\tofxBatchDownloaderReport report;\n\n\t\treport.owner = this;\n\n\t\treport.downloadPath = downloadFolder;\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 20, "score": 32738.781812012057 }, { "content": "\thttp.setProxyConfiguration(c);\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::setCredentials(const std::string& user, const std::string& password){\n\n\thttp.setCredentials(user, password);\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::setVerbose(bool b){}\n\n\n\n\n\nofxBatchDownloader::~ofxBatchDownloader(){\n\n\tif (busy) {\n\n\t\tcancelBatch(false /*notify*/);\n\n\t}\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::update(){\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 21, "score": 32738.23247255028 }, { "content": "\t\tfor (int j = 0; j < okList.size(); j++){\n\n\t\t\tif ( okList[j] == originalUrlList[i] ){\n\n\t\t\t\tfound = true;\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor (int j = 0; j < failedList.size(); j++){\n\n\t\t\tif ( failedList[j] == originalUrlList[i] ){\n\n\t\t\t\tfound = true;\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (!found) res.push_back(originalUrlList[i]);\n\n\t}\n\n\treturn res;\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::reset(){\n\n\tfailedList.clear();\n\n\tokList.clear();\n\n\tresponses.clear();\n\n}\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 22, "score": 32737.767047752634 }, { "content": "\n\nbool ofxBatchDownloader::isBusy(){\n\n\treturn busy;\n\n};\n\n\n\nint ofxBatchDownloader::getNumSuppliedUrls(){\n\n\treturn originalUrlList.size();\n\n}\n\n\n\nint ofxBatchDownloader::getNumFailedUrls(){\n\n\treturn failedList.size();\n\n}\n\n\n\nvoid ofxBatchDownloader::startDownloading(){\n\n\n\n\tif (!busy){\n\n\t\tbusy = true;\n\n\t\treset();\n\n\n\n\t\tofLogVerbose(\"ofxBatchDownloader\") << \"starting downloads! \";\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 23, "score": 32737.66613541973 }, { "content": "\thttp.update();\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::setTimeOut(float timeOut){\n\n\thttp.setTimeOut(timeOut);\n\n}\n\n\n\nvoid ofxBatchDownloader::setSpeedLimit(float KB_per_sec){\n\n\thttp.setSpeedLimit(KB_per_sec);\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::cancelBatch(bool notify){\n\n\thttp.stopCurrentDownload(true);\n\n\thttp.waitForThread(true);\n\n\tif(notify){\n\n\t\tofxBatchDownloaderReport report;\n\n\t\treport.owner = this;\n\n\t\treport.downloadPath = downloadFolder;\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 24, "score": 32737.50965333005 }, { "content": "\tonlySkipDownloadIfChecksumMatches = true;\n\n\tmaxURLsToList = 4;\n\n\tidleTimeAfterDownload = 0.0f;\n\n\tmaxConcurrentDownloads = 1;\n\n\ttimeOut = -1.0f;\n\n\tfailedJobsSoFar = failedJobsStartNumber = 0;\n\n}\n\n\n\nofxDownloadCentral::~ofxDownloadCentral(){\n\n\tcancelAllDownloads();\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::setMaxConcurrentDownloads(int numConcurrentDownloads){\n\n\tmaxConcurrentDownloads = ofClamp(numConcurrentDownloads, 1, INT_MAX);\n\n}\n\n\n\nvoid ofxDownloadCentral::setCopyBufferSize(float bufferInKb){\n\n\tcopyBufferSize = bufferInKb;\n\n}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 25, "score": 32737.21700744624 }, { "content": "void ofxDownloadCentral::cancelCurrentDownload(){\n\n\tif (busy){\n\n\t\tfor(int i = activeDownloaders.size() - 1; i >= 0; i--){\n\n\t\t\tofxBatchDownloader * bd = activeDownloaders[i];\n\n\t\t\tbd->cancelBatch(true);\n\n\t\t}\n\n\t}\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::cancelAllDownloads(){\n\n\tif (busy){\n\n\t\tcancelCurrentDownload(); //active downloads get stopped\n\n\t\twhile(downloaders.size() > 0){\n\n\t\t\tdelete downloaders[0];\n\n\t\t\tdownloaders.erase(downloaders.begin());\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 26, "score": 32736.53507541873 }, { "content": "void ofxDownloadCentral::setVerbose(bool b){\n\n\tverbose = b;\n\n}\n\n\n\nvoid ofxDownloadCentral::setIdleTimeAfterEachDownload(float seconds){\n\n\tidleTimeAfterDownload = seconds;\n\n}\n\n\n\n\n\n\n\nvoid ofxDownloadCentral::setNeedsChecksumMatchToSkipDownload(bool needs){\n\n\tonlySkipDownloadIfChecksumMatches = needs;\n\n}\n\n\n\nvoid ofxDownloadCentral::startQueue(){\n\n\n\n\tfor(int i = activeDownloaders.size(); i < maxConcurrentDownloads; i++){\n\n\t\tif(downloaders.size() > 0){\n\n\t\t\tbusy = true;\n\n\t\t\tofxBatchDownloader * bd = downloaders[0];\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 27, "score": 32735.628274617044 }, { "content": "\n\nvoid ofxDownloadCentral::setChecksumType(ofxChecksum::Type type){\n\n\tchecksumType = type;\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::startDownloading(){\n\n\tif (!busy){\n\n\t\tdownloadStartJobsNumber = downloaders.size();\n\n\t\tfailedJobsStartNumber = failedJobsSoFar;\n\n\t\tstartQueue();\n\n\t}\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::setMaxURLsToList(int max){\n\n\tmaxURLsToList = max;\n\n}\n\n\n\n\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 28, "score": 32735.325825094184 }, { "content": "\t}\n\n\n\n\tstd::string spa = \" \";\n\n\tstd::string header = \"//// ofxDownloadCentral queued Jobs: \" + ofToString(numQueuedJobs) + \" ///////////////////////////\\n\"\n\n\t\"//// Jobs executed: \" + spa + ofToString(numProcessed) + \"\\n\" +\n\n\t\"//// Jobs failed: \" + spa + ofToString(numFailed) + \"\\n\" +\n\n//\t\"//// Total Downloads Left: \" + spa + ofToString(total) + \"\\n\" +\n\n\t\"//// Elapsed Time: \" + spa + ofxSimpleHttp::secondsToHumanReadable(elapsedTime, 1) + \"\\n\" +\n\n\t\"//// Estimated Time Left: \" + spa + ofxSimpleHttp::secondsToHumanReadable(timeLeft, 1) + \"\\n\"\n\n\t\"//// Estimated Completion: \" + spa + estFinish + \"\\n\" +\n\n\t\"//// Avg Download Speed: \" + spa + ofxSimpleHttp::bytesToHumanReadable(avg, 1) + \"/sec\\n\" +\n\n\t\"//// Downloaded So Far: \" + spa + ofxSimpleHttp::bytesToHumanReadable(downloadedSoFar, 1) +\n\n\t\"\\n\";\n\n\n\n\treturn header + httpDownloadersStatus + pendingDownloadsList;\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::draw(float x, float y, bool drawAllPending, bool detailedDownloadInfo){\n\n\tif (busy){\n\n\t\tstd::string aux = getDrawableInfo(drawAllPending, detailedDownloadInfo);\n\n\t\tofDrawBitmapString(aux, x, y);\n\n\t}\n\n}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 29, "score": 32733.652417067562 }, { "content": "\n\n\n\nstd::string ofxDownloadCentral::getDrawableInfo(bool drawAllPending, bool detailed){\n\n\n\n\tint total = 0;\n\n\tfor(int i = 0; i < activeDownloaders.size(); i++){\n\n\t\ttotal += activeDownloaders[i]->getNumSuppliedUrls();\n\n\t}\n\n\n\n\tfor(int i = 0; i < downloaders.size(); i++){\n\n\t\ttotal += downloaders[i]->getNumSuppliedUrls();\n\n\t}\n\n\n\n\tstd::string httpDownloadersStatus;\n\n\tstd::string pendingDownloadsList;\n\n\tint numQueuedJobs = downloaders.size() + activeDownloaders.size();\n\n\n\n\tstd::vector<std::string> allURLs;\n\n\tstd::vector<std::string> allPending;\n\n\tbool reachedListMaxLen = false;\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 30, "score": 32733.58286920666 }, { "content": "\n\nbool ofxDownloadCentral::isBusy(){\n\n\treturn busy;\n\n}\n\n\n\n\n\nint ofxDownloadCentral::getNumPendingDownloads(){\n\n\n\n\tint c = 0;\n\n\tfor(int i = 0; i < downloaders.size(); i++){\n\n\t\tstd::vector<std::string> pending = downloaders[i]->pendingURLs();\n\n\t\tc+= pending.size();\n\n\t}\n\n\treturn c;\n\n}\n\n\n\n\n\nint ofxDownloadCentral::getNumActiveDownloads(){\n\n\treturn activeDownloaders.size();\n\n}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 31, "score": 32733.57609124429 }, { "content": "\t}\n\n\tif(printingList) pendingDownloadsList += \"//////////////////////////////////////////////////////////////////\";\n\n\n\n\tfloat elapsedTime = ofGetElapsedTimef() - downloadStartTime;\n\n\tfloat timeLeft = 0.0f;\n\n\tint numProcessed = downloadStartJobsNumber - numQueuedJobs;\n\n\tint numFailed = failedJobsSoFar - failedJobsStartNumber;\n\n\tstd::string estFinish;\n\n\tif (numProcessed > 0){\n\n\t\ttimeLeft = numQueuedJobs * elapsedTime / float(numProcessed);\n\n\t\tPoco::Timespan timeToAdd;\n\n\t\ttimeToAdd.assign(timeLeft, 0);\n\n\t\tstd::string timeFormat = \"%H:%M on %w %e, %b %Y\";\n\n\t\tPoco::LocalDateTime now;\n\n\t\tnow += timeToAdd;\n\n\t\testFinish = Poco::DateTimeFormatter::format(now, timeFormat);\n\n\t}\n\n\tfloat avg = 0;\n\n\tfor(int i = 0; i < activeDownloaders.size(); i++){\n\n\t\tavg += avgSpeed[i];\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 32, "score": 32733.56070081176 }, { "content": "\n\n\n\nvoid ofxDownloadCentral::setSpeedLimit(float KB_per_sec){\n\n\tspeedLimit = KB_per_sec;\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::setTimeOut(float timeoutSecs){\n\n\ttimeOut = timeoutSecs;\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::setProxyConfiguration(const ofxSimpleHttp::ProxyConfig & c){\n\n\tproxyConfig = c;\n\n}\n\n\n\nvoid ofxDownloadCentral::setCredentials(const std::string& user, const std::string& password){\n\n\tcredentials.first = user;\n\n\tcredentials.second = password;\n\n}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 33, "score": 32733.14243680849 }, { "content": "\n\n\t\thttp.setMaxQueueLength(originalUrlList.size() * 2); //just in case\n\n\n\n\t\tfor(int i = 0; i < originalUrlList.size(); i++){\n\n\t\t\tstd::string sha = \"\";\n\n\t\t\tif (originalChecksumList.size()){\n\n\t\t\t\tsha = originalChecksumList[i];\n\n\t\t\t}\n\n\t\t\thttp.fetchURLToDisk(originalUrlList[i], sha, true, downloadFolder);\n\n\t\t}\n\n\t}\n\n}\n\n\n\n\n\n//this might or might not be called from the main thread! depending on the ofxSimpleHttp config\n\nvoid ofxBatchDownloader::httpResult(ofxSimpleHttpResponse &r){\n\n\n\n\t//int index = okList.size() + failedList.size();\n\n\n\n\tresponses.push_back(r);\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 34, "score": 32733.075649170092 }, { "content": "\n\nvoid ofxBatchDownloader::setChecksumType(ofxChecksum::Type t){\n\n\tchecksumType = t;\n\n\thttp.setChecksumType(t);\n\n}\n\n\n\nvoid ofxBatchDownloader::setNeedsChecksumMatchToSkipDownload(bool needsChecksum){\n\n\thttp.setNeedsChecksumMatchToSkipDownload(needsChecksum); \n\n}\n\n\n\nvoid ofxBatchDownloader::setCopyBufferSize(float bufferSizeKb){\n\n\thttp.setCopyBufferSize(bufferSizeKb);\n\n}\n\n\n\nvoid ofxBatchDownloader::setIdleTimeAfterEachDownload(float seconds){\n\n\thttp.setIdleTimeAfterEachDownload( seconds );\n\n}\n\n\n\n\n\nvoid ofxBatchDownloader::setProxyConfiguration(const ofxSimpleHttp::ProxyConfig & c){\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 35, "score": 32732.224105431316 }, { "content": "\t\t\tbd->startDownloading();\n\n\t\t\tactiveDownloaders.push_back(bd);\n\n\t\t\tdownloaders.erase(downloaders.begin());\n\n\t\t}\n\n\t}\n\n}\n\n\n\n\n\nvoid ofxDownloadCentral::update(){\n\n\n\n\tif (busy){\n\n\n\n\t\tfor(int i = activeDownloaders.size() - 1; i >= 0; i--){\n\n\n\n\t\t\tofxBatchDownloader * bd = activeDownloaders[i];\n\n\t\t\tbd->update();\n\n\n\n\t\t\tif (!bd->isBusy()){ //this one is over! start the next one!\n\n\t\t\t\tif(avgSpeed[i] <= 0.001f){\n\n\t\t\t\t\tavgSpeed[i] = bd->getAverageSpeed();\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 36, "score": 32731.705352226665 }, { "content": "\tint c = 0; //count how many pending urls have we printed\n\n\tbool printingList = false; //are we printing a pending list?\n\n\n\n\tif(activeDownloaders.size() > 0){\n\n\n\n\t\tif(!detailed) httpDownloadersStatus += \"\\n//// Active Downloaders (\" + ofToString(activeDownloaders.size()) + \") Status ///////////////////////////////\";\n\n\n\n\t\tfor(int i = 0; i < activeDownloaders.size(); i++){\n\n\t\t\tofxBatchDownloader * bd = activeDownloaders[i];\n\n\n\n\t\t\tif(!detailed){\n\n\t\t\t\tchar aux[5];\n\n\t\t\t\tsprintf(aux, \"%02d\", i);\n\n\t\t\t\thttpDownloadersStatus += \"\\n// (\" + std::string(aux) + \") \" + bd->getMinimalDrawableString();\n\n\t\t\t\tif(i == activeDownloaders.size() - 1) httpDownloadersStatus += \"\\n\\n\"; //last line more spce\n\n\t\t\t}else{\n\n\t\t\t\thttpDownloadersStatus += bd->getDrawableString();\n\n\t\t\t}\n\n\t\t\ttotal -= bd->getNumSuppliedUrls() - bd->pendingDownloads();\n\n\t\t}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 37, "score": 32731.685014754097 }, { "content": "//\n\n// ofxDownloadCentral.cpp\n\n// emptyExample\n\n//\n\n// Created by Oriol Ferrer Mesià on 14/03/14.\n\n//\n\n//\n\n\n\n\n\n#include \"ofxDownloadCentral.h\"\n\n#include \"ofEvents.h\"\n\n#include \"ofEventUtils.h\"\n\n#include \"Poco/LocalDateTime.h\"\n\n#include \"Poco/DateTimeFormatter.h\"\n\n\n\nofxDownloadCentral::ofxDownloadCentral(){\n\n\n\n\tverbose = true;\n\n\tbusy = false;\n\n\tspeedLimit = 0.0f;\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 38, "score": 32731.283698665182 }, { "content": "//\n\n// ofxBatchDownloader.cpp\n\n// emptyExample\n\n//\n\n// Created by Oriol Ferrer Mesià on 14/03/14.\n\n//\n\n//\n\n\n\n\n\n#include \"ofxBatchDownloader.h\"\n\n#include \"ofLog.h\"\n\n\n\nofxBatchDownloader::ofxBatchDownloader(){\n\n\tbusy = false;\n\n\tdownloadFolder = \"_downloads_\";\n\n\tdownloadedSoFar = 0;\n\n\t//add download listener\n\n\tofAddListener(http.httpResponse, this, &ofxBatchDownloader::httpResult);\n\n}\n\n\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 39, "score": 32730.6257801484 }, { "content": "\t\t\t\t}else{\n\n\t\t\t\t\tavgSpeed[i] = avgSpeed[i] * 0.75 + 0.25 * bd->getAverageSpeed();\n\n\t\t\t\t}\n\n\n\n\t\t\t\tdownloadedSoFar += bd->getDownloadedBytesSoFar();\n\n\t\t\t\tif(bd->getNumFailedUrls() > 0) failedJobsSoFar ++;\n\n\t\t\t\tactiveDownloaders.erase(activeDownloaders.begin() + i);\n\n\t\t\t\tdelete bd;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif(activeDownloaders.size() < maxConcurrentDownloads){\n\n\t\t\tstartQueue();\n\n\t\t}\n\n\t\tif(activeDownloaders.size() == 0){\n\n\t\t\tbusy = false;\n\n\t\t}\n\n\t}\n\n}\n\n\n\n\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 40, "score": 32730.570650790967 }, { "content": "\tif(!busy){\n\n\n\n\t\tfor(int i = 0; i < _urlList.size(); i++){\n\n\t\t\toriginalUrlList.push_back(_urlList[i]);\n\n\t\t\tif (_checksumList.size()){\n\n\t\t\t\toriginalChecksumList.push_back(_checksumList[i]);\n\n\t\t\t}\n\n\t\t\tofLogVerbose(\"ofxBatchDownloader\") << \"queueing \" << _urlList[i] << \" for download\";\n\n\t\t}\n\n\n\n\t}else{\n\n\t\tofLogWarning(\"ofxBatchDownloader\") << \"already working, wait for it to finish!\";\n\n\t}\n\n}\n\n\n\n\n\nint ofxBatchDownloader::pendingDownloads(){\n\n\treturn http.getPendingDownloads();\n\n}\n\n\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 41, "score": 32730.12618184844 }, { "content": "\n\n\t\tif(drawAllPending){\n\n\t\t\tprintingList = true;\n\n\t\t\tpendingDownloadsList += \"//// Remaining Downloads (\" + ofToString(total) + \") /////////////////////////////////////\\n\";\n\n\t\t\tfor(int i = 0; i < activeDownloaders.size(); i++){\n\n\t\t\t\tstd::vector<std::string> pending = activeDownloaders[i]->pendingURLs();\n\n\t\t\t\tfor(int j = 0; j < pending.size(); j++){\n\n\t\t\t\t\tallPending.push_back(pending[j]);\n\n\t\t\t\t\tif (c < maxURLsToList){\n\n\t\t\t\t\t\tpendingDownloadsList += \"// \" + pending[j] + \"\\n\";\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c == maxURLsToList ){\n\n\t\t\t\t\t\tpendingDownloadsList += \"// ...\\n\";\n\n\t\t\t\t\t\treachedListMaxLen = true;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tc++;\n\n\t\t\t\t}\n\n\t\t\t\tif (reachedListMaxLen) break;\n\n\t\t\t}\n\n\t\t}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 42, "score": 32730.033901927134 }, { "content": "std::string ofxBatchDownloader::getDrawableString(){\n\n\treturn http.drawableString();\n\n}\n\n\n\nstd::string ofxBatchDownloader::getMinimalDrawableString(){\n\n\treturn http.minimalDrawableString();\n\n}\n\n\n\nvoid ofxBatchDownloader::addResourcesToDownloadList( std::vector<std::string> _urlList ){\n\n\tstd::vector<std::string>_checksumList;\n\n\taddResourcesToDownloadList(_urlList, _checksumList);\n\n}\n\n\n\nvoid ofxBatchDownloader::addResourcesToDownloadList( std::vector<std::string> _urlList, std::vector<std::string>_checksumList ){\n\n\n\n\tif ( _checksumList.size() > 0 && (_urlList.size() != _checksumList.size()) ){\n\n\t\tofLogWarning(\"ofxBatchDownloader\") << \"addResourcesToDownloadList >> urlList & shaList element num mismatch!\";\n\n\t\treturn;\n\n\t}\n\n\n", "file_path": "src/ofxBatchDownloader.cpp", "rank": 43, "score": 32729.4182222191 }, { "content": "\t}\n\n\n\n\tif(drawAllPending){\n\n\t\tif(downloaders.size() > 0 && !reachedListMaxLen){\n\n\t\t\tfor(int i = 0; i < downloaders.size(); i++){\n\n\t\t\t\tstd::vector<std::string> pending = downloaders[i]->pendingURLs();\n\n\t\t\t\tfor(int j = 0; j < pending.size(); j++){\n\n\t\t\t\t\tallPending.push_back(pending[j]);\n\n\t\t\t\t\tif (c < maxURLsToList){\n\n\t\t\t\t\t\tpendingDownloadsList += \"// \" + pending[j] + \"\\n\";\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c == maxURLsToList ){\n\n\t\t\t\t\t\tpendingDownloadsList += \"// ...\\n\";\n\n\t\t\t\t\t\treachedListMaxLen = true;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tc++;\n\n\t\t\t\t}\n\n\t\t\t\tif (reachedListMaxLen ) break;\n\n\t\t\t}\n\n\t\t}\n", "file_path": "src/ofxDownloadCentral.cpp", "rank": 44, "score": 32729.14704623144 }, { "content": "#pragma once\n\n\n\n#include \"ofMain.h\"\n\n#include \"ofxBatchDownloader.h\"\n\n\n", "file_path": "example-ofxBatchDownloader/src/ofApp.h", "rank": 45, "score": 31601.178285767488 }, { "content": "#pragma once\n\n\n\n#include \"ofMain.h\"\n\n#include \"ofxDownloadCentral.h\"\n\n\n", "file_path": "example-ofxDownloadCentral/src/ofApp.h", "rank": 46, "score": 31601.178285767488 }, { "content": "\t\tdownloader.addResourcesToDownloadList(downloadList);\n\n\t}\n\n\n\n\tif(key==' '){\n\n\t\tdownloader.startDownloading();\n\n\t}\n\n\n\n\tif(key=='c'){\n\n\t\tdownloader.cancelBatch();\n\n\t}\n\n}\n\n\n\n\n\nvoid ofApp::downloadFinished(ofxBatchDownloaderReport &report){\n\n\n\n\tcout << \"download Finished!\" << endl;\n\n\tcout << report.successfulDownloads.size() << \" successful downloads, \" << report.failedDownloads.size() << \" failed downloads.\" << endl;\n\n\n\n\tif( report.failedDownloads.size() ){\n\n\t\tcout << \"these downloads failed: \" ;\n\n\t\tfor(int i = 0; i < report.failedDownloads.size(); i++ ){\n\n\t\t\tcout << \" - \" << report.failedDownloads[i] << endl;\n\n\t\t}\n\n\t}\n\n\n\n}", "file_path": "example-ofxBatchDownloader/src/ofApp.cpp", "rank": 48, "score": 30564.050264242167 }, { "content": "\tdownloadList.push_back(\"http://farm4.staticflickr.com/3740/9481659071_3159d318dc_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm4.staticflickr.com/3802/9484323300_6d3a6a78b5_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm6.staticflickr.com/5346/9484309488_11ee39298e_o.jpg\");\n\n\n\n\t//add download listener\n\n\tofAddListener(downloader.resourcesDownloadFinished, this, &ofApp::downloadFinished);\n\n\tdownloader.setDownloadFolder(\"tempDownloads\");\n\n\tdownloader.setNeedsChecksumMatchToSkipDownload(true);\n\n\tdownloader.setIdleTimeAfterEachDownload(0.2);\n\n\tdownloader.setVerbose(false);\n\n\n\n}\n\n\n\n\n\nvoid ofApp::update(){\n\n\n\n\tdownloader.update();\n\n}\n\n\n\nvoid ofApp::draw(){\n", "file_path": "example-ofxBatchDownloader/src/ofApp.cpp", "rank": 51, "score": 30547.897353960307 }, { "content": "#include \"ofMain.h\"\n\n#include \"ofApp.h\"\n\n#include \"ofAppGLFWWindow.h\"\n\n\n\n//========================================================================\n\nint main( ){\n\n\tofAppGLFWWindow win;\n\n\t//win.setNumSamples(8);\n\n\t//win.setOrientation(OF_ORIENTATION_90_LEFT);\n\n\t//win.setMultiDisplayFullscreen(true);\n\n\t//win.set\n\n\n\n\tofSetupOpenGL(&win, 800,500, OF_WINDOW);\t// <-------- setup the GL context\n\n\n\n\t// this kicks off the running of my app\n\n\t// can be OF_WINDOW or OF_FULLSCREEN\n\n\t// pass in width and height too:\n\n\tofRunApp(new ofApp());\n\n\n\n}\n", "file_path": "example-ofxBatchDownloader/src/main.cpp", "rank": 53, "score": 30544.869845725585 }, { "content": "#include \"ofMain.h\"\n\n#include \"ofApp.h\"\n\n#include \"ofAppGLFWWindow.h\"\n\n\n\n//========================================================================\n\nint main( ){\n\n\tofAppGLFWWindow win;\n\n\t//win.setNumSamples(8);\n\n\t//win.setOrientation(OF_ORIENTATION_90_LEFT);\n\n\t//win.setMultiDisplayFullscreen(true);\n\n\t//win.set\n\n\n\n\tofSetupOpenGL(&win, 800,600, OF_WINDOW);\t// <-------- setup the GL context\n\n\n\n\t// this kicks off the running of my app\n\n\t// can be OF_WINDOW or OF_FULLSCREEN\n\n\t// pass in width and height too:\n\n\tofRunApp(new ofApp());\n\n\n\n}\n", "file_path": "example-ofxDownloadCentral/src/main.cpp", "rank": 54, "score": 30544.869845725585 }, { "content": "\n\n\tdownloader.draw(30,30);\n\n\tofSetColor(255);\n\n\n\n\t//clock hand to see threading in action\n\n\tofPushMatrix();\n\n\n\n\tofTranslate(ofGetWidth() - 60,60, 0);\n\n\tofRotate( ofGetFrameNum() * 3, 0,0,1);\n\n ofSetColor(255,255,255);\n\n\tfloat h = 5;\n\n\tofRect(-h/2,h/2, h,50);\n\n\n\n\tofPopMatrix();\n\n}\n\n\n\n\n\nvoid ofApp::keyPressed(int key){\n\n\n\n\tif(key=='a'){\n", "file_path": "example-ofxBatchDownloader/src/ofApp.cpp", "rank": 56, "score": 30544.31603142723 }, { "content": "#include \"ofApp.h\"\n\n\n\n\n\n\n\nvoid ofApp::setup(){\n\n\n\n\tofSetFrameRate(63);\n\n\tofSetVerticalSync(true);\n\n\tofEnableAlphaBlending();\n\n\tofBackground(22);\n\n\tofSetWindowPosition(20, 20);\n\n\n\n\tdownloadList.push_back(\"http://farm8.staticflickr.com/7420/10032530563_86ff701d19_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm4.staticflickr.com/3686/9225463176_d0bf83a992_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm8.staticflickr.com/7255/6888724266_158ce261a2_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm8.staticflickr.com/7047/7034809565_5f80871bff_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm8.staticflickr.com/7438/9481688475_e83f92e8b5_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm8.staticflickr.com/7321/9481647489_e73bed28e1_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm8.staticflickr.com/7367/9484432454_9701453c66_o.jpg\");\n\n\tdownloadList.push_back(\"http://farm6.staticflickr.com/5537/9481654243_7b73b87ceb_o.jpg\");\n", "file_path": "example-ofxBatchDownloader/src/ofApp.cpp", "rank": 59, "score": 30542.265752999632 }, { "content": "class ofApp : public ofBaseApp{\n\n\n\npublic:\n\n\n\n\tvoid setup();\n\n\tvoid update();\n\n\tvoid draw();\n\n\tvoid keyPressed(int key);\n\n\tvoid drawClock();\n\n\n\n\t//download ready callback\n\n\tvoid downloadFinished(ofxBatchDownloaderReport &report);\n\n\n\n\tofxDownloadCentral downloader;\n\n\n\n};\n", "file_path": "example-ofxDownloadCentral/src/ofApp.h", "rank": 60, "score": 27760.162258016055 }, { "content": "class ofApp : public ofBaseApp{\n\n\n\n\tpublic:\n\n\t\tvoid setup();\n\n\t\tvoid update();\n\n\t\tvoid draw();\n\n\n\n\t\tvoid keyPressed(int key);\n\n\n\n\t\tfloat p1;\n\n\t\tbool timeSample;\n\n\n\n\t\tvoid downloadFinished(ofxBatchDownloaderReport &report);\n\n\n\n\t\tofxBatchDownloader downloader;\n\n\t\tvector<string> downloadList;\n\n\n\n};\n", "file_path": "example-ofxBatchDownloader/src/ofApp.h", "rank": 61, "score": 27760.162258016055 }, { "content": "\t\tvoid \t\t\t\t\tsetProxyConfiguration(const ProxyConfig & c);\n\n\n\n\t\tvoid\t\t\t\t\t\tsetTimeOut(int seconds);\n\n\t\tvoid\t\t\t\t\t\tsetUserAgent(std::string newUserAgent );\n\n\t\tvoid\t\t\t\t\t\tsetCredentials(std::string username, std::string password);\n\n\t\tvoid\t\t\t\t\t\tsetMaxQueueLength(int len);\n\n\t\tvoid \t\t\t\t\tsetCopyBufferSize(float KB); /*in KiloBytes (1 -> 1024 bytes)*/\n\n\t\tvoid\t\t\t\t\t\tsetIdleTimeAfterEachDownload(float seconds); //wait a bit before notifying once the dowload is over\n\n\t\tvoid\t\t\t\t\t\tsetChecksumType(ofxChecksum::Type); //when you supply a checksum to compare a downloaded file against, what type will it be?\n\n\n\n\t\tvoid\t\t\t\t\t\tsetCancelCurrentDownloadOnDestruction(bool doIt);\n\n\t\tvoid\t\t\t\t\t\tsetCancelPendingDownloadsOnDestruction(bool cancelAll);\n\n\n\n\t\tvoid\t\t\t\t\t\taddCustomHttpHeader(std::string headerName, std::string headerContent);\n\n\t\tvoid\t\t\t\t\t\tsetNotifyFromMainThread(bool mainThread);\n\n\n\n\t\t\t\t\t\t\t\t//if a download is requested and file already exists on disk,\n\n\t\t\t\t\t\t\t\t//do we require a checksum match to assume the file is good?\n\n\t\t\t\t\t\t\t\t//ie, if the user doesnt provide a checksum, what do we do?\n\n\t\tvoid\t\t\t\t\t\tsetNeedsChecksumMatchToSkipDownload(bool needs);\n", "file_path": "src/ofxSimpleHttp.h", "rank": 62, "score": 15.959096642740676 }, { "content": "\n\n}\n\n\n\n\n\nvoid ofApp::newResponse(ofxSimpleHttpResponse &r){\n\n\n\n\tcout << \"#########################################################\" << endl;\n\n\tcout << \"download of \" << r.url << \" returned : \"<< string(r.ok ? \"OK\" : \"KO\") << endl;\n\n\tcout << \"server reported size is \" << r.serverReportedSize << endl;\n\n\tcout << \"server status is \" << r.status << endl;\n\n\tcout << \"file content type is \" << r.contentType << endl;\n\n\tcout << \"file name is \" << r.fileName << endl;\n\n\n\n\tif(r.downloadToDisk){\n\n\t\tcout << \"file was saved to \" << r.absolutePath << endl;\n\n\n\n\t\t//move the file to wherever you need..\n\n\t\tofDirectory dir;\n\n\t\tdir.createDirectory(\"mySortedDownloads\");\n\n\n", "file_path": "example-ofxSimpleHttp/src/ofApp.cpp", "rank": 63, "score": 13.69333162671093 }, { "content": "\n\nvoid ofxSimpleHttp::setCopyBufferSize(float KB){\n\n\tCOPY_BUFFER_SIZE = KB * 1024;\n\n}\n\n\n\nvoid ofxSimpleHttp::setCancelCurrentDownloadOnDestruction(bool doIt){\n\n\tcancelCurrentDownloadOnDestruction = doIt;\n\n}\n\n\n\nvoid ofxSimpleHttp::setCancelPendingDownloadsOnDestruction(bool cancelAll){\n\n\tflushPendingRequestsOnDestruction = cancelAll;\n\n}\n\n\n\nvoid ofxSimpleHttp::setIdleTimeAfterEachDownload(float seconds){\n\n\tidleTimeAfterEachDownload = seconds;\n\n}\n\n\n\nvoid ofxSimpleHttp::setNotifyFromMainThread(bool mainThread){\n\n\tnotifyFromMainThread = mainThread;\n\n}\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 64, "score": 13.485707905891402 }, { "content": "\n\nvoid ofxSimpleHttp::setNeedsChecksumMatchToSkipDownload(bool needs){\n\n\tonlySkipDownloadIfChecksumMatches = needs;\n\n}\n\n\n\nvoid ofxSimpleHttp::setTimeOut(int seconds){\n\n\ttimeOut = seconds;\n\n}\n\n\n\nvoid ofxSimpleHttp::setChecksumType(ofxChecksum::Type type){\n\n\tchecksumType = type;\n\n}\n\n\n\nvoid ofxSimpleHttp::setUserAgent( std::string newUserAgent ){\n\n\tuserAgent = newUserAgent;\n\n}\n\n\n\nvoid ofxSimpleHttp::setCredentials(std::string username, std::string password){\n\n\tif(username.size() || password.size()){\n\n\t\tcredentials.setUsername(username);\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 65, "score": 12.508794549124636 }, { "content": "\t\t\t\tss << \" Avg Download Speed: \" << (serverReportedSize / 1024.f) / timeTakenToDownload << \"Kb/sec\" << endl;\n\n\t\t\t}\n\n\t\t\tif(downloadToDisk){\n\n\t\t\t\tss << \" File Saved at: \" << absolutePath << endl;\n\n\t\t\t}\n\n\t\t}\n\n\t}else{\n\n\t\tss << \" Download FAILED! \" << endl;\n\n\t\tss << \" Status: \" << status << \" - \" << reasonForStatus << endl;\n\n\t}\n\n\treturn ss.str();\n\n}\n\n\n\nvoid ofxSimpleHttpResponse::print(){\n\n\tif (ok){\n\n\t\tofLogNotice(\"ofxSimpleHttpResponse\") << toString();\n\n\t}else{\n\n\t\tofLogError(\"ofxSimpleHttpResponse\") << toString();\n\n\t}\n\n}\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 66, "score": 11.482966736445887 }, { "content": "\t\tvoid\t\t\t\t\t\tupdate(); //this is mainly used to get notifications in the main thread\n\n\n\n\t\tvoid\t\t\t\t\t\tdraw(float x, float y , float w , float h);\t//draws a box\n\n\t\tvoid\t\t\t\t\t\tdraw(float x, float y);\t//draws a box\n\n\t\tstd::string\t\t\t\tdrawableString(int urlLen = 0);\n\n\t\tvoid\t\t\t\t\t\tdrawMinimal(float x, float y,\n\n\t\t\t\t\t\t\t\t\t\t\tbool withBg = false,\n\n\t\t\t\t\t\t\t\t\t\t\tofColor fontColor = ofColor::white,\n\n\t\t\t\t\t\t\t\t\t\t\tofColor bgColor = ofColor::black);\t//draws a one-line status\n\n\t\tstd::string\t\t\t\tminimalDrawableString();\n\n\n\n\t\tvoid\t\t\t\t\t\tstopCurrentDownload(bool emptyQueue); //if there's more downloads on queue, next will start immediatelly\n\n\n\n\t\tint\t\t\t\t\t\tgetPendingDownloads();\n\n\t\tfloat\t\t\t\t\tgetCurrentDownloadProgress();\t//retuns [0..1] how complete is the download\n\n\t\tstd::string\t\t\t\tgetCurrentDownloadFileName();\t//only while downloading\n\n\t\tfloat\t\t\t\t\tgetAvgDownloadSpeed();\t\t\t// bytes/sec - also when not download\n\n\n\n\t\t// properties //////////////////////////////////////////////////////////\n\n\n", "file_path": "src/ofxSimpleHttp.h", "rank": 67, "score": 10.70248225640561 }, { "content": "\t\tstatic std::string\t\textractFileFromUrl(const std::string & url);\n\n\t\tstatic std::string\t\textractExtensionFromFileName(const std::string& fileName);\n\n\t\tstatic std::string\t\tgetFileSystemSafeString(const std::string & input);\n\n\n\n\tprotected:\n\n\n\n\t\tbool downloadURL( ofxSimpleHttpResponse * resp, bool sendResultThroughEvents, bool beingCalledFromMainThread, bool saveToDisk );\n\n\t\tvoid threadedFunction();\t//the queue runs here\n\n\n\n\t\tofxChecksum::Type \t\tchecksumType = ofxChecksum::Type::SHA1;\n\n\t\tbool\t\t\t\t\t\tnotifyFromMainThread;\n\n\t\tbool\t\t\t\t\t\tonlySkipDownloadIfChecksumMatches;\n\n\n\n\t\tbool \t\t\t\t\tsilent = false; //if true, no ofLog calls\n\n\t\tint\t\t\t\t\t\ttimeOut;\n\n\t\tstd::string\t\t\t\tuserAgent;\n\n\t\tstd::string\t\t\t\tacceptString;\n\n\t\tstd::queue<ofxSimpleHttpResponse*>\tq;\t\t//the pending requests\n\n\t\tbool\t\t\t\t\t\ttimeToStop;\n\n\t\tint\t\t\t\t\t\tqueueLenEstimation;\n", "file_path": "src/ofxSimpleHttp.h", "rank": 68, "score": 9.941185579171977 }, { "content": "\t\tint\t\t\t\t\t\tmaxQueueLen;\n\n\t\tfloat\t\t\t\t\tidleTimeAfterEachDownload;\t//seconds\n\n\t\tfloat\t\t\t\t\tavgDownloadSpeed;\n\n\t\tbool\t\t\t\t\t\tcancelCurrentDownloadOnDestruction;\n\n\t\tbool\t\t\t\t\t\tflushPendingRequestsOnDestruction;\n\n\n\n\t\tfloat\t\t\t\t\tspeedLimit; //in KiloBytes / sec\n\n\t\tofxSimpleHttpResponse\t\tresponse; //used by blocking fetch() methods\n\n\n\n\t\tProxyConfig\t\t\t\tproxyConfig;\n\n\t\tbool\t\t\t\t\t\tuseCredentials;\n\n\t\tPoco::Net::HTTPBasicCredentials\t\tcredentials;\n\n\n\n\t\tstd::queue<ofxSimpleHttpResponse>\t\tresponsesPendingNotification; //we store here downloads that arrived so that we can notify from main thread\n\n\t\tstd::map<std::string, std::string> \tcustomHttpHeaders;\n\n\n\n\t\tstatic \t\t\t\t\tPoco::Net::Context::Ptr pContext;\n\n\t\tint \t\t\t\t\t\tCOPY_BUFFER_SIZE;\n\n\t\tfloat \t\t\t\t\tavgSpeedNow;\n\n\n\n\t\tstd::streamsize streamCopyWithProgress(std::istream & in, std::ostream & out, std::streamsize totalBytes,\n\n\t\t\t\t\t\t\t\t\t\t\t std::streamsize &currentBytes, bool & speedSampled,\n\n\t\t\t\t\t\t\t\t\t\t\t float & progress, float &speed, const bool &shouldCancel);\n\n\n\n\n\n};\n", "file_path": "src/ofxSimpleHttp.h", "rank": 69, "score": 9.650169814469969 }, { "content": "\tlock();\n\n\tint n = q.size();\n\n\tif ( isThreadRunning() && n > 0){\n\n\t\tofxSimpleHttpResponse * r = q.front();\n\n\t\tif (!r->downloadCanceled){ //dont cancel it twice!\n\n\t\t\tif(!silent) ofLogNotice(\"ofxSimpleHttp\") << \"stopCurrentDownload() >> about to stop download of \" + r->fileName + \" ...\";\n\n\t\t\ttry{\n\n\t\t\t\tr->emptyWholeQueue = emptyQueue;\n\n\t\t\t\tr->downloadCanceled = true;\n\n\t\t\t}catch(Exception& exc){\n\n\t\t\t\tofLogError(\"ofxSimpleHttp\") << \"stopCurrentDownload(\" << r->fileName << \") >> Exception: \" << exc.displayText() ;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tunlock();\n\n}\n\n\n\n\n\n\n\n\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 70, "score": 8.059714792501683 }, { "content": "\t\tofFile f;\n\n\t\tf.open( r.absolutePath );\n\n\t\tif( f.exists() ){\n\n\t\t\tf.moveTo(\"mySortedDownloads/\" + r.fileName);\n\n\t\t}else{\n\n\t\t\tcout << \"file was not downloaded???!\" << r.absolutePath << endl;\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid ofApp::exit(){\n\n\tofxSimpleHttp::destroySslContext();\n\n}\n", "file_path": "example-ofxSimpleHttp/src/ofApp.cpp", "rank": 71, "score": 7.985005384174773 }, { "content": "\tif(customField.size()) ss << \"CustomField: \" << customField << endl;\n\n\tif (ok){\n\n\t\tif (fileWasHere){\n\n\t\t\tss << \" File was already on disk, no download needed!\" << endl;\n\n\t\t\tif (expectedChecksum.size()){\n\n\t\t\t\tss << \" File checksum \" << expectedChecksum << \" matched!\" << endl;\n\n\t\t\t}else{\n\n\t\t\t\tss << \" File checksum not supplied, assuming file is the same blindly\" << endl;\n\n\t\t\t}\n\n\t\t\tss << \" File saved at: \" << absolutePath << endl;\n\n\t\t}else{\n\n\t\t\tss << \" Server Status: \" << status << endl;\n\n\t\t\tss << \" Server Reported size: \" << serverReportedSize << endl;\n\n\t\t\tss << \" Content Type: \" << contentType << endl;\n\n\t\t\tif(expectedChecksum.length()){\n\n\t\t\t\tss << \" Expected Checksum: \" << expectedChecksum << endl;\n\n\t\t\t\tss << \" Checksum Match: \" << std::string(checksumOK ? \"YES\" : \"NO\") << endl;\n\n\t\t\t}\n\n\t\t\tss << \" Download Time taken: \" << timeTakenToDownload << \" seconds\" << endl;\n\n\t\t\tif (serverReportedSize != -1){\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 72, "score": 7.783833323103924 }, { "content": "\t}\n\n\n\n\tif(key=='6'){\n\n\t\thttp.setUserAgent(\"My Fake Browser\"); //github api requires User Agent string\n\n\t\tofxSimpleHttpResponse res = http.fetchURLBlocking(\"https://api.github.com/users/armadillu/events\");\n\n\t\tcout << res.responseBody << endl;\n\n\t}\n\n\n\n\n\n\tif(key=='7'){ //also supports file:// urls for local filesystem\n\n\t\thttp.fetchURLToDisk(\"file:///System/Library/Fonts/Optima.ttc\", true, OUTPUT_DIRECTORY );\n\n\t}\n\n\n\n\tif(key=='c'){\n\n\t\thttp.stopCurrentDownload(false);\n\n\t}\n\n\n\n\tif(key=='C'){\n\n\t\thttp.stopCurrentDownload(true);\n\n\t}\n", "file_path": "example-ofxSimpleHttp/src/ofApp.cpp", "rank": 73, "score": 7.598110873722316 }, { "content": "# ofxSimpleHttp\n\n\n\n[![Build Status](https://travis-ci.org/armadillu/ofxSimpleHttp.svg?branch=master)](https://travis-ci.org/armadillu/ofxSimpleHttp)\n\n[![Build status](https://ci.appveyor.com/api/projects/status/d8e634rmni9f7tmr/branch/master?svg=true)](https://ci.appveyor.com/project/armadillu/ofxsimplehttp/branch/master)\n\n\n\nOpenFrameworks addon to make http downloads easy; \n\n\n\n\n\n\n\n\n\n* supports http://, https:// and file://\n\n* threaded downloads\n\n* user agent customization\n\n* proxy support\n\n* custom timeouts\n\n* parallel downloads\n\n* download queues\n\n* cancel downloads\n\n* checksum checked downloads (sha1)\n\n* skip download if file is already there and sha1 matches\n\n* download reports (http status codes, download speed, total time, etc)\n\n* ofEvents from main thread, or bg thread if required\n\n\n\n![img1](https://farm6.staticflickr.com/5556/14785717148_c953b4d82e_z_d.jpg)\n\n\n\n![img1](https://farm4.staticflickr.com/3909/14785770407_718d5752cf_z_d.jpg)\n", "file_path": "ReadMe.md", "rank": 74, "score": 7.577868069375683 }, { "content": "\tuserAgent = \"ofxSimpleHttp (Poco Powered)\";\n\n\tacceptString = \"\";\n\n\tnotifyFromMainThread = true;\n\n\tonlySkipDownloadIfChecksumMatches = false;\n\n\tidleTimeAfterEachDownload = 0.0;\n\n\tavgDownloadSpeed = 0.0f;\n\n\tspeedLimit = 0.0f;\n\n\tuseCredentials = false;\n\n\tavgSpeedNow = 0.0f;\n\n}\n\n\n\n\n\nofxSimpleHttp::~ofxSimpleHttp(){\n\n\n\n\tif(flushPendingRequestsOnDestruction){\n\n\t\tif(queueLenEstimation > 0 && !silent) ofLogWarning(\"ofxSimpleHttp\") << \"Destructor canceling pending downloads (\" << queueLenEstimation << \")\";\n\n\t\ttimeToStop = true;\t//lets flag the thread so that it doesnt try access stuff while we delete things around\n\n\t}\n\n\n\n\tif(cancelCurrentDownloadOnDestruction && isThreadRunning()){\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 75, "score": 7.421857752849167 }, { "content": "\n\n#include \"ofxChecksum.h\"\n\n\n\n#include <Poco/SHA1Engine.h>\n\n#include <Poco/DigestStream.h>\n\n\n\n#include \"../libs/xxHash/xxhash.h\"\n\n#include \"../libs/sha1/sha1.h\"\n\n\n\n//#include \"ofxTimeMeasurements.h\"\n\n//extern \"C\" {\n\n//#include \"sha1.h\"\n\n//}\n\n\n\n\n\nbool ofxChecksum::sha1(const std::string& filePath,\n\n\t\t\t\t\t const std::string& sha1String,\n\n\t\t\t\t\t bool verbose){\n\n\tfloat t;\n\n\tif(verbose){\n", "file_path": "src/ofxChecksum.cpp", "rank": 76, "score": 7.352165590270129 }, { "content": "\t\t\t\t\t\t\t\tstd::string msg = \"downloadURL(\" + resp->fileName + \") >> Exception at file.open: \" + exc.displayText();\n\n\t\t\t\t\t\t\t\tofLogError(\"ofxSimpleHttp\") << msg ;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}else{\n\n\t\t\t\t\t\t\tresp->downloadedBytes = resp->responseBody.size();\n\n\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\tif(resp->timeTakenToDownload > 0.01f){\n\n\t\t\t\t\t\t\tresp->avgDownloadSpeed = (resp->downloadedBytes ) / resp->timeTakenToDownload; //bytes/sec\n\n\t\t\t\t\t\t\tif(!silent) ofLogNotice(\"ofxSimpleHttp\") << \"downloadURL() >> download completed - \\\"\" << resp->url << \"\\\" - avg Dl speed: \" <<\n\n\t\t\t\t\t\t\t\tbytesToHumanReadable(resp->avgDownloadSpeed,1) << \" - Dl Size: \" << bytesToHumanReadable(resp->downloadedBytes, 1) <<\n\n\t\t\t\t\t\t\t\t\" - dur: \" << secondsToHumanReadable(resp->timeTakenToDownload, 1);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tavgDownloadSpeed = resp->avgDownloadSpeed;\n\n\n\n\t\t\t\t\t\tbool isAPI = (resp->contentType == \"text/json\" || resp->contentType == \"application/json;charset=UTF-8\");\n\n\t\t\t\t\t\tbool sizeMissmatch = resp->serverReportedSize > 0 && resp->serverReportedSize != resp->downloadedBytes;\n\n\n\n\t\t\t\t\t\t//check download file size mismatch\n\n\t\t\t\t\t\tif ( sizeMissmatch && !isAPI ) {\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 77, "score": 7.2270864467157505 }, { "content": "\n\n\tavgDownloadSpeed = 0.95f * avgDownloadSpeed + 0.05f * avgSpeedNow;\n\n\tbool done = false;\n\n\n\n\twhile(!done){\n\n\t\tlock();\n\n\t\tint numPending = responsesPendingNotification.size();\n\n\t\tif(numPending > 0){\n\n\t\t\tofxSimpleHttpResponse r;\n\n\t\t\tr = responsesPendingNotification.front();\n\n\t\t\tresponsesPendingNotification.pop();\n\n\t\t\tunlock();\n\n\t\t\tofNotifyEvent( httpResponse, r, this ); //we want to be able to notify from outside the lock\n\n\t\t}else{\n\n\t\t\tunlock();\n\n\t\t\tdone = true;\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 78, "score": 6.966809466267102 }, { "content": "#pragma once\n\n\n\n#include \"ofMain.h\"\n\n#include \"ofxSimpleHttp.h\"\n\n\n\n#define OUTPUT_DIRECTORY \"tempDownloads\"\n\n\n", "file_path": "example-ofxSimpleHttp/src/ofApp.h", "rank": 79, "score": 6.946734207385544 }, { "content": "\t\t\t\t\t\tdefault: break;\n\n\t\t\t\t\t}\n\n\n\n\t\t\t\t\tresp->checksumOK = resp->expectedChecksum == resp->calculatedChecksum;\n\n\n\n\t\t\t\t\tif(!resp->checksumOK){\n\n\t\t\t\t\t\tif(!silent) ofLogNotice(\"ofxSimpleHttp\") << \"file:// copy OK but Checksum FAILED\";\n\n\t\t\t\t\t\tif(!silent) ofLogNotice(\"ofxSimpleHttp\") << \"Checksum (\" + ofxChecksum::toString(resp->checksumType) + \") was meant to be: \\\"\" << resp->expectedChecksum << \"\\\" but is: \\\"\" << resp->calculatedChecksum<< \"\\\"\";\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\n\n\t\t\t\trs.close();\n\n\t\t\t\tok = true;\n\n\t\t\t}else{\n\n\t\t\t\tofLogError(\"ofxSimpleHttp\") << \"Source File does not exist! \" << resp->url;\n\n\t\t\t\tresp->ok = false;\n\n\t\t\t\tresp->status = 404; //assume not found? todo!\n\n\t\t\t\tresp->reasonForStatus = \"Source File does not exist!\";\n\n\t\t\t\tresp->timeTakenToDownload = 0;\n\n\t\t\t\tresp->checksumOK = false;\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 80, "score": 6.836213375828944 }, { "content": "\tresponse.who = this;\n\n\tresponse.downloadCanceled = false;\n\n\tresponse.fileName = extractFileFromUrl(url);\n\n\tresponse.extension = extractExtensionFromFileName(response.fileName);\n\n\tresponse.notifyOnSuccess = true;\n\n\tresponse.checksumType = checksumType;\n\n\tbool ok = downloadURL(&response,\n\n\t\t\t\t\t\t false/*send res through events*/,\n\n\t\t\t\t\t\t true/*beingCalledFromMainThread*/,\n\n\t\t\t\t\t\t false/*to disk*/\n\n\t\t\t\t\t\t );\n\n\treturn response;\n\n}\n\n\n\nvoid ofxSimpleHttp::fetchURLToDisk(std::string url, std::string expectedChecksum, bool notifyOnSuccess,\n\n\t\t\t\t\t\t\t\t std::string dirWhereToSave, std::string customField){\n\n\n\n\tif (queueLenEstimation >= maxQueueLen){\n\n\t\tofLogError(\"ofxSimpleHttp\") << \"fetchURL can't do that, queue is too long already (\" << queueLenEstimation << \")!\";\n\n\t\treturn;\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 81, "score": 6.796075060572505 }, { "content": "\t\tcredentials.setPassword(password);\n\n\t\tuseCredentials = true;\n\n\t}\n\n}\n\n\n\nvoid ofxSimpleHttp::setMaxQueueLength(int len){\n\n\tmaxQueueLen = len;\n\n}\n\n\n\nvoid ofxSimpleHttp::addCustomHttpHeader(std::string headerName, std::string headerContent){\n\n\tcustomHttpHeaders[headerName] = headerContent;\n\n}\n\n\n\nstd::string ofxSimpleHttp::getCurrentDownloadFileName(){\n\n\n\n\tstd::string download = \"\";\n\n\tlock();\n\n\tint n = q.size();\n\n\tif ( isThreadRunning() && n > 0 ){\n\n\t\tofxSimpleHttpResponse * r = q.front();\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 82, "score": 6.781688795830549 }, { "content": "\n\n\t\t\t\tif (notifyFromMainThread){ //user wants to get notified form main thread, we need to enqueue the notification\n\n\t\t\t\t\tif (timeToStop == false){\t//see if we have been destructed! dont forward events if so\n\n\t\t\t\t\t\tlock();\n\n\t\t\t\t\t\tofxSimpleHttpResponse tempCopy = *resp;\n\n\t\t\t\t\t\tresponsesPendingNotification.push(tempCopy);\n\n\t\t\t\t\t\tunlock();\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{ //user doesnt care about main thread, the notificaiton can come from bg thread so we do it from here\n\n\t\t\t\t\tofNotifyEvent( httpResponse, *resp, this );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\treturn ok;\n\n}\n\n\n\n\n\nvoid ofxSimpleHttp::update(){\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 83, "score": 6.764506565490649 }, { "content": "\t\t\t\t\t\t\t\t\"press '6' call an https based API, print result on console\\n\"\n\n\t\t\t\t\t\t\t\t\"press '7' to download (copy) a local file (file:// url)\\n\"\n\n\t\t\t\t\t\t\t\t\"press 'c' to cancel current download\\n\"\n\n\t\t\t\t\t\t\t\t\"press 'C' to cancel current download and empty queue\",\n\n\t\t\t\t\t\t\t\t20,\n\n\t\t\t\t\t\t\t\tofGetHeight() - 133\n\n\t\t\t\t\t\t\t\t);\n\n\n\n\n\n}\n\n\n\n\n\nvoid ofApp::keyPressed(int key){\n\n\n\n\n\n\tif(key=='1'){\n\n\t\tstring url = downloadList[floor(ofRandom(downloadList.size()))];\n\n\t\thttp.fetchURLToDisk(url , true/*notify when done*/, OUTPUT_DIRECTORY);\n\n\t}\n\n\n", "file_path": "example-ofxSimpleHttp/src/ofApp.cpp", "rank": 84, "score": 6.7586984327252955 }, { "content": "\t\tvoid\t\t\t\t\t\tsetSpeedLimit(float KB_per_sec);\n\n\n\n\t\tvoid\t\t\t\t\t\tsetSilent(bool noLogging);\n\n\n\n\n\n\t\tofEvent<ofxSimpleHttpResponse> httpResponse;\n\n\n\n\t\t// https support //////////////////////////////////////////////////////////////\n\n\n\n\t\t//call once, before any https connection is made\n\n\t\tstatic void \t\t\t\tcreateSslContext(Poco::Net::Context::Usage = Poco::Net::Context::CLIENT_USE,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t Poco::Net::Context::VerificationMode verMode = Poco::Net::Context::VERIFY_NONE);\n\n\n\n\t\tstatic void \t\t\t\tdestroySslContext(); //call once when no longer need https, once all trasnfers are finished\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t//or just b4 app exit\n\n\n\n\t\t// STATIC Utility Methods ////////////////////////////////////////////////////////\n\n\n\n\t\tstatic std::string\t\tbytesToHumanReadable(long long bytes, int decimalPrecision);\n\n\t\tstatic std::string\t\tsecondsToHumanReadable(float sec, int decimalPrecision);\n", "file_path": "src/ofxSimpleHttp.h", "rank": 85, "score": 6.727509105310984 }, { "content": "\n\n\t\t\t\t\tstd::ostringstream output;\n\n\t\t\t\t\tstreamCopyWithProgress(rs, output, resp->serverReportedSize, resp->downloadedSoFar, resp->chunkTested,\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t resp->downloadProgress, resp->downloadSpeed, resp->downloadCanceled);\n\n\t\t\t\t\tresp->responseBody = output.str();\n\n\n\n\t\t\t\t}\n\n\t\t\t\tresp->ok = true;\n\n\t\t\t\tresp->status = 200;\n\n\t\t\t\tresp->timeTakenToDownload = ofGetElapsedTimef() - resp->timeDowloadStarted;\n\n\t\t\t\tresp->downloadedBytes = resp->serverReportedSize;\n\n\n\n\t\t\t\tif (resp->expectedChecksum.length() > 0){\n\n\t\t\t\t\tswitch(resp->checksumType){\n\n\t\t\t\t\t\tcase ofxChecksum::Type::SHA1:\n\n\t\t\t\t\t\t\tresp->calculatedChecksum = ofxChecksum::calcSha1(resp->absolutePath);\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase ofxChecksum::Type::XX_HASH:\n\n\t\t\t\t\t\t\tresp->calculatedChecksum = ofxChecksum::xxHash(resp->absolutePath);\n\n\t\t\t\t\t\t\tbreak;\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 86, "score": 6.604623383427125 }, { "content": "\t\t\tofStringReplace(srcFilePath, \"\\\\\", \"/\"); //for windows, replace escaped backslashes\n\n#endif\n\n\t\t\t//ofFile::copyFromTo(srcFile, resp->absolutePath);\n\n\n\n\t\t\tofFile srcOfFile;\n\n\t\t\tbool openOK = srcOfFile.open(ofToDataPath(srcFilePath, true), ofFile::ReadOnly);\n\n\t\t\tresp->downloadSpeed = 0;\n\n\t\t\tresp->downloadedBytes = 0;\n\n\n\n\t\t\tif(srcOfFile.exists()){\n\n\t\t\t\tuint64_t size = srcOfFile.getSize();\n\n\t\t\t\tresp->serverReportedSize = size;\n\n\t\t\t\tresp->timeDowloadStarted = ofGetElapsedTimef();\n\n\t\t\t\tstd::ifstream rs (ofToDataPath(srcFilePath, true).c_str(), std::ifstream::binary);\n\n\n\n\t\t\t\tif(saveToDisk){\n\n\t\t\t\t\tstreamCopyWithProgress(rs, myfile, resp->serverReportedSize, resp->downloadedSoFar, resp->chunkTested,\n\n\t\t\t\t\t\t\t\t\t resp->downloadProgress, resp->downloadSpeed, resp->downloadCanceled);\n\n\n\n\t\t\t\t}else{\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 87, "score": 6.582230335791583 }, { "content": "\tresponse.fileName = extractFileFromUrl(url);\n\n\tresponse.extension = extractExtensionFromFileName(response.fileName);\n\n\tresponse.notifyOnSuccess = true;\n\n\tresponse.downloadToDisk = true;\n\n\tbool ok = downloadURL(&response,\n\n\t\t\t\t\t\t false,/*send result through events*/\n\n\t\t\t\t\t\t true, /*beingCalledFromMainThread*/\n\n\t\t\t\t\t\t true/*to disk*/\n\n\t\t\t\t\t\t );\n\n\treturn response;\n\n}\n\n\n\n\n\nbool ofxSimpleHttp::downloadURL(ofxSimpleHttpResponse* resp, bool sendResultThroughEvents, bool beingCalledFromMainThread, bool saveToDisk){\n\n\n\n\tbool ok = false;\n\n\tofstream myfile;\n\n\tbool fileIsAlreadyHere = false;\n\n\tresp->responseBody = \"\";\n\n\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 88, "score": 6.485477128583245 }, { "content": "\t\t\t\t\t\t\tcase ofxChecksum::Type::XX_HASH:\n\n\t\t\t\t\t\t\t\tresp->calculatedChecksum = ofxChecksum::xxHash(resp->absolutePath);\n\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tdefault: break;\n\n\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\tresp->checksumOK = resp->expectedChecksum == resp->calculatedChecksum;\n\n\n\n\t\t\t\t\t\tif(!resp->checksumOK){\n\n\t\t\t\t\t\t\tofLogNotice(\"ofxSimpleHttp\") << \"downloaded OK but Checksum FAILED\";\n\n\t\t\t\t\t\t\tofLogNotice(\"ofxSimpleHttp\") << \"Checksum (\" + ofxChecksum::toString(resp->checksumType) + \") was meant to be: \\\"\" << resp->expectedChecksum << \"\\\" but is: \\\"\" << resp->calculatedChecksum<< \"\\\"\";\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\n\n\t\t\t\t\tresp->downloadSpeed = 0;\n\n\t\t\t\t\tresp->downloadedBytes = 0;\n\n\n\n\t\t\t\t\tif (resp->downloadCanceled){\n\n\t\t\t\t\t\t//delete half-baked download file\n\n\t\t\t\t\t\tif (resp->downloadToDisk){\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 89, "score": 6.439664741979257 }, { "content": "\n\n\n\nofxSimpleHttpResponse::ofxSimpleHttpResponse(){\n\n\twho = NULL;\n\n\tdownloadToDisk = emptyWholeQueue = false;\n\n\tchecksumOK = true;\n\n\tdownloadProgress = downloadSpeed = avgDownloadSpeed = downloadedBytes = 0.0f;\n\n\ttimeTakenToDownload = 0.0;\n\n\tserverReportedSize = -1;\n\n\tdownloadedSoFar = 0;\n\n\tstatus = -1;\n\n\tfileWasHere = false;\n\n\ttimeDowloadStarted = ofGetElapsedTimef();\n\n\tchunkTested = false;\n\n}\n\n\n\nstd::string ofxSimpleHttpResponse::toString(){\n\n\n\n\tstd::stringstream ss;\n\n\tss << \"URL: \" << url << endl;\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 90, "score": 6.429488111303279 }, { "content": "\t\t\t\t\t\t\tstd::string msg;\n\n\n\n\t\t\t\t\t\t\tif (resp->downloadedBytes == 0){\n\n\t\t\t\t\t\t\t\tif (resp->timeTakenToDownload > timeOut){\n\n\t\t\t\t\t\t\t\t\tmsg = \"downloadURLtoDiskBlocking() >> TimeOut! (\" + resp->fileName + \")\";\n\n\t\t\t\t\t\t\t\t\tresp->reasonForStatus = \"Request TimeOut\";\n\n\t\t\t\t\t\t\t\t\tresp->status = HTTPResponse::HTTP_REQUEST_TIMEOUT;\n\n\t\t\t\t\t\t\t\t}else{\n\n\t\t\t\t\t\t\t\t\tmsg = \"downloadURLtoDiskBlocking() >> Download file is 0 bytes (\" + resp->fileName + \")\";\n\n\t\t\t\t\t\t\t\t\tresp->reasonForStatus = \"Download size is 0 bytes!\";\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}else{\n\n\t\t\t\t\t\t\t\tmsg = \"downloadURLtoDiskBlocking() >> Download size mismatch (\" + resp->fileName + \") >> Server: \" +\n\n\t\t\t\t\t\t\t\tofToString(resp->serverReportedSize) + \" Downloaded: \" + ofToString(resp->downloadedBytes);\n\n\t\t\t\t\t\t\t\tresp->reasonForStatus = \"Download size mismatch\";\n\n\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\tif(!silent) ofLogWarning(\"ofxSimpleHttp\", msg);\n\n\t\t\t\t\t\t\tresp->status = -1;\n\n\t\t\t\t\t\t\tresp->ok = false;\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 91, "score": 6.399105844522036 }, { "content": "\t\tdownload = r->fileName;\n\n\t}\n\n\tunlock();\n\n\treturn download;\n\n}\n\n\n\n\n\nint ofxSimpleHttp::getPendingDownloads(){\n\n\tlock();\n\n\tqueueLenEstimation = q.size();\n\n\tunlock();\n\n\treturn queueLenEstimation;\n\n}\n\n\n\n\n\nfloat ofxSimpleHttp::getCurrentDownloadProgress(){\n\n\n\n\tfloat downloadPercent = -1;\n\n\tlock();\n\n\tint n = q.size();\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 92, "score": 6.227563919734032 }, { "content": "#include \"Poco/Net/HTTPRequest.h\"\n\n#include \"Poco/Net/HTTPResponse.h\"\n\n\n\n\n\nPoco::Net::Context::Ptr ofxSimpleHttp::pContext = NULL;\n\n\n\nusing namespace Poco::Net;\n\nusing namespace Poco;\n\nusing Poco::Exception;\n\nusing Poco::Net::HTTPClientSession;\n\n\n\nofxSimpleHttp::ofxSimpleHttp(){\n\n\n\n\tCOPY_BUFFER_SIZE = 1024 * 512; // kb buffer size\n\n\tcancelCurrentDownloadOnDestruction = true;\n\n\tflushPendingRequestsOnDestruction = true;\n\n\ttimeOut = 10;\n\n\tqueueLenEstimation = 0;\n\n\tmaxQueueLen = 1000;\n\n\ttimeToStop = false;\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 93, "score": 6.171685937679604 }, { "content": "\t\t\t\t\tresp->ok = false;\n\n\t\t\t\t\tresp->reasonForStatus = \"Unknown exception at streamCopy\";\n\n\t\t\t\t\tresp->status = -1;\n\n\t\t\t\t\tok = false;\n\n\t\t\t\t}\n\n\n\n\t\t\t\t//last check for OK flag\n\n\t\t\t\tif(!resp->checksumOK){\n\n\t\t\t\t\tresp->ok = false;\n\n\t\t\t\t\tresp->reasonForStatus += \" / Checksum mismatch! (\" + ofxChecksum::toString(resp->checksumType) + \")\";\n\n\t\t\t\t}\n\n\n\n\t\t\t}catch(Exception& exc){\n\n\n\n\t\t\t\tif (session) session->reset();\n\n\t\t\t\tmyfile.close();\n\n\t\t\t\tstd::string msg = \"downloadURL(\" + resp->fileName + \") >> Exception: \" + exc.displayText();\n\n\t\t\t\tresp->timeTakenToDownload = ofGetElapsedTimef() - resp->timeDowloadStarted;\n\n\t\t\t\tif (resp->timeTakenToDownload > timeOut){\n\n\t\t\t\t\tmsg = \"downloadURLtoDiskBlocking() >> TimeOut! (\" + resp->fileName + \")\";\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 94, "score": 5.86977766135613 }, { "content": "\t\tmsg += \"] \";\n\n\t\tmsg += std::string( r->downloadToDisk ? ofFilePath::getFileName(r->absolutePath) : \"\");\n\n\t\tmsg += \" (\" + bytesToHumanReadable((long long)r->downloadSpeed, 1) + \"/s\";\n\n\t\tif(r->serverReportedSize > 0){\n\n\t\t\tmsg += \" | \" + bytesToHumanReadable(r->serverReportedSize, 1) + \" file)\";\n\n\t\t}else{\n\n\t\t\tmsg += \")\";\n\n\t\t}\n\n\t}\n\n\tunlock();\n\n\treturn msg;\n\n}\n\n\n\n\n\nstd::string ofxSimpleHttp::drawableString(int urlLen){\n\n\n\n\tstd::string aux;\n\n\tlock();\n\n\tint n = q.size();\n\n\tif( isThreadRunning() && n > 0 ){\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 95, "score": 5.747129308651704 }, { "content": "float ofxSimpleHttp::getAvgDownloadSpeed(){\n\n\treturn avgDownloadSpeed;\n\n}\n\n\n\n\n\nstd::string ofxSimpleHttp::minimalDrawableString(){\n\n\n\n\tstd::string msg;\n\n\tlock();\n\n\tint n = q.size();\n\n\tif( isThreadRunning() && n > 0 ){\n\n\t\tofxSimpleHttpResponse * r = q.front();\n\n\t\tchar aux[16];\n\n\t\tsprintf(aux, \"% 4d%%\", (int)(r->downloadProgress * 100.0f));\n\n\t\tmsg += std::string(aux) + \" [\";\n\n\t\tfloat barLen = 12;\n\n\t\tfloat numFill = r->downloadProgress * barLen;\n\n\t\tfor(int i = 0; i < barLen; i++){\n\n\t\t\tmsg += std::string(i < numFill ? \"*\" : \" \");\n\n\t\t}\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 96, "score": 5.719555012050627 }, { "content": " SHA1_Update(context, finalcount, 8); /* Should cause a SHA1_Transform() */\n\n for (i = 0; i < SHA1_DIGEST_SIZE; i++) {\n\n digest[i] = (uint8_t)\n\n ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);\n\n }\n\n\n\n /* Wipe variables */\n\n i = 0;\n\n memset(context->buffer, 0, 64);\n\n memset(context->state, 0, 20);\n\n memset(context->count, 0, 8);\n\n memset(finalcount, 0, 8);\t/* SWR */\n\n}\n\n\n\n//-----------------------------------------------------------------------------\n\n\n\nvoid sha1_32a ( const void * key, int len, uint32_t seed, void * out )\n\n{\n\n SHA1_CTX context;\n\n\n", "file_path": "libs/sha1/sha1.cpp", "rank": 97, "score": 5.655032096750761 }, { "content": "\t\t}\n\n\t}else{\n\n\t\tresp->timeTakenToDownload = 0;\n\n\t\tok = true;\n\n\t}\n\n\n\n\t//enqueue the operation result!\n\n\tif (sendResultThroughEvents ){\n\n\n\n\t\tif ( resp->notifyOnSuccess ){\n\n\n\n\t\t\tif(idleTimeAfterEachDownload > 0.0f){\n\n\t\t\t\tofSleepMillis(idleTimeAfterEachDownload * 1000);\n\n\t\t\t}\n\n\n\n\t\t\tif (beingCalledFromMainThread){ //we running on main thread, we can just snd the notif from here\n\n\n\n\t\t\t\tofNotifyEvent( httpResponse, *resp, this );\n\n\n\n\t\t\t}else{ //we are running from a bg thread\n", "file_path": "src/ofxSimpleHttp.cpp", "rank": 98, "score": 5.6225075677152905 }, { "content": "}\n\n\n\n\n\nint main(int argc, char** argv)\n\n{\n\n int k;\n\n SHA1_CTX context;\n\n uint8_t digest[20];\n\n char output[80];\n\n\n\n fprintf(stdout, \"verifying SHA-1 implementation... \");\n\n\n\n for (k = 0; k < 2; k++){\n\n SHA1_Init(&context);\n\n SHA1_Update(&context, (uint8_t*)test_data[k], strlen(test_data[k]));\n\n SHA1_Final(&context, digest);\n\n digest_to_hex(digest, output);\n\n\n\n if (strcmp(output, test_results[k])) {\n\n fprintf(stdout, \"FAIL\\n\");\n", "file_path": "libs/sha1/sha1.cpp", "rank": 99, "score": 5.597978025450921 } ]
C++
lizy1.kurisu/include/lizy1/impl/kurisu/BuiltInCase.hpp
li-zhong-yuan/lizy1.kurisu
dba9136bfc966e2e81bee2b469ae4cc3a8157ca4
namespace lizy1::kurisu::impl_K { template<class T> constexpr std::uint64_t fundamental_digest() { if constexpr(std::same_as<T, std::nullptr_t>) return 0x0000000000000000; if constexpr(_in<T, _P<signed char, unsigned char>>::value) return 0x3CFE619CFCD8B82B; if constexpr(_in<T, _P<std::int64_t, std::uint64_t>>::value) return 0x66128932B8AD5CC4; if constexpr(std::same_as<T, float>) return 0x7610A451BF5CF3B4; if constexpr(std::same_as<T, double>) return 0x811C5E393414342A; if constexpr(std::same_as<T, long double>) return 0x4B0070DF621771A5; } } template<lizy1::kurisu::Nullptr T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { static constexpr std::uint64_t __digest__() { return fundamental_digest<T>(); } template<class Os> static void __dump__(Os &, T const&) {} template<class Is> static void __load__(Is &, T &) {} }; template<lizy1::kurisu::Integral T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { protected: using bA = typename std::is_signed<T>::type; using bB = _in<T, type::_P<bool, char, signed char, \ unsigned char, std::int8_t, std::uint8_t>>; using tC = _C<bA::value, signed char, unsigned char>; using tD = _C<bA::value, std::int64_t, std::uint64_t>; using tE = _C<bB::value, tC, tD>; public: static constexpr std::uint64_t __digest__() { return fundamental_digest<tE>(); } template<OStream Os> static void __dump__(Os &os, T const& t) { dump_machine_bytes(os, static_cast<tE>(t)); } template<IStream Is> static void __load__(Is &is, T & t) { t = static_cast<T>(load_machine_bytes<tE>(is)); } }; template<lizy1::kurisu::FloatingPoint T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { static constexpr std::uint64_t __digest__() { return fundamental_digest<T>(); } template<OStream Os> static void __dump__(Os &os, T const& t) { dump_machine_bytes(os, t); } template<IStream Is> static void __load__(Is &is, T & t) { load_machine_bytes(is, t); } }; template<lizy1::kurisu::Enumeration T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { using U = std::underlying_type_t<T>; static constexpr std::uint64_t __digest__() { return digest<U>(); } template<OStream Os> static void __dump__(Os &os, T const& t) { dump(os, static_cast<U>(t)); } template<IStream Is> static void __load__(Is &is, T & t) { t = T{ construct<U>(is) }; } }; template<lizy1::kurisu::Array T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { using U = type::_Ur<decltype(std::declval<T &>()[0])>; static constexpr std::uint64_t __digest__() { constexpr std::uint64_t feature_code = 0xDEBB5C656EBA9F75; constexpr std::uint64_t element_digest = digest<U>(); constexpr std::uint64_t size = sizeof(T) / sizeof(U); return combine_digests({ feature_code, element_digest, size }); } template<class Os> requires Dumpable<const U, Os> static void __dump__(Os &os, T const& t) { for(auto &x : t) dump(os, x); } template<class Os> requires Dumpable<U , Os> static void __dump__(Os &os, T & t) { for(auto &x : t) dump(os, x); } template<class Is> requires Loadable<U , Is> static void __load__(Is &is, T & t) { for(auto &x : t) load(is, x); } }; namespace lizy1::kurisu::impl_K { template<class Is, class... Ts> \ constexpr bool is_aggregate_constructible(std::tuple<Ts...> *) \ { return (Constructible<_Ucr<Ts>, Is> && ...); } template<class T, class Is, class... Ts> \ inline T construct_aggregate(Is &is, std::tuple<Ts...> *) \ { return T{ construct<_A<Ts>>(is)... }; } } template<lizy1::kurisu::Aggregate T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { static constexpr std::uint64_t __digest__() \ { return digest<decltype(unpack(std::declval<T &>()))>(); } template<class Os> \ requires requires(T const& t) { { unpack(t) } -> Dumpable<Os>; } \ static void __dump__(Os &os, T const& t) { dump(os, unpack(t)); } template<class Os> \ requires requires(T &t) { { unpack(t) } -> Dumpable<Os>; } \ static void __dump__(Os &os, T &t) { dump(os, unpack(t)); } template<class Is> \ requires requires(T &t) { { unpack(t) } -> Loadable<Is>; } \ static void __load__(Is &is, T &t) { load(is, unpack(t)); } template<class Is> requires (is_aggregate_constructible<Is>((decltype(unpack(std::declval<T &>())) *)0)) static T __construct__(Is &is) { return construct_aggregate<T>(is, (decltype(unpack(std::declval<T &>())) *)0); } };
namespace lizy1::kurisu::impl_K { template<class T> constexpr std::uint64_t fundamental_digest() { if constexpr(std::same_as<T, std::nullptr_t>) return 0x0000000000000000; if constexpr(_in<T, _P<signed char, unsigned char>>::value) return 0x3CFE619CFCD8B82B; if constexpr(_in<T, _P<std::int64_t, std::uint64_t>>::value) return 0x66128932B8AD5CC4; if constexpr(std::same_as<T, float>) return 0x7610A451BF5CF3B4; if constexpr(std::same_as<T, double>) return 0x811C5E393414342A; if constexpr(std::same_as<T, long double>) return 0x4B0070DF621771A5; } } template<lizy1::kurisu::Nullptr T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { static constexpr std::uint64_t __digest__() { return fundamental_digest<T>(); } template<class Os> static void __dump__(Os &, T const&) {} template<class Is> static void __load__(Is &, T &) {} }; template<lizy1::kurisu::Integral T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { protected: using bA = typename std::is_signed<T>::type; using bB = _in<T, type::_P<bool, char, signed char, \ unsigned char, std::int8_t, std::uint8_t>>; using tC = _C<bA::value, signed char, unsigned char>; using tD = _C<bA::value, std::int64_t, std::uint64_t>; using tE = _C<bB::value, tC, tD>; public: static constexpr std::uint64_t __digest__() { return fundamental_digest<tE>(); } template<OStream Os> static void __dump__(Os &os, T const& t) { dump_machine_bytes(os, static_cast<tE>(t)); } template<IStream Is> static void __load__(Is &is, T & t) { t = static_cast<T>(load_machine_bytes<tE>(is)); } }; template<lizy1::kurisu::FloatingPoint T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { static constexpr std::uint64_t __digest__() { return fundamental_digest<T>(
constexpr std::uint64_t size = sizeof(T) / sizeof(U); return combine_digests({ feature_code, element_digest, size }); } template<class Os> requires Dumpable<const U, Os> static void __dump__(Os &os, T const& t) { for(auto &x : t) dump(os, x); } template<class Os> requires Dumpable<U , Os> static void __dump__(Os &os, T & t) { for(auto &x : t) dump(os, x); } template<class Is> requires Loadable<U , Is> static void __load__(Is &is, T & t) { for(auto &x : t) load(is, x); } }; namespace lizy1::kurisu::impl_K { template<class Is, class... Ts> \ constexpr bool is_aggregate_constructible(std::tuple<Ts...> *) \ { return (Constructible<_Ucr<Ts>, Is> && ...); } template<class T, class Is, class... Ts> \ inline T construct_aggregate(Is &is, std::tuple<Ts...> *) \ { return T{ construct<_A<Ts>>(is)... }; } } template<lizy1::kurisu::Aggregate T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { static constexpr std::uint64_t __digest__() \ { return digest<decltype(unpack(std::declval<T &>()))>(); } template<class Os> \ requires requires(T const& t) { { unpack(t) } -> Dumpable<Os>; } \ static void __dump__(Os &os, T const& t) { dump(os, unpack(t)); } template<class Os> \ requires requires(T &t) { { unpack(t) } -> Dumpable<Os>; } \ static void __dump__(Os &os, T &t) { dump(os, unpack(t)); } template<class Is> \ requires requires(T &t) { { unpack(t) } -> Loadable<Is>; } \ static void __load__(Is &is, T &t) { load(is, unpack(t)); } template<class Is> requires (is_aggregate_constructible<Is>((decltype(unpack(std::declval<T &>())) *)0)) static T __construct__(Is &is) { return construct_aggregate<T>(is, (decltype(unpack(std::declval<T &>())) *)0); } };
); } template<OStream Os> static void __dump__(Os &os, T const& t) { dump_machine_bytes(os, t); } template<IStream Is> static void __load__(Is &is, T & t) { load_machine_bytes(is, t); } }; template<lizy1::kurisu::Enumeration T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { using U = std::underlying_type_t<T>; static constexpr std::uint64_t __digest__() { return digest<U>(); } template<OStream Os> static void __dump__(Os &os, T const& t) { dump(os, static_cast<U>(t)); } template<IStream Is> static void __load__(Is &is, T & t) { t = T{ construct<U>(is) }; } }; template<lizy1::kurisu::Array T> struct lizy1::kurisu::impl_K::BuiltInCase<T> { using U = type::_Ur<decltype(std::declval<T &>()[0])>; static constexpr std::uint64_t __digest__() { constexpr std::uint64_t feature_code = 0xDEBB5C656EBA9F75; constexpr std::uint64_t element_digest = digest<U>();
random
[]
C++
ttk/core/vtk/ttkFiberSurface/ttkFiberSurface.cpp
julesvidal/wasserstein-pd-barycenter
1f62a5e1c40700030357b2bfb9a2f86fe4736861
#include <ttkFiberSurface.h> using namespace std; using namespace ttk; vtkStandardNewMacro(ttkFiberSurface) ttkFiberSurface::ttkFiberSurface(){ UseAllCores = true; RangeCoordinates = true; EdgeParameterization = true; EdgeIds = true; TetIds = true; CaseIds = true; PointMerge = false; RangeOctree = true; PointMergeDistanceThreshold = 0.000001; SetNumberOfInputPorts(2); } ttkFiberSurface::~ttkFiberSurface(){ } int ttkFiberSurface::doIt(vector<vtkDataSet *> &inputs, vector<vtkDataSet *> &outputs){ Memory m; Timer t; vtkDataSet *input = inputs[0]; vtkUnstructuredGrid *polygon = vtkUnstructuredGrid::SafeDownCast(inputs[1]); vtkPolyData *output = vtkPolyData::SafeDownCast(outputs[0]); vtkDataArray *dataUfield = NULL, *dataVfield = NULL, *polygonUfield = NULL, *polygonVfield = NULL; if(DataUcomponent.length()){ dataUfield = input->GetPointData()->GetArray(DataUcomponent.data()); } else{ dataUfield = input->GetPointData()->GetArray(0); } if(!dataUfield){ stringstream msg; msg << "[ttkFiberSurface] Error1: Could not find data array '" << DataUcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -1; } if(DataVcomponent.length()){ dataVfield = input->GetPointData()->GetArray(DataVcomponent.data()); } else{ dataVfield = input->GetPointData()->GetArray(0); } if(!dataVfield){ stringstream msg; msg << "[ttkFiberSurface] Error2: Could not find data array '" << DataVcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -2; } if(PolygonUcomponent.length()){ polygonUfield = polygon->GetPointData()->GetArray(PolygonUcomponent.data()); } else{ polygonUfield = polygon->GetPointData()->GetArray(0); } if(!polygonUfield){ stringstream msg; msg << "[ttkFiberSurface] Error3: Could not find data array '" << PolygonUcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -3; } if(PolygonVcomponent.length()){ polygonVfield = polygon->GetPointData()->GetArray(PolygonVcomponent.data()); } else{ polygonVfield = polygon->GetPointData()->GetArray(0); } if(!polygonVfield){ stringstream msg; msg << "[ttkFiberSurface] Error4: Could not find data array '" << PolygonVcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -4; } if(!((input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID) ||(input->GetDataObjectType() == VTK_IMAGE_DATA))){ stringstream msg; msg << "[ttkFiberSurface] Error5: Unsupported VTK data-structure (" << input->GetDataObjectType() << ")" << endl; dMsg(cerr, msg.str(), fatalMsg); return -5; } Triangulation *triangulation = ttkTriangulation::getTriangulation(input); if(!triangulation) return -1; triangulation->setWrapper(this); fiberSurface_.setupTriangulation(triangulation); fiberSurface_.setWrapper(this); outputVertexList_.clear(); fiberSurface_.setGlobalVertexList(&outputVertexList_); fiberSurface_.setInputField( dataUfield->GetVoidPointer(0), dataVfield->GetVoidPointer(0)); fiberSurface_.setPolygonEdgeNumber(polygon->GetNumberOfCells()); threadedTriangleList_.resize(polygon->GetNumberOfCells()); threadedVertexList_.resize(polygon->GetNumberOfCells()); fiberSurface_.setPolygon(&inputPolygon_); fiberSurface_.setPointMerging(PointMerge); fiberSurface_.setPointMergingThreshold(PointMergeDistanceThreshold); #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE if((!RangeOctree) ||(dataUfield->GetMTime() > GetMTime()) ||(dataVfield->GetMTime() > GetMTime())){ { stringstream msg; msg << "[ttkFiberSurface] Resetting octree..." << endl; dMsg(cout, msg.str(), infoMsg); } fiberSurface_.flushOctree(); Modified(); } #endif inputPolygon_.clear(); #if !defined(_WIN32) || defined(_WIN32) && defined(VTK_USE_64BIT_IDS) const long long int *cellArray = polygon->GetCells()->GetPointer(); #else int* pt = polygon->GetCells()->GetPointer(); long long extra_pt = *pt; const long long int *cellArray = &extra_pt; #endif SimplexId cellNumber = polygon->GetNumberOfCells(); SimplexId vertexId0, vertexId1; pair<pair<double, double>, pair<double, double> > rangeEdge; for(SimplexId i = 0; i < cellNumber; i++){ vertexId0 = cellArray[3*i + 1]; vertexId1 = cellArray[3*i + 2]; rangeEdge.first.first = polygonUfield->GetTuple1(vertexId0); rangeEdge.first.second = polygonVfield->GetTuple1(vertexId0); rangeEdge.second.first = polygonUfield->GetTuple1(vertexId1); rangeEdge.second.second = polygonVfield->GetTuple1(vertexId1); inputPolygon_.push_back(rangeEdge); } for(SimplexId i = 0; i < (SimplexId) threadedTriangleList_.size(); i++){ threadedTriangleList_[i].clear(); fiberSurface_.setTriangleList(i, &(threadedTriangleList_[i])); threadedVertexList_[i].clear(); fiberSurface_.setVertexList(i, &(threadedVertexList_[i])); } #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE switch(vtkTemplate2PackMacro(dataUfield->GetDataType(), dataVfield->GetDataType())){ ttkTemplate2Macro({ if (RangeOctree) fiberSurface_.buildOctree<VTK_T1 TTK_COMMA VTK_T2>(); fiberSurface_.computeSurface<VTK_T1 TTK_COMMA VTK_T2>(); }); } #else switch(vtkTemplate2PackMacro(dataUfield->GetDataType(), dataVfield->GetDataType())){ ttkTemplate2Macro(fiberSurface_.computeSurface<VTK_T1 TTK_COMMA VTK_T2>()); } #endif SimplexId triangleNumber = 0; for(SimplexId i = 0; i < (SimplexId) threadedTriangleList_.size(); i++){ triangleNumber += threadedTriangleList_[i].size(); } vtkSmartPointer<vtkPoints> outputVertexList = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkDoubleArray> outputU = vtkSmartPointer<vtkDoubleArray>::New(); vtkSmartPointer<vtkDoubleArray> outputV = vtkSmartPointer<vtkDoubleArray>::New(); vtkSmartPointer<vtkDoubleArray> outputParameterization = vtkSmartPointer<vtkDoubleArray>::New(); vtkSmartPointer<vtkCellArray> outputTriangleList = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<ttkSimplexIdTypeArray> outputEdgeIds = vtkSmartPointer<ttkSimplexIdTypeArray>::New(); vtkSmartPointer<ttkSimplexIdTypeArray> outputTetIds = vtkSmartPointer<ttkSimplexIdTypeArray>::New(); vtkSmartPointer<ttkSimplexIdTypeArray> outputCaseIds = vtkSmartPointer<ttkSimplexIdTypeArray>::New(); if(RangeCoordinates){ outputU->SetName(DataUcomponent.data()); outputU->SetNumberOfTuples(outputVertexList_.size()); outputV->SetName(DataVcomponent.data()); outputV->SetNumberOfTuples(outputVertexList_.size()); } if(EdgeParameterization){ outputParameterization->SetName("EdgeParameterization"); outputParameterization->SetNumberOfTuples(outputVertexList_.size()); } outputVertexList->SetNumberOfPoints(outputVertexList_.size()); output->SetPoints(outputVertexList); #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < (SimplexId) outputVertexList_.size(); i++){ outputVertexList->SetPoint(i, outputVertexList_[i].p_[0], outputVertexList_[i].p_[1], outputVertexList_[i].p_[2]); if(RangeCoordinates){ outputU->SetTuple1(i, outputVertexList_[i].uv_.first); outputV->SetTuple1(i, outputVertexList_[i].uv_.second); } if(EdgeParameterization){ outputParameterization->SetTuple1(i, outputVertexList_[i].t_); } } if(RangeCoordinates){ output->GetPointData()->AddArray(outputU); output->GetPointData()->AddArray(outputV); } else{ output->GetPointData()->RemoveArray(DataUcomponent.data()); output->GetPointData()->RemoveArray(DataVcomponent.data()); } if(EdgeParameterization){ output->GetPointData()->AddArray(outputParameterization); } else{ output->GetPointData()->RemoveArray("EdgeParameterization"); } if(EdgeIds){ outputEdgeIds->SetName("EdgeIds"); outputEdgeIds->SetNumberOfTuples(triangleNumber); } if(TetIds){ outputTetIds->SetName("TetIds"); outputTetIds->SetNumberOfTuples(triangleNumber); } if(CaseIds){ outputCaseIds->SetName("CaseIds"); outputCaseIds->SetNumberOfTuples(triangleNumber); } vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New(); idList->SetNumberOfIds(3); triangleNumber = 0; for(SimplexId i = 0; i < (SimplexId) threadedTriangleList_.size(); i++){ for(SimplexId j = 0; j < (SimplexId) threadedTriangleList_[i].size(); j++){ for(int k = 0; k < 3; k++){ idList->SetId(k, threadedTriangleList_[i][j].vertexIds_[k]); } outputTriangleList->InsertNextCell(idList); if(EdgeIds){ outputEdgeIds->SetTuple1(triangleNumber, i); } if(TetIds){ outputTetIds->SetTuple1(triangleNumber, threadedTriangleList_[i][j].tetId_); } if(CaseIds){ outputCaseIds->SetTuple1(triangleNumber, threadedTriangleList_[i][j].caseId_); } triangleNumber++; } } output->SetPolys(outputTriangleList); if(EdgeIds){ output->GetCellData()->AddArray(outputEdgeIds); } else{ output->GetCellData()->RemoveArray("EdgeIds"); } if(TetIds){ output->GetCellData()->AddArray(outputTetIds); } else{ output->GetCellData()->RemoveArray("TetIds"); } if(CaseIds){ output->GetCellData()->AddArray(outputCaseIds); } else{ output->GetCellData()->RemoveArray("CaseIds"); } { stringstream msg; msg << "[ttkFiberSurface] Memory usage: " << m.getElapsedUsage() << " MB." << endl; dMsg(cout, msg.str(), memoryMsg); } return 0; }
#include <ttkFiberSurface.h> using namespace std; using namespace ttk; vtkStandardNewMacro(ttkFiberSurface) ttkFiberSurface::ttkFiberSurface(){ UseAllCores = true; RangeCoordinates = true; EdgeParameterization = true; EdgeIds = true; TetIds = true; CaseIds =
ttkFiberSurface::~ttkFiberSurface(){ } int ttkFiberSurface::doIt(vector<vtkDataSet *> &inputs, vector<vtkDataSet *> &outputs){ Memory m; Timer t; vtkDataSet *input = inputs[0]; vtkUnstructuredGrid *polygon = vtkUnstructuredGrid::SafeDownCast(inputs[1]); vtkPolyData *output = vtkPolyData::SafeDownCast(outputs[0]); vtkDataArray *dataUfield = NULL, *dataVfield = NULL, *polygonUfield = NULL, *polygonVfield = NULL; if(DataUcomponent.length()){ dataUfield = input->GetPointData()->GetArray(DataUcomponent.data()); } else{ dataUfield = input->GetPointData()->GetArray(0); } if(!dataUfield){ stringstream msg; msg << "[ttkFiberSurface] Error1: Could not find data array '" << DataUcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -1; } if(DataVcomponent.length()){ dataVfield = input->GetPointData()->GetArray(DataVcomponent.data()); } else{ dataVfield = input->GetPointData()->GetArray(0); } if(!dataVfield){ stringstream msg; msg << "[ttkFiberSurface] Error2: Could not find data array '" << DataVcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -2; } if(PolygonUcomponent.length()){ polygonUfield = polygon->GetPointData()->GetArray(PolygonUcomponent.data()); } else{ polygonUfield = polygon->GetPointData()->GetArray(0); } if(!polygonUfield){ stringstream msg; msg << "[ttkFiberSurface] Error3: Could not find data array '" << PolygonUcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -3; } if(PolygonVcomponent.length()){ polygonVfield = polygon->GetPointData()->GetArray(PolygonVcomponent.data()); } else{ polygonVfield = polygon->GetPointData()->GetArray(0); } if(!polygonVfield){ stringstream msg; msg << "[ttkFiberSurface] Error4: Could not find data array '" << PolygonVcomponent << "'!" << endl; dMsg(cerr, msg.str(), fatalMsg); return -4; } if(!((input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID) ||(input->GetDataObjectType() == VTK_IMAGE_DATA))){ stringstream msg; msg << "[ttkFiberSurface] Error5: Unsupported VTK data-structure (" << input->GetDataObjectType() << ")" << endl; dMsg(cerr, msg.str(), fatalMsg); return -5; } Triangulation *triangulation = ttkTriangulation::getTriangulation(input); if(!triangulation) return -1; triangulation->setWrapper(this); fiberSurface_.setupTriangulation(triangulation); fiberSurface_.setWrapper(this); outputVertexList_.clear(); fiberSurface_.setGlobalVertexList(&outputVertexList_); fiberSurface_.setInputField( dataUfield->GetVoidPointer(0), dataVfield->GetVoidPointer(0)); fiberSurface_.setPolygonEdgeNumber(polygon->GetNumberOfCells()); threadedTriangleList_.resize(polygon->GetNumberOfCells()); threadedVertexList_.resize(polygon->GetNumberOfCells()); fiberSurface_.setPolygon(&inputPolygon_); fiberSurface_.setPointMerging(PointMerge); fiberSurface_.setPointMergingThreshold(PointMergeDistanceThreshold); #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE if((!RangeOctree) ||(dataUfield->GetMTime() > GetMTime()) ||(dataVfield->GetMTime() > GetMTime())){ { stringstream msg; msg << "[ttkFiberSurface] Resetting octree..." << endl; dMsg(cout, msg.str(), infoMsg); } fiberSurface_.flushOctree(); Modified(); } #endif inputPolygon_.clear(); #if !defined(_WIN32) || defined(_WIN32) && defined(VTK_USE_64BIT_IDS) const long long int *cellArray = polygon->GetCells()->GetPointer(); #else int* pt = polygon->GetCells()->GetPointer(); long long extra_pt = *pt; const long long int *cellArray = &extra_pt; #endif SimplexId cellNumber = polygon->GetNumberOfCells(); SimplexId vertexId0, vertexId1; pair<pair<double, double>, pair<double, double> > rangeEdge; for(SimplexId i = 0; i < cellNumber; i++){ vertexId0 = cellArray[3*i + 1]; vertexId1 = cellArray[3*i + 2]; rangeEdge.first.first = polygonUfield->GetTuple1(vertexId0); rangeEdge.first.second = polygonVfield->GetTuple1(vertexId0); rangeEdge.second.first = polygonUfield->GetTuple1(vertexId1); rangeEdge.second.second = polygonVfield->GetTuple1(vertexId1); inputPolygon_.push_back(rangeEdge); } for(SimplexId i = 0; i < (SimplexId) threadedTriangleList_.size(); i++){ threadedTriangleList_[i].clear(); fiberSurface_.setTriangleList(i, &(threadedTriangleList_[i])); threadedVertexList_[i].clear(); fiberSurface_.setVertexList(i, &(threadedVertexList_[i])); } #ifdef TTK_ENABLE_FIBER_SURFACE_WITH_RANGE_OCTREE switch(vtkTemplate2PackMacro(dataUfield->GetDataType(), dataVfield->GetDataType())){ ttkTemplate2Macro({ if (RangeOctree) fiberSurface_.buildOctree<VTK_T1 TTK_COMMA VTK_T2>(); fiberSurface_.computeSurface<VTK_T1 TTK_COMMA VTK_T2>(); }); } #else switch(vtkTemplate2PackMacro(dataUfield->GetDataType(), dataVfield->GetDataType())){ ttkTemplate2Macro(fiberSurface_.computeSurface<VTK_T1 TTK_COMMA VTK_T2>()); } #endif SimplexId triangleNumber = 0; for(SimplexId i = 0; i < (SimplexId) threadedTriangleList_.size(); i++){ triangleNumber += threadedTriangleList_[i].size(); } vtkSmartPointer<vtkPoints> outputVertexList = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkDoubleArray> outputU = vtkSmartPointer<vtkDoubleArray>::New(); vtkSmartPointer<vtkDoubleArray> outputV = vtkSmartPointer<vtkDoubleArray>::New(); vtkSmartPointer<vtkDoubleArray> outputParameterization = vtkSmartPointer<vtkDoubleArray>::New(); vtkSmartPointer<vtkCellArray> outputTriangleList = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<ttkSimplexIdTypeArray> outputEdgeIds = vtkSmartPointer<ttkSimplexIdTypeArray>::New(); vtkSmartPointer<ttkSimplexIdTypeArray> outputTetIds = vtkSmartPointer<ttkSimplexIdTypeArray>::New(); vtkSmartPointer<ttkSimplexIdTypeArray> outputCaseIds = vtkSmartPointer<ttkSimplexIdTypeArray>::New(); if(RangeCoordinates){ outputU->SetName(DataUcomponent.data()); outputU->SetNumberOfTuples(outputVertexList_.size()); outputV->SetName(DataVcomponent.data()); outputV->SetNumberOfTuples(outputVertexList_.size()); } if(EdgeParameterization){ outputParameterization->SetName("EdgeParameterization"); outputParameterization->SetNumberOfTuples(outputVertexList_.size()); } outputVertexList->SetNumberOfPoints(outputVertexList_.size()); output->SetPoints(outputVertexList); #ifdef TTK_ENABLE_OPENMP #pragma omp parallel for num_threads(threadNumber_) #endif for(SimplexId i = 0; i < (SimplexId) outputVertexList_.size(); i++){ outputVertexList->SetPoint(i, outputVertexList_[i].p_[0], outputVertexList_[i].p_[1], outputVertexList_[i].p_[2]); if(RangeCoordinates){ outputU->SetTuple1(i, outputVertexList_[i].uv_.first); outputV->SetTuple1(i, outputVertexList_[i].uv_.second); } if(EdgeParameterization){ outputParameterization->SetTuple1(i, outputVertexList_[i].t_); } } if(RangeCoordinates){ output->GetPointData()->AddArray(outputU); output->GetPointData()->AddArray(outputV); } else{ output->GetPointData()->RemoveArray(DataUcomponent.data()); output->GetPointData()->RemoveArray(DataVcomponent.data()); } if(EdgeParameterization){ output->GetPointData()->AddArray(outputParameterization); } else{ output->GetPointData()->RemoveArray("EdgeParameterization"); } if(EdgeIds){ outputEdgeIds->SetName("EdgeIds"); outputEdgeIds->SetNumberOfTuples(triangleNumber); } if(TetIds){ outputTetIds->SetName("TetIds"); outputTetIds->SetNumberOfTuples(triangleNumber); } if(CaseIds){ outputCaseIds->SetName("CaseIds"); outputCaseIds->SetNumberOfTuples(triangleNumber); } vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New(); idList->SetNumberOfIds(3); triangleNumber = 0; for(SimplexId i = 0; i < (SimplexId) threadedTriangleList_.size(); i++){ for(SimplexId j = 0; j < (SimplexId) threadedTriangleList_[i].size(); j++){ for(int k = 0; k < 3; k++){ idList->SetId(k, threadedTriangleList_[i][j].vertexIds_[k]); } outputTriangleList->InsertNextCell(idList); if(EdgeIds){ outputEdgeIds->SetTuple1(triangleNumber, i); } if(TetIds){ outputTetIds->SetTuple1(triangleNumber, threadedTriangleList_[i][j].tetId_); } if(CaseIds){ outputCaseIds->SetTuple1(triangleNumber, threadedTriangleList_[i][j].caseId_); } triangleNumber++; } } output->SetPolys(outputTriangleList); if(EdgeIds){ output->GetCellData()->AddArray(outputEdgeIds); } else{ output->GetCellData()->RemoveArray("EdgeIds"); } if(TetIds){ output->GetCellData()->AddArray(outputTetIds); } else{ output->GetCellData()->RemoveArray("TetIds"); } if(CaseIds){ output->GetCellData()->AddArray(outputCaseIds); } else{ output->GetCellData()->RemoveArray("CaseIds"); } { stringstream msg; msg << "[ttkFiberSurface] Memory usage: " << m.getElapsedUsage() << " MB." << endl; dMsg(cout, msg.str(), memoryMsg); } return 0; }
true; PointMerge = false; RangeOctree = true; PointMergeDistanceThreshold = 0.000001; SetNumberOfInputPorts(2); }
function_block-function_prefixed
[ { "content": " class AtomicVector : public std::vector<type>\n\n {\n\n private:\n\n std::size_t nextId;\n\n // for initialization\n\n const type defaultValue;\n\n\n\n public:\n\n AtomicVector(const std::size_t initSize = 1, const type &dv = type{})\n\n : std::vector<type>(), nextId(0), defaultValue{dv}\n\n {\n\n#ifndef TTK_ENABLE_KAMIKAZE\n\n if (!initSize) {\n\n std::cout << \"Caution, Atomic vector need a non-0 init size !\" << std::endl;\n\n std::vector<type>::resize(1, defaultValue);\n\n } else\n\n#endif\n\n {\n\n std::vector<type>::resize(initSize, defaultValue);\n\n }\n", "file_path": "ttk/core/base/ftmTree/AtomicVector.h", "rank": 0, "score": 69033.67509844416 }, { "content": "namespace ttk\n\n{\n\nnamespace ftm\n\n{\n\n // Compute parameters (global)\n\n struct Params {\n\n TreeType treeType;\n\n bool segm = true;\n\n bool normalize = true;\n\n bool advStats = true;\n\n int samplingLvl = 0;\n\n };\n\n\n\n#ifdef TTK_ENABLE_FTM_TREE_STATS_TIME\n\n struct ActiveTask {\n\n float begin = -1;\n\n float end = -1;\n\n SimplexId origin = nullVertex;\n\n };\n\n#endif\n\n\n\n // Scalar related containers (global)\n\n struct Scalars {\n\n SimplexId size;\n\n void* values;\n\n void* offsets;\n\n\n\n std::shared_ptr<std::vector<SimplexId>> sortedVertices, mirrorVertices;\n\n\n\n // Need vertices to be sorted : use mirrorVertices.\n\n\n\n bool isLower(SimplexId a, SimplexId b) const\n\n {\n\n return (*mirrorVertices)[a] < (*mirrorVertices)[b];\n\n }\n\n bool isEqLower(SimplexId a, SimplexId b) const\n\n {\n\n return (*mirrorVertices)[a] <= (*mirrorVertices)[b];\n\n }\n\n\n\n bool isHigher(SimplexId a, SimplexId b) const\n\n {\n\n return (*mirrorVertices)[a] > (*mirrorVertices)[b];\n\n }\n\n bool isEqHigher(SimplexId a, SimplexId b) const\n\n {\n\n return (*mirrorVertices)[a] >= (*mirrorVertices)[b];\n\n }\n\n\n\n Scalars()\n\n : size(0),\n\n values(nullptr),\n\n offsets(nullptr),\n\n sortedVertices(nullptr),\n\n mirrorVertices(nullptr)\n\n {\n\n }\n\n\n\n // Heavy\n\n Scalars(const Scalars& o)\n\n : size(o.size),\n\n values(o.values),\n\n offsets(o.offsets),\n\n sortedVertices(o.sortedVertices),\n\n mirrorVertices(o.mirrorVertices)\n\n {\n\n std::cout << \"copy in depth, bad perfs\" << std::endl;\n\n }\n\n\n\n // Sort\n\n template <typename type>\n\n void qsort(type arr[], const long int begin, const long int stop,\n\n std::function<bool(type, type)> comp) const\n\n {\n\n if (begin >= stop)\n\n return;\n\n\n\n static const long int MINSIZE = 10;\n\n\n\n long int left = begin - 1;\n\n long int right = stop + 1;\n\n const type pivot = arr[begin];\n\n\n\n while (1) {\n\n while (comp(pivot, arr[--right]))\n\n ;\n\n while (++left <= stop && !comp(pivot, arr[left]))\n\n ;\n\n\n\n if (left < right)\n\n swap_el<type>(arr, left, right);\n\n else\n\n break;\n\n }\n\n\n\n swap_el<type>(arr, begin, right);\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp task untied if (right - begin > MINSIZE)\n\n#endif\n\n qsort(arr, begin, right - 1, comp);\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp task untied if (stop - right > MINSIZE)\n\n#endif \n\n qsort(arr, right + 1, stop, comp);\n\n }\n\n\n\n private:\n\n template <typename type>\n\n static void swap_el(type arr[], const size_t a, const size_t b)\n\n {\n\n const type tmp = arr[a];\n\n arr[a] = arr[b];\n\n arr[b] = tmp;\n\n }\n\n };\n\n\n\n struct CurrentState {\n\n SimplexId vertex;\n\n boost::heap::fibonacci_heap<SimplexId, boost::heap::compare<VertCompFN>> propagation;\n\n\n\n CurrentState(SimplexId startVert, VertCompFN vertComp)\n\n : vertex(startVert), propagation(vertComp)\n\n {\n\n }\n\n\n\n CurrentState(VertCompFN vertComp)\n\n : vertex(nullVertex), propagation(vertComp)\n\n {\n\n // will need to use setStartVert before use\n\n }\n\n\n\n void setStartVert(const SimplexId v)\n\n {\n\n vertex = v;\n\n }\n\n\n\n SimplexId getNextMinVertex(void)\n\n {\n\n vertex = propagation.top();\n\n propagation.pop();\n\n return vertex;\n\n }\n\n\n\n void addNewVertex(const SimplexId v)\n\n {\n\n propagation.emplace(v);\n\n }\n\n\n\n void merge(CurrentState& other)\n\n {\n\n propagation.merge(other.propagation);\n\n vertex = propagation.top();\n\n }\n\n\n\n bool empty()\n\n {\n\n return propagation.empty();\n\n }\n\n\n\n // DEBUG ONLY\n\n bool find(SimplexId v)\n\n {\n\n return std::find(propagation.begin(), propagation.end(), v) != propagation.end();\n\n }\n", "file_path": "ttk/core/base/ftmTree/Structures.h", "rank": 1, "score": 46674.56527775849 }, { "content": "namespace ttk{\n\n /// \\brief Identifier type for simplices of any dimension.\n\n using LongSimplexId = long long int;\n\n\n\n /// \\brief Identifier type for simplices of any dimension.\n\n#ifdef TTK_ENABLE_64BIT_IDS\n\n using SimplexId = long long int;\n\n#else\n\n using SimplexId = int;\n\n#endif\n\n\n\n /// \\brief Identifier type for threads (i.e. with OpenMP).\n\n using ThreadId = int;\n\n\n\n /// \\brief Identifier type for tasks (i.e. with OpenMP).\n\n using TaskId = int;\n\n\n\n /// default name for mask scalar field\n\n const char MaskScalarFieldName[]=\"ttkMaskScalarField\";\n\n\n\n /// default name for vertex scalar field\n\n const char VertexScalarFieldName[]=\"ttkVertexScalarField\";\n\n\n\n /// default name for offset scalar field\n\n const char OffsetScalarFieldName[]=\"ttkOffsetScalarField\";\n\n\n\n /// default name for bivariate offset fields\n\n const char OffsetFieldUName[]=\"ttkOffsetFieldU\";\n\n const char OffsetFieldVName[]=\"ttkOffsetFieldV\";\n\n\n\n /// default value for critical index\n\n enum class CriticalType { \n\n Local_minimum = 0, Saddle1, Saddle2, Local_maximum, Degenerate, Regular };\n", "file_path": "ttk/core/base/common/DataTypes.h", "rank": 2, "score": 46674.56527775849 }, { "content": "namespace ttk {\n\n\ttemplate<typename dataType>\n\n\tstd::vector<KDTree<dataType>*> KDTree<dataType>::build(dataType* data, const int& ptNumber, const int& dimension, std::vector<std::vector<dataType>>& weights, const int weight_number){\n\n\t\tstd::vector<KDTree<dataType>*> correspondance_map(ptNumber);\n\n\t\t// First, perform a argsort on the data\n\n\t\t// initialize original index locations\n\n\t\tfor(int axis = 0; axis<dimension; axis++){\n\n\t\t\tcoords_min_.push_back(std::numeric_limits<dataType>::lowest());\n\n\t\t\tcoords_max_.push_back(std::numeric_limits<dataType>::max());\n\n\t\t}\n\n\t\tstd::vector<int> idx(ptNumber);\n\n\t\tfor(int i=0; i<ptNumber; i++){\n\n\t\t\tidx[i] = i;\n\n\t\t}\n\n\t\t// sort indexes based on comparing values in coordinates\n\n\t\tsort(idx.begin(), idx.end(), [&](int i1, int i2) {return data[dimension*i1+coords_number_] < data[dimension*i2+coords_number_];});\n\n\t\tint median_loc = (int) (ptNumber-1)/2;\n\n\t\tint median_idx = idx[median_loc];\n\n\t\tcorrespondance_map[median_idx] = this;\n\n\t\t\n\n\t\tfor(int axis=0; axis<dimension; axis++){\n\n\t\t\tcoordinates_.push_back(data[dimension*median_idx + axis]); \n\n\t\t}\n\n\t\tfor(int i=0; i<weight_number; i++){\n\n\t\t\tweight_.push_back(weights[i][median_idx]);\n\n\t\t\tmin_subweights_.push_back(weights[i][median_idx]);\n\n\t\t}\n\n\n\n\t\tid_ = median_idx;\n\n\t\tparent_ = nullptr;\n\n\t\tlevel_ = 0;\n\n\t\t\n\n\t\tif(idx.size()>2){\n\n\t\t\t// Build left leaf\n\n\t\t\tstd::vector<int> idx_left;\n\n\t\t\tfor(int i=0; i<median_loc; i++){\n\n\t\t\t\tidx_left.push_back(idx[i]);\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\tKDTree* left = new KDTree(this, (coords_number_+1)%dimension, true);\n\n\t\t\tleft->buildRecursive(data, idx_left, ptNumber, dimension, this, correspondance_map, weights, weight_number);\n\n\t\t\tleft_ = left;\n\n\t\t}\n\n\t\t\n\n\t\tif(idx.size()>1){\n\n\t\t\t// Build right leaf\n\n\t\t\tstd::vector<int> idx_right(ptNumber - median_loc - 1);\n\n\t\t\tfor(int i=0; i<ptNumber - median_loc - 1; i++){\n\n\t\t\t\tidx_right[i] = idx[i + median_loc + 1];\n\n\t\t\t}\n\n\t\t\tKDTree* right = new KDTree(this, (coords_number_+1)%dimension, false);\n\n\t\t\tright->buildRecursive(data, idx_right, ptNumber, dimension, this, correspondance_map, weights, weight_number);\n\n\t\t\tright_ = right;\n\n\t\t}\n\n\n\n\t\treturn correspondance_map;\n\n\t}\n\n\t\n\n\n\n\ttemplate<typename dataType>\n\n\tvoid KDTree<dataType>::buildRecursive(dataType* data, std::vector<int> idx_side, const int& ptNumber, const int& dimension, KDTree<dataType>* parent, std::vector<KDTree<dataType>*>& correspondance_map, std::vector<std::vector<dataType>>& weights, const int weight_number){\n\n\t\t// First, perform a argsort on the data\n\n\t\tsort(idx_side.begin(), idx_side.end(), [&](int i1, int i2) {return data[dimension*i1 + coords_number_] < data[dimension*i2 + coords_number_]; });\n\n\t\tint median_loc = (int) (idx_side.size()-1)/2;\n\n\t\tint median_idx = idx_side[median_loc];\n\n\t\tcorrespondance_map[median_idx] = this;\n\n\t\t\n\n\t\tfor(int axis=0; axis<dimension; axis++){\n\n\t\t\tcoordinates_.push_back(data[dimension*median_idx + axis]);\n\n\t\t}\n\n\t\t\n\n\t\tid_ = median_idx;\n\n\t\tparent_ = parent;\n\n\t\tlevel_ = parent->level_ +1;\n\n\t\t\n\n\t\tfor(int i=0; i<weight_number; i++){\n\n\t\t\tweight_.push_back(weights[i][median_idx]);\n\n\t\t\tmin_subweights_.push_back(weights[i][median_idx]);\n\n\t\t}\n\n\t\t\n\n\t\tif(idx_side.size()>1){\n\n\t\t\t// Once we get to a leaf, update min_subweights of the parents\n\n\t\t\tfor(int w=0; w<weight_number; w++){\n\n\t\t\t\tthis->updateMinSubweight(w);\n\n\t\t\t}\n\n\t\t}\n\n\t\t\t\n\n\t\t// Create bounding box\n\n\t\tfor(int axis = 0; axis<dimension; axis++){\n\n\t\t\tcoords_min_.push_back(parent_->coords_min_[axis]);\n\n\t\t\tcoords_max_.push_back(parent_->coords_max_[axis]);\n\n\t\t}\n\n\t\tif(is_left_ && !this->isRoot()){\n\n\t\t\tcoords_max_[parent_->coords_number_] = parent_->coordinates_[parent_->coords_number_];\n\n\t\t}\n\n\t\telse if(!is_left_ && !this->isRoot()){\n\n\t\t\tcoords_min_[parent_->coords_number_] = parent_->coordinates_[parent_->coords_number_];\n\n\t\t}\n\n\t\t\n\n\t\tif(idx_side.size()>2){\n\n\t\t\t// Build left leaf\n\n\t\t\tstd::vector<int> idx_left(median_loc);\n\n\t\t\tfor(int i=0; i<median_loc; i++){\n\n\t\t\t\tidx_left[i] = idx_side[i];\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\tKDTree* left = new KDTree(this, (coords_number_+1)%dimension, true);\n\n\t\t\tleft->buildRecursive(data, idx_left, ptNumber, dimension, this, correspondance_map, weights, weight_number);\n\n\t\t\tleft_ = left;\n\n\t\t}\n\n\t\t\n\n\t\tif(idx_side.size()>1){\n\n\t\t\t// Build right leaf\n\n\t\t\tstd::vector<int> idx_right(idx_side.size() - median_loc-1);\n\n\t\t\tfor(unsigned int i=0; i<idx_side.size() - median_loc-1; i++){\n\n\t\t\t\tidx_right[i] = idx_side[i + median_loc + 1];\n\n\t\t\t}\n\n\t\t\tKDTree* right = new KDTree(this, (coords_number_+1)%dimension, false);\n\n\t\t\tright->buildRecursive(data, idx_right, ptNumber, dimension, this, correspondance_map, weights, weight_number);\n\n\t\t\tright_ = right;\n\n\t\t}\n\n\t\treturn;\n\n\t}\t\n", "file_path": "ttk/core/base/kdTree/buildWeights.h", "rank": 3, "score": 46541.78294768764 }, { "content": "namespace ttk{\n\n \n\n template <class dataTypeU, class dataTypeV> class JacobiSet : public Debug{\n\n\n\n public:\n\n \n\n JacobiSet();\n\n \n\n ~JacobiSet();\n\n\n\n int connectivityPreprocessing(const std::vector<std::vector<SimplexId> > &edgeStarList,\n\n std::vector<std::vector<std::pair<SimplexId, SimplexId> > > &edgeFanLinkEdgeLists,\n\n std::vector<std::vector<LongSimplexId> > &edgeFans,\n\n std::vector<SimplexId> &sosOffsets) const;\n\n \n\n int execute(std::vector<std::pair<SimplexId, char> > &jacobiSet);\n\n \n\n char getCriticalType(const SimplexId &edgeId);\n\n \n\n int perturbate(const dataTypeU &uEpsilon = pow(10, -DBL_DIG),\n\n const dataTypeV &vEpsilon = pow(10, -DBL_DIG)) const;\n\n \n\n int setEdgeFans(const std::vector<std::vector<SimplexId> > *edgeFans){\n\n edgeFans_ = edgeFans;\n\n return 0;\n\n }\n\n \n\n int setEdgeFanLinkEdgeList(\n\n const std::vector<std::vector<std::pair<SimplexId, SimplexId> > > *edgeFanLinkEdgeLists){\n\n edgeFanLinkEdgeLists_ = edgeFanLinkEdgeLists;\n\n return 0;\n\n }\n\n \n\n int setEdgeList(const std::vector<std::pair<SimplexId, SimplexId> > *edgeList){\n\n edgeList_ = edgeList;\n\n return 0;\n\n }\n\n \n\n int setInputField(const void *uField, const void *vField){\n\n \n\n uField_ = uField;\n\n vField_ = vField;\n\n return 0;\n\n }\n\n \n\n int setSosOffsets(std::vector<SimplexId> *sosOffsets){\n\n // legacy API\n\n return setSosOffsetsU(sosOffsets);\n\n }\n\n \n\n int setSosOffsetsU(std::vector<SimplexId> *sosOffsets){\n\n sosOffsetsU_ = sosOffsets;\n\n return 0;\n\n }\n\n \n\n int setSosOffsetsV(std::vector<SimplexId> *sosOffsets){\n\n sosOffsetsV_ = sosOffsets;\n\n return 0;\n\n }\n\n\n\n // NOTE: here it's not clear how vtk builds vtkIdType \n\n // to check on bigger data-sets\n\n int setTetList(const SimplexId *tetList){\n\n tetList_ = tetList;\n\n return 0;\n\n }\n\n \n\n int setVertexNumber(const SimplexId &vertexNumber){\n\n vertexNumber_ = vertexNumber;\n\n return 0;\n\n }\n\n \n\n int setupTriangulation(Triangulation *triangulation){\n\n \n\n triangulation_ = triangulation;\n\n \n\n // pre-condition functions\n\n if(triangulation_){\n\n triangulation_->preprocessEdges();\n\n triangulation_->preprocessEdgeStars();\n\n }\n\n \n\n return 0;\n\n }\n\n \n\n protected:\n\n \n\n int executeLegacy(std::vector<std::pair<SimplexId, char> > &jacobiSet);\n\n \n\n SimplexId vertexNumber_;\n\n const SimplexId *tetList_;\n\n const void *uField_, *vField_;\n\n const std::vector<std::pair<SimplexId, SimplexId> > *edgeList_;\n\n // for each edge, one skeleton of its triangle fan\n\n const std::vector<std::vector<std::pair<SimplexId, SimplexId> > > *edgeFanLinkEdgeLists_;\n\n // for each edge, the one skeleton of its triangle fan\n\n const std::vector<std::vector<SimplexId> > *edgeFans_;\n\n std::vector<SimplexId> *sosOffsetsU_, *sosOffsetsV_;\n\n std::vector<SimplexId> localSosOffsetsU_, localSosOffsetsV_;\n\n Triangulation *triangulation_;\n\n };\n", "file_path": "ttk/core/base/jacobiSet/JacobiSet.h", "rank": 4, "score": 46541.78294768764 }, { "content": "namespace ttk\n\n{\n\nnamespace cf\n\n{\n\n\n\n// ------------------- Contour Forests\n\n\n\n// Process\n\n// {\n\n\n\ntemplate <typename scalarType>\n\nint ContourForests::build()\n\n{\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n omp_set_num_threads(parallelParams_.nbThreads);\n\n#endif\n\n\n\n DebugTimer timerTOTAL;\n\n\n\n // -----------\n\n // Paramemters\n\n // -----------\n\n initTreeType();\n\n initNbScalars();\n\n initNbPartitions();\n\n initSoS();\n\n\n\n if (params_->debugLevel >= 2) {\n\n // print params:\n\n std::cout << \"threads :\" << \n\nstatic_cast<unsigned>(parallelParams_.nbThreads) << std::endl;\n\n std::cout << \"partitions : \" \n\n<<static_cast<unsigned>(parallelParams_.nbPartitions) << std::endl;\n\n if(params_->simplifyThreshold){\n\n std::cout << \"simplify method : \" << params_->simplifyMethod << \n\nstd::endl;\n\n std::cout << \"simplify thresh.: \" << params_->simplifyThreshold << \n\nstd::endl;\n\n }\n\n }\n\n printDebug(timerTOTAL, \"Initialization \");\n\n\n\n // ---------\n\n // Sort Step\n\n // ---------\n\n\n\n DebugTimer timerSort;\n\n sortInput<scalarType>();\n\n printDebug(timerSort, \"Sort scalars (+mirror) \");\n\n\n\n // -------------------\n\n // Interface & Overlap\n\n // -------------------\n\n\n\n DebugTimer timerInitOverlap;\n\n initInterfaces();\n\n initOverlap();\n\n if(params_->debugLevel > 3){\n\n for (idInterface i = 0; i < parallelParams_.nbInterfaces; i++) {\n\n std::cout << \"interface : \" << static_cast<unsigned>(i);\n\n std::cout << \" seed : \" << parallelData_.interfaces[i].getSeed();\n\n std::cout << std::endl;\n\n }\n\n }\n\n printDebug(timerInitOverlap, \"Interface and overlap init. \");\n\n\n\n // -----------------------\n\n // Allocate parallel trees\n\n // -----------------------\n\n\n\n DebugTimer timerAllocPara;\n\n // Union find std::vector for each partition\n\n std::vector<std::vector<ExtendedUnionFind *>> \n\nvect_baseUF_JT(parallelParams_.nbPartitions),\n\n \n\nvect_baseUF_ST(parallelParams_.nbPartitions);\n\n const SimplexId &resSize = (scalars_->size / parallelParams_.nbPartitions) / \n\n10;\n\n\n\n parallelData_.trees.clear();\n\n parallelData_.trees.reserve(parallelParams_.nbPartitions);\n\n\n\n for (idPartition tree = 0; tree < parallelParams_.nbPartitions; ++tree) {\n\n // Tree array initialization\n\n parallelData_.trees.emplace_back(params_,mesh_,scalars_, tree);\n\n }\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp parallel for num_threads(parallelParams_.nbPartitions) \\\n\nschedule(static)\n\n#endif\n\n for (idPartition tree = 0; tree < parallelParams_.nbPartitions; ++tree) {\n\n // Tree array initialization\n\n parallelData_.trees[tree].flush();\n\n\n\n // UF-array reserve\n\n vect_baseUF_JT[tree].resize(scalars_->size);\n\n vect_baseUF_ST[tree].resize(scalars_->size);\n\n\n\n // Statistical reserve\n\n parallelData_.trees[tree].jt_->treeData_.nodes.reserve(resSize);\n\n parallelData_.trees[tree].jt_->treeData_.superArcs.reserve(resSize);\n\n parallelData_.trees[tree].st_->treeData_.nodes.reserve(resSize);\n\n parallelData_.trees[tree].st_->treeData_.superArcs.reserve(resSize);\n\n\n\n }\n\n printDebug(timerAllocPara, \"Parallel allocations \");\n\n\n\n // -------------------------\n\n // Build trees in partitions\n\n // -------------------------\n\n\n\n DebugTimer timerbuild;\n\n parallelBuild<scalarType>(vect_baseUF_JT, vect_baseUF_ST);\n\n\n\n if (params_->debugLevel >= 4) {\n\n if (params_->treeType == TreeType::Contour) {\n\n for (idPartition i = 0; i < parallelParams_.nbPartitions; i++) {\n\n std::cout << i << \" :\" << std::endl;\n\n parallelData_.trees[i].printTree2();\n\n std::cout << \"-----\" << std::endl;\n\n }\n\n } else {\n\n for (idPartition i = 0; i < parallelParams_.nbPartitions; i++) {\n\n std::cout << i << \" jt:\" << std::endl;\n\n parallelData_.trees[i].jt_->printTree2();\n\n std::cout << i << \" st:\" << std::endl;\n\n parallelData_.trees[i].st_->printTree2();\n\n std::cout << \"-----\" << std::endl;\n\n }\n\n }\n\n }\n\n\n\n printDebug(timerbuild, \"ParallelBuild \");\n\n\n\n // --------------------\n\n // Stitching partitions\n\n // --------------------\n\n\n\n DebugTimer timerZip;\n\n if (parallelParams_.partitionNum == -1 && parallelParams_.nbPartitions > 1 ) \n\n{\n\n stitch();\n\n for (idPartition p = 0; p < parallelParams_.nbPartitions; ++p) {\n\n \n\nparallelData_.trees[p].parallelInitNodeValence(parallelParams_.nbThreads);\n\n }\n\n }\n\n\n\n if (params_->debugLevel >= 4) {\n\n printVectCT();\n\n }\n\n\n\n printDebug(timerZip, \"Stitch \");\n\n\n\n // -------------------------------------------------\n\n // Unification : create one tree from stitched trees\n\n // -------------------------------------------------\n\n\n\n DebugTimer timerUnify;\n\n if (params_->treeType == TreeType::Contour) {\n\n if(parallelParams_.partitionNum >= 0){\n\n if (parallelParams_.partitionNum > parallelParams_.nbInterfaces) {\n\n clone(&parallelData_.trees[parallelParams_.nbPartitions - 1]);\n\n } else {\n\n clone(&parallelData_.trees[parallelParams_.partitionNum]);\n\n }\n\n } else if (parallelParams_.nbPartitions == 1) {\n\n clone(&parallelData_.trees[0]);\n\n } else {\n\n unify();\n\n // for global simlify\n\n parallelInitNodeValence(parallelParams_.nbThreads);\n\n }\n\n } else {\n\n if(parallelParams_.partitionNum >= 0){\n\n if(parallelParams_.partitionNum > parallelParams_.nbInterfaces){\n\n jt_->clone(parallelData_.trees[parallelParams_.nbInterfaces].jt_);\n\n st_->clone(parallelData_.trees[parallelParams_.nbInterfaces].st_);\n\n } else {\n\n jt_->clone(parallelData_.trees[parallelParams_.partitionNum].jt_);\n\n st_->clone(parallelData_.trees[parallelParams_.partitionNum].st_);\n\n }\n\n } else if (parallelParams_.nbPartitions == 1) {\n\n jt_->clone(parallelData_.trees[0].jt_);\n\n st_->clone(parallelData_.trees[0].st_);\n\n } else {\n\n unify();\n\n jt_->parallelInitNodeValence(parallelParams_.nbThreads);\n\n st_->parallelInitNodeValence(parallelParams_.nbThreads);\n\n }\n\n }\n\n\n\n printDebug(timerUnify, \"Create Contour tree \");\n\n\n\n // -------------------\n\n // Simplification step\n\n // -------------------\n\n\n\n if (params_->treeType == TreeType::Contour && parallelParams_.partitionNum \n\n== -1 &&\n\n params_->simplifyThreshold) {\n\n DebugTimer timerGlobalSimplify;\n\n SimplexId simplifed = globalSimplify<scalarType>(-1, nullVertex);\n\n if(params_->debugLevel >=1){\n\n printDebug(timerGlobalSimplify, \"Simplify Contour tree \");\n\n std::cout << \" ( \" << simplifed << \" pairs merged )\" << std::endl;\n\n }\n\n }\n\n\n\n printDebug(timerTOTAL, \"TOTAL \");\n\n\n\n // ------------------------------\n\n // Debug print and memory reclaim\n\n // ------------------------------\n\n\n\n if (params_->debugLevel >= 5) {\n\n if(params_->treeType == TreeType::Contour)\n\n printTree2();\n\n else {\n\n std::cout << \"JT :\" << std::endl;\n\n jt_->printTree2();\n\n std::cout << \"ST :\" << std::endl;\n\n st_->printTree2();\n\n }\n\n } else if (params_->debugLevel > 2) {\n\n if(params_->treeType == TreeType::Contour)\n\n std::cout << \"max node : \" << getNumberOfNodes() << std::endl;\n\n else {\n\n std::cout << \"JT max node : \" << jt_->getNumberOfNodes() << \n\nstd::endl;\n\n std::cout << \"ST max node : \" << st_->getNumberOfNodes() << \n\nstd::endl;\n\n }\n\n }\n\n\n\n if (params_->treeType == TreeType::Contour) {\n\n updateSegmentation();\n\n } else {\n\n jt_->updateSegmentation();\n\n st_->updateSegmentation();\n\n }\n\n\n\n // reclaim memory\n\n {\n\n for (idPartition tree = 0; tree < parallelParams_.nbPartitions; ++tree) {\n\n parallelData_.trees[tree].jt_->treeData_.nodes.shrink_to_fit();\n\n parallelData_.trees[tree].jt_->treeData_.superArcs.shrink_to_fit();\n\n parallelData_.trees[tree].st_->treeData_.nodes.shrink_to_fit();\n\n parallelData_.trees[tree].st_->treeData_.superArcs.shrink_to_fit();\n\n }\n\n // Not while arc segmentation depends on std::vector in partitions\n\n //parallelData_.interfaces.clear();\n\n //parallelData_.trees.clear();\n\n }\n\n\n\n return 0;\n\n}\n\n\n\ntemplate <typename scalarType>\n\nint ContourForests::parallelBuild(std::vector<std::vector<ExtendedUnionFind *>> \n\n&vect_baseUF_JT,\n\n std::vector<std::vector<ExtendedUnionFind *>> \n\n&vect_baseUF_ST)\n\n{\n\n std::vector<float> timeSimplify(parallelParams_.nbPartitions, 0);\n\n std::vector<float> speedProcess(parallelParams_.nbPartitions*2, 0);\n\n#ifdef TTK_ENABLE_CONTOUR_FORESTS_PARALLEL_SIMPLIFY\n\n SimplexId nbPairMerged = 0;\n\n#endif\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n omp_set_nested(1);\n\n#endif\n\n\n\n//std::cout << \"NO PARALLEL DEBUG MODE\" << std::endl;\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp parallel for num_threads(parallelParams_.nbPartitions) \\\n\nschedule(static)\n\n#endif\n\n for (idPartition i = 0; i < parallelParams_.nbPartitions; ++i) {\n\n DebugTimer timerMergeTree;\n\n\n\n // ------------------------------------------------------\n\n // Skip partition that are not asked to compute if needed\n\n // ------------------------------------------------------\n\n\n\n if (parallelParams_.partitionNum != -1 && parallelParams_.partitionNum != \n\ni)\n\n continue;\n\n\n\n // ------------------------------------------------------\n\n // Retrieve boundary & overlap list for current partition\n\n // ------------------------------------------------------\n\n\n\n std::tuple<SimplexId, SimplexId> rangeJT = getJTRange(i);\n\n std::tuple<SimplexId, SimplexId> rangeST = getSTRange(i);\n\n std::tuple<SimplexId, SimplexId> seedsPos = getSeedsPos(i);\n\n std::tuple<std::vector<SimplexId>, std::vector<SimplexId>> overlaps = \n\ngetOverlaps(i);\n\n const SimplexId &partitionSize = abs(std::get<0>(rangeJT) - \n\nstd::get<1>(rangeJT)) +\n\n std::get<0>(overlaps).size() + \n\nstd::get<1>(overlaps).size();\n\n\n\n // ---------------\n\n // Build JT and ST\n\n // ---------------\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp parallel sections num_threads(2) if (parallelParams_.lessPartition)\n\n#endif\n\n {\n\n\n\n // if less partition : we built JT and ST in parallel\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp section\n\n#endif\n\n {\n\n if(params_->treeType == TreeType::Join\n\n || params_->treeType == TreeType::Contour\n\n || params_->treeType == TreeType::JoinAndSplit)\n\n {\n\n DebugTimer timerSimplify;\n\n DebugTimer timerBuild;\n\n parallelData_.trees[i].getJoinTree()->build(vect_baseUF_JT[i],\n\n std::get<0>(overlaps), std::get<1>(overlaps),\n\n std::get<0>(rangeJT), std::get<1>(rangeJT),\n\n std::get<0>(seedsPos), std::get<1>(seedsPos)\n\n );\n\n speedProcess[i] = partitionSize / timerBuild.getElapsedTime();\n\n\n\n#ifdef TTK_ENABLE_CONTOUR_FORESTS_PARALLEL_SIMPLIFY\n\n timerSimplify.reStart();\n\n const SimplexId tmpMerge =\n\n \n\nparallelData_.trees[i].getJoinTree()->localSimplify<scalarType>(\n\n std::get<0>(seedsPos), std::get<1>(seedsPos));\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp atomic update\n\n#endif\n\n timeSimplify[i] += timerSimplify.getElapsedTime();\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp atomic update\n\n#endif\n\n nbPairMerged += tmpMerge;\n\n#endif\n\n }\n\n }\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp section\n\n#endif\n\n {\n\n if(params_->treeType == TreeType::Split\n\n || params_->treeType == TreeType::Contour\n\n || params_->treeType == TreeType::JoinAndSplit)\n\n {\n\n DebugTimer timerSimplify;\n\n DebugTimer timerBuild;\n\n parallelData_.trees[i].getSplitTree()->build(vect_baseUF_ST[i],\n\n std::get<1>(overlaps), std::get<0>(overlaps),\n\n std::get<0>(rangeST), std::get<1>(rangeST),\n\n std::get<0>(seedsPos), std::get<1>(seedsPos)\n\n );\n\n speedProcess[parallelParams_.nbPartitions + i] =\n\n partitionSize / timerBuild.getElapsedTime();\n\n\n\n#ifdef TTK_ENABLE_CONTOUR_FORESTS_PARALLEL_SIMPLIFY\n\n timerSimplify.reStart();\n\n const SimplexId tmpMerge =\n\n \n\nparallelData_.trees[i].getSplitTree()->localSimplify<scalarType>(\n\n std::get<0>(seedsPos), std::get<1>(seedsPos));\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp atomic update\n\n#endif\n\n timeSimplify[i] += timerSimplify.getElapsedTime();\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp atomic update\n\n#endif\n\n nbPairMerged += tmpMerge;\n\n#endif\n\n }\n\n }\n\n\n\n\n\n }\n\n\n\n {\n\n std::stringstream mt;\n\n mt << \"[ParallelBuild] Merge Tree \" << static_cast<unsigned>(i)\n\n << \" constructed in : \" << timerMergeTree.getElapsedTime() << \n\nstd::endl;\n\n dMsg(std::cout, mt.str(), infoMsg);\n\n }\n\n\n\n // Update segmentation of each arc if needed\n\n if ( params_->simplifyThreshold || params_->treeType != \n\nTreeType::Contour){\n\n DebugTimer timerUpdateSegm;\n\n parallelData_.trees[i].getJoinTree()->updateSegmentation();\n\n parallelData_.trees[i].getSplitTree()->updateSegmentation();\n\n\n\n if (params_->debugLevel >= 3) {\n\n std::cout << \"Local MT : updated in \" << \n\ntimerUpdateSegm.getElapsedTime() << std::endl;\n\n }\n\n }\n\n\n\n // ---------------\n\n // Combine JT & ST\n\n // ---------------\n\n\n\n if (params_->treeType == TreeType::Contour) {\n\n DebugTimer timerCombine;\n\n\n\n // clone here if we do not want to destry original merge trees!\n\n auto *jt = parallelData_.trees[i].getJoinTree();\n\n auto *st = parallelData_.trees[i].getSplitTree();\n\n\n\n // Copy missing nodes of a tree to the other one\n\n // Maintain this traversal order for good insertion\n\n for (idNode t = 0; t < st->getNumberOfNodes(); ++t) {\n\n if (!st->getNode(t)->isHidden()) {\n\n // std::cout << \"insert in jt : \" << \n\n // st->getNode(t)->getVertexId() << std::endl;\n\n jt->insertNode(st->getNode(t), true);\n\n }\n\n }\n\n // and vice versa\n\n for (idNode t = 0; t < jt->getNumberOfNodes(); ++t) {\n\n if (!jt->getNode(t)->isHidden()) {\n\n // std::cout << \"insert in st : \" << \n\n // jt->getNode(t)->getVertexId() << std::endl;\n\n st->insertNode(jt->getNode(t), true);\n\n }\n\n }\n\n\n\n // debug print current JT / ST\n\n if (params_->debugLevel >= 6) {\n\n std::cout << \"Local JT :\" << std::endl;\n\n parallelData_.trees[i].getJoinTree()->printTree2();\n\n std::cout << \"Local ST :\" << std::endl;\n\n parallelData_.trees[i].getSplitTree()->printTree2();\n\n std::cout << \"combine\" << std::endl;\n\n }\n\n\n\n // Combine, destroy JT and ST to compute CT\n\n parallelData_.trees[i].combine(std::get<0>(seedsPos), \n\nstd::get<1>(seedsPos));\n\n parallelData_.trees[i].updateSegmentation();\n\n\n\n if (params_->debugLevel > 2) {\n\n printDebug(timerCombine, \"Trees combined in \");\n\n }\n\n\n\n // debug print CT\n\n if (params_->debugLevel >= 4) {\n\n parallelData_.trees[i].printTree2();\n\n }\n\n } else {\n\n if (params_->debugLevel >= 6) {\n\n std::cout << \"Local JT :\" << std::endl;\n\n parallelData_.trees[i].getJoinTree()->printTree2();\n\n std::cout << \"Local ST :\" << std::endl;\n\n parallelData_.trees[i].getSplitTree()->printTree2();\n\n std::cout << \"combine\" << std::endl;\n\n }\n\n }\n\n }\n\n\n\n // -------------------------------------\n\n // Print process speed and simplify info\n\n // -------------------------------------\n\n\n\n if(params_->debugLevel > 2) {\n\n#ifdef TTK_ENABLE_CONTOUR_FORESTS_PARALLEL_SIMPLIFY\n\n if (params_->simplifyThreshold) {\n\n auto maxSimplifIt = max_element(timeSimplify.cbegin(), \n\ntimeSimplify.cend());\n\n float maxSimplif = *maxSimplifIt;\n\n std::cout \n\n << \"Local simplification maximum time :\" \n\n << maxSimplif;\n\n std::cout << \" ( \" << nbPairMerged << \" pairs merged )\" << std::endl;\n\n }\n\n#endif\n\n auto maxProcSpeed = max_element(speedProcess.cbegin(), \n\nspeedProcess.cend());\n\n auto minProcSpeed = min_element(speedProcess.cbegin(), \n\nspeedProcess.cend());\n\n std::cout << \"process speed : \";\n\n std::cout << \" min is \" << *minProcSpeed << \" vert/sec\";\n\n std::cout << \" max is \" << *maxProcSpeed << \" vert/sec\";\n\n std::cout << std::endl;\n\n }\n\n\n\n return 0;\n\n}\n\n\n\n//}\n\n\n\n}\n", "file_path": "ttk/core/base/contourForests/ContourForestsTemplate.h", "rank": 5, "score": 46413.79000936405 }, { "content": "namespace ttk\n\n{\n\nnamespace cf\n\n{\n\n// Init\n\n// {\n\n\n\ntemplate <typename scalarType>\n\nvoid MergeTree::sortInput(void)\n\n{\n\n const auto &nbVertices = scalars_->size;\n\n auto & sortedVect = scalars_->sortedVertices;\n\n\n\n if (!sortedVect.size()) {\n\n auto indirect_sort = [&](const size_t &a, const size_t &b) {\n\n return isLower<scalarType>(a, b);\n\n };\n\n\n\n sortedVect.resize(nbVertices, 0);\n\n iota(sortedVect.begin(), sortedVect.end(), 0);\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n# ifdef _GLIBCXX_PARALLEL_FEATURES_H\n\n // ensure this namespace exists\n\n __gnu_parallel::sort(sortedVect.begin(), sortedVect.end(), indirect_sort);\n\n# else\n\n sort(sortedVect.begin(), sortedVect.end(), indirect_sort);\n\n# endif\n\n#else\n\n sort(sortedVect.begin(), sortedVect.end(), indirect_sort);\n\n#endif\n\n }\n\n\n\n if (!scalars_->mirrorVertices.size()) {\n\n scalars_->mirrorVertices.resize(nbVertices);\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp parallel for\n\n#endif\n\n for (SimplexId i = 0; i < nbVertices; i++) {\n\n scalars_->mirrorVertices[sortedVect[i]] = i;\n\n }\n\n }\n\n}\n\n// }\n\n\n\n// Process\n\n// {\n\n\n\n// Simplify\n\n\n\ntemplate <typename scalarType>\n\nSimplexId MergeTree::localSimplify(const SimplexId &posSeed0, const SimplexId &posSeed1)\n\n{\n\n\n\n // if null threshold, leave\n\n if (!params_->simplifyThreshold) {\n\n return 0;\n\n }\n\n\n\n const bool DEBUG = false;\n\n\n\n // -----------------\n\n // Persistance pairs\n\n // -----------------\n\n // {\n\n\n\n std::vector<std::tuple<SimplexId, SimplexId, scalarType, bool>> pairs;\n\n computePersistencePairs<scalarType>(pairs);\n\n\n\n if (DEBUG) {\n\n std::cout << \"pairs : ( threshold : \" << params_->simplifyThreshold \n\n << \" )\" << std::endl;\n\n for (const auto &p : pairs) {\n\n const SimplexId & thisOriginVert = std::get<0>(p);\n\n const SimplexId & thisEndVert = std::get<1>(p);\n\n const scalarType &thisPersist = std::get<2>(p);\n\n const bool thisNeedUp = std::get<3>(p);\n\n std::cout << thisOriginVert << \" - \" << thisEndVert << \" : \" << \n\nthisPersist;\n\n std::cout << \" ( \" << thisNeedUp << \" )\" << std::endl;\n\n }\n\n std::cout << std::endl;\n\n }\n\n\n\n // }\n\n // --------------\n\n // Simplify\n\n // --------------\n\n // {\n\n\n\n return simplifyTree<scalarType>(posSeed0, posSeed1, pairs);\n\n\n\n // }\n\n}\n\n\n\ntemplate <typename scalarType>\n\nSimplexId MergeTree::globalSimplify(const SimplexId posSeed0, const SimplexId \n\nposSeed1)\n\n{\n\n\n\n // if null threshold, leave\n\n if (!params_->simplifyThreshold) {\n\n return 0;\n\n }\n\n\n\n //---------------------\n\n // Sort Nodes\n\n //---------------------\n\n //{\n\n\n\n auto isLowerComp = [&](const idNode &n1, const idNode &n2) {\n\n return isLower(getNode(n1)->getVertexId(), getNode(n2)->getVertexId());\n\n };\n\n\n\n const auto nbNode = getNumberOfNodes();\n\n\n\n std::vector<idNode> sortedNodes(nbNode);\n\n iota(sortedNodes.begin(), sortedNodes.end(), 0);\n\n// Sort nodes by vertex scalar\n\n//{\n\n#ifdef TTK_ENABLE_OPENMP\n\n# ifdef _GLIBCXX_PARALLEL_FEATURES_H\n\n __gnu_parallel::sort(sortedNodes.begin(), sortedNodes.end(), isLowerComp);\n\n#else\n\n sort(sortedNodes.begin(), sortedNodes.end(), isLowerComp);\n\n#endif\n\n#else\n\n sort(sortedNodes.begin(), sortedNodes.end(), isLowerComp);\n\n#endif\n\n//}\n\n\n\n //}\n\n //---------------------\n\n // Make pairs\n\n //---------------------\n\n //{\n\n\n\n // origin, end, persistance, needToGoUp\n\n std::vector<std::tuple<SimplexId, SimplexId, scalarType,bool>> pairsJT;\n\n std::vector<std::tuple<SimplexId, SimplexId, scalarType,bool>> pairsST;\n\n\n\n recoverMTPairs<scalarType>(sortedNodes, pairsJT, pairsST);\n\n\n\n //}\n\n //---------------------\n\n // Fusionne & Sort pairs\n\n //---------------------\n\n //{\n\n\n\n auto pairComp = [](const std::tuple<SimplexId, SimplexId, scalarType, bool> \n\n&a,\n\n const std::tuple<SimplexId, SimplexId, scalarType, bool> \n\n&b) {\n\n // sort by persistence\n\n return std::get<2>(a) < std::get<2>(b);\n\n };\n\n\n\n std::vector<std::tuple<SimplexId, SimplexId, scalarType, bool>> sortedPairs;\n\n size_t sizePJT = pairsJT.size(), sizePST = pairsST.size();\n\n\n\n sortedPairs.reserve(sizePJT + sizePST);\n\n\n\n sortedPairs.insert(sortedPairs.end(), pairsJT.begin(), pairsJT.end());\n\n sortedPairs.insert(sortedPairs.end(), pairsST.begin(), pairsST.end());\n\n\n\n // Sort pairs by persistence\n\n //{\n\n // IS SET STILL BETTER ? (parallel sort) TODO\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n# ifdef _GLIBCXX_PARALLEL_FEATURES_H\n\n __gnu_parallel::sort(sortedPairs.begin(), sortedPairs.end(), pairComp);\n\n# else\n\n sort(sortedPairs.begin(), sortedPairs.end(), pairComp);\n\n# endif\n\n#else\n\n sort(sortedPairs.begin(), sortedPairs.end(), pairComp);\n\n#endif\n\n\n\n auto last = unique(sortedPairs.begin(), sortedPairs.end());\n\n sortedPairs.erase(last, sortedPairs.end());\n\n\n\n //}\n\n //---------------------\n\n // Traverse pairs and merge on the tree\n\n //---------------------\n\n //{\n\n\n\n // identify subtrees and merge them in recept'arcs\n\n return simplifyTree<scalarType>(posSeed0, posSeed1, sortedPairs);\n\n //}\n\n}\n\n\n\ntemplate <typename scalarType>\n\nSimplexId MergeTree::simplifyTree(\n\n const SimplexId &posSeed0, const SimplexId &posSeed1,\n\n const std::vector<std::tuple<SimplexId, SimplexId, scalarType, bool>> \n\n&sortedPairs)\n\n{\n\n const auto nbNode = getNumberOfNodes();\n\n const auto nbArcs = getNumberOfSuperArcs();\n\n // Retain the relation between merge coming from st, jt\n\n // also retain info about what we keep\n\n std::vector<ExtendedUnionFind *> subtreeUF(nbNode, nullptr);\n\n\n\n // nb arc seen below / above this node\n\n std::vector<std::pair<idSuperArc, idSuperArc>> valenceOffset(nbNode, \n\nstd::make_pair(0,0));\n\n SimplexId nbPairMerged = 0;\n\n\n\n const bool DEBUG = false;\n\n\n\n if (DEBUG) {\n\n std::cout << \"Imapct simplify on tree btwn : \" << posSeed0 << \" and \" << \n\nposSeed1 << std::endl;\n\n }\n\n\n\n //----------\n\n // Make subtrees\n\n //-----------\n\n //{\n\n\n\n std::queue<std::tuple<idNode,bool>> node2see;\n\n\n\n // Add the origin of all pairs that need to merge\n\n for (const auto & pp : sortedPairs) {\n\n if (std::get<2>(pp) < params_->simplifyThreshold ) {\n\n const SimplexId &thisOriginVert = std::get<0>(pp);\n\n const SimplexId &thisEndVert = std::get<1>(pp);\n\n const idNode & thisOriginId = \n\ngetCorrespondingNodeId(thisOriginVert);\n\n\n\n if (scalars_->mirrorVertices[thisOriginVert] <= posSeed0 ||\n\n scalars_->mirrorVertices[thisOriginVert] >= posSeed1 ||\n\n scalars_->mirrorVertices[thisEndVert] <= posSeed0 ||\n\n scalars_->mirrorVertices[thisEndVert] >= posSeed1) {\n\n continue;\n\n }\n\n\n\n node2see.emplace(thisOriginId, std::get<3>(pp));\n\n subtreeUF[thisOriginId] = new ExtendedUnionFind(0);\n\n ++nbPairMerged;\n\n if(DEBUG){\n\n std::cout << \"willSee \" << printNode(thisOriginId) << std::endl;\n\n }\n\n } else break;\n\n }\n\n\n\n //---\n\n // In UF :\n\n // Origin is the size of the segmentation\n\n // Data is negative : -idNodeRoot-1\n\n // Data is positive : Receptacle Arc id\n\n //--\n\n // Use the queue to mark Arc that will be merged and UF to identify\n\n // subtree. When a node have only one way out : enqueue it to continue \n\n //travresall\n\n while (!node2see.empty()) {\n\n idNode curNodeId;\n\n bool needToGoUp; // identify up/down traversall\n\n\n\n std::tie(curNodeId, needToGoUp) = node2see.front(); \n\n // should have only one arc valid to take\n\n node2see.pop();\n\n\n\n if (DEBUG) {\n\n std::cout << \"process : \" << printNode(curNodeId) << std::endl;\n\n }\n\n\n\n // Here we take the only available arc :\n\n idSuperArc mergingArcId;\n\n idNode parentNodeId;\n\n // continue traversall\n\n if(needToGoUp){\n\n mergingArcId = newUpArc(curNodeId, subtreeUF);\n\n parentNodeId = getSuperArc(mergingArcId)->getUpNodeId();\n\n ++valenceOffset[curNodeId].second;\n\n ++valenceOffset[parentNodeId].first;\n\n } else {\n\n mergingArcId = newDownArc(curNodeId, subtreeUF);\n\n parentNodeId = getSuperArc(mergingArcId)->getDownNodeId();\n\n ++valenceOffset[curNodeId].first;\n\n ++valenceOffset[parentNodeId].second;\n\n }\n\n\n\n markThisArc(subtreeUF, curNodeId, mergingArcId, parentNodeId);\n\n\n\n // if we have processed all but one arc of this node, we nee to continue \n\n // traversall\n\n // throug it\n\n if (valenceOffset[parentNodeId].first + \n\nvalenceOffset[parentNodeId].second + 1 ==\n\n getNode(parentNodeId)->getValence()) {\n\n // only one way out, is it up ?\n\n node2see.emplace(parentNodeId, valenceOffset[parentNodeId].second + \n\n1 ==\n\n \n\ngetNode(parentNodeId)->getUpValence());\n\n if(DEBUG){\n\n std::cout << \" add to see \" << printNode(parentNodeId) << \n\nstd::endl;\n\n }\n\n }\n\n } // end while node2see\n\n\n\n // for each node valenceOffset is the number of arc attached to this node \n\n // that will merge\n\n\n\n // Debug print\n\n if (DEBUG) {\n\n std::cout << \"node subtrees before creating receptarc \" << std::endl;\n\n for (idNode nid = 0; nid < nbNode; nid++) {\n\n if (subtreeUF[nid]) {\n\n std::cout << \"node \" << getNode(nid)->getVertexId() \n\n << \" is in subtree rooted :\";\n\n const idNode &root = -subtreeUF[nid]->find()->getData() - 1;\n\n std::cout << getNode(root)->getVertexId();\n\n const SimplexId &segmSize = subtreeUF[nid]->find()->getOrigin();\n\n std::cout << \" with segmentation of \" << segmSize << std::endl;\n\n }\n\n }\n\n }\n\n\n\n //}\n\n //----------\n\n // Create the recept'arcs\n\n //-----------\n\n //{\n\n\n\n // Add the origin of all pairs that need to merge\n\n for (const auto & pp : sortedPairs) {\n\n if (std::get<2>(pp) < params_->simplifyThreshold ) {\n\n const SimplexId &thisOriginVert = std::get<0>(pp);\n\n const SimplexId &thisEndVert = std::get<1>(pp);\n\n const idNode & thisOriginId = \n\ngetCorrespondingNodeId(thisOriginVert);\n\n //const idNode & thisEndId = getCorrespondingNode(thisEndVert);\n\n\n\n if (scalars_->mirrorVertices[thisOriginVert] <= posSeed0 ||\n\n scalars_->mirrorVertices[thisOriginVert] >= posSeed1 ||\n\n scalars_->mirrorVertices[thisEndVert] <= posSeed0 ||\n\n scalars_->mirrorVertices[thisEndVert] >= posSeed1) {\n\n continue;\n\n }\n\n\n\n if (subtreeUF[thisOriginId]->find()->getData() < 0) {\n\n // create receptarc\n\n const idNode &subtreeRoot = \n\n-subtreeUF[thisOriginId]->find()->getData() - 1;\n\n // The id of the next arc to be created : NOT PARALLEL\n\n const idSuperArc receptArcId = treeData_.superArcs.size();\n\n // down , up, segmentation size\n\n // create the receptacle arc and merge arc not in sub-tree in it\n\n const std::tuple<idNode, idNode, SimplexId> &receptArc =\n\n createReceptArc(subtreeRoot, receptArcId, subtreeUF, \n\nvalenceOffset);\n\n\n\n // make superArc and do the makeAlloc on it\n\n const bool overlapB =\n\n \n\nscalars_->mirrorVertices[getNode(std::get<0>(receptArc))->getVertexId()] < \n\nposSeed0;\n\n const bool overlapA =\n\n \n\nscalars_->mirrorVertices[getNode(std::get<1>(receptArc))->getVertexId()] >= \n\nposSeed1;\n\n const idSuperArc na = makeSuperArc(std::get<0>(receptArc), \n\nstd::get<1>(receptArc), overlapB, overlapA, nullptr, -1);\n\n\n\n if(overlapB){\n\n treeData_.arcsCrossingBelow.emplace_back(na);\n\n }\n\n\n\n if(overlapA){\n\n treeData_.arcsCrossingAbove.emplace_back(na);\n\n }\n\n\n\n subtreeUF[thisOriginId]->find()->setData(receptArcId);\n\n getSuperArc(receptArcId)->makeAllocGlobal(std::get<2>(receptArc));\n\n\n\n if (DEBUG) {\n\n std::cout << \"create arc : \" << printArc(receptArcId)\n\n << \" with segm : \" << std::get<2>(receptArc) << std::endl;\n\n }\n\n }\n", "file_path": "ttk/core/base/contourForestsTree/MergeTreeTemplate.h", "rank": 6, "score": 46290.331926858074 }, { "content": "namespace ttk\n\n{\n\nnamespace ftm\n\n{\n\n\n\ntemplate <typename scalarType, typename idType>\n\nvoid ftm::FTMTree_MT::sortInput(void)\n\n{\n\n const auto &nbVertices = scalars_->size;\n\n\n\n auto *sortedVect = scalars_->sortedVertices.get();\n\n if (sortedVect == nullptr) {\n\n sortedVect = new std::vector<SimplexId>(0);\n\n scalars_->sortedVertices.reset(sortedVect);\n\n } else {\n\n sortedVect->clear();\n\n }\n\n\n\n auto indirect_sort = [&](const size_t &a, const size_t &b) { return isLower<scalarType,idType>(a, b); };\n\n\n\n sortedVect->resize(nbVertices, 0);\n\n std::iota(sortedVect->begin(), sortedVect->end(), 0);\n\n\n\n// #pragma omp parallel\n\n// #pragma omp single\n\n// scalars_->qsort<SimplexId>(sortedVect->data(), 0, scalars_->size -1, indirect_sort);\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n# ifdef __clang__\n\n std::cout << \"Caution, outside GCC, sequential sort\" << std::endl;\n\n std::sort(sortedVect->begin(), sortedVect->end(), indirect_sort);\n\n# else\n\n __gnu_parallel::sort(sortedVect->begin(), sortedVect->end(), indirect_sort);\n\n# endif\n\n#else\n\n std::sort(sortedVect->begin(), sortedVect->end(), indirect_sort);\n\n#endif\n\n\n\n auto *mirrorVert = scalars_->mirrorVertices.get();\n\n if (mirrorVert == nullptr) {\n\n mirrorVert = new std::vector<SimplexId>(0);\n\n scalars_->mirrorVertices.reset(mirrorVert);\n\n } else {\n\n mirrorVert->clear();\n\n }\n\n\n\n scalars_->mirrorVertices->resize(nbVertices);\n\n\n\n#ifdef TTK_ENABLE_OPENMP\n\n#pragma omp parallel for\n\n#endif\n\n for (SimplexId i = 0; i < nbVertices; i++) {\n\n (*scalars_->mirrorVertices)[(*sortedVect)[i]] = i;\n\n }\n\n}\n\n\n\n}\n", "file_path": "ttk/core/base/ftmTree/FTMTree_MT_Template.h", "rank": 7, "score": 46290.331926858074 }, { "content": "namespace ttk{\n\n\n\n template <class dataType> class ScalarFieldCriticalPoints : public Debug{\n\n\n\n public:\n\n \n\n ScalarFieldCriticalPoints();\n\n \n\n ~ScalarFieldCriticalPoints();\n\n\n\n /// Execute the package.\n\n /// \\param argment Dummy integer argument.\n\n /// \\return Returns 0 upon success, negative values otherwise.\n\n int execute();\n\n \n\n char getCriticalType(const SimplexId &vertexId) const{\n\n \n\n return getCriticalType(vertexId, triangulation_);\n\n }\n\n\n\n char getCriticalType(const SimplexId &vertexId,\n\n Triangulation *triangulation) const;\n\n \n\n char getCriticalType(const SimplexId &vertexId,\n\n const std::vector<std::pair<SimplexId, SimplexId> > &vertexLinkEdgeList) const;\n\n \n\n static bool isSosHigherThan(const SimplexId &offset0, const dataType &value0,\n\n const SimplexId &offset1, const dataType &value1){\n\n \n\n return ((value0 > value1)||((value0 == value1)&&(offset0 > offset1)));\n\n }\n\n \n\n static bool isSosLowerThan(const SimplexId &offset0, const dataType &value0,\n\n const SimplexId &offset1, const dataType &value1){\n\n \n\n return ((value0 < value1)||((value0 == value1)&&(offset0 < offset1)));\n\n }\n\n \n\n int setDomainDimension(const int &dimension){\n\n \n\n dimension_ = dimension;\n\n \n\n return 0;\n\n }\n\n \n\n int setOutput(std::vector<std::pair<SimplexId, char> > *criticalPoints){\n\n \n\n criticalPoints_ = criticalPoints;\n\n \n\n return 0;\n\n }\n\n \n\n int setupTriangulation(Triangulation *triangulation){\n\n \n\n triangulation_ = triangulation;\n\n \n\n // pre-condition functions\n\n if(triangulation_){\n\n triangulation_->preprocessVertexNeighbors();\n\n triangulation_->preprocessVertexStars();\n\n }\n\n \n\n return 0;\n\n }\n\n \n\n int setScalarValues(const void *data){\n\n \n\n scalarValues_ = (const dataType *) data;\n\n \n\n return 0;\n\n }\n\n \n\n int setSosOffsets(std::vector<SimplexId> *offsets){\n\n \n\n sosOffsets_ = offsets;\n\n \n\n return 0;\n\n }\n\n \n\n int setVertexLinkEdgeLists(\n\n const std::vector<std::vector<std::pair<SimplexId, SimplexId> > > *edgeList){\n\n \n\n vertexLinkEdgeLists_ = edgeList;\n\n \n\n return 0;\n\n }\n\n \n\n /// Set the number of vertices in the scalar field.\n\n /// \\param vertexNumber Number of vertices in the data-set.\n\n /// \\return Returns 0 upon success, negative values otherwise. \n\n int setVertexNumber(const SimplexId &vertexNumber){\n\n vertexNumber_ = vertexNumber;\n\n return 0;\n\n }\n\n \n\n \n\n protected:\n\n \n\n int dimension_;\n\n SimplexId vertexNumber_;\n\n const dataType *scalarValues_;\n\n const std::vector<std::vector<std::pair<SimplexId, SimplexId> > > *vertexLinkEdgeLists_;\n\n std::vector<std::pair<SimplexId, char> > *criticalPoints_;\n\n std::vector<SimplexId> *sosOffsets_;\n\n std::vector<SimplexId> localSosOffSets_;\n\n Triangulation *triangulation_;\n\n };\n", "file_path": "ttk/core/base/scalarFieldCriticalPoints/ScalarFieldCriticalPoints.h", "rank": 8, "score": 46056.08928306435 }, { "content": "using namespace ttk;\n", "file_path": "ttk/core/base/persistenceDiagramsBarycenter/PDBarycenterImpl.h", "rank": 9, "score": 43655.506951274365 }, { "content": "using namespace ttk;\n", "file_path": "ttk/core/base/persistenceDiagramsClustering/PDClusteringImpl.h", "rank": 10, "score": 43655.506951274365 }, { "content": "#else\n\nclass ttkTriangulation : public ttk::Debug {\n\n#endif\n\n\n\n public:\n\n \n\n ttkTriangulation();\n\n ~ttkTriangulation();\n\n \n\n /// Allocates the memory for the internal ttk::Triangulation data-structure.\n\n /// \\warning Internal TTK usage only.\n\n int allocate();\n\n \n\n /// Retrieves a pointer to the internal ttk::Triangulation of the current \n\n /// object. Traversal can only be performed on a ttk::Triangulation object.\n\n /// \\return Returns a pointer to a valid ttk::Triangulation object upon \n\n /// success, NULL otherwise.\n\n /// \\sa ttk::Triangulation\n\n ttk::Triangulation* getTriangulation(){ return triangulation_;};\n\n \n\n /// Retrieves a pointer to a ttk::Triangulation object from a vtkDataSet.\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 11, "score": 34069.2373668983 }, { "content": "class ttkKeyHandler : public ttk::Debug{\n\n \n\n public:\n\n \n\n virtual int OnKeyPress(\n\n vtkRenderWindowInteractor *interactor, std::string &key) = 0;\n\n};\n\n\n", "file_path": "ttk/core/vtk/ttkUserInterfaceBase/ttkUserInterfaceBase.h", "rank": 12, "score": 33660.27519716504 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKCOMMONDATAMODEL_EXPORT ttkTriangulation : public ttk::Debug {\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 13, "score": 31808.848403716274 }, { "content": "#else\n\nclass ttkFTMTree : public vtkDataSetAlgorithm, public ttk::Wrapper\n\n#endif\n\n{\n\n public:\n\n static ttkFTMTree* New();\n\n\n\n vtkTypeMacro(ttkFTMTree, vtkDataSetAlgorithm);\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n\n\n void SetThreadNumber(int threadNumber)\n\n {\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n }\n\n\n\n void SetUseAllCores(bool onOff)\n\n {\n\n UseAllCores = onOff;\n", "file_path": "ttk/core/vtk/ttkFTMTree/ttkFTMTree.h", "rank": 14, "score": 29561.08868701747 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkFTMTree : public vtkDataSetAlgorithm, public ttk::Wrapper\n", "file_path": "ttk/core/vtk/ttkFTMTree/ttkFTMTree.h", "rank": 15, "score": 27903.49833768591 }, { "content": "#!/usr/bin/env pvpython\n\n\n\n#/// \\ingroup examples\n\n#/// \\author Julien Tierny <[email protected]>\n\n#/// \\date October 2017.\n\n#/// \n\n#/// \\brief Minimalist python TTK example pipeline, including:\n\n#/// -# The computation of a persistence curve\n\n#/// -# The computation of a persistence diagram\n\n#/// -# The selection of the most persistent pairs of the diagram\n\n#/// -# The pre-simplification of the data according to this selection\n\n#/// -# The computation of the Morse-Smale complex on this simplified data\n\n#/// -# The storage of the output of this pipeline to disk.\n\n#///\n\n#/// This example reproduces the Figure 1 of the TTK companion paper:\n\n#/// \"The Topology ToolKit\", J. Tierny, G. Favelier, J. Levine, C. Gueunet, M.\n\n#/// Michaux., IEEE Transactions on Visualization and Computer Graphics, Proc.\n\n#/// of IEEE VIS 2017.\n\n\n\nfrom paraview.simple import *\n\n\n\nif len(sys.argv) == 2:\n\n inputFilePath = sys.argv[1]\n\nelse:\n\n print(\"Missing mandatory argument: Path to input VTU file\")\n\n sys.exit() \n\n\n\n# 1. loading the input data\n\ninputData = XMLUnstructuredGridReader(FileName=[inputFilePath])\n\n\n\n# 2. computing the persistence curve\n\npersistenceCurve = TTKPersistenceCurve(inputData)\n\n\n\n# 3. computing the persitence diagram\n\npersistenceDiagram = TTKPersistenceDiagram(inputData)\n\n\n\n# 4. selecting the critical point pairs\n\ncriticalPointPairs = Threshold(persistenceDiagram)\n\ncriticalPointPairs.Scalars = ['CELLS', 'PairIdentifier']\n\ncriticalPointPairs.ThresholdRange = [-0.1, 999999]\n\n\n\n# 5. selecting the most persistent pairs\n\npersistentPairs = Threshold(criticalPointPairs)\n\npersistentPairs.Scalars = ['CELLS', 'Persistence']\n\npersistentPairs.ThresholdRange = [0.05, 999999]\n\n\n\n# 6. simplifying the input data to remove non-persistent pairs\n\ntopologicalSimplification = TTKTopologicalSimplification(\n\n Domain=inputData, Constraints=persistentPairs)\n\n\n\n# 7. computing the Morse-Smale complex\n\nmorseSmaleComplex = TTKMorseSmaleComplex(topologicalSimplification)\n\n\n\n# 8. saving the output data\n\nSaveData('curve.vtk', OutputPort(persistenceCurve, 3))\n\nSaveData('separatrices.vtu', OutputPort(morseSmaleComplex, 1))\n\nSaveData('segmentation.vtu', OutputPort(morseSmaleComplex, 3))\n", "file_path": "ttk/examples/python/ttkExample-python.py", "rank": 16, "score": 24351.23999180596 }, { "content": "def doIt(X, method, ncomponents, nneighbors, njobs, rstate, params):\n\n\n\n import importlib\n\n\n\n # check if numpy is installed\n\n loader = importlib.find_loader('numpy')\n\n found = loader is not None\n\n if found:\n\n print(\"[DimensionReduction] Python: numpy module found.\")\n\n else:\n\n print(\"[DimensionReduction] Python error: numpy module not found.\")\n\n return 0\n\n\n\n # check if scipy is installed\n\n loader = importlib.find_loader('scipy')\n\n found = loader is not None\n\n if found:\n\n print(\"[DimensionReduction] Python: scipy module found.\")\n\n else:\n\n print(\"[DimensionReduction] Python error: scipy module not found.\")\n\n return 0\n\n\n\n # check if scikit-learn is installed\n\n loader = importlib.find_loader('sklearn')\n\n found = loader is not None\n\n if found:\n\n print(\"[DimensionReduction] Python: sklearn module found.\")\n\n else:\n\n print(\"[DimensionReduction] Python error: sklearn module not found.\")\n\n return 0\n\n\n\n from sklearn import manifold\n\n from sklearn import decomposition\n\n import numpy as np\n\n from sys import platform\n\n \n\n if platform == \"darwin\":\n\n import sklearn\n\n sklearn.utils.parallel_backend('threading')\n\n\n\n if rstate > 0:\n\n np.random.seed(0)\n\n\n\n try:\n\n if method == 0:\n\n seParams = params[0]\n\n if seParams[2] == \"None\":\n\n se = manifold.SpectralEmbedding(n_components=ncomponents,\n\n affinity=seParams[0],\n\n gamma=seParams[1],\n\n eigen_solver=None,\n\n n_neighbors=nneighbors,\n\n n_jobs=njobs)\n\n else:\n\n se = manifold.SpectralEmbedding(n_components=ncomponents,\n\n affinity=seParams[0],\n\n gamma=seParams[1],\n\n eigen_solver=seParams[2],\n\n n_neighbors=nneighbors,\n\n n_jobs=njobs)\n\n Y = se.fit_transform(X)\n\n elif method == 1:\n\n lleParams = params[1]\n\n lle = manifold.LocallyLinearEmbedding(n_neighbors=nneighbors,\n\n n_components=ncomponents,\n\n reg=lleParams[0],\n\n eigen_solver=lleParams[1],\n\n tol=lleParams[2],\n\n max_iter=lleParams[3],\n\n method=lleParams[4],\n\n hessian_tol=lleParams[5],\n\n modified_tol=lleParams[6],\n\n neighbors_algorithm=lleParams[7],\n\n n_jobs=njobs)\n\n Y = lle.fit_transform(X)\n\n elif method == 2:\n\n mdsParams = params[2]\n\n mds = manifold.MDS(n_components=ncomponents,\n\n metric=mdsParams[0],\n\n n_init=mdsParams[1],\n\n max_iter=mdsParams[2],\n\n verbose=mdsParams[3],\n\n eps=mdsParams[4],\n\n dissimilarity=mdsParams[5],\n\n n_jobs=njobs)\n\n Y = mds.fit_transform(X)\n\n elif method == 3:\n\n tsneParams = params[3]\n\n tsne = manifold.TSNE(n_components=ncomponents,\n\n perplexity=tsneParams[0],\n\n early_exaggeration=tsneParams[1],\n\n learning_rate=tsneParams[2],\n\n n_iter=tsneParams[3],\n\n n_iter_without_progress=tsneParams[4],\n\n min_grad_norm=tsneParams[5],\n\n metric=tsneParams[6],\n\n init=tsneParams[7],\n\n verbose=tsneParams[8],\n\n method=tsneParams[9],\n\n angle=tsneParams[10])\n\n Y = tsne.fit_transform(X)\n\n elif method == 4:\n\n isoParams = params[4]\n\n iso = manifold.Isomap(n_neighbors=nneighbors,\n\n n_components=ncomponents,\n\n eigen_solver=isoParams[0],\n\n tol=isoParams[1],\n\n max_iter=isoParams[2],\n\n path_method=isoParams[3],\n\n neighbors_algorithm=isoParams[4],\n\n n_jobs=njobs)\n\n Y = iso.fit_transform(X)\n\n elif method == 5:\n\n pcaParams = params[5]\n\n if pcaParams[4] == \"auto\":\n\n pca = decomposition.PCA(n_components=ncomponents,\n\n copy=pcaParams[0],\n\n whiten=pcaParams[1],\n\n svd_solver=pcaParams[2],\n\n tol=pcaParams[3],\n\n iterated_power=\"auto\")\n\n else:\n\n pca = decomposition.PCA(n_components=ncomponents,\n\n copy=pcaParams[0],\n\n whiten=pcaParams[1],\n\n svd_solver=pcaParams[2],\n\n tol=pcaParams[3],\n\n iterated_power=int(pcaParams[4]))\n\n Y = pca.fit_transform(X)\n\n\n\n L = [Y.shape[0], Y.shape[1], np.ravel(Y, 'F')]\n\n return L\n\n except Exception as inst:\n\n print('[DimensionReduction] Error: unexpected behaviour detected in the python script.')\n\n print(type(inst)) # the exception instance\n\n print(inst.args) # arguments stored in .args\n\n print(inst)\n\n return []\n", "file_path": "ttk/core/base/dimensionReduction/dimensionReduction.py", "rank": 17, "score": 22362.879955300094 }, { "content": "#else\n\nclass ttkFiber\n\n#endif\n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkFiber* New();\n\n \n\n vtkTypeMacro(ttkFiber, vtkDataSetAlgorithm);\n\n \n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n\n\n void SetThreads(){\n\n if(!UseAllCores)\n\n threadNumber_ = ThreadNumber;\n\n else{\n\n threadNumber_ = ttk::OsCall::getNumberOfCores();\n\n }\n\n Modified();\n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 18, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkIdentifiers\n\n#endif \n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkIdentifiers* New();\n\n \n\n vtkTypeMacro(ttkIdentifiers, vtkDataSetAlgorithm);\n\n\n\n vtkSetMacro(CellFieldName, std::string);\n\n vtkGetMacro(CellFieldName, std::string);\n\n\n\n vtkSetMacro(VertexFieldName, std::string);\n\n vtkGetMacro(VertexFieldName, std::string);\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n\n\n void SetThreads(){\n", "file_path": "ttk/core/vtk/ttkIdentifiers/ttkIdentifiers.h", "rank": 19, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkForEachRow\n\n#endif\n\n: public vtkMultiBlockDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkForEachRow* New();\n\n vtkTypeMacro(ttkForEachRow, vtkMultiBlockDataSetAlgorithm)\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n void SetThreads(){\n\n threadNumber_ = !UseAllCores ? ThreadNumber : ttk::OsCall::getNumberOfCores();\n\n Modified();\n\n }\n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n }\n\n void SetUseAllCores(bool onOff){\n", "file_path": "ttk/core/vtk/ttkForEachRow/ttkForEachRow.h", "rank": 20, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkBlank\n\n#endif\n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkBlank* New();\n\n vtkTypeMacro(ttkBlank, vtkDataSetAlgorithm)\n\n \n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n \n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n }\n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n\n SetThreads();\n\n }\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 21, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkOFFWriter \n\n#endif\n\n : public vtkDataSetWriter{\n\n \n\n public:\n\n \n\n vtkTypeMacro(ttkOFFWriter, vtkDataSetWriter);\n\n void PrintSelf(ostream &os, vtkIndent indent) override;\n\n\n\n static ttkOFFWriter *New();\n\n\n\n // Description:\n\n // Specify file name of the .abc file.\n\n vtkSetStringMacro(FileName);\n\n vtkGetStringMacro(FileName);\n\n\n\n protected:\n\n ttkOFFWriter();\n\n ~ttkOFFWriter();\n\n \n", "file_path": "ttk/core/vtk/ttkOFFWriter/ttkOFFWriter.h", "rank": 22, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkEndFor\n\n#endif\n\n: public vtkPassInputTypeAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkEndFor* New();\n\n vtkTypeMacro(ttkEndFor, vtkPassInputTypeAlgorithm)\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n void SetThreads(){\n\n threadNumber_ = !UseAllCores ? ThreadNumber : ttk::OsCall::getNumberOfCores();\n\n Modified();\n\n }\n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n }\n\n void SetUseAllCores(bool onOff){\n", "file_path": "ttk/core/vtk/ttkEndFor/ttkEndFor.h", "rank": 23, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkOFFReader \n\n#endif\n\n : public vtkUnstructuredGridAlgorithm\n\n{\n\n public:\n\n vtkTypeMacro(ttkOFFReader, vtkUnstructuredGridAlgorithm);\n\n void PrintSelf(ostream &os, vtkIndent indent) override;\n\n\n\n static ttkOFFReader *New();\n\n\n\n // Description:\n\n // Specify file name of the .abc file.\n\n vtkSetStringMacro(FileName);\n\n vtkGetStringMacro(FileName);\n\n\n\n protected:\n\n ttkOFFReader();\n\n ~ttkOFFReader() = default;\n\n\n\n int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *) override;\n", "file_path": "ttk/core/vtk/ttkOFFReader/ttkOFFReader.h", "rank": 24, "score": 9026.325166417297 }, { "content": "#else\n\nclass ttkUnstructuredGrid :\n\n#endif\n\n public ttkTriangulation,\n\n public vtkUnstructuredGrid{\n\n\n\n public:\n\n static ttkUnstructuredGrid* New();\n\n ttkTypeMacro(ttkUnstructuredGrid, vtkUnstructuredGrid);\n\n \n\n void CopyStructure(vtkDataSet *other);\n\n\n\n void DeepCopy(vtkDataObject *other);\n\n\n\n void ShallowCopy(vtkDataObject *other);\n\n \n\n protected:\n\n \n\n ttkUnstructuredGrid();\n\n\n\n ~ttkUnstructuredGrid();\n\n \n\n};\n\n\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 25, "score": 8922.120517228102 }, { "content": "#else\n\nclass ttkPolyData :\n\n#endif\n\n public ttkTriangulation,\n\n public vtkPolyData{\n\n\n\n public:\n\n static ttkPolyData* New();\n\n ttkTypeMacro(ttkPolyData, vtkPolyData);\n\n\n\n void CopyStructure(vtkDataSet *other);\n\n\n\n void DeepCopy(vtkDataObject *other);\n\n\n\n void ShallowCopy(vtkDataObject *other);\n\n \n\n protected:\n\n \n\n ttkPolyData();\n\n\n\n ~ttkPolyData();\n\n \n\n};\n\n\n\n#endif // _TTK_TRIANGULATION_H\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 26, "score": 8922.120517228102 }, { "content": "#else\n\nclass ttkImageData :\n\n#endif\n\n public ttkTriangulation,\n\n public vtkImageData{\n\n\n\n public:\n\n static ttkImageData* New();\n\n ttkTypeMacro(ttkImageData, vtkImageData);\n\n\n\n void CopyStructure(vtkDataSet *other);\n\n\n\n void DeepCopy(vtkDataObject *other);\n\n\n\n void ShallowCopy(vtkDataObject *other);\n\n \n\n protected:\n\n \n\n ttkImageData();\n\n\n\n ~ttkImageData();\n\n \n\n};\n\n\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 27, "score": 8922.120517228102 }, { "content": "#else\n\nclass ttkTriangulationFilter\n\n#endif\n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkTriangulationFilter* New();\n\n \n\n vtkTypeMacro(ttkTriangulationFilter, vtkDataSetAlgorithm);\n\n \n\n protected:\n\n \n\n ttkTriangulationFilter();\n\n ~ttkTriangulationFilter(){};\n\n \n\n int RequestData(vtkInformation *request, \n\n vtkInformationVector **inputVector, vtkInformationVector *outputVector) override;\n\n \n\n int RequestDataObject(vtkInformation *request,\n\n vtkInformationVector **inputVector, vtkInformationVector *outputVector) override;\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 28, "score": 8922.120517228102 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkForEachRow\n", "file_path": "ttk/core/vtk/ttkForEachRow/ttkForEachRow.h", "rank": 29, "score": 8826.133300188498 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkOFFReader\n", "file_path": "ttk/core/vtk/ttkOFFReader/ttkOFFReader.h", "rank": 30, "score": 8826.133300188498 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkEndFor\n", "file_path": "ttk/core/vtk/ttkEndFor/ttkEndFor.h", "rank": 31, "score": 8826.133300188498 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkIdentifiers\n", "file_path": "ttk/core/vtk/ttkIdentifiers/ttkIdentifiers.h", "rank": 32, "score": 8826.133300188498 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkBlank\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 33, "score": 8826.133300188498 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKIOLEGACY_EXPORT ttkOFFWriter\n", "file_path": "ttk/core/vtk/ttkOFFWriter/ttkOFFWriter.h", "rank": 34, "score": 8826.133300188498 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkFiber\n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 35, "score": 8826.133300188498 }, { "content": "// break;\n\n// }\n\n// \n\n// return 1;\n\n// }\n\n // end of TODO-3\n\n \n\n \n\n protected:\n\n \n\n ttkBlank(){\n\n \n\n // init\n\n SomeIntegerArgument = 1;\n\n SomeDoubleArgument = 1;\n\n SomeOption = true;\n\n outputScalarField_ = NULL;\n\n \n\n UseAllCores = true;\n\n \n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 36, "score": 8794.208610383143 }, { "content": " }\n\n \n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n } \n\n \n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n\n SetThreads();\n\n }\n\n // end of default ttk setters\n\n \n\n vtkGetMacro(Ucomponent, std::string);\n\n vtkSetMacro(Ucomponent, std::string);\n\n \n\n vtkGetMacro(Uvalue, double);\n\n vtkSetMacro(Uvalue, double);\n\n \n\n vtkGetMacro(Vcomponent, std::string);\n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 37, "score": 8792.283787226974 }, { "content": " private:\\\n\n int doIt(std::vector<vtkDataSet *> &inputs, std::vector<vtkDataSet *> &outputs);\\\n\n \\\n\n bool needsToAbort() override { return GetAbortExecute();};\\\n\n \\\n\n int updateProgress(const float &progress) override { \\\n\n UpdateProgress(progress);\\\n\n return 0;\\\n\n };\\\n\n protected:\\\n\n bool UseAllCores;\\\n\n int ThreadNumber;\\\n\n \n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 38, "score": 8791.539628917673 }, { "content": "/// ttk::Triangulation class documentation.\n\n/// \\sa ttk::Triangulation\n\n\n\n#ifndef _TTK_TRIANGULATION_H\n\n#define _TTK_TRIANGULATION_H\n\n\n\n// c++ includes\n\n#include <algorithm>\n\n\n\n// base code includes\n\n#include <Triangulation.h>\n\n#include <Wrapper.h>\n\n\n\n// VTK includes\n\n#include <vtkCellArray.h>\n\n#include <vtkDataSet.h>\n\n#include <vtkDataSetAlgorithm.h>\n\n#include <vtkFiltersCoreModule.h>\n\n#include <vtkImageData.h>\n\n#include <vtkInformation.h>\n\n#include <vtkInformationVector.h>\n\n#include <vtkObjectFactory.h>\n\n#include <vtkPolyData.h>\n\n#include <vtkSmartPointer.h>\n\n#include <vtkUnstructuredGrid.h>\n\n\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 39, "score": 8791.385132537045 }, { "content": "#ifndef _TTK_IDENTIFIERS_H\n\n#define _TTK_IDENTIFIERS_H\n\n\n\n// VTK includes -- to adapt\n\n#include <vtkCellData.h>\n\n#include <vtkDataArray.h>\n\n#include <vtkDataSet.h>\n\n#include <vtkDataSetAlgorithm.h>\n\n#include <vtkFiltersCoreModule.h>\n\n#include <vtkInformation.h>\n\n#include <vtkIntArray.h>\n\n#include <vtkIdTypeArray.h>\n\n#include <vtkObjectFactory.h>\n\n#include <vtkPointData.h>\n\n#include <vtkSmartPointer.h>\n\n\n\n// ttk code includes\n\n#include <ttkWrapper.h>\n\n\n\n// in this example, this wrapper takes a data-set on the input and produces a \n\n// data-set on the output - to adapt.\n\n// see the documentation of the vtkAlgorithm class to decide from which VTK \n\n// class your wrapper should inherit.\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkIdentifiers/ttkIdentifiers.h", "rank": 40, "score": 8790.98641412488 }, { "content": "///\n\n/// \\b Related \\b publication \\n\n\n/// \"Fast and Exact Fiber Surface Extraction for Tetrahedral Meshes\" \\n \n\n/// Pavol Klacansky, Julien Tierny, Hamish Carr, Zhao Geng \\n \n\n/// IEEE Transactions on Visualization and Computer Graphics, 2016.\n\n///\n\n/// \\sa ttkFiberSurface\n\n///\n\n#ifndef _TTK_FIBER_H\n\n#define _TTK_FIBER_H\n\n\n\n// VTK includes -- to adapt\n\n#include <vtkContourFilter.h>\n\n#include <vtkDataSet.h>\n\n#include <vtkDataSetAlgorithm.h>\n\n#include <vtkFiltersCoreModule.h>\n\n#include <vtkInformation.h>\n\n#include <vtkObjectFactory.h>\n\n#include <vtkPointData.h>\n\n#include <vtkPolyData.h>\n\n#include <vtkSmartPointer.h>\n\n\n\n// ttk code includes\n\n#include <Wrapper.h>\n\n\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 41, "score": 8790.92178932386 }, { "content": " protected:\n\n \n\n ttkIdentifiers();\n\n \n\n ~ttkIdentifiers();\n\n \n\n int RequestData(vtkInformation *request, \n\n vtkInformationVector **inputVector, vtkInformationVector *outputVector);\n\n \n\n \n\n private:\n\n \n\n bool UseAllCores;\n\n ttk::ThreadId ThreadNumber;\n\n std::string CellFieldName, VertexFieldName;\n\n \n\n // base code features\n\n int doIt(vtkDataSet *input, vtkDataSet *output);\n\n \n\n bool needsToAbort();\n\n \n\n int updateProgress(const float &progress);\n\n \n\n};\n\n\n\n#endif // _TTK_IDENTIFIERS_H\n", "file_path": "ttk/core/vtk/ttkIdentifiers/ttkIdentifiers.h", "rank": 42, "score": 8790.756104828082 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkOFFWriter\n\n/// \\author Julien Tierny\n\n/// \\date December 2017.<[email protected]>\n\n/// \\brief ttkOFFWriter - Object File Format Writer\n\n///\n\n/// Writes an .off file into VTK format.\n\n\n\n#pragma once\n\n\n\n#include <vtkPoints.h>\n\n#include <vtkSmartPointer.h>\n\n#include <vtkDataSetWriter.h>\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkOFFWriter/ttkOFFWriter.h", "rank": 43, "score": 8790.459129545006 }, { "content": " private:\n\n \n\n bool UseAllCores;\n\n int ThreadNumber;\n\n \n\n double Uvalue, Vvalue;\n\n std::string Ucomponent, Vcomponent;\n\n \n\n // base code features\n\n int doIt(vtkDataSet *input, vtkPolyData *output);\n\n \n\n bool needsToAbort();\n\n \n\n int updateProgress(const float &progress);\n\n \n\n};\n\n\n\n#endif // _TTK_RANGEPOLYGON_H\n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 44, "score": 8790.40644058054 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkForEachRow\n\n/// \\author Jonas Lukasczyk <[email protected]>\n\n/// \\date 01.11.2018\n\n///\n\n/// \\brief TTK VTK-filter that iterates over rows of a vtkTable.\n\n///\n\n/// This filter works in conjunction with the ttkEndFor filter to iterate over rows of a vtkTable.\n\n///\n\n/// \\param Input vtkTable table that will be iterated over\n\n/// \\param Output vtkTable table that contains only one row of the input\n\n\n\n#pragma once\n\n\n\n// VTK includes\n\n#include <vtkMultiBlockDataSetAlgorithm.h>\n\n\n\n// TTK includes\n\n#include <ttkWrapper.h>\n\n\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkForEachRow/ttkForEachRow.h", "rank": 45, "score": 8790.339281565708 }, { "content": "\n\n// VTK includes -- to adapt\n\n#include <vtkCharArray.h>\n\n#include <vtkDataArray.h>\n\n#include <vtkDataSet.h>\n\n#include <vtkDataSetAlgorithm.h>\n\n#include <vtkDoubleArray.h>\n\n#include <vtkFiltersCoreModule.h>\n\n#include <vtkFloatArray.h>\n\n#include <vtkInformation.h>\n\n#include <vtkIntArray.h>\n\n#include <vtkObjectFactory.h>\n\n#include <vtkPointData.h>\n\n#include <vtkSmartPointer.h>\n\n\n\n// ttk code includes\n\n#include <Blank.h>\n\n#include <ttkWrapper.h>\n\n\n\n// in this example, this wrapper takes a data-set on the input and produces a \n\n// data-set on the output - to adapt.\n\n// see the documentation of the vtkAlgorithm class to decide from which VTK \n\n// class your wrapper should inherit.\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 46, "score": 8790.303540052275 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkEndFor\n\n/// \\author Jonas Lukasczyk <[email protected]>\n\n/// \\date 01.11.2018\n\n///\n\n/// \\brief TTK VTK-filter that requests data as long as it is available.\n\n///\n\n/// This filter requests more data as long as the maximum number of elements is not reached. This filter works in conjunction with the ttkForEachRow filter.\n\n///\n\n/// \\param Input vtkDataObject that will be passed through after all iterations.\n\n/// \\param Output vtkDataObject Shallow copy of the input\n\n\n\n#pragma once\n\n\n\n// VTK includes\n\n#include <vtkPassInputTypeAlgorithm.h>\n\n\n\n// TTK includes\n\n#include <ttkWrapper.h>\n\n\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkEndFor/ttkEndFor.h", "rank": 47, "score": 8790.234752152184 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkOFFReader\n\n/// \\author Charles Gueunet <[email protected]>\n\n/// \\date December 2017.\n\n/// \\brief ttkOFFReader - Object File Format Reader\n\n///\n\n/// Load an .off file into VTK format\n\n///\n\n/// Note: This reader is not able to deal with comment on the file\n\n\n\n#pragma once\n\n\n\n#include <vtkFiltersCoreModule.h>\n\n#include \"vtkPoints.h\"\n\n#include \"vtkSmartPointer.h\"\n\n#include \"vtkUnstructuredGridAlgorithm.h\"\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\n#ifndef TTK_PLUGIN\n", "file_path": "ttk/core/vtk/ttkOFFReader/ttkOFFReader.h", "rank": 48, "score": 8790.21841495429 }, { "content": "/// \\defgroup vtk vtk\n\n/// \\brief The Topology ToolKit - VTK wrapping code for the processing \n\n/// packages.\n\n/// @{\n\n/// \\ingroup vtk\n\n/// \\class ttkWrapper\n\n/// \\author Julien Tierny <[email protected]>\n\n/// \\date February 2016.\n\n/// \n\n\n\n#pragma once\n\n\n\n#include <vtkDataSetAlgorithm.h>\n\n#include <vtkImageData.h>\n\n#include <vtkPolyData.h>\n\n#include <vtkUnstructuredGrid.h>\n\n\n\n#include <Wrapper.h>\n\n#include <ttkTriangulation.h>\n\n\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 49, "score": 8789.85520473457 }, { "content": " if(!UseAllCores)\n\n threadNumber_ = ThreadNumber;\n\n else{\n\n threadNumber_ = ttk::OsCall::getNumberOfCores();\n\n }\n\n Modified();\n\n }\n\n \n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n } \n\n \n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n\n SetThreads();\n\n }\n\n // end of default ttk setters\n\n \n\n \n", "file_path": "ttk/core/vtk/ttkIdentifiers/ttkIdentifiers.h", "rank": 50, "score": 8789.252675440264 }, { "content": "#endif\n\n\n\n#ifndef _MSC_VER \n\n#define ttkTemplateMacro(s) vtkTemplateMacro((s));\n\n#define ttkTemplate2Macro(s) vtkTemplate2Macro((s));\n\n#else\n\n#define ttkTemplateMacro(s) vtkTemplateMacro(s);\n\n#define ttkTemplate2Macro(s) vtkTemplate2Macro(s);\n\n#endif\n\n\n\n#ifdef TTK_ENABLE_64BIT_IDS\n\nusing ttkSimplexIdTypeArray = vtkIdTypeArray;\n\n#else\n\nusing ttkSimplexIdTypeArray = vtkIntArray;\n\n#endif\n\n\n\n#define TTK_COMMA ,\n\n\n\n// Macros for vtkWrappers\n\n#define TTK_POLY_DATA_NEW(i, ouputInformation, dataTYpe)\\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 51, "score": 8789.176999954927 }, { "content": "\n\n int countVertsData(std::string line);\n\n int countCellsData(std::string line);\n\n int processLineVert(vtkIdType curLine, std::string &line);\n\n int processLineCell(vtkIdType curLine, std::string &line);\n\n\n\n private:\n\n ttkOFFReader(const ttkOFFReader &) = delete;\n\n void operator=(const ttkOFFReader &) = delete;\n\n\n\n char *FileName;\n\n vtkIdType nbVerts_, nbCells_;\n\n vtkIdType nbVertsData_, nbCellsData_;\n\n\n\n vtkSmartPointer<vtkUnstructuredGrid> mesh_;\n\n vtkSmartPointer<vtkPoints> points_;\n\n std::vector<vtkSmartPointer<vtkDoubleArray>> vertScalars_;\n\n std::vector<vtkSmartPointer<vtkDoubleArray>> cellScalars_;\n\n};\n", "file_path": "ttk/core/vtk/ttkOFFReader/ttkOFFReader.h", "rank": 52, "score": 8788.521943115149 }, { "content": " /// \\warning This function will return a non null pointer if and only if\n\n /// the VTK data-set has undergone a ttkTriangulationFilter (i.e. if it\n\n /// is the direct output of a ttkTriangulationFilter or if a\n\n /// ttkTriangulationFilter has been called in an earlier stage of the \n\n /// pipeline).\n\n /// \\param dataSet Input VTK data-set.\n\n /// \\return Returns a pointer to a valid ttk::Triangulation object upon \n\n /// success, NULL otherwise.\n\n /// \\sa ttk::Triangulation\n\n /// \\sa ttkWrapper\n\n /// \\sa ttkTriangulationFilter\n\n static ttk::Triangulation* getTriangulation(vtkDataSet *dataSet);\n\n \n\n /// Translates the current triangulation into a vtkUnstructuredGrid object.\n\n /// This function, used in conjunction with a vtkXMLUnstructuredGridWriter\n\n /// object, can be useful to store the current triangulation on disk as a\n\n /// VTU file.\n\n /// \\return Returns a valid pointer to a vtkUnstructuredGrid object \n\n /// representing the current triangulation.\n\n ///\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 53, "score": 8788.36880118505 }, { "content": " \\\n\n if(((int) inputs.size() == GetNumberOfInputPorts())\\\n\n &&((int) outputs.size() == GetNumberOfOutputPorts()))\\\n\n doIt(inputs, outputs);\\\n\n \\\n\n return 1;\\\n\n }\n\n\n\n#define TTK_SETUP()\\\n\n public:\\\n\n TTK_PIPELINE_REQUEST();\\\n\n TTK_OUTPUT_MANAGEMENT();\\\n\n void SetThreads(){\\\n\n if(!UseAllCores)\\\n\n threadNumber_ = ThreadNumber;\\\n\n else{\\\n\n threadNumber_ = ttk::OsCall::getNumberOfCores();\\\n\n }\\\n\n Modified();\\\n\n }\\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 54, "score": 8788.039329697312 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkBlank\n\n/// \\author Your Name Here <Your Email Address Here>\n\n/// \\date The Date Here.\n\n///\n\n/// \\brief TTK VTK-filter that wraps the blank processing package.\n\n///\n\n/// VTK wrapping code for the @Blank package.\n\n/// \n\n/// \\param Input Input scalar field (vtkDataSet)\n\n/// \\param Output Output scalar field (vtkDataSet)\n\n///\n\n/// This filter can be used as any other VTK filter (for instance, by using the \n\n/// sequence of calls SetInputData(), Update(), GetOutput()).\n\n///\n\n/// See the related ParaView example state files for usage examples within a \n\n/// VTK pipeline.\n\n///\n\n/// \\sa ttk::Blank\n\n#pragma once\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 55, "score": 8787.788010233258 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkIdentifiers\n\n/// \\author Julien Tierny <[email protected]>\n\n/// \\date August 2015.\n\n///\n\n/// \\brief TTK VTK-filter that computes the global identifiers for each vertex \n\n/// and each cell as point data and cell data scalar fields.\n\n///\n\n/// This filter is useful to retrieve the global identifiers of vertices or \n\n/// cells in subsequent filters throughout the VTK pipeline.\n\n///\n\n/// \\param Input Input data-set (vtkDataSet)\n\n/// \\param Output Output data-set with identifier fields (vtkDataSet)\n\n///\n\n/// This filter can be used as any other VTK filter (for instance, by using the \n\n/// sequence of calls SetInputData(), Update(), GetOutput()).\n\n///\n\n/// See the related ParaView example state files for usage examples within a \n\n/// VTK pipeline.\n\n///\n", "file_path": "ttk/core/vtk/ttkIdentifiers/ttkIdentifiers.h", "rank": 56, "score": 8787.13250978188 }, { "content": " // TODO-1\n\n // Specify the number of input and output ports.\n\n // By default, this filter has one input and one output.\n\n // In this example, we define 2 inputs and 2 outputs.\n\n// SetNumberOfInputPorts(2);\n\n// SetNumberOfOutputPorts(2);\n\n // end of TODO-1\n\n }\n\n \n\n ~ttkBlank(){};\n\n \n\n TTK_SETUP();\n\n \n\n \n\n private:\n\n \n\n int SomeIntegerArgument;\n\n double SomeDoubleArgument;\n\n bool SomeOption;\n\n std::string ScalarField;\n\n vtkDataArray *outputScalarField_;\n\n ttk::blank::Blank blank_;\n\n \n\n};\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 57, "score": 8787.104586430376 }, { "content": "\n\n protected:\n\n\n\n ttkForEachRow(){\n\n UseAllCores = false;\n\n\n\n SetNumberOfInputPorts(1);\n\n SetNumberOfOutputPorts(1);\n\n }\n\n ~ttkForEachRow(){};\n\n\n\n bool UseAllCores;\n\n int ThreadNumber;\n\n\n\n int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override;\n\n int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override;\n\n\n\n private:\n\n\n\n bool needsToAbort() override { return GetAbortExecute(); };\n\n int updateProgress(const float &progress) override {\n\n UpdateProgress(progress);\n\n return 0;\n\n };\n\n};", "file_path": "ttk/core/vtk/ttkForEachRow/ttkForEachRow.h", "rank": 58, "score": 8786.900648935421 }, { "content": " TTK_POLY_DATA_NEW(i, outputInformation, dataType);\\\n\n }\\\n\n }\\\n\n \\\n\n return 1;\\\n\n }\\\n\n public:\n\n \n\n#define TTK_PIPELINE_REQUEST() \\\n\n protected:\\\n\n std::vector<vtkSmartPointer<ttkTriangulationFilter> > inputTriangulations_;\\\n\n int RequestData(vtkInformation *request, \\\n\n vtkInformationVector **inputVector, \\\n\n vtkInformationVector *outputVector) override {\\\n\n \\\n\n if((int) inputTriangulations_.size() != GetNumberOfInputPorts()){\\\n\n inputTriangulations_.resize(GetNumberOfInputPorts());\\\n\n for(int i = 0; i < (int) inputTriangulations_.size(); i++){\\\n\n inputTriangulations_[i] = \\\n\n vtkSmartPointer<ttkTriangulationFilter>::New();\\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 59, "score": 8786.760835569705 }, { "content": " }\n\n\n\n protected:\n\n\n\n ttkEndFor(){\n\n nextIndex = 0;\n\n\n\n UseAllCores = false;\n\n\n\n SetNumberOfInputPorts(2);\n\n SetNumberOfOutputPorts(1);\n\n }\n\n ~ttkEndFor(){};\n\n\n\n bool UseAllCores;\n\n int ThreadNumber;\n\n\n\n int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override;\n\n int RequestUpdateExtent(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override;\n\n int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override;\n", "file_path": "ttk/core/vtk/ttkEndFor/ttkEndFor.h", "rank": 60, "score": 8786.723056202558 }, { "content": " vtkSetMacro(Vcomponent, std::string);\n\n \n\n vtkGetMacro(Vvalue, double);\n\n vtkSetMacro(Vvalue, double);\n\n \n\n int FillOutputPortInformation(int port, vtkInformation *info){\n\n info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkPolyData\"); \n\n return 1;\n\n }\n\n \n\n protected:\n\n \n\n ttkFiber();\n\n \n\n ~ttkFiber();\n\n \n\n int RequestData(vtkInformation *request, \n\n vtkInformationVector **inputVector, vtkInformationVector *outputVector);\n\n \n\n \n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 61, "score": 8786.07475663211 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkFiber\n\n/// \\author Julien Tierny <[email protected]>\n\n/// \\date May 2016.\n\n///\n\n/// \\brief TTK VTK-filter for fiber computation on bivariate volumetric data.\n\n///\n\n/// Given a point in the range, this filter computes its fiber (i.e. pre-image) \n\n/// on bivariate volumetric data. The bivariate input data must be provided as \n\n/// two independent scalar fields attached as point data to the input geometry.\n\n///\n\n/// \\param Input Input bivariate volumetric data-set, either regular grid or\n\n/// triangulation (vtkDataSet)\n\n/// \\param Output Fiber (vtkPolyData)\n\n///\n\n/// This filter can be used as any other VTK filter (for instance, by using the \n\n/// sequence of calls SetInputData(), Update(), GetOutput()).\n\n///\n\n/// See the related ParaView example state files for usage examples within a \n\n/// VTK pipeline.\n", "file_path": "ttk/core/vtk/ttkFiber/ttkFiber.h", "rank": 62, "score": 8785.965159263718 }, { "content": " // end of default ttk setters\n\n \n\n \n\n // TODO-4\n\n // set-getters macros to define from each variable you want to access from \n\n // the outside (in particular from paraview) - to adapt.\n\n // Note that the XML file for the ParaView plug-in specification needs to be\n\n // edited accordingly.\n\n vtkSetMacro(SomeIntegerArgument, int);\n\n vtkGetMacro(SomeIntegerArgument, int);\n\n \n\n vtkSetMacro(SomeDoubleArgument, double);\n\n vtkGetMacro(SomeDoubleArgument, double);\n\n \n\n vtkSetMacro(SomeOption, bool);\n\n vtkGetMacro(SomeOption, bool);\n\n \n\n vtkSetMacro(ScalarField, std::string);\n\n vtkGetMacro(ScalarField, std::string);\n\n // end of TODO-4\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 63, "score": 8785.324101715189 }, { "content": " /// \\warning If the encapsulated ttk::Triangulation object is representing \n\n /// implicitly a regular grid, this grid will be explicitly converted into \n\n /// a triangulation in the output vtkUnstructuredGrid object. This is \n\n /// likely to be very memory-expensive.\n\n vtkUnstructuredGrid* getVtkUnstructuredGrid();\n\n \n\n /// Check if the connectivity of the input data-set \\p dataSet changed \n\n /// since the last time the VTK object \\p callingObject has been modified.\n\n /// This function is particularly useful in vtkWrappers to check if the \n\n /// input geometry changed (requiring a reset of the computation or not).\n\n /// \\param dataSet Input VTK data-set.\n\n /// \\param callingObject Calling VTK object (typically a vtkWrapper)\n\n /// \\return Returns 0 upon success, negative values otherwise.\n\n /// \\sa ttkFTMTree\n\n /// \\sa vtkMorseSmaleComplex\n\n /// \\sa vtkReebSpace\n\n static bool hasChangedConnectivity(ttk::Triangulation *triangulation,\n\n vtkDataSet *dataSet, vtkObject *callingObject);\n\n \n\n /// Specify the input VTK object representing a triangulation or a regular \n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 64, "score": 8784.844691566275 }, { "content": " UseAllCores = onOff;\n\n SetThreads();\n\n }\n\n // end of default ttk setters\n\n\n\n int FillInputPortInformation(int port, vtkInformation* info) override {\n\n switch(port){\n\n case 0: info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkTable\"); break;\n\n default: return 0;\n\n }\n\n return 1;\n\n }\n\n\n\n int FillOutputPortInformation(int port, vtkInformation* info) override {\n\n switch(port){\n\n case 0: info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkTable\"); break;\n\n default: return 0;\n\n }\n\n return 1;\n\n }\n", "file_path": "ttk/core/vtk/ttkForEachRow/ttkForEachRow.h", "rank": 65, "score": 8784.689240958782 }, { "content": " int OpenFile();\n\n virtual void WriteData() override;\n\n \n\n char *FileName;\n\n ofstream *Stream;\n\n \n\n private:\n\n ttkOFFWriter(const ttkOFFWriter &) = delete;\n\n void operator=(const ttkOFFWriter &) = delete;\n\n\n\n};\n", "file_path": "ttk/core/vtk/ttkOFFWriter/ttkOFFWriter.h", "rank": 66, "score": 8784.091310207483 }, { "content": " UseAllCores = onOff;\n\n SetThreads();\n\n }\n\n // end of default ttk setters\n\n\n\n int FillInputPortInformation(int port, vtkInformation* info) override {\n\n switch(port){\n\n case 0: info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkDataObject\"); break;\n\n case 1: info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkTable\"); break;\n\n default: return 0;\n\n }\n\n return 1;\n\n }\n\n\n\n int FillOutputPortInformation(int port, vtkInformation* info) override {\n\n switch(port){\n\n case 0: info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkDataObject\"); break;\n\n default: return 0;\n\n }\n\n return 1;\n", "file_path": "ttk/core/vtk/ttkEndFor/ttkEndFor.h", "rank": 67, "score": 8784.026514512123 }, { "content": " int RequestDataObject(vtkInformation *request, \\\n\n vtkInformationVector **inputVector, vtkInformationVector *outputVector) override {\\\n\n \\\n\n vtkDataSetAlgorithm::RequestDataObject(\\\n\n request, inputVector, outputVector);\\\n\n \\\n\n for(int i = 0; i < GetNumberOfOutputPorts(); i++){\\\n\n \\\n\n vtkInformation *outputInformation =\\\n\n outputVector->GetInformationObject(i);\\\n\n \\\n\n vtkDataSet *output = vtkDataSet::SafeDownCast(\\\n\n outputInformation->Get(vtkDataObject::DATA_OBJECT()));\\\n\n \\\n\n if(output){\\\n\n \\\n\n std::string dataType = output->GetClassName();\\\n\n \\\n\n TTK_UNSTRUCTURED_GRID_NEW(i, outputInformation, dataType);\\\n\n \\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 68, "score": 8783.756815085357 }, { "content": " \\\n\n ttkUnstructuredGrid *data = ttkUnstructuredGrid::SafeDownCast(\\\n\n outputInformation->Get(vtkDataObject::DATA_OBJECT()));\\\n\n \\\n\n if(!data){\\\n\n data = ttkUnstructuredGrid::New();\\\n\n outputInformation->Set(vtkDataObject::DATA_OBJECT(), data);\\\n\n data->FastDelete();\\\n\n data->CopyInformationFromPipeline(outputInformation);\\\n\n GetOutputPortInformation(i)->Set(\\\n\n vtkDataObject::DATA_EXTENT_TYPE(), data->GetExtentType());\\\n\n }\\\n\n \\\n\n if((data)&&(!data->getTriangulation())){\\\n\n data->allocate();\\\n\n }\\\n\n }\n\n\n\n#define TTK_OUTPUT_MANAGEMENT() \\\n\n protected: \\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 69, "score": 8783.48770007721 }, { "content": "/// ttk::Triangulation supports both explicit and implicit triangulations: \n\n/// -# Explicit triangulations with vtkUnstructuredGrid or vtkPolyData \n\n/// objects: Given a vtkUnstructuredGrid or a vtkPolyData representing a valid \n\n/// triangulation, ttk:Triangulation provides time efficient accesses \n\n/// (requiring adequate pre-processing, see the ttk::Triangulation class \n\n/// documentation).\n\n/// -# Implicit triangulations with vtkImageData objects: Given a vtkImageData\n\n/// representing a regular grid, ttk::Triangulation will perform an implicit \n\n/// triangulation of the grid, enabling both time and memory efficient \n\n/// traversals of triangulations of regular grids.\n\n///\n\n/// Apart from pre-processes, ttk::Triangulation requires no memory overhead in\n\n/// addition to the input vtkUnstructuredGrid, vtkPolyData or vtkImageData \n\n/// objects (the actual data is passed through pointers). This also means that \n\n/// the input VTK objects (vtkUnstructuredGrid, vtkPolyData or vtkImageData) \n\n/// must persist as long as their corresponding ttk::Triangulation object \n\n/// (unspecified behavior otherwise).\n\n///\n\n/// \\note\n\n/// Only pre-process the information you need! See the \n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 70, "score": 8783.386466920301 }, { "content": " if(dataType == \"vtkPolyData\"){\\\n\n ttkPolyData *data = ttkPolyData::SafeDownCast(\\\n\n outputInformation->Get(vtkDataObject::DATA_OBJECT()));\\\n\n \\\n\n if(!data){\\\n\n data = ttkPolyData::New();\\\n\n outputInformation->Set(vtkDataObject::DATA_OBJECT(), data);\\\n\n data->FastDelete();\\\n\n data->CopyInformationFromPipeline(outputInformation);\\\n\n GetOutputPortInformation(i)->Set(\\\n\n vtkDataObject::DATA_EXTENT_TYPE(), data->GetExtentType());\\\n\n }\\\n\n \\\n\n if((data)&&(!data->getTriangulation())){\\\n\n data->allocate();\\\n\n }\\\n\n }\n\n\n\n#define TTK_UNSTRUCTURED_GRID_NEW(i, ouputInformation, dataTYpe)\\\n\n if(dataType == \"vtkUnstructuredGrid\"){\\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 71, "score": 8783.206275248749 }, { "content": "/// \\ingroup vtk\n\n/// \\class ttkTriangulation\n\n/// \\author Julien Tierny <[email protected]>\n\n/// \\date January 2016.\n\n/// \n\n/// \\brief ttkTriangulation is a wrapper for the ttk::Triangulation class, which\n\n/// provides time and memory efficient traversal methods on triangulations of \n\n/// piecewise linear manifolds. It provides the following features:\n\n/// -# Given a vertex, it provides: the list of edges that are connected to \n\n/// it, the list of its neighbors, its link, its star, etc.\n\n/// -# Given an edge, it provides: its vertices, its star, etc.\n\n/// -# Given a triangle, its provides: its vertices, its edges, etc.\n\n/// -# Given a tetrahedron, its provides: its vertices, its edges, its \n\n/// neighbor tetrahedra, etc.\n\n/// -# Given a triangulation, it provides: its list of vertices, edges, \n\n/// triangles and tetrahedra.\n\n///\n\n/// ttk::Triangulation implements faster accesses than, more general-purpose, \n\n/// competing VTK data structures such as the vtkUnstructuredGrid class.\n\n/// \n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 72, "score": 8783.156521768593 }, { "content": " \n\n int shallowCopy(vtkDataObject *other);\n\n \n\n\n\n bool hasAllocated_;\n\n \n\n vtkDataSet *inputDataSet_;\n\n vtkSmartPointer<vtkPoints> \n\n vtkPoints_;\n\n vtkSmartPointer<vtkUnstructuredGrid>\n\n vtkUnstructuredGrid_;\n\n \n\n ttk::Triangulation *triangulation_;\n\n \n\n private:\n\n \n\n};\n\n\n\n// Internal things to allow the ttkTriangulation to travel through a VTK \n\n// pipeline.\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 73, "score": 8782.931494993572 }, { "content": " }\\\n\n }\\\n\n \\\n\n std::vector<vtkDataSet *> inputs(GetNumberOfInputPorts(), NULL);\\\n\n std::vector<vtkDataSet *> outputs(GetNumberOfOutputPorts(), NULL);\\\n\n \\\n\n for(int i = 0; i < GetNumberOfInputPorts(); i++){\\\n\n vtkDataSet *input = vtkDataSet::GetData(inputVector[i]);\\\n\n if(input){\\\n\n inputTriangulations_[i]->SetInputData(input);\\\n\n inputTriangulations_[i]->Update();\\\n\n inputs[i] = inputTriangulations_[i]->GetOutput();\\\n\n }\\\n\n }\\\n\n for(int i = 0; i < GetNumberOfOutputPorts(); i++){\\\n\n outputs[i] = vtkDataSet::SafeDownCast(\\\n\n \\\n\n outputVector->GetInformationObject(i)->Get(\\\n\n vtkDataObject::DATA_OBJECT()));\\\n\n }\\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 74, "score": 8782.247683682388 }, { "content": " /// grid.\n\n /// \\param dataSet Input VTK object (vtkImageData, vtkPolyData or \n\n /// vtkUnstructuredGrid).\n\n /// \\return Returns 0 upon success, negative values otherwise.\n\n ///\n\n /// \\warning If the internal ttk::Triangulation object is already \n\n /// representing a valid triangulation, this information will be \n\n /// over-written (which means that pre-processing functions should \n\n /// be called again).\n\n /// \n\n /// \\warning For memory-efficiency purposes, this function makes NO DATA \n\n /// COPY. This means that, if the object \\p dataSet is destroyed after this \n\n /// function, the behavior of the internal ttk::Triangulation will be \n\n /// unspecified (well, this is a nice way to say it's gonna crash).\n\n int setInputData(vtkDataSet *dataSet);\n\n \n\n \n\n protected:\n\n \n\n int deepCopy(vtkDataObject *other);\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 75, "score": 8782.051368729724 }, { "content": "#define ttkTypeMacro(thisClass, superClass) \\\n\n protected: \\\n\n const char* GetClassNameInternal() const{ \\\n\n return #superClass; \\\n\n } \\\n\n public: \\\n\n typedef superClass Superclass; \\\n\n static bool IsTypeOf(const char *type){ \\\n\n if(!strcmp(\"superClass\", type)){ \\\n\n return 1;\\\n\n } \\\n\n return superClass::IsTypeOf(type); \\\n\n } \\\n\n int IsA(const char *type){ \\\n\n return this->thisClass::IsTypeOf(type); \\\n\n } \\\n\n static thisClass* SafeDownCast(vtkObjectBase *o){ \\\n\n if((o)&&(o->IsA(\"thisClass\"))){ \\\n\n return static_cast<thisClass *>(o); \\\n\n } \\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 76, "score": 8781.546597486249 }, { "content": " return NULL;\\\n\n } \\\n\n thisClass *NewInstance() const { \\\n\n return thisClass::SafeDownCast(this->NewInstanceInternal()); \\\n\n }\\\n\n protected: \\\n\n vtkObjectBase* NewInstanceInternal() const{ \\\n\n return thisClass::New();\\\n\n } \\\n\n public:\\\n\n\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 77, "score": 8777.689020324144 }, { "content": "#if VTK_MAJOR_VERSION <= 8\n\n#define vtkTemplate2Macro(call) \\\n\n vtkTemplate2MacroCase1(VTK_DOUBLE, double, call); \\\n\n vtkTemplate2MacroCase1(VTK_FLOAT, float, call); \\\n\n vtkTemplate2MacroCase1(VTK_LONG_LONG, long long, call); \\\n\n vtkTemplate2MacroCase1(VTK_UNSIGNED_LONG_LONG, unsigned long long, call); \\\n\n vtkTemplate2MacroCase1(VTK_ID_TYPE, vtkIdType, call); \\\n\n vtkTemplate2MacroCase1(VTK_LONG, long, call); \\\n\n vtkTemplate2MacroCase1(VTK_UNSIGNED_LONG, unsigned long, call); \\\n\n vtkTemplate2MacroCase1(VTK_INT, int, call); \\\n\n vtkTemplate2MacroCase1(VTK_UNSIGNED_INT, unsigned int, call); \\\n\n vtkTemplate2MacroCase1(VTK_SHORT, short, call); \\\n\n vtkTemplate2MacroCase1(VTK_UNSIGNED_SHORT, unsigned short, call); \\\n\n vtkTemplate2MacroCase1(VTK_CHAR, char, call); \\\n\n vtkTemplate2MacroCase1(VTK_SIGNED_CHAR, signed char, call); \\\n\n vtkTemplate2MacroCase1(VTK_UNSIGNED_CHAR, unsigned char, call)\n\n#define vtkTemplate2MacroCase1(type1N, type1, call) \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_DOUBLE, double, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_FLOAT, float, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_LONG_LONG, long long, call); \\\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 78, "score": 8777.689020324144 }, { "content": "\n\n private:\n\n\n\n double nextIndex;\n\n\n\n bool needsToAbort() override { return GetAbortExecute(); };\n\n int updateProgress(const float &progress) override {\n\n UpdateProgress(progress);\n\n return 0;\n\n };\n\n};", "file_path": "ttk/core/vtk/ttkEndFor/ttkEndFor.h", "rank": 79, "score": 8777.689020324144 }, { "content": " vtkTemplate2MacroCase2(type1N, type1, VTK_UNSIGNED_LONG_LONG, unsigned long long, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_ID_TYPE, vtkIdType, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_LONG, long, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_UNSIGNED_LONG, unsigned long, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_INT, int, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_UNSIGNED_INT, unsigned int, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_SHORT, short, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_UNSIGNED_SHORT, unsigned short, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_CHAR, char, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_SIGNED_CHAR, signed char, call); \\\n\n vtkTemplate2MacroCase2(type1N, type1, VTK_UNSIGNED_CHAR, unsigned char, call)\n\n#define vtkTemplate2MacroCase2(type1N, type1, type2N, type2, call) \\\n\n case vtkTemplate2PackMacro(type1N, type2N): { \\\n\n typedef type1 VTK_T1; \\\n\n typedef type2 VTK_T2; \\\n\n call; \\\n\n }; break\n\n#define vtkTemplate2PackMacro(type1N, type2N) \\\n\n ((((type1N) & 0xFF) << 8) | \\\n\n((type2N) & 0xFF))\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 80, "score": 8777.689020324144 }, { "content": "\n\n // TODO-2\n\n // Over-ride the input types.\n\n // By default, this filter has one input and one output, of the same type.\n\n // Here, you can re-define the input types, on a per input basis.\n\n // In this example, the first input type is forced to vtkUnstructuredGrid.\n\n // The second input type is forced to vtkImageData.\n\n// int FillInputPortInformation(int port, vtkInformation *info) override {\n\n// \n\n// switch(port){\n\n// case 0:\n\n// info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkUnstructuredGrid\"); \n\n// break;\n\n// case 1:\n\n// info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkImageData\"); \n\n// break;\n\n// default:\n\n// break;\n\n// }\n\n// \n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 81, "score": 8777.689020324144 }, { "content": " \n\n private:\n\n \n\n bool needsToAbort() override;\n\n \n\n int updateProgress(const float &progress) override;\n\n \n\n};\n\n\n\n/// @}\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 82, "score": 8777.689020324144 }, { "content": "// return 1;\n\n// }\n\n // end of TODO-2\n\n \n\n // TODO-3\n\n // Over-ride the output types.\n\n // By default, this filter has one input and one output, of the same type.\n\n // Here, you can re-define the output types, on a per output basis.\n\n // In this example, the first output type is forced to vtkUnstructuredGrid.\n\n // The second output type is forced to vtkImageData.\n\n// int FillOutputPortInformation(int port, vtkInformation *info) override {\n\n// \n\n// switch(port){\n\n// case 0:\n\n// info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkUnstructuredGrid\"); \n\n// break;\n\n// case 1:\n\n// info->Set(vtkDataObject::DATA_TYPE_NAME(), \"vtkImageData\"); \n\n// break;\n\n// default:\n", "file_path": "ttk/core/vtk/ttkBlank/ttkBlank.h", "rank": 83, "score": 8777.689020324144 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKCOMMONDATAMODEL_EXPORT ttkPolyData :\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 84, "score": 8726.605188497328 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKCOMMONDATAMODEL_EXPORT ttkUnstructuredGrid :\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 85, "score": 8726.605188497328 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKFILTERSCORE_EXPORT ttkTriangulationFilter\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkWrapper.h", "rank": 86, "score": 8726.605188497328 }, { "content": "#ifndef TTK_PLUGIN\n\nclass VTKCOMMONDATAMODEL_EXPORT ttkImageData :\n", "file_path": "ttk/core/vtk/ttkTriangulation/ttkTriangulation.h", "rank": 87, "score": 8726.605188497328 }, { "content": "#else\n\nclass ttkBlockAggregator\n\n#endif\n\n: public vtkMultiBlockDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkBlockAggregator* New();\n\n vtkTypeMacro(ttkBlockAggregator, vtkMultiBlockDataSetAlgorithm)\n\n\n\n vtkSetMacro(ForceReset, bool);\n\n vtkGetMacro(ForceReset, bool);\n\n\n\n vtkSetMacro(FlattenInput, bool);\n\n vtkGetMacro(FlattenInput, bool);\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n void SetThreads(){\n\n threadNumber_ = !UseAllCores ? ThreadNumber : ttk::OsCall::getNumberOfCores();\n\n Modified();\n", "file_path": "ttk/core/vtk/ttkBlockAggregator/ttkBlockAggregator.h", "rank": 88, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkIntegralLines\n\n#endif\n\n: public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkIntegralLines* New();\n\n\n\n vtkTypeMacro(ttkIntegralLines, vtkDataSetAlgorithm);\n\n\n\n vtkSetMacro(debugLevel_, int);\n\n\n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n }\n\n\n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n\n SetThreads();\n", "file_path": "ttk/core/vtk/ttkIntegralLines/ttkIntegralLines.h", "rank": 89, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkLDistance\n\n#endif \n\n : public vtkDataSetAlgorithm, public ttk::Wrapper \n\n{\n\n\n\n public:\n\n \n\n static ttkLDistance* New();\n\n \n\n vtkTypeMacro(ttkLDistance, vtkDataSetAlgorithm);\n\n \n\n // Default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n \n\n void SetThreadNumber(int threadNumber) {\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n } \n\n \n\n void SetUseAllCores(bool onOff) {\n", "file_path": "ttk/core/vtk/ttkLDistance/ttkLDistance.h", "rank": 90, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkContourForests\n\n#endif \n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n \n\n \n\n public:\n\n \n\n static ttkContourForests* New();\n\n\n\n vtkTypeMacro(ttkContourForests, vtkDataSetAlgorithm);\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n\n\n vtkSetMacro(FieldId, int);\n\n\n\n void SetThreadNumber(int threadNumber);\n\n void SetDebugLevel(int d);\n\n void SetUseAllCores(bool onOff);\n\n // end of default ttk setters\n", "file_path": "ttk/core/vtk/ttkContourForests/ttkContourForests.h", "rank": 91, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkJacobiSet\n\n#endif \n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkJacobiSet* New();\n\n \n\n vtkTypeMacro(ttkJacobiSet, vtkDataSetAlgorithm);\n\n \n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n\n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n } \n\n \n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n", "file_path": "ttk/core/vtk/ttkJacobiSet/ttkJacobiSet.h", "rank": 92, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkManifoldCheck\n\n#endif\n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkManifoldCheck* New();\n\n vtkTypeMacro(ttkManifoldCheck, vtkDataSetAlgorithm)\n\n \n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n \n\n void SetThreadNumber(int threadNumber){\\\n\n ThreadNumber = threadNumber;\\\n\n SetThreads();\\\n\n }\\\n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n\n SetThreads();\n\n }\n", "file_path": "ttk/core/vtk/ttkManifoldCheck/ttkManifoldCheck.h", "rank": 93, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkCinemaReader\n\n#endif\n\n: public vtkTableReader, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkCinemaReader* New();\n\n vtkTypeMacro(ttkCinemaReader, vtkTableReader)\n\n\n\n vtkSetMacro(DatabasePath, std::string);\n\n vtkGetMacro(DatabasePath, std::string);\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n void SetThreads(){\n\n threadNumber_ = !UseAllCores ? ThreadNumber : ttk::OsCall::getNumberOfCores();\n\n Modified();\n\n }\n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n", "file_path": "ttk/core/vtk/ttkCinemaReader/ttkCinemaReader.h", "rank": 94, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkGeometrySmoother\n\n#endif \n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkGeometrySmoother* New();\n\n \n\n vtkTypeMacro(ttkGeometrySmoother, vtkDataSetAlgorithm);\n\n \n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n \n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n } \n\n \n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n", "file_path": "ttk/core/vtk/ttkGeometrySmoother/ttkGeometrySmoother.h", "rank": 95, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkIcoSphere\n\n#endif\n\n: public vtkUnstructuredGridAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkIcoSphere* New();\n\n vtkTypeMacro(ttkIcoSphere, vtkUnstructuredGridAlgorithm)\n\n\n\n vtkSetMacro(Subdivisions, int);\n\n vtkGetMacro(Subdivisions, int);\n\n\n\n vtkSetVector3Macro(Center, float);\n\n vtkGetVector3Macro(Center, float);\n\n\n\n vtkSetMacro(Radius, float);\n\n vtkGetMacro(Radius, float);\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n", "file_path": "ttk/core/vtk/ttkIcoSphere/ttkIcoSphere.h", "rank": 96, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkCinemaQuery\n\n#endif\n\n: public vtkTableAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n static ttkCinemaQuery* New();\n\n vtkTypeMacro(ttkCinemaQuery, vtkTableAlgorithm)\n\n\n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n void SetThreads(){\n\n threadNumber_ = !UseAllCores ? ThreadNumber : ttk::OsCall::getNumberOfCores();\n\n Modified();\n\n }\n\n void SetThreadNumber(int threadNumber){\n\n ThreadNumber = threadNumber;\n\n SetThreads();\n\n }\n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n", "file_path": "ttk/core/vtk/ttkCinemaQuery/ttkCinemaQuery.h", "rank": 97, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkMeshGraph\n\n#endif\n\n: public vtkUnstructuredGridAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n\n\n static ttkMeshGraph* New();\n\n vtkTypeMacro(ttkMeshGraph, vtkUnstructuredGridAlgorithm)\n\n\n\n vtkSetMacro(UseVariableSize, bool);\n\n vtkGetMacro(UseVariableSize, bool);\n\n\n\n vtkSetMacro(SizeFieldName, std::string);\n\n vtkGetMacro(SizeFieldName, std::string);\n\n\n\n vtkSetMacro(SizeAxis, int);\n\n vtkGetMacro(SizeAxis, int);\n\n\n\n vtkSetMacro(SizeScale, float);\n\n vtkGetMacro(SizeScale, float);\n", "file_path": "ttk/core/vtk/ttkMeshGraph/ttkMeshGraph.h", "rank": 98, "score": 8720.76628401961 }, { "content": "#else\n\nclass ttkIdentifierRandomizer\n\n#endif \n\n : public vtkDataSetAlgorithm, public ttk::Wrapper{\n\n\n\n public:\n\n \n\n static ttkIdentifierRandomizer* New();\n\n vtkTypeMacro(ttkIdentifierRandomizer, vtkDataSetAlgorithm)\n\n \n\n // default ttk setters\n\n vtkSetMacro(debugLevel_, int);\n\n \n\n void SetThreadNumber(int threadNumber){\\\n\n ThreadNumber = threadNumber;\\\n\n SetThreads();\\\n\n }\\\n\n void SetUseAllCores(bool onOff){\n\n UseAllCores = onOff;\n\n SetThreads();\n\n }\n", "file_path": "ttk/core/vtk/ttkIdentifierRandomizer/ttkIdentifierRandomizer.h", "rank": 99, "score": 8720.76628401961 } ]
C++
src/GrainViewer/Ui/Gui.cpp
eliemichel/GrainViewer
91d4922b3185ada90508f0944f2691ba8eba45e3
#include <OpenGL> #include "Logger.h" #include "Gui.h" #include "Window.h" #include "Scene.h" #include "Dialog.h" #include "RuntimeObject.h" #include "ShaderPool.h" #include "GlobalTimer.h" #include "Ui/SceneDialog.h" #include "Ui/DeferredShadingDialog.h" #include "Ui/WorldDialog.h" #include "Ui/GlobalTimerDialog.h" #include <GLFW/glfw3.h> #include <imgui.h> #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include <iostream> using namespace std; #include "LightGizmoDialog.h" #include "FarGrainRendererDialog.h" #include "TransformDialog.h" #include "PointCloudSplitterDialog.h" #include "InstanceGrainRendererDialog.h" #include "ImpostorGrainRendererDialog.h" #include "GrainBehaviorDialog.h" #include "MeshRendererDialog.h" #include "QuadMeshDataDialog.h" static std::shared_ptr<Dialog> makeComponentDialog(std::string type, std::shared_ptr<Behavior> component) { #define handleBehavior(T) \ if (type == BehaviorRegistryEntry<T>::Name()) { \ auto dialog = DialogFactory<T>().MakeShared(); \ dialog->setControlledBehavior(std::dynamic_pointer_cast<T>(component)); \ return std::dynamic_pointer_cast<Dialog>(dialog); \ } handleBehavior(LightGizmo); handleBehavior(FarGrainRenderer); handleBehavior(TransformBehavior); handleBehavior(PointCloudSplitter); handleBehavior(InstanceGrainRenderer); handleBehavior(ImpostorGrainRenderer); handleBehavior(GrainBehavior); handleBehavior(MeshRenderer); handleBehavior(QuadMeshData); return nullptr; #undef handleType } void Gui::Init(const Window & window) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; ImGui_ImplGlfw_InitForOpenGL(window.glfw(), true); ImGui_ImplOpenGL3_Init("#version 150"); ImGui::GetStyle().WindowRounding = 0.0f; } void Gui::NewFrame() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); } void Gui::DrawFrame() { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } void Gui::Shutdown() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } static void printUsage() { cerr << "GrainViewer -- real time grain viewer" << endl << "Author : Élie Michel (http://perso.telecom-paristech.fr/~emichel)" << endl << endl << "Keyboard commands" << endl << "------------------" << endl << " r: Reload shaders" << endl << " ctrl+r: Reload scene" << endl << " p: Toggle panel" << endl << " a: Tilt camera left" << endl << " e: Tilt camera right" << endl << " d: Switch deferred shading on/off" << endl << " c: Print camera matrix (row major)" << endl << " <space>: Pause physics" << endl << " ?: Print help" << endl << " q, <esc>: Quit" << endl << endl; } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onKey(key, scancode, action, mode); } static void cursor_pos_callback(GLFWwindow* window, double x, double y) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onCursorPosition(x, y); } static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onMouseButton(button, action, mods); } static void window_size_callback(GLFWwindow* window, int width, int height) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onResize(width, height); } static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onScroll(xoffset, yoffset); } void Gui::setupCallbacks() { if (auto window = m_window.lock()) { glfwSetWindowUserPointer(window->glfw(), static_cast<void*>(this)); glfwSetKeyCallback(window->glfw(), key_callback); glfwSetCursorPosCallback(window->glfw(), cursor_pos_callback); glfwSetMouseButtonCallback(window->glfw(), mouse_button_callback); glfwSetWindowSizeCallback(window->glfw(), window_size_callback); glfwSetScrollCallback(window->glfw(), scroll_callback); } } Gui::Gui(std::shared_ptr<Window> window) : m_window(window) , m_scene(nullptr) { setupCallbacks(); Init(*window); int width, height; glfwGetFramebufferSize(window->glfw(), &width, &height); onResize(width, height); } Gui::~Gui() { Shutdown(); } void Gui::setScene(std::shared_ptr<Scene> scene) { m_scene = scene; setupDialogs(); } void Gui::beforeLoading() { NewFrame(); ImGui::SetNextWindowSize(ImVec2(m_windowWidth, m_windowHeight)); ImGui::SetNextWindowPos(ImVec2(0.f, 0.f)); ImGui::Begin("Reload", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); ImGui::Text(" "); ImGui::Text(" "); ImGui::Text("Loading scene..."); ImGui::End(); DrawFrame(); if (auto window = m_window.lock()) { glfwSwapBuffers(window->glfw()); } } void Gui::afterLoading() { if (auto window = m_window.lock()) { int width, height; glfwGetFramebufferSize(window->glfw(), &width, &height); onResize(width, height); } m_startTime = static_cast<float>(glfwGetTime()); setupDialogs(); } void Gui::setupDialogs() { m_dialogGroups.clear(); if (m_scene) { addDialogGroup<DeferredShadingDialog>("Deferred Shading", m_scene->deferredShader()); addDialogGroup<WorldDialog>("World", m_scene->world()); addDialogGroup<GlobalTimerDialog>("Timers", GlobalTimer::GetInstance()); addDialogGroup<SceneDialog>("Scene:", m_scene); for (const auto& obj : m_scene->objects()) { DialogGroup group; group.title = " - " + obj->name; IBehaviorHolder::ConstBehaviorIterator it, end; for (it = obj->cbeginBehaviors(), end = obj->cendBehaviors(); it != end; ++it) { auto dialog = makeComponentDialog(it->first, it->second); if (dialog) { group.dialogs.push_back(dialog); } } m_dialogGroups.push_back(group); } } } void Gui::update() { updateImGui(); if (m_scene) { m_scene->update(static_cast<float>(glfwGetTime()) - m_startTime); if (auto window = m_window.lock()) { if (m_scene->mustQuit()) { glfwSetWindowShouldClose(window->glfw(), GL_TRUE); } } } } void Gui::updateImGui() { NewFrame(); ImVec4 clear_color = ImColor(114, 144, 154); static float f = 0.0f; ImGui::SetNextWindowPos(ImVec2(0.f, 0.f)); ImGui::SetNextWindowSize(ImVec2(420.f, 0.f)); ImGui::Begin("Framerate", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); int frame = m_scene ? m_scene->frame() : 0; ImGui::Text("Application average %.3f ms/frame (%.1f FPS) | #%d", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate, frame); ImGui::End(); int dialogId = 0; for (auto & dg : m_dialogGroups) { ImGui::PushID(dialogId++); for (auto d : dg.dialogs) { d->drawHandles(0, 0, m_windowWidth, m_windowHeight); } ImGui::PopID(); } if (m_showPanel) { ImGui::SetNextWindowSize(ImVec2(m_panelWidth, m_windowHeight)); ImGui::SetNextWindowPos(ImVec2(m_windowWidth - m_panelWidth, 0.f)); ImGui::Begin("Dialogs", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); ImGui::PushID(0); int dialogId = 0; bool pressed; for (auto & dg : m_dialogGroups) { ImGui::PushID(dialogId); dialogId += static_cast<int>(dg.dialogs.size()); pressed = ImGui::Selectable(dg.title.c_str(), &dg.enabled); if (pressed && m_isControlPressed == 0) { for (auto & other : m_dialogGroups) { other.enabled = &other == &dg; } } ImGui::PopID(); } ImGui::PopID(); ImGui::PushID(1); dialogId = 0; for (auto & dg : m_dialogGroups) { if (dg.enabled) { for (auto d : dg.dialogs) { ImGui::PushID(dialogId++); d->draw(); ImGui::PopID(); } } else { dialogId += static_cast<int>(dg.dialogs.size()); } } ImGui::PopID(); ImGui::End(); } } void Gui::render() { if (m_scene) { m_scene->render(); } if (!m_scene || m_scene->properties().ui) { glBindFramebuffer(GL_FRAMEBUFFER, 0); DrawFrame(); } if (m_scene) { m_scene->onPostRender(static_cast<float>(glfwGetTime()) - m_startTime); } } void Gui::onResize(int width, int height) { m_windowWidth = static_cast<float>(width); m_windowHeight = static_cast<float>(height); if (auto window = m_window.lock()) { int fbWidth, fbHeight; glfwGetFramebufferSize(window->glfw(), &fbWidth, &fbHeight); glViewport(0, 0, fbWidth, fbHeight); if (m_scene) { m_scene->setResolution(fbWidth, fbHeight); } } } #define forAllCameras(method) \ for (auto& camera : m_scene->cameras()) { \ if (camera->properties().controlInViewport) { \ camera->method(); \ } \ } void Gui::onMouseButton(int button, int action, int mods) { if (m_imguiFocus || !m_scene) { return; } m_isMouseMoveStarted = action == GLFW_PRESS; switch (button) { case GLFW_MOUSE_BUTTON_LEFT: if (action == GLFW_PRESS) { forAllCameras(startMouseRotation); } else { forAllCameras(stopMouseRotation); } break; case GLFW_MOUSE_BUTTON_MIDDLE: if (action == GLFW_PRESS) { forAllCameras(startMouseZoom); } else { forAllCameras(stopMouseZoom); } break; case GLFW_MOUSE_BUTTON_RIGHT: if (action == GLFW_PRESS) { forAllCameras(startMousePanning); } else { forAllCameras(stopMousePanning); } break; } } void Gui::onCursorPosition(double x, double y) { double limit = static_cast<double>(m_windowWidth) - static_cast<double>(m_panelWidth); m_imguiFocus = x >= limit && m_showPanel && !m_isMouseMoveStarted; if (m_imguiFocus) { return; } if (m_scene) { for (auto& camera : m_scene->cameras()) { if (camera->properties().controlInViewport) { camera->updateMousePosition(static_cast<float>(x), static_cast<float>(y)); } } } } void Gui::onScroll(double xoffset, double yoffset) { if (m_imguiFocus) { return; } if (m_scene) { for (auto& camera : m_scene->cameras()) { if (camera->properties().controlInViewport) { camera->zoom(- 2 * static_cast<float>(yoffset)); } } } } void Gui::onKey(int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: if (auto window = getWindow().lock()) { glfwSetWindowShouldClose(window->glfw(), GL_TRUE); } break; case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: ++m_isControlPressed; break; } } if (action == GLFW_RELEASE) { switch (key) { case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: m_isControlPressed = 0; break; } } if (action == GLFW_PRESS && !m_imguiFocus) { switch (key) { case GLFW_KEY_ESCAPE: if (auto window = m_window.lock()) { glfwSetWindowShouldClose(window->glfw(), GL_TRUE); } break; case GLFW_KEY_P: m_showPanel = !m_showPanel; break; case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: ++m_isControlPressed; break; } } if (action == GLFW_PRESS && !m_imguiFocus && m_scene) { switch (key) { case GLFW_KEY_R: if (mods & GLFW_MOD_CONTROL) { beforeLoading(); ShaderPool::Clear(); m_scene->load(m_scene->filename()); afterLoading(); } else { m_scene->reloadShaders(); } break; case GLFW_KEY_U: m_scene->properties().ui = !m_scene->properties().ui; break; case GLFW_KEY_A: forAllCameras(tiltLeft); break; case GLFW_KEY_E: forAllCameras(tiltRight); break; case GLFW_KEY_C: if (mods & GLFW_MOD_CONTROL) { ShaderPool::Clear(); m_scene->clear(); } else { if (m_scene->viewportCamera()) { glm::mat4 m = m_scene->viewportCamera()->viewMatrix(); DEBUG_LOG << "View Matrix: \n" << "[" << m[0][0] << "," << m[0][1] << "," << m[0][2] << "," << m[0][3] << "," << m[1][0] << "," << m[1][1] << "," << m[1][2] << "," << m[1][3] << "," << m[2][0] << "," << m[2][1] << "," << m[2][2] << "," << m[2][3] << "," << m[3][0] << "," << m[3][1] << "," << m[3][2] << "," << m[3][3] << "]"; std::ostringstream ss; m_scene->viewportCamera()->serialize(ss); DEBUG_LOG << ss.str(); } } break; case GLFW_KEY_SPACE: m_scene->togglePause(); break; } } } #undef forAllCameras
#include <OpenGL> #include "Logger.h" #include "Gui.h" #include "Window.h" #include "Scene.h" #include "Dialog.h" #include "RuntimeObject.h" #include "ShaderPool.h" #include "GlobalTimer.h" #include "Ui/SceneDialog.h" #include "Ui/DeferredShadingDialog.h" #include "Ui/WorldDialog.h" #include "Ui/GlobalTimerDialog.h" #include <GLFW/glfw3.h> #include <imgui.h> #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include <iostream> using namespace std; #include "LightGizmoDialog.h" #include "FarGrainRendererDialog.h" #include "TransformDialog.h" #include "PointCloudSplitterDialog.h" #include "InstanceGrainRendererDialog.h" #include "ImpostorGrainRendererDialog.h" #include "GrainBehaviorDialog.h" #include "MeshRendererDialog.h" #include "QuadMeshDataDialog.h" static std::shared_ptr<Dialog> makeComponentDialog(std::string type, std::shared_ptr<Behavior> component) { #define handleBehavior(T) \ if (type == BehaviorRegistryEntry<T>::Name()) { \ auto dialog = DialogFactory<T>().MakeShared(); \ dialog->setControlledBehavior(std::dynamic_pointer_cast<T>(component)); \ return std::dynamic_pointer_cast<Dialog>(dialog); \ } handleBehavior(LightGizmo); handleBehavior(FarGrainRenderer); handleBehavior(TransformBehavior); handleBehavior(PointCloudSplitter); handleBehavior(InstanceGrainRenderer); handleBehavior(ImpostorGrainRenderer); handleBehavior(GrainBehavior); handleBehavior(MeshRenderer); handleBehavior(QuadMeshData); return nullptr; #undef handleType } void Gui::Init(const Window & window) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; ImGui_ImplGlfw_InitForOpenGL(window.glfw(), true); ImGui_ImplOpenGL3_Init("#version 150"); ImGui::GetStyle().WindowRounding = 0.0f; } void Gui::NewFrame() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); } void Gui::DrawFrame() { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } void Gui::Shutdown() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } static void printUsage() { cerr << "GrainViewer -- real time grain viewer" << endl << "Author : Élie Michel (http://perso.telecom-paristech.fr/~emichel)" << endl << endl << "Keyboard commands" << endl << "------------------" << endl << " r: Reload shaders" << endl << " ctrl+r: Reload scene" << endl << " p: Toggle panel" << endl << " a: Tilt camera left" << endl << " e: Tilt camera right" << endl << " d: Switch deferred shading on/off" << endl << " c: Print camera matrix (row major)" << endl << " <space>: Pause physics" << endl << " ?: Print help" << endl << " q, <esc>: Quit" << endl << endl; } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onKey(key, scancode, action, mode); } static void cursor_pos_callback(GLFWwindow* window, double x, double y) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onCursorPosition(x, y); } static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onMouseButton(button, action, mods); } static void window_size_callback(GLFWwindow* window, int width, int height) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onResize(width, height); } static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { Gui* gui = static_cast<Gui*>(glfwGetWindowUserPointer(window)); gui->onScroll(xoffset, yoffset); } void Gui::setupCallbacks() { if (auto window = m_window.lock()) { glfwSetWindowUserPointer(window->glfw(), static_cast<void*>(this)); glfwSetKeyCallback(window->glfw(), key_callback); glfwSetCursorPosCallback(window->glfw(), cursor_pos_callback); glfwSetMouseButtonCallback(window->glfw(), mouse_button_callback); glfwSetWindowSizeCallback(window->glfw(), window_size_callback); glfwSetScrollCallback(window->glfw(), scroll_callback); } } Gui::Gui(std::shared_ptr<Window> window) : m_window(window) , m_scene(nullptr) { setupCallbacks(); Init(*window); int width, height; glfwGetFramebufferSize(window->glfw(), &width, &height); onResize(width, height); } Gui::~Gui() { Shutdown(); } void Gui::setScene(std::shared_ptr<Scene> scene) { m_scene = scene; setupDialogs(); } void Gui::beforeLoading() { NewFrame(); ImGui::SetNextWindowSize(ImVec2(m_windowWidth, m_windowHeight)); ImGui::SetNextWindowPos(ImVec2(0.f, 0.f)); ImGui::Begin("Reload", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); ImGui::Text(" "); ImGui::Text(" "); ImGui::Text("Loading scene..."); ImGui::End(); DrawFrame(); if (auto window = m_window.lock()) { glfwSwapBuffers(window->glfw()); } } void Gui::afterLoading() { if (auto window = m_window.lock()) { int width, height; glfwGetFramebufferSize(window->glfw(), &width, &height); onResize(width, height); } m_startTime = static_cast<float>(glfwGetTime()); setupDialogs(); } void Gui::setupDialogs() { m_dialogGroups.clear(); if (m_scene) { addDialogGroup<DeferredShadingDialog>("Deferred Shading", m_scene->deferredShader()); addDialogGroup<WorldDialog>("World", m_scene->world()); addDialogGroup<GlobalTimerDialo
void Gui::update() { updateImGui(); if (m_scene) { m_scene->update(static_cast<float>(glfwGetTime()) - m_startTime); if (auto window = m_window.lock()) { if (m_scene->mustQuit()) { glfwSetWindowShouldClose(window->glfw(), GL_TRUE); } } } } void Gui::updateImGui() { NewFrame(); ImVec4 clear_color = ImColor(114, 144, 154); static float f = 0.0f; ImGui::SetNextWindowPos(ImVec2(0.f, 0.f)); ImGui::SetNextWindowSize(ImVec2(420.f, 0.f)); ImGui::Begin("Framerate", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); int frame = m_scene ? m_scene->frame() : 0; ImGui::Text("Application average %.3f ms/frame (%.1f FPS) | #%d", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate, frame); ImGui::End(); int dialogId = 0; for (auto & dg : m_dialogGroups) { ImGui::PushID(dialogId++); for (auto d : dg.dialogs) { d->drawHandles(0, 0, m_windowWidth, m_windowHeight); } ImGui::PopID(); } if (m_showPanel) { ImGui::SetNextWindowSize(ImVec2(m_panelWidth, m_windowHeight)); ImGui::SetNextWindowPos(ImVec2(m_windowWidth - m_panelWidth, 0.f)); ImGui::Begin("Dialogs", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); ImGui::PushID(0); int dialogId = 0; bool pressed; for (auto & dg : m_dialogGroups) { ImGui::PushID(dialogId); dialogId += static_cast<int>(dg.dialogs.size()); pressed = ImGui::Selectable(dg.title.c_str(), &dg.enabled); if (pressed && m_isControlPressed == 0) { for (auto & other : m_dialogGroups) { other.enabled = &other == &dg; } } ImGui::PopID(); } ImGui::PopID(); ImGui::PushID(1); dialogId = 0; for (auto & dg : m_dialogGroups) { if (dg.enabled) { for (auto d : dg.dialogs) { ImGui::PushID(dialogId++); d->draw(); ImGui::PopID(); } } else { dialogId += static_cast<int>(dg.dialogs.size()); } } ImGui::PopID(); ImGui::End(); } } void Gui::render() { if (m_scene) { m_scene->render(); } if (!m_scene || m_scene->properties().ui) { glBindFramebuffer(GL_FRAMEBUFFER, 0); DrawFrame(); } if (m_scene) { m_scene->onPostRender(static_cast<float>(glfwGetTime()) - m_startTime); } } void Gui::onResize(int width, int height) { m_windowWidth = static_cast<float>(width); m_windowHeight = static_cast<float>(height); if (auto window = m_window.lock()) { int fbWidth, fbHeight; glfwGetFramebufferSize(window->glfw(), &fbWidth, &fbHeight); glViewport(0, 0, fbWidth, fbHeight); if (m_scene) { m_scene->setResolution(fbWidth, fbHeight); } } } #define forAllCameras(method) \ for (auto& camera : m_scene->cameras()) { \ if (camera->properties().controlInViewport) { \ camera->method(); \ } \ } void Gui::onMouseButton(int button, int action, int mods) { if (m_imguiFocus || !m_scene) { return; } m_isMouseMoveStarted = action == GLFW_PRESS; switch (button) { case GLFW_MOUSE_BUTTON_LEFT: if (action == GLFW_PRESS) { forAllCameras(startMouseRotation); } else { forAllCameras(stopMouseRotation); } break; case GLFW_MOUSE_BUTTON_MIDDLE: if (action == GLFW_PRESS) { forAllCameras(startMouseZoom); } else { forAllCameras(stopMouseZoom); } break; case GLFW_MOUSE_BUTTON_RIGHT: if (action == GLFW_PRESS) { forAllCameras(startMousePanning); } else { forAllCameras(stopMousePanning); } break; } } void Gui::onCursorPosition(double x, double y) { double limit = static_cast<double>(m_windowWidth) - static_cast<double>(m_panelWidth); m_imguiFocus = x >= limit && m_showPanel && !m_isMouseMoveStarted; if (m_imguiFocus) { return; } if (m_scene) { for (auto& camera : m_scene->cameras()) { if (camera->properties().controlInViewport) { camera->updateMousePosition(static_cast<float>(x), static_cast<float>(y)); } } } } void Gui::onScroll(double xoffset, double yoffset) { if (m_imguiFocus) { return; } if (m_scene) { for (auto& camera : m_scene->cameras()) { if (camera->properties().controlInViewport) { camera->zoom(- 2 * static_cast<float>(yoffset)); } } } } void Gui::onKey(int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: if (auto window = getWindow().lock()) { glfwSetWindowShouldClose(window->glfw(), GL_TRUE); } break; case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: ++m_isControlPressed; break; } } if (action == GLFW_RELEASE) { switch (key) { case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: m_isControlPressed = 0; break; } } if (action == GLFW_PRESS && !m_imguiFocus) { switch (key) { case GLFW_KEY_ESCAPE: if (auto window = m_window.lock()) { glfwSetWindowShouldClose(window->glfw(), GL_TRUE); } break; case GLFW_KEY_P: m_showPanel = !m_showPanel; break; case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: ++m_isControlPressed; break; } } if (action == GLFW_PRESS && !m_imguiFocus && m_scene) { switch (key) { case GLFW_KEY_R: if (mods & GLFW_MOD_CONTROL) { beforeLoading(); ShaderPool::Clear(); m_scene->load(m_scene->filename()); afterLoading(); } else { m_scene->reloadShaders(); } break; case GLFW_KEY_U: m_scene->properties().ui = !m_scene->properties().ui; break; case GLFW_KEY_A: forAllCameras(tiltLeft); break; case GLFW_KEY_E: forAllCameras(tiltRight); break; case GLFW_KEY_C: if (mods & GLFW_MOD_CONTROL) { ShaderPool::Clear(); m_scene->clear(); } else { if (m_scene->viewportCamera()) { glm::mat4 m = m_scene->viewportCamera()->viewMatrix(); DEBUG_LOG << "View Matrix: \n" << "[" << m[0][0] << "," << m[0][1] << "," << m[0][2] << "," << m[0][3] << "," << m[1][0] << "," << m[1][1] << "," << m[1][2] << "," << m[1][3] << "," << m[2][0] << "," << m[2][1] << "," << m[2][2] << "," << m[2][3] << "," << m[3][0] << "," << m[3][1] << "," << m[3][2] << "," << m[3][3] << "]"; std::ostringstream ss; m_scene->viewportCamera()->serialize(ss); DEBUG_LOG << ss.str(); } } break; case GLFW_KEY_SPACE: m_scene->togglePause(); break; } } } #undef forAllCameras
g>("Timers", GlobalTimer::GetInstance()); addDialogGroup<SceneDialog>("Scene:", m_scene); for (const auto& obj : m_scene->objects()) { DialogGroup group; group.title = " - " + obj->name; IBehaviorHolder::ConstBehaviorIterator it, end; for (it = obj->cbeginBehaviors(), end = obj->cendBehaviors(); it != end; ++it) { auto dialog = makeComponentDialog(it->first, it->second); if (dialog) { group.dialogs.push_back(dialog); } } m_dialogGroups.push_back(group); } } }
function_block-function_prefixed
[ { "content": "class DeferredShadingDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid drawHandles(float x, float y, float w, float h) override;\n\n\tvoid setController(std::weak_ptr<GlDeferredShader> shading) { m_cont = shading; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<GlDeferredShader> m_cont;\n\n};\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.h", "rank": 0, "score": 250529.7370123773 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#pragma once\n\n\n\n#include \"Dialog.h\"\n\n#include \"GlDeferredShader.h\"\n\n\n\n#include <memory>\n\n\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.h", "rank": 1, "score": 209794.68330255308 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.h", "rank": 2, "score": 209792.60358511625 }, { "content": "class GlDeferredShader;\n", "file_path": "src/GrainViewer/Scene.h", "rank": 3, "score": 209646.06110032668 }, { "content": "class SceneDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setController(std::weak_ptr<Scene> scene) { m_cont = scene; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<Scene> m_cont;\n\n};\n", "file_path": "src/GrainViewer/Ui/SceneDialog.h", "rank": 4, "score": 209115.00366870622 }, { "content": "class Window;\n", "file_path": "src/GrainViewer/Ui/Gui.h", "rank": 5, "score": 207104.15554968888 }, { "content": "class Scene;\n", "file_path": "src/GrainViewer/Ui/Gui.h", "rank": 6, "score": 207016.34915488012 }, { "content": "class Dialog;\n\n\n\n#include <string>\n\n#include <vector>\n\n#include <memory>\n\n\n", "file_path": "src/GrainViewer/Ui/Gui.h", "rank": 7, "score": 206854.80552042165 }, { "content": "struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleObjectType,\n\n typename = void>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 8, "score": 203812.99383772598 }, { "content": "{\n\n\tif (auto cont = m_cont.lock()) {\n\n\t\tif (ImGui::CollapsingHeader(\"Deferred Shading\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\n\t\t\tGlDeferredShader::Properties & props = cont->properties();\n\n\n\n\t\t\tautoUi(props);\n\n\t\t\tImGui::Text(\"Shadow Map Bias: %f\", props.ShadowMapBias());\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid DeferredShadingDialog::drawHandles(float x, float y, float w, float h)\n\n{\n\n\tif (auto cont = m_cont.lock()) {\n\n\t\tGlDeferredShader::Properties & props = cont->properties();\n\n\n\n\t\tif (props.showSampleCount) {\n\n\t\t\tImGui::SetNextWindowPos(ImVec2(x, y + h - 60));\n\n\t\t\tImGui::SetNextWindowSize(ImVec2(540, 60));\n\n\t\t\tImGui::Begin(\"DeferredShadingDialog Handle\", nullptr,\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.cpp", "rank": 9, "score": 202421.22076512894 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#include \"DeferredShadingDialog.h\"\n\n#include \"utils/guiutils.h\"\n\n#include \"utils/behaviorutils.h\"\n\n#include \"GlTexture.h\"\n\n\n\n#include <glm/gtc/type_ptr.hpp>\n\n\n\n#include <limits>\n\n#include <imgui.h>\n\n\n\nvoid DeferredShadingDialog::draw()\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.cpp", "rank": 10, "score": 202414.80137244772 }, { "content": "\t\t\t\tImGuiWindowFlags_NoResize |\n\n\t\t\t\tImGuiWindowFlags_NoMove |\n\n\t\t\t\tImGuiWindowFlags_NoCollapse |\n\n\t\t\t\tImGuiWindowFlags_NoTitleBar);\n\n\t\t\t\n\n\t\t\tif (cont->hasColorMap()) {\n\n\t\t\t\tconst float spacing = ImGui::GetStyle().ItemSpacing.x;\n\n\n\n\t\t\t\tGLuint tex = cont->colormap().raw();\n\n\t\t\t\tImGui::Image((void*)(intptr_t)tex, ImVec2(540 - 2 * spacing, 20));\n\n\t\t\t\tImGui::Text(\"0\");\n\n\t\t\t\t\n\n\t\t\t\tstatic float inputWidth = 30.0f;\n\n\t\t\t\tImGui::SameLine(ImGui::GetWindowWidth() - spacing - inputWidth);\n\n\t\t\t\tImGui::PushItemWidth(inputWidth);\n\n\t\t\t\tImGui::InputFloat(\"##maxSampleCount\", &props.maxSampleCount, 0, 0, \"%.0f\");\n\n\t\t\t\tinputWidth = ImGui::GetItemRectSize().x;\n\n\t\t\t}\n\n\n\n\t\t\tImGui::End();\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.cpp", "rank": 11, "score": 202409.96164780163 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Ui/DeferredShadingDialog.cpp", "rank": 12, "score": 202407.67311384843 }, { "content": "class Window;\n\n\n\n#include <string>\n\n#include <vector>\n\n#include <memory>\n\n\n\n/**\n\n * Gui for tests, displaying a progress bar and some debug info\n\n */\n", "file_path": "src/GrainViewer/Ui/TestGui.h", "rank": 13, "score": 200788.8140703006 }, { "content": "struct underlying_type<T, true> : std::underlying_type<std::decay_t<T>> {};\n\n\n\ntemplate <typename E, bool = is_enum_v<E>>\n", "file_path": "src/External/refl-cpp/include/magic_enum.hpp", "rank": 14, "score": 187948.61908053723 }, { "content": "class GlDeferredShader {\n\npublic:\n\n\tenum ShadingMode {\n\n\t\tBeautyPass,\n\n\t\tNormalPass,\n\n\t\tBaseColorPass,\n\n\t\tMetallicPass,\n\n\t\tRoughnessPass,\n\n\t\tWorldPositionPass,\n\n\t\tDepthPass,\n\n\t\tRawGBuffer0,\n\n\t\tRawGBuffer1,\n\n\t\tRawGBuffer2,\n\n\t};\n\n\tstruct Properties {\n\n\t\tShadingMode shadingMode = BeautyPass;\n\n\t\tbool transparentFilm = false;\n\n\t\tbool showSampleCount = false;\n\n\t\tfloat maxSampleCount = 10;\n\n\t\tbool debugVectors = false;\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 15, "score": 181480.2010682164 }, { "content": " stbi_io_callbacks io;\n", "file_path": "src/External/tinygltf/include/stb_image.h", "rank": 16, "score": 181177.0912757329 }, { "content": " stbi__uint32 type;\n", "file_path": "src/External/tinygltf/include/stb_image.h", "rank": 17, "score": 181064.29677016204 }, { "content": "class Camera {\n\npublic:\n\n\tenum ProjectionType {\n\n\t\tPerspectiveProjection,\n\n\t\tOrthographicProjection,\n\n\t};\n\n\tstruct OutputSettings {\n\n\t\tbool autoOutputResolution = true;\n\n\t\tint width;\n\n\t\tint height;\n\n\t\tstd::string outputFrameBase;\n\n\t\tbool isRecordEnabled = false;\n\n\t\tbool saveOnDisc = true; // if false, get pixel data from gpu but don't actually write them to disc. They can be used to measure stats\n\n\t};\n", "file_path": "src/GrainViewer/Camera.h", "rank": 18, "score": 179478.70305060587 }, { "content": "class Scene {\n\npublic:\n\n\tScene();\n\n\n\n\tbool load(const std::string & filename);\n\n\tconst std::string & filename() const { return m_filename; }\n\n\n\n\tvoid setResolution(int width, int height);\n\n\t\n\n\tvoid reloadShaders();\n\n\tvoid update(float time);\n\n\tvoid render() const;\n\n\tvoid onPostRender(float time);\n\n\n\n\t// Clear scene\n\n\tvoid clear();\n\n\n\n\tstd::shared_ptr<Camera> viewportCamera() const;\n\n\tinline const std::vector<std::shared_ptr<RuntimeObject>> & objects() const { return m_objects; }\n\n\tinline const std::vector<std::shared_ptr<Camera>>& cameras() const { return m_cameras; }\n", "file_path": "src/GrainViewer/Scene.h", "rank": 19, "score": 179478.70305060587 }, { "content": "class Shader {\n\npublic:\n\n Shader(GLenum shaderType = 0);\n\n ~Shader();\n\n\n\n /**\n\n * Load file into the shader\n\n * @param filename Shader file\n\n */\n\n bool load(const std::string &filename, const std::vector<std::string> & defines = {}, const std::map<std::string, std::string> & snippets = {});\n\n\n\n /**\n\n * Compile the shader\n\n */\n\n inline void compile() { glCompileShader(m_shaderId); }\n\n\n\n /**\n\n * Check that the shader has been successfully compiled\n\n * @param name Name displayed in error message\n\n * @param success status\n", "file_path": "src/GrainViewer/Shader.h", "rank": 20, "score": 179385.88006071266 }, { "content": "class Window {\n\npublic:\n\n\tWindow(int width, int height, const char *title);\n\n\t~Window();\n\n\n\n\t/**\n\n\t * @return the raw GLFWwindow object, or nullptr if initialization failed.\n\n\t */\n\n\tGLFWwindow *glfw() const;\n\n\n\n\t/**\n\n\t * @return true iff window has correctly been initialized\n\n\t */\n\n\tbool isValid() const;\n\n\n\n\tvoid pollEvents() const;\n\n\tvoid swapBuffers() const;\n\n\tbool shouldClose() const;\n\n\n\nprivate:\n\n\tGLFWwindow *m_window = nullptr;\n\n};\n", "file_path": "src/GrainViewer/Ui/Window.h", "rank": 21, "score": 174881.95420636336 }, { "content": "class Gui {\n\npublic:\n\n\t// For tools that don't use the main Gui\n\n\tstatic void Init(const Window & window);\n\n\tstatic void NewFrame();\n\n\tstatic void DrawFrame();\n\n\tstatic void Shutdown();\n\npublic:\n\n\tGui(std::shared_ptr<Window> window);\n\n\t~Gui();\n\n\n\n\tvoid setScene(std::shared_ptr<Scene> scene);\n\n\n\n\t// Call these resp. before and after loading the scene\n\n\tvoid beforeLoading();\n\n\tvoid afterLoading();\n\n\n\n\tvoid update();\n\n\tvoid render();\n\n\n", "file_path": "src/GrainViewer/Ui/Gui.h", "rank": 22, "score": 174798.8067738239 }, { "content": "class Dialog {\n\npublic:\n\n\t/**\n\n\t * Draw panel (in right-hand side bar).\n\n\t */\n\n\tvirtual void draw() {}\n\n\n\n\t/**\n\n\t * Draw on top of 3D render\n\n\t * x, y, w, h is the viewport rect\n\n\t */\n\n\tvirtual void drawHandles(float x, float y, float w, float h) {}\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "src/GrainViewer/Ui/Dialog.h", "rank": 23, "score": 174591.76059389743 }, { "content": "\t\tfloat debugVectorsScale = 0.1f;\n\n\t\tfloat debugVectorsGrid = 20.0f;\n\n\t\tfloat shadowMapBiasBase = 0.1f;\n\n\t\tint shadowMapBiasExponent = -5;\n\n\n\n\t\tfloat ShadowMapBias() const;\n\n\t};\n\npublic:\n\n\tGlDeferredShader();\n\n\t~GlDeferredShader();\n\n\n\n\tvoid bindFramebuffer(const Camera& camera) const;\n\n\n\n\tbool deserialize(const rapidjson::Value & json);\n\n\tvoid reloadShaders();\n\n\tvoid update(float time);\n\n\n\n\tvoid render(const Camera & camera, const World & world, RenderType target) const;\n\n\n\n\tProperties & properties() { return m_properties; }\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 24, "score": 172989.04525076345 }, { "content": "\tconst Properties & properties() const { return m_properties; }\n\n\n\n\tbool hasColorMap() const { return m_colormap != nullptr; }\n\n\t// Use only if hasColorMap is truc\n\n\tconst GlTexture & colormap() const { return *m_colormap; }\n\n\n\n\tvoid setBlitOffset(GLint x, GLint y) { m_blitOffset = glm::vec2(static_cast<float>(x), static_cast<float>(y)); }\n\n\n\nprivate:\n\n\tProperties m_properties;\n\n\tShaderProgram m_shader, m_debugShader;\n\n\tGLuint m_vao;\n\n\tstd::unique_ptr<GlTexture> m_colormap; // colormap used as ramp for outputting debug images\n\n\tglm::vec2 m_blitOffset = glm::vec2(0.0f); // offset when writing to output framebuffer\n\n};\n\n\n\n#define _ ReflectionAttributes::\n\nREFL_TYPE(GlDeferredShader::Properties)\n\nREFL_FIELD(shadingMode)\n\nREFL_FIELD(transparentFilm)\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 25, "score": 172987.57054615513 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 26, "score": 172979.9455604596 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#pragma once\n\n\n\n#include \"ShaderProgram.h\"\n\n#include \"Framebuffer.h\"\n\n#include \"Camera.h\"\n\n#include \"World.h\"\n\n#include \"RenderType.h\"\n\n#include \"utils/ReflectionAttributes.h\"\n\n\n\n#include <glm/glm.hpp>\n\n#include <rapidjson/document.h>\n\n#include <refl.hpp>\n\n\n\n#include <vector>\n\n#include <memory>\n\n\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 27, "score": 172979.28813583872 }, { "content": "REFL_FIELD(showSampleCount)\n\nREFL_FIELD(maxSampleCount, _ HideInDialog())\n\nREFL_FIELD(debugVectors)\n\nREFL_FIELD(debugVectorsScale, _ Range(0, 2))\n\nREFL_FIELD(debugVectorsGrid, _ Range(0, 40))\n\nREFL_FIELD(shadowMapBiasBase)\n\nREFL_FIELD(shadowMapBiasExponent, _ Range(-8, 2))\n\nREFL_END\n\n#undef _\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 28, "score": 172960.59679267445 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Ui/SceneDialog.h", "rank": 29, "score": 172940.61734253404 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#pragma once\n\n\n\n#include \"Dialog.h\"\n\n#include \"Scene.h\"\n\n\n\n#include <memory>\n\n\n", "file_path": "src/GrainViewer/Ui/SceneDialog.h", "rank": 30, "score": 172939.12680145647 }, { "content": "struct is_scoped_enum<T, true> : std::bool_constant<!std::is_convertible_v<T, std::underlying_type_t<T>>> {};\n\n\n\ntemplate <typename T, bool = std::is_enum_v<T>>\n", "file_path": "src/External/refl-cpp/include/magic_enum.hpp", "rank": 31, "score": 170124.9516092033 }, { "content": "struct is_unscoped_enum<T, true> : std::bool_constant<std::is_convertible_v<T, std::underlying_type_t<T>>> {};\n\n\n\ntemplate <typename T, bool = std::is_enum_v<std::decay_t<T>>>\n", "file_path": "src/External/refl-cpp/include/magic_enum.hpp", "rank": 32, "score": 170124.9516092033 }, { "content": "class GrainBehaviorDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<GrainBehavior> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<GrainBehavior> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(GrainBehaviorDialog, GrainBehavior)\n", "file_path": "src/GrainViewer/Ui/GrainBehaviorDialog.h", "rank": 33, "score": 169898.25240448213 }, { "content": "struct DialogFactory<BehaviorType> { \\\n\n\tstatic std::shared_ptr<DialogType> MakeShared() { return std::make_shared<DialogType>(); } \\\n\n};\n\n\n", "file_path": "src/GrainViewer/Ui/Dialog.h", "rank": 34, "score": 168321.16975719662 }, { "content": "\n\n\treturn true;\n\n}\n\n\n\nvoid GlDeferredShader::bindFramebuffer(const Camera& camera) const\n\n{\n\n\tauto fbo = camera.getExtraFramebuffer(Camera::ExtraFramebufferOption::GBufferDepth);\n\n\tfbo->bind();\n\n}\n\n\n\nvoid GlDeferredShader::reloadShaders()\n\n{\n\n\tm_shader.load();\n\n\tm_debugShader.load();\n\n}\n\n\n\nvoid GlDeferredShader::update(float time)\n\n{\n\n\tm_shader.setUniform(\"uTime\", static_cast<GLfloat>(time));\n\n\tm_debugShader.setUniform(\"uTime\", static_cast<GLfloat>(time));\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 35, "score": 166686.14758300834 }, { "content": "}\n\n\n\nvoid GlDeferredShader::render(const Camera & camera, const World & world, RenderType target) const\n\n{\n\n\tauto fbo = camera.getExtraFramebuffer(Camera::ExtraFramebufferOption::GBufferDepth);\n\n\n\n\tglClearColor(0.2f, 0.3f, 0.3f, 1.0f);\n\n\t//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglDepthMask(GL_TRUE);\n\n\tglDisable(GL_DEPTH_TEST);\n\n\tglDisable(GL_BLEND);\n\n\n\n\tconst ShaderProgram& shader = properties().debugVectors ? m_debugShader : m_shader;\n\n\n\n\tshader.bindUniformBlock(\"Camera\", camera.ubo());\n\n\n\n\tshader.setUniform(\"uBlitOffset\", m_blitOffset);\n\n\n\n\tGLint o = 0;\n\n\tfor (int i = 0; i < fbo->colorTextureCount(); ++i) {\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 36, "score": 166672.000150556 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 37, "score": 166668.84289122792 }, { "content": "\t\tshader.setUniform(MAKE_STR(\"gbuffer\" << i), o);\n\n\t\tglBindTextureUnit(static_cast<GLuint>(o), fbo->colorTexture(i));\n\n\t\t++o;\n\n\t}\n\n\n\n\tshader.setUniform(\"in_depth\", o);\n\n\tglBindTextureUnit(static_cast<GLuint>(o), fbo->depthTexture());\n\n\t++o;\n\n\n\n\t// TODO: Use UBO, move to World\n\n\tauto lights = world.lights();\n\n\tfor (size_t k = 0; k < lights.size(); ++k) {\n\n\t\tstd::string prefix = MAKE_STR(\"light[\" << k << \"].\");\n\n\t\tshader.setUniform(prefix + \"position_ws\", lights[k]->position());\n\n\t\tshader.setUniform(prefix + \"color\", lights[k]->color());\n\n\t\tshader.setUniform(prefix + \"matrix\", lights[k]->shadowMap().camera().projectionMatrix() * lights[k]->shadowMap().camera().viewMatrix());\n\n\t\tshader.setUniform(prefix + \"isRich\", lights[k]->isRich() ? 1 : 0);\n\n\t\tshader.setUniform(prefix + \"hasShadowMap\", lights[k]->hasShadowMap() ? 1 : 0);\n\n\t\tshader.setUniform(prefix + \"shadowMap\", o);\n\n\t\tglBindTextureUnit(static_cast<GLuint>(o), lights[k]->shadowMap().depthTexture());\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 38, "score": 166667.82583581816 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#include \"Logger.h\"\n\n#include \"GlDeferredShader.h\"\n\n#include \"Light.h\"\n\n#include \"ShadowMap.h\"\n\n#include \"ResourceManager.h\"\n\n#include \"GlTexture.h\"\n\n#include \"utils/strutils.h\"\n\n#include \"utils/jsonutils.h\"\n\n#include \"utils/behaviorutils.h\"\n\n#include \"Framebuffer.h\"\n\n\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 39, "score": 166665.28646380216 }, { "content": "bool GlDeferredShader::deserialize(const rapidjson::Value & json)\n\n{\n\n\tif (!json.IsObject()) return false;\n\n\n\n\tstd::vector<std::string> defines;\n\n\tif (jrOption(json, \"defines\", defines)) {\n\n\t\tfor (const auto& def : defines) {\n\n\t\t\tm_shader.define(def);\n\n\t\t\tm_debugShader.define(def);\n\n\t\t}\n\n\t}\n\n\tm_debugShader.define(\"DEBUG_VECTORS\");\n\n\n\n\tstd::string colormapFilename;\n\n\tif (jrOption(json, \"colormap\", colormapFilename)) {\n\n\t\tm_colormap = ResourceManager::loadTexture(colormapFilename);\n\n\t\tm_colormap->setWrapMode(GL_CLAMP_TO_EDGE);\n\n\t}\n\n\n\n\tautoDeserialize(json, m_properties);\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 40, "score": 166664.32596965984 }, { "content": "#include <vector>\n\n#include <sstream>\n\n\n\nfloat GlDeferredShader::Properties::ShadowMapBias() const\n\n{\n\n\treturn shadowMapBiasBase * static_cast<float>(pow(10, shadowMapBiasExponent));\n\n}\n\n\n\nGlDeferredShader::GlDeferredShader()\n\n\t: m_shader(\"deferred-shader\")\n\n\t, m_debugShader(\"deferred-shader\")\n\n{\n\n\tglCreateVertexArrays(1, &m_vao);\n\n}\n\n\n\nGlDeferredShader::~GlDeferredShader()\n\n{\n\n\tglDeleteVertexArrays(1, &m_vao);\n\n}\n\n\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 41, "score": 166663.19505028406 }, { "content": "\t\t++o;\n\n\t\tif (lights[k]->isRich()) {\n\n\t\t\tshader.setUniform(prefix + \"richShadowMap\", o);\n\n\t\t\tglBindTextureUnit(static_cast<GLuint>(o), lights[k]->shadowMap().colorTexture(0));\n\n\t\t\t++o;\n\n\t\t}\n\n\t}\n\n\n\n\tshader.setUniform(\"uIsShadowMapEnabled\", world.isShadowMapEnabled());\n\n\n\n\tautoSetUniforms(shader, m_properties);\n\n\tshader.setUniform(\"uShadowMapBias\", m_properties.ShadowMapBias());\n\n\n\n\tshader.setUniform(\"uHasColormap\", static_cast<bool>(m_colormap));\n\n\tif (m_colormap) {\n\n\t\tshader.setUniform(\"uColormap\", static_cast<GLint>(o));\n\n\t\tm_colormap->bind(static_cast<GLuint>(o));\n\n\t\t++o;\n\n\t}\n\n\n\n\tshader.use();\n\n\tglBindVertexArray(m_vao);\n\n\tglDrawArrays(GL_POINTS, 0, 1);\n\n\tglBindVertexArray(0);\n\n}\n", "file_path": "src/GrainViewer/GlDeferredShader.cpp", "rank": 42, "score": 166658.97114598923 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#include \"SceneDialog.h\"\n\n#include \"Light.h\"\n\n#include \"utils/guiutils.h\"\n\n#include \"utils/behaviorutils.h\"\n\n\n\n#include <imgui.h>\n\n#include <glm/gtc/type_ptr.hpp>\n\n\n\nvoid SceneDialog::draw()\n\n{\n\n\tif (auto cont = m_cont.lock()) {\n", "file_path": "src/GrainViewer/Ui/SceneDialog.cpp", "rank": 43, "score": 166636.71822644307 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Ui/SceneDialog.cpp", "rank": 44, "score": 166630.94977337035 }, { "content": "\t\tif (ImGui::CollapsingHeader(\"Scene\", ImGuiTreeNodeFlags_DefaultOpen)) {\n\n\t\t\tif (ImGui::Button(\"Take Screenshot\")) {\n\n\t\t\t\tcont->takeScreenshot();\n\n\t\t\t}\n\n\n\n\t\t\tif (cont->isPaused()) {\n\n\t\t\t\tif (ImGui::Button(\"Play\")) {\n\n\t\t\t\t\tcont->play();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tif (ImGui::Button(\"Pause\")) {\n\n\t\t\t\t\tcont->pause();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\tautoUi(cont->properties());\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "src/GrainViewer/Ui/SceneDialog.cpp", "rank": 45, "score": 166630.41586401346 }, { "content": "class ImpostorGrainRendererDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<ImpostorGrainRenderer> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<ImpostorGrainRenderer> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(ImpostorGrainRendererDialog, ImpostorGrainRenderer)\n", "file_path": "src/GrainViewer/Ui/ImpostorGrainRendererDialog.h", "rank": 46, "score": 164493.0947507245 }, { "content": "class InstanceGrainRendererDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<InstanceGrainRenderer> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<InstanceGrainRenderer> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(InstanceGrainRendererDialog, InstanceGrainRenderer)\n", "file_path": "src/GrainViewer/Ui/InstanceGrainRendererDialog.h", "rank": 47, "score": 164493.09475072453 }, { "content": "class FarGrainRendererDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<FarGrainRenderer> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<FarGrainRenderer> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(FarGrainRendererDialog, FarGrainRenderer)\n", "file_path": "src/GrainViewer/Ui/FarGrainRendererDialog.h", "rank": 48, "score": 164493.0947507245 }, { "content": "class GlTexture;\n\n\n", "file_path": "src/GrainViewer/GlDeferredShader.h", "rank": 49, "score": 160774.8606524287 }, { "content": "class TurntableCamera : public Camera {\n\npublic:\n\n\tTurntableCamera();\n\n\n\n\tvoid update(float time) override {}\n\n\n\n\tvoid deserialize(const rapidjson::Value& json, const EnvironmentVariables& env, std::shared_ptr<AnimationManager> animations) override;\n\n\tstd::ostream& serialize(std::ostream& out) override;\n\n\n\nprotected:\n\n\tvoid updateDeltaMouseRotation(float x1, float y1, float x2, float y2) override;\n\n\tvoid updateDeltaMouseZoom(float x1, float y1, float x2, float y2) override;\n\n\tvoid updateDeltaMousePanning(float x1, float y1, float x2, float y2) override;\n\n\tvoid tilt(float theta);\n\n\n\nprivate:\n\n\t/**\n\n\t* Construct view matrix given quat, center and zoom\n\n\t*/\n\n\tvoid updateViewMatrix();\n\n\n\nprivate:\n\n\tglm::vec3 m_center;\n\n\tglm::quat m_quat;\n\n\tfloat m_zoom;\n\n\tfloat m_sensitivity; // relative to screen size\n\n\tfloat m_zoomSensitivity;\n\n};\n\n\n", "file_path": "src/GrainViewer/TurntableCamera.h", "rank": 50, "score": 160737.13590302636 }, { "content": "class WorldDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setController(std::weak_ptr<World> world) { m_cont = world; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<World> m_cont;\n\n};\n", "file_path": "src/GrainViewer/Ui/WorldDialog.h", "rank": 51, "score": 157119.01909388174 }, { "content": "class TransformDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<TransformBehavior> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<TransformBehavior> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(TransformDialog, TransformBehavior)\n", "file_path": "src/GrainViewer/Ui/TransformDialog.h", "rank": 52, "score": 157119.01909388174 }, { "content": "struct enum_traits<E, true> {\n\n using type = E;\n\n using underlying_type = typename detail::underlying_type<E>::type;\n\n\n\n inline static constexpr std::string_view type_name = detail::type_name_v<E>;\n\n\n\n inline static constexpr bool is_unscoped = detail::is_unscoped_enum<E>::value;\n\n inline static constexpr bool is_scoped = detail::is_scoped_enum<E>::value;\n\n inline static constexpr bool is_dense = detail::range_size_v<E> == detail::count_v<E>;\n\n inline static constexpr bool is_sparse = detail::range_size_v<E> != detail::count_v<E>;\n\n\n\n inline static constexpr std::size_t count = detail::count_v<E>;\n\n inline static constexpr std::array<E, count> values = detail::values_v<E>;\n\n inline static constexpr std::array<std::string_view, count> names = detail::names<E>(std::make_index_sequence<count_v<E>>{});\n\n inline static constexpr std::array<std::pair<E, std::string_view>, count> entries = detail::entries<E>(std::make_index_sequence<count_v<E>>{});\n\n\n\n [[nodiscard]] static constexpr bool reflected(E value) noexcept {\n\n return reflected(static_cast<U>(value));\n\n }\n\n\n", "file_path": "src/External/refl-cpp/include/magic_enum.hpp", "rank": 53, "score": 156495.00777940036 }, { "content": "struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};\n\n\n\n//////////////////////////\n\n// aliases for detected //\n\n//////////////////////////\n\n\n\ntemplate <typename T>\n\nusing mapped_type_t = typename T::mapped_type;\n\n\n\ntemplate <typename T>\n\nusing key_type_t = typename T::key_type;\n\n\n\ntemplate <typename T>\n\nusing value_type_t = typename T::value_type;\n\n\n\ntemplate <typename T>\n\nusing difference_type_t = typename T::difference_type;\n\n\n\ntemplate <typename T>\n\nusing pointer_t = typename T::pointer;\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 54, "score": 152025.6246818939 }, { "content": "class LightGizmoDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<LightGizmo> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<LightGizmo> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(LightGizmoDialog, LightGizmo)\n", "file_path": "src/GrainViewer/Ui/LightGizmoDialog.h", "rank": 55, "score": 150749.98916862626 }, { "content": "class MeshRendererDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<MeshRenderer> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<MeshRenderer> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(MeshRendererDialog, MeshRenderer)\n", "file_path": "src/GrainViewer/Ui/MeshRendererDialog.h", "rank": 56, "score": 150749.98916862626 }, { "content": "class GlobalTimerDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setController(std::weak_ptr<GlobalTimer> timer) { m_cont = timer; }\n\n\tvoid drawHandles(float x, float y, float w, float h);\n\n\n\nprivate:\n\n\tstd::weak_ptr<GlobalTimer> m_cont;\n\n};\n", "file_path": "src/GrainViewer/Ui/GlobalTimerDialog.h", "rank": 57, "score": 150749.98916862626 }, { "content": " int x,y,w2,h2;\n", "file_path": "src/External/tinygltf/include/stb_image.h", "rank": 58, "score": 146951.81384128655 }, { "content": "struct is_complete_type : std::false_type {};\n\n\n\ntemplate <typename T>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 59, "score": 146934.0665825149 }, { "content": "enum class RenderType\n\n{\n\n\t/**\n\n\t * Direct rendering, without deferred shading\n\n\t */\n\n\tDirect,\n\n\n\n\t/**\n\n\t * Default render type (deferred shading)\n\n\t */\n\n\tDefault,\n\n\n\n\t/**\n\n\t * Shadow map rendering, only depth matters\n\n\t */\n\n\tShadowMap,\n", "file_path": "src/GrainViewer/RenderType.h", "rank": 60, "score": 146254.91946517082 }, { "content": "bool checkShader(GLuint shader, const char *name);\n", "file_path": "src/GrainViewer/utils/shader.h", "rank": 61, "score": 146192.33506331695 }, { "content": "class QuadMeshDataDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<QuadMeshData> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<QuadMeshData> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(QuadMeshDataDialog, QuadMeshData)\n", "file_path": "src/GrainViewer/Ui/QuadMeshDataDialog.h", "rank": 62, "score": 145019.7718030954 }, { "content": "class PointCloudSplitterDialog : public Dialog {\n\npublic:\n\n\tvoid draw() override;\n\n\tvoid setControlledBehavior(std::weak_ptr<PointCloudSplitter> behavior) { m_cont = behavior; }\n\n\n\nprivate:\n\n\tstd::weak_ptr<PointCloudSplitter> m_cont;\n\n};\n\n\n\nregisterDialogForBehavior(PointCloudSplitterDialog, PointCloudSplitter)\n", "file_path": "src/GrainViewer/Ui/PointCloudSplitterDialog.h", "rank": 63, "score": 145019.7718030954 }, { "content": "struct is_compatible_type_impl: std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 64, "score": 143688.56118836752 }, { "content": "registerSerializationType(int)\n", "file_path": "src/GrainViewer/SerializationType.h", "rank": 65, "score": 143164.8784430084 }, { "content": "class ExportCameraMatrixBuffer(Operator, ExportHelper):\n\n \"\"\"Export the camera view matrix as a raw binary buffer\"\"\"\n\n bl_idname = \"export.camera_matrix_buffer\" # important since its how bpy.ops.import_test.some_data is constructed\n\n bl_label = \"Export Camera Matrix Buffer\"\n\n\n\n filename_ext = \".bin\"\n\n\n\n filter_glob: StringProperty(\n\n default=\"*.bin\",\n\n options={'HIDDEN'},\n\n maxlen=255, # Max internal buffer length, longer would be clamped.\n\n )\n\n\n\n def execute(self, context):\n", "file_path": "share/scripts/blender_export_transform_matrix.py", "rank": 66, "score": 142648.60119484775 }, { "content": "\t// These must match defines in the shader (magic_enum reflexion is used to set defines)\n\n\t// the first one mirrors RenderTypeCaching (which is for diaplay)\n\n\tenum class RenderTypeShaderVariant {\n\n\t\tRENDER_TYPE_FORGET,\n\n\t\tRENDER_TYPE_CACHE,\n\n\t\tRENDER_TYPE_PRECOMPUTE,\n\n\t};\n", "file_path": "src/GrainViewer/Behavior/PointCloudSplitter.h", "rank": 67, "score": 140875.7801466399 }, { "content": "struct is_compatible_array_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleArrayType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 68, "score": 140617.5075502597 }, { "content": "struct is_compatible_integer_type_impl : std::false_type {};\n\n\n\ntemplate <typename RealIntegerType, typename CompatibleNumberIntegerType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 69, "score": 140617.5075502597 }, { "content": "struct is_compatible_object_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleObjectType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 70, "score": 140617.5075502597 }, { "content": "struct is_constructible_object_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleObjectType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 71, "score": 140617.5075502597 }, { "content": "struct is_constructible_array_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleArrayType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 72, "score": 140617.5075502597 }, { "content": "struct is_constructible_string_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 73, "score": 140617.5075502597 }, { "content": "struct is_compatible_string_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleStringType>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 74, "score": 140617.5075502597 }, { "content": "\n\n\tstd::shared_ptr<World> world() { return m_world; }\n\n\tstd::shared_ptr<GlDeferredShader> deferredShader() { return m_deferredShader; }\n\n\n\n\tbool mustQuit() const { return m_mustQuit; }\n\n\tint frame() const { return m_frameIndex; }\n\n\n\n\tstd::shared_ptr<RuntimeObject> findObjectByName(const std::string& name);\n\n\n\n\tvoid takeScreenshot() const;\n\n\tvoid play();\n\n\tvoid pause();\n\n\tvoid togglePause();\n\n\tbool isPaused() const;\n\n\n\npublic:\n\n\tstruct Properties {\n\n\t\tbool freezeOcclusionCamera = false;\n\n\t\tbool realTime = false;\n\n\t\tbool ui = true;\n", "file_path": "src/GrainViewer/Scene.h", "rank": 75, "score": 138909.87142259564 }, { "content": "\tfloat m_timeOffset = 0.0f;\n\n\tbool m_paused = false;\n\n\tfloat m_fps;\n\n\tint m_quitAfterFrame = -1; // -1 to deactivate this feature, otherwise automatically quit the program after the specified frame (usefull for batch rendering)\n\n\tbool m_mustQuit = false;\n\n\n\n\t// Post render stats\n\n\tstd::string m_outputStats; // path to stats file\n\n\tstd::vector<glm::vec3> m_statsCountColors; // colors to count pixels in render\n\n\tstd::ofstream m_outputStatsFile;\n\n\n\n\t// Not really related to the scene, save window resolution\n\n\tint m_width;\n\n\tint m_height;\n\n};\n\n\n\nREFL_TYPE(Scene::Properties)\n\nREFL_FIELD(freezeOcclusionCamera)\n\nREFL_FIELD(realTime)\n\nREFL_FIELD(ui)\n\nREFL_END\n", "file_path": "src/GrainViewer/Scene.h", "rank": 76, "score": 138902.5251753407 }, { "content": "\tProperties m_properties;\n\n\tstd::string m_filename;\n\n\tstd::shared_ptr<World> m_world;\n\n\tstd::shared_ptr<GlDeferredShader> m_deferredShader;\n\n\tint m_viewportCameraIndex;\n\n\tint m_occlusionCameraIndex;\n\n\tbool m_wasFreezeOcclusionCamera = false;\n\n\tstd::vector<std::shared_ptr<Camera>> m_cameras;\n\n\tstd::vector<std::shared_ptr<RuntimeObject>> m_objects;\n\n\tstd::shared_ptr<AnimationManager> m_animationManager;\n\n\tbool m_isDeferredShadingEnabled = true;\n\n\n\n\t// Framebuffer used before writing image if the output resolution is different from camera resolution\n\n\tmutable std::unique_ptr<Framebuffer> m_outputFramebuffer; // lazyly allocated in recordFrame\n\n\tint m_frameIndex = -1;\n\n\t// TODO: wrap those data into proper logic/class\n\n\tstd::vector<uint8_t> m_pixels;\n\n\tmutable std::vector<GLfloat> m_floatPixels; // for EXR screenshots\n\n\n\n\tfloat m_time;\n", "file_path": "src/GrainViewer/Scene.h", "rank": 77, "score": 138893.65462241997 }, { "content": "\n\n\tinline glm::mat4 viewMatrix() const { return m_uniforms.viewMatrix; }\n\n\tinline void setViewMatrix(glm::mat4 matrix) { m_uniforms.viewMatrix = matrix; } // use with caution\n\n\n\n\tinline glm::mat4 projectionMatrix() const { return m_uniforms.projectionMatrix; }\n\n\tinline void setProjectionMatrix(glm::mat4 matrix) { m_uniforms.projectionMatrix = matrix; } // use with caution\n\n\tvoid setProjectionType(ProjectionType projectionType);\n\n\n\n\tinline glm::vec2 resolution() const { return m_uniforms.resolution; }\n\n\tvoid setResolution(glm::vec2 resolution);\n\n\tinline void setResolution(int w, int h) { setResolution(glm::vec2(static_cast<float>(w), static_cast<float>(h))); }\n\n\tvoid setFreezeResolution(bool freeze);\n\n\n\n\tfloat fov() const { return m_fov; }\n\n\tfloat focalLength() const;\n\n\tvoid setFov(float fov);\n\n\n\n\tfloat nearDistance() const { return m_uniforms.uNear; }\n\n\tvoid setNearDistance(float distance);\n\n\n", "file_path": "src/GrainViewer/Camera.h", "rank": 78, "score": 138885.86192721484 }, { "content": "\n\n\t/**\n\n\t* Called when mouse moves and panning has started\n\n\t* x1, y1: old mouse position\n\n\t* x2, y2: new mouse position\n\n\t*/\n\n\tvirtual void updateDeltaMousePanning(float x1, float y1, float x2, float y2) {}\n\n\n\n\tvirtual void tilt(float theta) {}\n\n\n\nprivate:\n\n\t// Memory layout on GPU, matches shaders/include/uniform/camera.inc.glsl\n\n\tstruct CameraUbo {\n\n\t\tglm::mat4 viewMatrix;\n\n\t\tglm::mat4 projectionMatrix;\n\n\t\tglm::mat4 inverseViewMatrix;\n\n\t\tglm::vec2 resolution;\n\n\t\tfloat uNear = 0.001f;\n\n\t\tfloat uFar = 1000.f;\n\n\t\tfloat uLeft;\n", "file_path": "src/GrainViewer/Camera.h", "rank": 79, "score": 138885.00703478875 }, { "content": "\tinline void stopMousePanning() { m_isMousePanningStarted = false; }\n\n\n\n\tinline void tiltLeft() { tilt(-0.1f); }\n\n\tinline void tiltRight() { tilt(0.1f); }\n\n\n\n\tvoid updateMousePosition(float x, float y);\n\n\n\n\tvirtual void deserialize(const rapidjson::Value & json, const EnvironmentVariables & env, std::shared_ptr<AnimationManager> animations);\n\n\tvirtual std::ostream & serialize(std::ostream & out);\n\n\n\n\t/**\n\n\t * Get a framebuffer that has the same resolution as the camera, to be used\n\n\t * as intermediate step in render. Once you're done with it, release the\n\n\t * framebuffer with releaseExtraFramebuffer(). It is safe to call this\n\n\t * every frame.\n\n\t * TODO: implement a proper dynamic framebuffer pool mechanism\n\n\t */\n\n\tstd::shared_ptr<Framebuffer> getExtraFramebuffer(ExtraFramebufferOption option = ExtraFramebufferOption::Rgba32fDepth) const;\n\n\tvoid releaseExtraFramebuffer(std::shared_ptr<Framebuffer>) const;\n\n\n", "file_path": "src/GrainViewer/Camera.h", "rank": 80, "score": 138884.9571983721 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Camera.h", "rank": 81, "score": 138884.41946057582 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Scene.h", "rank": 82, "score": 138884.41946057582 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#pragma once\n\n\n\n#include <OpenGL>\n\n\n\n#include \"Camera.h\"\n\n#include \"TurntableCamera.h\"\n\n#include \"Framebuffer.h\"\n\n\n\n#include <refl.hpp>\n\n\n\n#include <memory>\n\n#include <vector>\n\n#include <string>\n\n#include <fstream>\n\n#include <sstream>\n\n\n", "file_path": "src/GrainViewer/Scene.h", "rank": 83, "score": 138879.13318322078 }, { "content": "\tbool m_isMouseRotationStarted, m_isMouseZoomStarted, m_isMousePanningStarted;\n\n\tbool m_isLastMouseUpToDate;\n\n\tfloat m_lastMouseX, m_lastMouseY;\n\n\n\n\tbool m_freezeResolution;\n\n\n\n\t// When resolution is freezed, this target framebuffer is allocated at the\n\n\t// fixed resolution and can be bound by the render pipeline\n\n\tstd::shared_ptr<Framebuffer> m_targetFramebuffer;\n\n\n\n\tmutable std::vector<std::shared_ptr<Framebuffer>> m_extraFramebuffers; // lazy initialized\n\n\n\n\tOutputSettings m_outputSettings;\n\n\tProjectionType m_projectionType;\n\n};\n\n\n\n#define _ ReflectionAttributes::\n\nREFL_TYPE(Camera::Properties)\n\nREFL_FIELD(viewRect)\n\nREFL_FIELD(displayInViewport)\n\nREFL_FIELD(controlInViewport)\n\nREFL_FIELD(viewLayers, _ HideInDialog())\n\nREFL_END\n\n#undef _\n", "file_path": "src/GrainViewer/Camera.h", "rank": 84, "score": 138878.51095595016 }, { "content": "\t};\n\n\tProperties& properties() { return m_properties; }\n\n\tconst Properties& properties() const { return m_properties; }\n\n\n\nprivate:\n\n\tvoid renderCamera(const Camera & camera) const;\n\n\tstd::shared_ptr<Camera> occlusionCamera() const;\n\n\tvoid measureStats();\n\n\t// TODO: This should be in another section of the code\n\n\tenum RecordFormat {\n\n\t\tRecordExr,\n\n\t\tRecordPng,\n\n\t};\n\n\t// Return the number of pixels in output images\n\n\tsize_t getOutputPixelCount(const Camera& camera) const;\n\n\tvoid recordFrame(const Camera & camera, const std::string & filename, RecordFormat format) const;\n\n\t// Record frame only if enabled in camera options\n\n\tvoid recordFrame(const Camera & camera) const;\n\n\n\nprivate:\n", "file_path": "src/GrainViewer/Scene.h", "rank": 85, "score": 138877.77041112236 }, { "content": "\t\tfloat uRight;\n\n\t\tfloat uTop;\n\n\t\tfloat uBottom;\n\n\t};\n\n\n\nprivate:\n\n\tvoid updateProjectionMatrix();\n\n\n\nprotected:\n\n\t// Core data\n\n\tProperties m_properties;\n\n\tCameraUbo m_uniforms;\n\n\tGLuint m_ubo;\n\n\n\n\t// Other data, used to build matrices but not shared with gpu\n\n\tglm::vec3 m_position;\n\n\tfloat m_fov;\n\n\tfloat m_orthographicScale;\n\n\n\n\t// Move related attributes\n", "file_path": "src/GrainViewer/Camera.h", "rank": 86, "score": 138877.6779758586 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#pragma once\n\n\n\n#include <OpenGL>\n\n\n\n#include \"EnvironmentVariables.h\"\n\n#include \"ViewLayerMask.h\"\n\n#include \"utils/ReflectionAttributes.h\"\n\n\n\n#include <refl.hpp>\n\n#include <rapidjson/document.h>\n\n#include <glm/glm.hpp>\n\n\n\n#include <memory>\n\n#include <string>\n\n#include <vector>\n\n\n", "file_path": "src/GrainViewer/Camera.h", "rank": 87, "score": 138873.8040856453 }, { "content": "\tfloat farDistance() const { return m_uniforms.uFar; }\n\n\tvoid setFarDistance(float distance);\n\n\n\n\tvoid setOrthographicScale(float orthographicScale);\n\n\tfloat orthographicScale() const { return m_orthographicScale; }\n\n\n\n\tOutputSettings & outputSettings() { return m_outputSettings; }\n\n\tconst OutputSettings & outputSettings() const { return m_outputSettings; }\n\n\n\n\tstd::shared_ptr<Framebuffer> targetFramebuffer() const { return m_targetFramebuffer; }\n\n\n\n\tinline void startMouseRotation() { m_isMouseRotationStarted = true; m_isLastMouseUpToDate = false; }\n\n\tinline void stopMouseRotation() { m_isMouseRotationStarted = false; }\n\n\n\n\tinline void startMouseZoom() { m_isMouseZoomStarted = true; m_isLastMouseUpToDate = false; }\n\n\tinline void stopMouseZoom() { m_isMouseZoomStarted = false; }\n\n\n\n\tinline void zoom(float factor) { updateDeltaMouseZoom(0, 0, 0, factor); }\n\n\t\n\n\tinline void startMousePanning() { m_isMousePanningStarted = true; m_isLastMouseUpToDate = false; }\n", "file_path": "src/GrainViewer/Camera.h", "rank": 88, "score": 138870.30256594828 }, { "content": "\t/**\n\n\t * Bounding circle of the projected sphere (which is an ellipsis).\n\n\t * xy is the center, z is the radius, all in pixels\n\n\t */\n\n\tglm::vec3 projectSphere(glm::vec3 center, float radius) const;\n\n\n\n\t/**\n\n\t * Convert depth value from Z-buffer to a linear depth in camera space units\n\n\t */\n\n\tfloat linearDepth(float zbufferDepth) const;\n\n\n\n\tpublic:\n\n\t\tstruct Properties {\n\n\t\t\t// xy: offset, relative to screen size\n\n\t\t\t// zw: size, relative to screen size\n\n\t\t\t// e.g. for fullscreen: (0, 0, 1, 1)\n\n\t\t\tglm::vec4 viewRect = glm::vec4(0, 0, 1, 1);\n\n\n\n\t\t\tbool displayInViewport = true;\n\n\t\t\tbool controlInViewport = true; // receive mouse input\n", "file_path": "src/GrainViewer/Camera.h", "rank": 89, "score": 138868.73597677305 }, { "content": "\n\n\t\t\tViewLayerMask viewLayers;\n\n\t\t};\n\n\t\tconst Properties& properties() const { return m_properties; }\n\n\t\tProperties & properties(){ return m_properties; }\n\n\n\nprotected:\n\n\t/**\n\n\t* Called when mouse moves and rotation has started\n\n\t* x1, y1: old mouse position\n\n\t* x2, y2: new mouse position\n\n\t*/\n\n\tvirtual void updateDeltaMouseRotation(float x1, float y1, float x2, float y2) {}\n\n\n\n\t/**\n\n\t* Called when mouse moves and zoom has started\n\n\t* x1, y1: old mouse position\n\n\t* x2, y2: new mouse position\n\n\t*/\n\n\tvirtual void updateDeltaMouseZoom(float x1, float y1, float x2, float y2) {}\n", "file_path": "src/GrainViewer/Camera.h", "rank": 90, "score": 138861.70679097873 }, { "content": "/**\n\n * This file is part of GrainViewer, the reference implementation of:\n\n *\n\n * Michel, Élie and Boubekeur, Tamy (2020).\n\n * Real Time Multiscale Rendering of Dense Dynamic Stackings,\n\n * Computer Graphics Forum (Proc. Pacific Graphics 2020), 39: 169-179.\n\n * https://doi.org/10.1111/cgf.14135\n\n *\n\n * Copyright (c) 2017 - 2020 -- Télécom Paris (Élie Michel <[email protected]>)\n\n *\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n\n * of this software and associated documentation files (the “Software”), to\n\n * deal in the Software without restriction, including without limitation the\n\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n\n * sell copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n\n *\n\n * The above copyright notice and this permission notice shall be included in\n\n * all copies or substantial portions of the Software.\n\n *\n", "file_path": "src/GrainViewer/Shader.h", "rank": 91, "score": 138792.6070980899 }, { "content": " * The Software is provided “as is”, without warranty of any kind, express or\n\n * implied, including but not limited to the warranties of merchantability,\n\n * fitness for a particular purpose and non-infringement. In no event shall the\n\n * authors or copyright holders be liable for any claim, damages or other\n\n * liability, whether in an action of contract, tort or otherwise, arising\n\n * from, out of or in connection with the software or the use or other dealings\n\n * in the Software.\n\n */\n\n\n\n#pragma once\n\n\n\n#include <OpenGL>\n\n\n\n#ifndef NDEBUG\n\n#include \"ShaderPreprocessor.h\"\n\n#endif\n\n\n\n#include <glm/glm.hpp>\n\n\n\n#include <string>\n\n#include <vector>\n\n#include <set>\n\n#include <map>\n\n#include <memory>\n\n\n\n/**\n\n * Utility class providing an OO API to OpenGL shaders\n\n */\n", "file_path": "src/GrainViewer/Shader.h", "rank": 92, "score": 138786.57811784322 }, { "content": " */\n\n bool check(const std::string & name = \"shader\") const;\n\n\n\n inline GLuint shaderId() const { return m_shaderId; }\n\n\n\nprivate:\n\n GLuint m_shaderId;\n\n\n\n#ifndef NDEBUG\n\n\t// Keep shader source\n\n\tShaderPreprocessor m_preprocessor;\n\n#endif\n\n};\n", "file_path": "src/GrainViewer/Shader.h", "rank": 93, "score": 138776.5338371446 }, { "content": "struct has_from_json : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename T>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 94, "score": 137142.5560099402 }, { "content": "struct has_to_json : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename T>\n", "file_path": "src/External/tinygltf/include/json.hpp", "rank": 95, "score": 137142.5560099402 }, { "content": "struct DialogFactory {\n\n\tstatic std::shared_ptr<Dialog> MakeShared() { return std::make_shared<Dialog>(); }\n\n};\n\n\n\n#define registerDialogForBehavior(DialogType, BehaviorType) \\\n\ntemplate<> \\\n", "file_path": "src/GrainViewer/Ui/Dialog.h", "rank": 96, "score": 136258.85929862515 }, { "content": "class ShaderProgram {\n\npublic:\n\n\tenum ShaderProgramType {\n\n\t\tRenderShader,\n\n\t\tComputeShader,\n\n\t};\n\npublic:\n\n\tShaderProgram(const std::string& shaderName = \"\");\n\n\t~ShaderProgram();\n\n\tShaderProgram(ShaderProgram&) = delete;\n\n\tShaderProgram& operator=(ShaderProgram&) = delete;\n\n\tShaderProgram(ShaderProgram&&) = default;\n\n\tShaderProgram& operator=(ShaderProgram&&) = default;\n\n\n\n\t/**\n\n\t * NB: Changing shader name does not reload it. You may want to call load() then.\n\n\t */\n\n\tinline void setShaderName(const std::string& shaderName) { m_shaderName = shaderName; }\n\n\tinline const std::string& shaderName() const { return m_shaderName; }\n\n\n", "file_path": "src/GrainViewer/ShaderProgram.h", "rank": 97, "score": 136226.9344083893 }, { "content": "class ShaderPool {\n\npublic:\n\n\tstatic void AddShader(\n\n\t\tconst std::string& shaderName,\n\n\t\tconst std::string& baseFile,\n\n\t\tShaderProgram::ShaderProgramType type = ShaderProgram::RenderShader,\n\n\t\tconst std::vector<std::string>& defines = {},\n\n\t\tconst std::map<std::string, std::string> & snippets = {});\n\n\n\n\t/**\n\n\t * Copy a base shader and add an extra define. If the define is already\n\n\t * activated in the original shader, this creates an alias pointing to the\n\n\t * previous shader, not a deep copy. This has no effect if there is no\n\n\t * shader called baseShaderName.\n\n\t */\n\n\tstatic void AddShaderVariant(\n\n\t\tconst std::string & shaderName,\n\n\t\tconst std::string & baseShaderName,\n\n\t\tconst std::string & define);\n\n\n", "file_path": "src/GrainViewer/ShaderPool.h", "rank": 98, "score": 136226.9344083893 }, { "content": "class ShaderPreprocessor {\n\npublic:\n\n\t/**\n\n\t * Load a shader from a file, and reccursively include #include'd files\n\n\t * You can specity a list of defines to #define where ever\n\n\t * `#include \"sys:defines\"` is found in the shader.\n\n\t */\n\n\tbool load(const std::string & filename, const std::vector<std::string> & defines = {}, const std::map<std::string, std::string> & snippets = {});\n\n\n\n\t/**\n\n\t * Return a buffer to the pure GLSL source, post-preprocessing, to be fed into\n\n\t * glShaderSource.\n\n\t */\n\n\tvoid source(std::vector<GLchar> & buf) const;\n\n\n\n\t/**\n\n\t * Log a traceback corresponding to the line `line` in the processed source.\n\n\t */\n\n\tvoid logTraceback(size_t line) const;\n\n\n\nprivate:\n\n\tstd::vector<std::string> m_lines;\n\n\n\nprivate:\n\n\tstatic bool loadShaderSourceAux(const std::string & filename, const std::vector<std::string> & defines, const std::map<std::string, std::string> & snippets, std::vector<std::string> & lines_accumulator);\n\n};\n\n\n", "file_path": "src/GrainViewer/ShaderPreprocessor.h", "rank": 99, "score": 136226.9344083893 } ]
C++
main/main.cpp
jmautari/playsound
5885c693d486c5a417a9ec1a96465d83f5492b1c
#include "shared/platform.h" #include <mmdeviceapi.h> #include <Endpointvolume.h> #include <audioclient.h> #include <atlbase.h> #include <Mmsystem.h> #include <string> #include <iostream> #include <filesystem> constexpr wchar_t kEventName[] = L"PlaySoundEvent"; constexpr wchar_t kOptRepeat[] = L"-r"; constexpr wchar_t kOptStop[] = L"-s"; constexpr wchar_t kOptTime[] = L"-t"; constexpr wchar_t kOptMuteMic[] = L"-m"; constexpr int kGetTimeValue = -1; bool PickDevice(IMMDevice** device_to_use, EDataFlow which_end_point = eCapture) { HRESULT hr; CComPtr<IMMDeviceEnumerator> device_enumerator; hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&device_enumerator)); if (FAILED(hr)) { return false; } hr = device_enumerator->GetDefaultAudioEndpoint( which_end_point, eConsole, device_to_use); return SUCCEEDED(hr) ? true : false; } bool SetMicMute(bool mute, bool& muted) { if (FAILED(::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED))) { return false; } HRESULT hr; CComPtr<IMMDevice> endPoint; CComPtr<IAudioClient> audioClient; CComPtr<IAudioEndpointVolume> volumeControl; float current_volume = 0.0f; bool res = false; do { if (!PickDevice(&endPoint)) { break; } hr = endPoint->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&audioClient)); if (FAILED(hr)) { break; } hr = endPoint->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID*)&volumeControl); if (FAILED(hr)) { break; } BOOL mute_status; hr = volumeControl->GetMute(&mute_status); if (FAILED(hr)) { break; } hr = volumeControl->SetMute(mute, nullptr); if (FAILED(hr)) { break; } muted = !!mute_status; res = true; } while (false); volumeControl.Release(); endPoint.Release(); audioClient.Release(); ::CoUninitialize(); return res; } int wmain(int argc, wchar_t* argv[]) { if (argc < 2) { std::cout << "Usage:" << std::endl << "playsound [options] [path-to-file]" << std::endl << "Where options can be:" << std::endl << "-r repeat the sound until playsound is called again with -s option" << std::endl << std::endl << "-s stop a sound that was previously played with -r option" << std::endl << std::endl << "-t X play the sound for up to X seconds. This option has no effect " "if the sound file duration is shorter than X seconds" << std::endl << std::endl << "-m mute default microphone until playsound is called again with -m " "-s options" << std::endl << std::endl << "All options but -m are mutually exclusive" << std::endl; return 1; } HANDLE event_handle = nullptr; bool repeat = false; bool stop = false; bool mute = false; int time = 0; const auto get_opt = [&] { for (int i = 1; i < argc; i++) { if (wcsncmp(argv[i], kOptRepeat, _TRUNCATE) == 0) { if (!stop) repeat = true; } else if (wcsncmp(argv[i], kOptStop, _TRUNCATE) == 0) { if (!repeat) stop = true; } else if (wcsncmp(argv[i], kOptTime, _TRUNCATE) == 0) { time = kGetTimeValue; } else if (time == kGetTimeValue) { time = std::stoi(argv[i]); } else if (wcsncmp(argv[i], kOptMuteMic, _TRUNCATE) == 0) { mute = true; } } }; const auto get_filename = [&]() -> std::filesystem::path { return argv[argc - 1]; }; get_opt(); if (stop) { event_handle = OpenEventW(EVENT_MODIFY_STATE, false, kEventName); if (event_handle == nullptr) { std::cout << "Sound event not found. Make sure a sound was being played" << std::endl; return 1; } std::cout << "Stopping sound" << std::endl; SetEvent(event_handle); PlaySound(nullptr, 0, 0); return 0; } const auto filename = get_filename(); std::error_code ec; if (!std::filesystem::exists(filename, ec)) { std::cout << "File not found" << std::endl; return 1; } if (mute) { event_handle = OpenEventW(EVENT_MODIFY_STATE, false, kEventName); if (event_handle != nullptr) { CloseHandle(event_handle); return 1; } } DWORD flags = SND_FILENAME; bool muted = false; bool reset_mic = false; if (repeat || mute) { std::cout << "Repeating sound " << (mute ? "and muting default mic" : "") << " until playsound is started with -s option" << std::endl; flags |= SND_LOOP | SND_ASYNC; event_handle = CreateEventW(nullptr, false, false, kEventName); if (mute) { reset_mic = SetMicMute(true, muted); if (!reset_mic) { std::cout << "Couldn't get current mic volume. Not muting mic" << std::endl; } } } else if (time > 0) { flags |= SND_ASYNC; } PlaySoundW(filename.native().c_str(), nullptr, flags); if (event_handle != nullptr) { WaitForSingleObject(event_handle, INFINITE); CloseHandle(event_handle); if (mute && reset_mic) SetMicMute(false, muted); } else if (time > 0) { Sleep(time * 1000); } return 0; }
#include "shared/platform.h" #include <mmdeviceapi.h> #include <Endpointvolume.h> #include <audioclient.h> #include <atlbase.h> #include <Mmsystem.h> #include <string> #include <iostream> #include <filesystem> constexpr wchar_t kEventName[] = L"PlaySoundEvent"; constexpr wchar_t kOptRepeat[] = L"-r"; constexpr wchar_t kOptStop[] = L"-s"; constexpr wchar_t kOptTime[] = L"-t"; constexpr wchar_t kOptMuteMic[] = L"-m"; constexpr int kGetTimeValue = -1; bool PickDevice(IMMDevice** device_to_use, EDataFlow which_end_point = eCapture) { HRESULT hr; CComPtr<IMMDeviceEnumerator> device_enumerator; hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&device_enumerator)); if (FAILED(hr)) { return false; } hr = device_enumerator->GetDefaultAudioEndpoint( which_end_point, eConsole, device_to_use); return SUCCEEDED(hr) ? true : false; } bool SetMicMute(bool mute, bool& muted) { if (FAILED(::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED))) { return false; } HRESULT hr; CComPtr<IMMDevice> endPoint; CComPtr<IAudioClient> audioClient; CComPtr<IAudioEndpointVolume> volumeControl; float current_volume = 0.0f; bool re
rue, muted); if (!reset_mic) { std::cout << "Couldn't get current mic volume. Not muting mic" << std::endl; } } } else if (time > 0) { flags |= SND_ASYNC; } PlaySoundW(filename.native().c_str(), nullptr, flags); if (event_handle != nullptr) { WaitForSingleObject(event_handle, INFINITE); CloseHandle(event_handle); if (mute && reset_mic) SetMicMute(false, muted); } else if (time > 0) { Sleep(time * 1000); } return 0; }
s = false; do { if (!PickDevice(&endPoint)) { break; } hr = endPoint->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&audioClient)); if (FAILED(hr)) { break; } hr = endPoint->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID*)&volumeControl); if (FAILED(hr)) { break; } BOOL mute_status; hr = volumeControl->GetMute(&mute_status); if (FAILED(hr)) { break; } hr = volumeControl->SetMute(mute, nullptr); if (FAILED(hr)) { break; } muted = !!mute_status; res = true; } while (false); volumeControl.Release(); endPoint.Release(); audioClient.Release(); ::CoUninitialize(); return res; } int wmain(int argc, wchar_t* argv[]) { if (argc < 2) { std::cout << "Usage:" << std::endl << "playsound [options] [path-to-file]" << std::endl << "Where options can be:" << std::endl << "-r repeat the sound until playsound is called again with -s option" << std::endl << std::endl << "-s stop a sound that was previously played with -r option" << std::endl << std::endl << "-t X play the sound for up to X seconds. This option has no effect " "if the sound file duration is shorter than X seconds" << std::endl << std::endl << "-m mute default microphone until playsound is called again with -m " "-s options" << std::endl << std::endl << "All options but -m are mutually exclusive" << std::endl; return 1; } HANDLE event_handle = nullptr; bool repeat = false; bool stop = false; bool mute = false; int time = 0; const auto get_opt = [&] { for (int i = 1; i < argc; i++) { if (wcsncmp(argv[i], kOptRepeat, _TRUNCATE) == 0) { if (!stop) repeat = true; } else if (wcsncmp(argv[i], kOptStop, _TRUNCATE) == 0) { if (!repeat) stop = true; } else if (wcsncmp(argv[i], kOptTime, _TRUNCATE) == 0) { time = kGetTimeValue; } else if (time == kGetTimeValue) { time = std::stoi(argv[i]); } else if (wcsncmp(argv[i], kOptMuteMic, _TRUNCATE) == 0) { mute = true; } } }; const auto get_filename = [&]() -> std::filesystem::path { return argv[argc - 1]; }; get_opt(); if (stop) { event_handle = OpenEventW(EVENT_MODIFY_STATE, false, kEventName); if (event_handle == nullptr) { std::cout << "Sound event not found. Make sure a sound was being played" << std::endl; return 1; } std::cout << "Stopping sound" << std::endl; SetEvent(event_handle); PlaySound(nullptr, 0, 0); return 0; } const auto filename = get_filename(); std::error_code ec; if (!std::filesystem::exists(filename, ec)) { std::cout << "File not found" << std::endl; return 1; } if (mute) { event_handle = OpenEventW(EVENT_MODIFY_STATE, false, kEventName); if (event_handle != nullptr) { CloseHandle(event_handle); return 1; } } DWORD flags = SND_FILENAME; bool muted = false; bool reset_mic = false; if (repeat || mute) { std::cout << "Repeating sound " << (mute ? "and muting default mic" : "") << " until playsound is started with -s option" << std::endl; flags |= SND_LOOP | SND_ASYNC; event_handle = CreateEventW(nullptr, false, false, kEventName); if (mute) { reset_mic = SetMicMute(t
random
[ { "content": "# Playsound\n\n\n\nSimple utility program to play a wav file.\n\n\n\nPrimarily used by [Widgets][1]\n\n\n\n## Usage\n\n\n\n```\n\nplaysound [options] [path-to-file]\n\n```\n\n\n\nWhere `options` can be:\n\n\n\n`-r` repeat the sound until `playsound` is called again with `-s` option\n\n\n\n`-m` same as `-r` but also mute default microphone until `playsound` is called again with `-s` option\n\n\n\n`-s` stop a sound that was previously played with `-r` option\n\n\n\n`-t X` play the sound for up to `X` seconds. This option has no effect if the sound file duration is shorter than `X` seconds\n\n\n\n**All options are mutually exclusive.**\n\n\n\n## Examples\n\n\n\nPlays `beep.wav` wave file repeatedly until `playsound -s` is called.\n\n\n\n```\n\nplaysound -r beep.wav\n\n```\n\n\n\nStops a sound that was started previously with `-r` option.\n\n\n\n```\n\nplaysound -s\n\n```\n\n\n\nPlays `song.wav` for 5 seconds.\n\n\n\n```\n\nplaysound -t 5 song.wav\n\n```\n\n\n\n[1]: https://github.com/jmautari/widgets\n", "file_path": "README.md", "rank": 10, "score": 0.6536595401937257 } ]
C++
CODE_S1_Wed_Friday/CODE_S1_Wed_Friday/theMainFunction.cpp
Freethetan/INFO3111-S21
b0526d641c5e744c38e6a48d1b66a47f0d8dd592
#include "globalStuff.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <stdlib.h> #include <stdio.h> #include <string> #include <iostream> #include <vector> #include <sstream> #include "cShaderManager.h" #include "cVAOManager.h" #include "cMeshObject.h" static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } bool generateQnDHeaderFileFromPLY(std::string plyFileName, std::string headerFileName, unsigned int& numVertices); float getRandFloat(float LO, float HI) { float r3 = LO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI - LO))); return r3; } void DrawObject( cMeshObject& curMesh, glm::mat4& matModel, glm::mat4& matProjection, glm::mat4& matView, float ratio, cVAOManager* pVAOMan, GLuint program); int main(void) { GLFWwindow* window = NULL; GLuint vertex_buffer = 0; GLuint program = 0; GLint vpos_location = 0; GLint vcol_location = 0; glfwSetErrorCallback(error_callback); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); glfwSwapInterval(1); cShaderManager* pShaderManager = new cShaderManager(); cShaderManager::cShader myVertexShader; cShaderManager::cShader myFragmentShader; pShaderManager->setBasePath("assets/shaders/"); myVertexShader.fileName = "myVertShad.glsl"; myFragmentShader.fileName = "myFragShad.glsl"; if (pShaderManager->createProgramFromFile("SimpleShader", myVertexShader, myFragmentShader)) { std::cout << "Compiled the shader program OK" << std::endl; } else { std::cout << "Oh NO!: Here's why: " << pShaderManager->getLastError() << std::endl; } program = pShaderManager->getIDFromFriendlyName("SimpleShader"); cVAOManager* pVAOMan = new cVAOManager(); sModelDrawInfo mdoBunny; if (pVAOMan->LoadModelIntoVAO("assets/models/bun_zipper_res2_xyz_rgba.ply", mdoBunny, program)) { std::cout << "Bunny loaded OK" << std::endl; std::cout << "Has: " << mdoBunny.numberOfVertices << " vertices" << std::endl; } sModelDrawInfo mdoFish; pVAOMan->LoadModelIntoVAO("assets/models/PacificCod0_xyz_rgba.ply",mdoFish, program); sModelDrawInfo mdoEagleShaceShip; pVAOMan->LoadModelIntoVAO("assets/models/Eagle_xyz_rgba.ply", mdoEagleShaceShip, program); sModelDrawInfo mdoOcto; pVAOMan->LoadModelIntoVAO("assets/models/Santa_Octopus_xyz_rgba.ply", mdoOcto, program); sModelDrawInfo mdoCube; pVAOMan->LoadModelIntoVAO("assets/models/1x1x1Cube.ply", mdoCube, program); cMeshObject bunny; bunny.meshName = "assets/models/bun_zipper_res2_xyz_rgba.ply"; bunny.scale = 6.43f; bunny.position.x = 1.0f; bunny.orientation.y = 0.5f; bunny.orientation.z = 0.1f; bunny.wholeObjectColour = glm::vec4(0.0f, 0.5f, 1.0f, 1.0f); bunny.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(bunny); cMeshObject spaceShip; spaceShip.meshName = "assets/models/Eagle_xyz_rgba.ply"; spaceShip.scale = 0.03994727f; spaceShip.position.y = -0.5f; spaceShip.wholeObjectColour = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); spaceShip.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(spaceShip); cMeshObject spaceShip2; spaceShip2.meshName = "assets/models/Eagle_xyz_rgba.ply"; spaceShip2.scale = 0.03994727f * 2.0f; spaceShip2.position.y = 0.75f; spaceShip2.wholeObjectColour = glm::vec4(1.0f, 1.0f, 0.0f, 1.0f); spaceShip2.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(spaceShip2); cMeshObject santaOcto; santaOcto.meshName = "assets/models/Santa_Octopus_xyz_rgba.ply"; santaOcto.position.x = +2.0f; santaOcto.position.z = +2.0f; santaOcto.wholeObjectColour = glm::vec4(1.0f,0.6f, 0.3f, 1.0f); santaOcto.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(santaOcto); ::g_DebugCube.meshName = "assets/models/1x1x1Cube.ply"; ::g_DebugCube.isWireframe = true; ::g_DebugCube.wholeObjectColour = glm::vec4(1.0f,1.0f, 1.0f, 1.0f); ::g_DebugCube.bUseWholeObjectColour = true; itSelectedObject = g_vecObjectsToDraw.begin(); while ( ! glfwWindowShouldClose(window) ) { float ratio; int width, height; glm::mat4 matModel; glm::mat4 matProjection; glm::mat4 matView; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float)height; glViewport(0, 0, width, height); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); for (unsigned int index = 0; index != ::g_vecObjectsToDraw.size(); index++) { cMeshObject curMesh = ::g_vecObjectsToDraw[index]; DrawObject( curMesh, matModel, matProjection, matView, ratio, pVAOMan, program ); } std::stringstream ssTitle; switch (::g_CurrentMode) { case EDIT_VIEW: ssTitle << "(EDIT MODE) "; ::g_DebugCube.position = itSelectedObject->position; DrawObject(::g_DebugCube, matModel, matProjection, matView, ratio, pVAOMan, program); break; case CAMERA_VIEW: ssTitle << "(CAMERA MODE) "; ssTitle << ::g_cameraEye.x << ", " << ::g_cameraEye.y << ", " << ::g_cameraEye.z; break; } glfwSetWindowTitle(window, ssTitle.str().c_str()); glfwSwapBuffers(window); glfwPollEvents(); doKeyboardMouseStuffAsync(window); } delete pShaderManager; delete pVAOMan; glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } void DrawObject( cMeshObject &curMesh, glm::mat4 &matModel, glm::mat4 &matProjection, glm::mat4 &matView, float ratio, cVAOManager* pVAOMan, GLuint program) { matModel = glm::mat4(1.0f); glm::mat4 matRotateZ; glm::mat4 matRotateY; glm::mat4 matRotateX; glm::mat4 matScale; glm::mat4 matTranslate; matRotateZ = glm::rotate(glm::mat4(1.0f), curMesh.orientation.z, glm::vec3(0.0f, 0.0f, 1.0f)); matRotateY = glm::rotate(glm::mat4(1.0f), curMesh.orientation.y, glm::vec3(0.0f, 1.0, 0.0f)); matRotateX = glm::rotate(glm::mat4(1.0f), curMesh.orientation.x, glm::vec3(1.0f, 0.0, 0.0f)); float uniformScale = curMesh.scale; matScale = glm::scale(glm::mat4(1.0f), glm::vec3(uniformScale, uniformScale, uniformScale)); matTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(curMesh.position.x, curMesh.position.y, curMesh.position.z)); matModel = matModel * matTranslate; matModel = matModel * matRotateX; matModel = matModel * matRotateY; matModel = matModel * matRotateZ; matModel = matModel * matScale; matProjection = glm::perspective(0.6f, ratio, 0.1f, 1000.0f); matView = glm::mat4(1.0f); glm::vec3 upVector = glm::vec3(0.0f, 1.0f, 0.0f); matView = glm::lookAt(::g_cameraEye, ::g_cameraTarget, upVector); GLint mView_UniLocID = glGetUniformLocation(program, "mView"); glUniformMatrix4fv(mView_UniLocID, 1, GL_FALSE, glm::value_ptr(matView)); GLint mModel_UniLocID = glGetUniformLocation(program, "mModel"); glUniformMatrix4fv(mModel_UniLocID, 1, GL_FALSE, glm::value_ptr(matModel)); GLint mProj_UniLocID = glGetUniformLocation(program, "mProj"); glUniformMatrix4fv(mProj_UniLocID, 1, GL_FALSE, glm::value_ptr(matProjection)); GLint wholeObjCol_UniLocID = glGetUniformLocation(program, "wholeObjCol"); glUniform4f(wholeObjCol_UniLocID, curMesh.wholeObjectColour.r, curMesh.wholeObjectColour.g, curMesh.wholeObjectColour.b, curMesh.wholeObjectColour.a); GLint bUseVertColour_UniLocID = glGetUniformLocation(program, "bUseVertColour"); if (curMesh.bUseWholeObjectColour) { glUniform1i(bUseVertColour_UniLocID, GL_FALSE); } else { glUniform1i(bUseVertColour_UniLocID, GL_TRUE); } glUseProgram(program); if (curMesh.isWireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } sModelDrawInfo mdoMesh; if (pVAOMan->FindDrawInfoByModelName(curMesh.meshName, mdoMesh)) { glBindVertexArray(mdoMesh.VAO_ID); glDrawElements(GL_TRIANGLES, mdoMesh.numberOfIndices, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } return; }
#include "globalStuff.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <stdlib.h> #include <stdio.h> #include <string> #include <iostream> #include <vector> #include <sstream> #include "cShaderManager.h" #include "cVAOManager.h" #include "cMeshObject.h" static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } bool generateQnDHeaderFileFromPLY(std::string plyFileName, std::string headerFileName, unsigned int& numVertices); float getRandFloat(float LO, float HI) { float r3 = LO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI - LO))); return r3; } void DrawObject( cMeshObject& curMesh, glm::mat4& matModel, glm::mat4& matProjection, glm::mat4& matView, float ratio, cVAOManager* pVAOMan, GLuint program); int main(void) { GLFWwindow* window = NULL; GLuint vertex_buffer = 0; GLuint program = 0; GLint vpos_location = 0; GLint vcol_location = 0; glfwSetErrorCallback(error_callback); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); glfwSwapInterval(1); cShaderManager* pShaderManager = new cShaderManager(); cShaderManager::cShader myVertexShader; cShaderManager::cShader myFragmentShader; pShaderManager->setBasePath("assets/shaders/"); myVertexShader.fileName = "myVertShad.glsl"; myFragmentShader.fileName = "myFragShad.glsl"; if (pShaderManager->createProgramFromFile("SimpleShader", myVertexShader, myFragmentShader)) { std::cout << "Compiled the shader program OK" << std::endl; } else { std::cout << "Oh NO!: Here's why: " << pShaderManager->getLastError() << std::endl; } program = pShaderManager->getIDFromFriendlyName("SimpleShader"); cVAOManager* pVAOMan = new cVAOManager(); sModelDrawInfo mdoBunny; if (pVAOMan->LoadModelIntoVAO("assets/models/bun_zipper_res2_xyz_rgba.ply", mdoBunny, program)) { std::cout << "Bunny loaded OK" << std::endl; std::cout << "Has: " << mdoBunny.numberOfVertices << " vertices" << std::endl; } sModelDrawInfo mdoFish; pVAOMan->LoadModelIntoVAO("assets/models/PacificCod0_xyz_rgba.ply",mdoFish, program); sModelDrawInfo mdoEagleShaceShip; pVAOMan->LoadModelIntoVAO("assets/models/Eagle_xyz_rgba.ply", mdoEagleShaceShip, program); sModelDrawInfo mdoOcto; pVAOMan->LoadModelIntoVAO("assets/models/Santa_Octopus_xyz_rgba.ply", mdoOcto, program); sModelDrawInfo mdoCube; pVAOMan->LoadModelIntoVAO("assets/models/1x1x1Cube.ply", mdoCube, program); cMeshObject bunny; bunny.meshName = "assets/models/bun_zipper_res2_xyz_rgba.ply"; bunny.scale = 6.43f; bunny.position.x = 1.0f; bunny.orientation.y = 0.5f; bunny.orientation.z = 0.1f; bunny.wholeObjectColour = glm::vec4(0.0f, 0.5f, 1.0f, 1.0f); bunny.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(bunny); cMeshObject spaceShip; spaceShip.meshName = "assets/models/Eagle_xyz_rgba.ply"; spaceShip.scale = 0.03994727f; spaceShip.position.y = -0.5f; spaceShip.wholeObjectColour = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); spaceShip.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(spaceShip); cMeshObject spaceShip2; spaceShip2.meshName = "assets/models/Eagle_xyz_rgba.ply"; spaceShip2.scale = 0.03994727f * 2.0f; spaceShip2.position.y = 0.75f; spaceShip2.wholeObjectColour = glm::vec4(1.0f, 1.0f, 0.0f, 1.0f); spaceShip2.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(spaceShip2); cMeshObject santaOcto; santaOcto.meshName = "assets/models/Santa_Octopus_xyz_rgba.ply"; santaOcto.position.x = +2.0f; santaOcto.position.z = +2.0f; santaOcto.wholeObjectColour = glm::vec4(1.0f,0.6f, 0.3f, 1.0f); santaOcto.bUseWholeObjectColour = true; ::g_vecObjectsToDraw.push_back(santaOcto); ::g_DebugCube.meshName = "assets/models/1x1x1Cube.ply"; ::g_DebugCube.isWireframe = true; ::g_DebugCube.wholeObjectColour = glm::vec4(1.0f,1.0f, 1.0f, 1.0f); ::g_DebugCube.bUseWholeObjectColour = true; itSelectedObject = g_vecObjectsToDraw.begin(); while ( ! glfwWindowShouldClose(window) ) { float ratio; int width, height; glm::mat4 matModel; glm::mat4 matProjection; glm::mat4 matView; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float)height; glViewport(0, 0, width, height); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); for (unsigned int index = 0; index != ::g_vecObjectsToDraw.size(); index++) { cMeshObject curMesh = ::g_vecObjectsToDraw[index]; DrawObject( curMesh, matModel, matProjection, matView, ratio, pVAOMan, program ); } std::stringstream ssTitle; switch (::g_CurrentMode) { case EDIT_VIEW: ssTitle << "(EDIT MODE) "; ::g_DebugCube.position = itSelectedObject->position; DrawObject(::g_DebugCube, matModel, matProjection, matView, ratio, pVAOMan, program); break; case CAMERA_VIEW: ssTitle << "(CAMERA MODE) "; ssTitle << ::g_cameraEye.x << ", " << ::g_cameraEye.y << ", " << ::g_cameraEye.z;
eX = glm::rotate(glm::mat4(1.0f), curMesh.orientation.x, glm::vec3(1.0f, 0.0, 0.0f)); float uniformScale = curMesh.scale; matScale = glm::scale(glm::mat4(1.0f), glm::vec3(uniformScale, uniformScale, uniformScale)); matTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(curMesh.position.x, curMesh.position.y, curMesh.position.z)); matModel = matModel * matTranslate; matModel = matModel * matRotateX; matModel = matModel * matRotateY; matModel = matModel * matRotateZ; matModel = matModel * matScale; matProjection = glm::perspective(0.6f, ratio, 0.1f, 1000.0f); matView = glm::mat4(1.0f); glm::vec3 upVector = glm::vec3(0.0f, 1.0f, 0.0f); matView = glm::lookAt(::g_cameraEye, ::g_cameraTarget, upVector); GLint mView_UniLocID = glGetUniformLocation(program, "mView"); glUniformMatrix4fv(mView_UniLocID, 1, GL_FALSE, glm::value_ptr(matView)); GLint mModel_UniLocID = glGetUniformLocation(program, "mModel"); glUniformMatrix4fv(mModel_UniLocID, 1, GL_FALSE, glm::value_ptr(matModel)); GLint mProj_UniLocID = glGetUniformLocation(program, "mProj"); glUniformMatrix4fv(mProj_UniLocID, 1, GL_FALSE, glm::value_ptr(matProjection)); GLint wholeObjCol_UniLocID = glGetUniformLocation(program, "wholeObjCol"); glUniform4f(wholeObjCol_UniLocID, curMesh.wholeObjectColour.r, curMesh.wholeObjectColour.g, curMesh.wholeObjectColour.b, curMesh.wholeObjectColour.a); GLint bUseVertColour_UniLocID = glGetUniformLocation(program, "bUseVertColour"); if (curMesh.bUseWholeObjectColour) { glUniform1i(bUseVertColour_UniLocID, GL_FALSE); } else { glUniform1i(bUseVertColour_UniLocID, GL_TRUE); } glUseProgram(program); if (curMesh.isWireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } sModelDrawInfo mdoMesh; if (pVAOMan->FindDrawInfoByModelName(curMesh.meshName, mdoMesh)) { glBindVertexArray(mdoMesh.VAO_ID); glDrawElements(GL_TRIANGLES, mdoMesh.numberOfIndices, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } return; }
break; } glfwSetWindowTitle(window, ssTitle.str().c_str()); glfwSwapBuffers(window); glfwPollEvents(); doKeyboardMouseStuffAsync(window); } delete pShaderManager; delete pVAOMan; glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } void DrawObject( cMeshObject &curMesh, glm::mat4 &matModel, glm::mat4 &matProjection, glm::mat4 &matView, float ratio, cVAOManager* pVAOMan, GLuint program) { matModel = glm::mat4(1.0f); glm::mat4 matRotateZ; glm::mat4 matRotateY; glm::mat4 matRotateX; glm::mat4 matScale; glm::mat4 matTranslate; matRotateZ = glm::rotate(glm::mat4(1.0f), curMesh.orientation.z, glm::vec3(0.0f, 0.0f, 1.0f)); matRotateY = glm::rotate(glm::mat4(1.0f), curMesh.orientation.y, glm::vec3(0.0f, 1.0, 0.0f)); matRotat
random
[]
C++
tools/trainers/retargetTrainer/src/RetargetArguments.cpp
kernhanda/ELL
370c0de4e4c190ca0cb43654b4246b3686bca464
#include "RetargetArguments.h" namespace ell { void ParsedRetargetArguments::AddArgs(utilities::CommandLineParser& parser) { using namespace common; parser.AddOption(inputModelFilename, "inputModelFilename", "imf", "Name of the pre-trained ELL model file (e.g. model1.ell) that will be used as a featurizer for a linear predictor", ""); parser.AddOption(outputModelFilename, "outputModelFilename", "omf", "Name of the output file that will hold the saved retargeted model (e.g. retargetedModel.ell)", ""); parser.AddOption(refineIterations, "refineIterations", "ri", "If cutting the neural network using a node id, specifies the maximum number of refinement iterations", 1); parser.AddOption(targetPortElements, "targetPortElements", "tpe", "The port elements of the pre-trained model to use as input to the subsequent linear predictor e.g. \"1115.output\" to use the full output from Node 1115", ""); parser.AddOption(removeLastLayers, "removeLastLayers", "rem", "Instead of using a node id, a neural network model can be retargeted by removing the last N layers", 0); parser.AddOption( inputDataFilename, "inputDataFilename", "idf", "Path to the input dataset file", ""); parser.AddOption( multiClass, "multiClass", "mc", "Indicates whether the input dataset is multi-class or binary.", false); parser.AddOption(normalize, "normalize", "n", "Perform sparsity-preserving normalization", false); parser.AddOption(regularization, "regularization", "r", "The L2 regularization parameter", 0.005); parser.AddOption(desiredPrecision, "desiredPrecision", "de", "The desired duality gap at which to stop optimizing", 1.0e-5); parser.AddOption(maxEpochs, "maxEpochs", "me", "The maximum number of optimization epochs to run", 1000); parser.AddOption(permute, "permute", "p", "Whether or not to randomly permute the training data before each epoch", true); parser.AddOption(randomSeedString, "randomSeedString", "seed", "The random seed string", "ABCDEFG"); parser.AddOption( verbose, "verbose", "v", "Print diagnostic output during the execution of the tool to stdout", false); parser.AddOption( lossFunctionArguments.lossFunction, "lossFunction", "lf", "Choice of loss function", { { "squared", LossFunctionArguments::LossFunction::squared }, { "log", LossFunctionArguments::LossFunction::log }, {"smoothHinge", LossFunctionArguments::LossFunction::smoothHinge} }, "log"); parser.AddOption( useBlas, "blas", "", "Emit code that calls BLAS, used when compiling the input model to create mapped datasets", true); } }
#include "RetargetArguments.h" namespace ell { void ParsedRetargetArguments::AddArgs(utilities::CommandLineParser& parser) { using namespace common; parser.AddOption(inputModelFilename, "inputModelFilename", "imf", "Name of the pre-trained ELL model file (e.g. model1.ell) that will be used as a featurizer for a linear predictor", ""); parser.AddOption(outputModelFilename, "outputModelFilename", "omf", "Name of the output file that will hold the saved retargeted model (e.g. retargetedModel.ell)", ""); parser.AddOption(refineIterations, "refineIterations", "ri", "If cutting the neural network using a node id, specifies the maximum number of refinement iterations", 1); parser.AddOption(targetPortElements, "targetPortElements", "tpe", "The port elements of the pre-trained model to use as input to the subsequent linear predictor e.g. \"1115.output\" to use the full output from Node 1115", ""); parser.AddOption(removeLastLayers, "removeLastLayers", "rem", "Instead of using a node id, a neural network model can be retargeted by removing the last N layers", 0); parser.AddOption( inputDataFilename, "inputDataFilename", "idf", "Path to the input dataset file", ""); parser.AddOption( multiClass, "multiClass", "mc", "Indicates whether the input dataset is multi-class or binary.", false); parser.AddOption(normalize, "normalize", "n", "Perform sparsity-preserving normalization", false); parser.AddOption(regularization, "regularization", "r", "The L2 regularization parameter", 0.005); parser.AddOption(desiredPrecision, "desiredP
}
recision", "de", "The desired duality gap at which to stop optimizing", 1.0e-5); parser.AddOption(maxEpochs, "maxEpochs", "me", "The maximum number of optimization epochs to run", 1000); parser.AddOption(permute, "permute", "p", "Whether or not to randomly permute the training data before each epoch", true); parser.AddOption(randomSeedString, "randomSeedString", "seed", "The random seed string", "ABCDEFG"); parser.AddOption( verbose, "verbose", "v", "Print diagnostic output during the execution of the tool to stdout", false); parser.AddOption( lossFunctionArguments.lossFunction, "lossFunction", "lf", "Choice of loss function", { { "squared", LossFunctionArguments::LossFunction::squared }, { "log", LossFunctionArguments::LossFunction::log }, {"smoothHinge", LossFunctionArguments::LossFunction::smoothHinge} }, "log"); parser.AddOption( useBlas, "blas", "", "Emit code that calls BLAS, used when compiling the input model to create mapped datasets", true); }
function_block-function_prefixed
[ { "content": "class NeuralNetworkPredictorNode : public model::Node\n\n{\n\npublic:\n\n /// @name Input and Output Ports\n\n /// @{\n\n const model::InputPort<ValueType>& input = _input;\n\n const model::OutputPort<ValueType>& output = _output;\n\n /// @}\n\n\n\n using PredictorType = typename predictors::NeuralNetworkPredictor<ValueType>;\n\n using Layer = typename predictors::neural::Layer<ValueType>;\n\n\n\n /// <summary> Default Constructor </summary>\n\n NeuralNetworkPredictorNode();\n\n\n\n /// <summary> Constructor </summary>\n\n ///\n\n /// <param name=\"input\"> The signal to predict from </param>\n\n /// <param name=\"predictor\"> The predictor to use when making the prediction. </param>\n\n NeuralNetworkPredictorNode(const model::PortElements<ValueType>& input, const PredictorType& predictor);\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 0, "score": 364894.67257152253 }, { "content": " class NeuralNetworkLayerNodeBase : public model::CompilableNode\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n const model::InputPort<ValueType>& input = _input;\n\n const model::OutputPort<ValueType>& output = _output;\n\n /// @}\n\n\n\n /// <summary> Gets information about the input memory layout </summary>\n\n virtual model::PortMemoryLayout& GetInputMemoryLayout() = 0;\n\n\n\n /// <summary> Gets information about the input memory layout </summary>\n\n virtual const model::PortMemoryLayout& GetInputMemoryLayout() const = 0;\n\n\n\n /// <summary> Gets information about the output memory layout </summary>\n\n virtual const model::PortMemoryLayout& GetOutputMemoryLayout() const = 0;\n\n\n\n /// <summary> Gets information about the output memory layout </summary>\n\n virtual model::PortMemoryLayout& GetOutputMemoryLayout() = 0;\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 1, "score": 326306.6461136015 }, { "content": " class LinearPredictorNode : public model::Node\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n static constexpr const char* weightedElementsPortName = \"weightedElements\";\n\n const model::InputPort<ElementType>& input = _input;\n\n const model::OutputPort<ElementType>& output = _output;\n\n const model::OutputPort<ElementType>& weightedElements = _weightedElements;\n\n /// @}\n\n\n\n using LinearPredictorType = typename predictors::LinearPredictor<ElementType>;\n\n\n\n /// <summary> Default Constructor </summary>\n\n LinearPredictorNode();\n\n\n\n /// <summary> Constructor </summary>\n\n ///\n\n /// <param name=\"input\"> The signal to predict from </param>\n\n /// <param name=\"predictor\"> The linear predictor to use when making the prediction. </param>\n", "file_path": "libraries/nodes/include/LinearPredictorNode.h", "rank": 2, "score": 319689.4142621102 }, { "content": " class BatchNormalizationLayerNode : public NeuralNetworkLayerNode<BatchNormalizationLayerNode<ValueType>, predictors::neural::BatchNormalizationLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::BatchNormalizationLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<BatchNormalizationLayerNode<ValueType>, predictors::neural::BatchNormalizationLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n BatchNormalizationLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The batch normalization layer to wrap. </param>\n\n BatchNormalizationLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::BatchNormalizationLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/BatchNormalizationLayerNode.h", "rank": 3, "score": 319290.28798345575 }, { "content": " class BinaryConvolutionalLayerNode : public NeuralNetworkLayerNode<BinaryConvolutionalLayerNode<ValueType>, predictors::neural::BinaryConvolutionalLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::BinaryConvolutionalLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<BinaryConvolutionalLayerNode<ValueType>, predictors::neural::BinaryConvolutionalLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n BinaryConvolutionalLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n BinaryConvolutionalLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::BinaryConvolutionalLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/BinaryConvolutionalLayerNode.h", "rank": 4, "score": 319189.383427211 }, { "content": " class InputLayer : public Layer<ElementType>\n\n {\n\n public:\n\n\n\n using Shape = typename Layer<ElementType>::Shape;\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using TensorType = typename Layer<ElementType>::TensorType;\n\n using DataVectorType = typename Layer<ElementType>::DataVectorType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n using Layer<ElementType>::AssignValues;\n\n\n\n /// <summary> Parameters common to all layers. </summary>\n\n struct InputParameters\n\n {\n\n /// <summary> Shape of the input tensor. </summary>\n\n Shape inputShape;\n", "file_path": "libraries/predictors/neural/include/InputLayer.h", "rank": 5, "score": 318387.82625474787 }, { "content": "struct hash<ell::model::PortElementBase>\n\n{\n\n using argument_type = ell::model::PortElementBase;\n\n using result_type = std::size_t;\n\n\n\n /// <summary> Computes a hash of the input value. </summary>\n\n ///\n\n /// <returns> A hash value for the given input. </returns>\n\n result_type operator()(argument_type const& id) const;\n\n};\n\n\n\ntemplate <>\n", "file_path": "libraries/model/include/PortElements.h", "rank": 6, "score": 312938.78851706104 }, { "content": " class BatchNormalizationLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n using Layer<ElementType>::AssignValues;\n\n\n\n /// <summary> Instantiates an instance of a batch normalization layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"mean\"> The mean values. </param>\n\n /// <param name=\"variance\"> The variance values. </param>\n\n /// <param name=\"epsilon\"> The epsilon added to the denominator to avoid division by zero. </param>\n\n /// <param name=\"EpsilonSummand\"> Which component will the epsilon will be applied to the denominator. </param>\n\n BatchNormalizationLayer(const LayerParameters& layerParameters, const VectorType& mean, const VectorType& variance, ElementType epsilon, EpsilonSummand epsilonSummand);\n\n\n", "file_path": "libraries/predictors/neural/include/BatchNormalizationLayer.h", "rank": 7, "score": 305519.856650054 }, { "content": " class BinaryConvolutionalLayer : public Layer<ElementType>\n\n {\n\n public:\n\n\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using MatrixType = typename Layer<ElementType>::MatrixType;\n\n using TensorType = typename Layer<ElementType>::TensorType;\n\n using ConstTensorReferenceType = typename Layer<ElementType>::ConstTensorReferenceType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n \n\n /// <summary> Instantiates an instance of a binarized convolutional layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"convolutionalParameters\"> The hyperparameters for this convolutional layer. </param>\n\n /// <param name=\"weights\"> The set of weights to apply. </param>\n\n BinaryConvolutionalLayer(const LayerParameters& layerParameters, const BinaryConvolutionalParameters& convolutionalParameters, const ConstTensorReferenceType& weights);\n\n\n", "file_path": "libraries/predictors/neural/include/BinaryConvolutionalLayer.h", "rank": 8, "score": 305421.892063225 }, { "content": "struct hash<ell::model::PortRange>\n\n{\n\n using argument_type = ell::model::PortRange;\n\n using result_type = std::size_t ;\n\n\n\n /// <summary> Computes a hash of the input value. </summary>\n\n ///\n\n /// <returns> A hash value for the given input. </returns>\n\n result_type operator()(argument_type const& id) const;\n\n};\n\n}\n\n\n\n#include \"../tcc/PortElements.tcc\"\n", "file_path": "libraries/model/include/PortElements.h", "rank": 9, "score": 304438.66845003463 }, { "content": " class BatchNormalizationLayer : public Layer<ElementType>\n\n {\n\n public:\n\n BatchNormalizationLayer(const LayerParameters& layerParameters, const std::vector<ElementType>& mean, const std::vector<ElementType>& variance, ElementType epsilon, EpsilonSummand epsilonSummand)\n\n : Layer<ElementType>(layerParameters), mean(mean), variance(variance), epsilon(epsilon), epsilonSummand(epsilonSummand)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::batchNormalization; }\n\n\n\n const std::vector<ElementType> mean;\n\n const std::vector<ElementType> variance;\n\n const ElementType epsilon;\n\n const EpsilonSummand epsilonSummand;\n\n };\n\n\n\n // Api projection for BiasLayer\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 10, "score": 296772.21799292916 }, { "content": " class BinaryConvolutionalLayer : public Layer<ElementType>\n\n {\n\n public:\n\n BinaryConvolutionalLayer(const LayerParameters& layerParameters, const BinaryConvolutionalParameters& convolutionalParameters, const ell::api::math::Tensor<ElementType>& weightsTensor)\n\n : Layer<ElementType>(layerParameters), weights(weightsTensor.data, weightsTensor.shape.rows, weightsTensor.shape.columns, weightsTensor.shape.channels), convolutionalParameters(convolutionalParameters)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::binaryConvolution; }\n\n\n\n API_READONLY(ell::api::math::Tensor<ElementType> weights);\n\n const BinaryConvolutionalParameters convolutionalParameters;\n\n };\n\n\n\n // Api projections for ConvolutionalLayer\n\n using ConvolutionMethod = ell::predictors::neural::ConvolutionMethod;\n\n using ConvolutionalParameters = ell::predictors::neural::ConvolutionalParameters;\n\n\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 11, "score": 296698.66302006016 }, { "content": " class Node;\n\n\n", "file_path": "libraries/model/include/InputPort.h", "rank": 12, "score": 292921.2693570775 }, { "content": " class Node;\n\n\n", "file_path": "libraries/model/include/OutputPort.h", "rank": 13, "score": 292876.5632452623 }, { "content": "void TestNeuralNetworkLayerNodes();\n", "file_path": "libraries/nodes/test/include/NeuralNetworkLayerNodesTests.h", "rank": 14, "score": 288707.3568119006 }, { "content": "class InputPortIterator\n\n{\n\npublic:\n\n InputPortIterator() = default;\n\n bool IsValid();\n\n void Next();\n\n InputPort Get();\n\n#ifndef SWIG\n\n InputPortIterator(std::vector<ell::model::InputPortBase*> ports);\n\n#endif\n\nprivate:\n\n size_t _i = 0;\n\n std::vector<ell::model::InputPortBase*> _ports;\n\n};\n\n\n\n//\n\n// OutputPortIterator\n\n//\n\n\n", "file_path": "interfaces/common/include/ModelInterface.h", "rank": 15, "score": 285812.08524728415 }, { "content": "class OutputPortIterator\n\n{\n\npublic:\n\n OutputPortIterator() = default;\n\n bool IsValid();\n\n void Next();\n\n OutputPort Get();\n\n#ifndef SWIG\n\n OutputPortIterator(std::vector<ell::model::OutputPortBase*> ports);\n\n#endif\n\nprivate:\n\n size_t _i = 0;\n\n std::vector<ell::model::OutputPortBase*> _ports;\n\n};\n\n\n", "file_path": "interfaces/common/include/ModelInterface.h", "rank": 16, "score": 285770.2165875055 }, { "content": "namespace ell\n\n{\n\nnamespace common\n\n{\n\n /// <summary> A struct that holds command line parameters for saving models. </summary>\n\n struct ModelSaveArguments\n\n {\n\n /// <summary> The filename to store the output model in. </summary>\n\n std::string outputModelFilename = \"\";\n\n\n\n utilities::OutputStreamImpostor outputModelStream;\n\n };\n\n\n\n /// <summary> A version of ModelSaveArguments that adds its members to the command line parser. </summary>\n\n struct ParsedModelSaveArguments : public ModelSaveArguments, public utilities::ParsedArgSet\n\n {\n\n /// <summary> Adds the arguments to the command line parser. </summary>\n\n ///\n\n /// <param name=\"parser\"> [in,out] The parser. </param>\n\n void AddArgs(utilities::CommandLineParser& parser) override;\n\n\n\n /// <summary> Check arguments. </summary>\n\n ///\n\n /// <param name=\"parser\"> The parser. </param>\n\n ///\n\n /// <returns> An utilities::CommandLineParseResult. </returns>\n\n utilities::CommandLineParseResult PostProcess(const utilities::CommandLineParser& parser) override;\n\n };\n\n}\n", "file_path": "libraries/common/include/ModelSaveArguments.h", "rank": 17, "score": 283132.4611327436 }, { "content": "namespace ell\n\n{\n\nnamespace common\n\n{\n\n /// <summary> Appends a predictor node of the given type to the model in a map. </summary>\n\n ///\n\n /// <typeparam name=\"PredictorNodeType\"> The type of the new predictor node to add </typeparam>\n\n /// <typeparam name=\"PredictorType\"> The type of the predictor to add </typeparam>\n\n /// <param name=\"map\"> The map </param>\n\n /// <param name=\"predictor\"> The predictor to wrap in a node and add to the model </param>\n\n /// <returns> The new model, with the predictor node appended </returns>\n\n template <typename PredictorNodeType, typename PredictorType>\n\n model::Model AppendNodeToModel(model::Map& map, const PredictorType& predictor);\n\n}\n", "file_path": "libraries/common/include/AppendNodeToModel.h", "rank": 18, "score": 282011.060945121 }, { "content": " class ConvolutionalLayerNode : public NeuralNetworkLayerNode<ConvolutionalLayerNode<ValueType>, predictors::neural::ConvolutionalLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::ConvolutionalLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<ConvolutionalLayerNode<ValueType>, predictors::neural::ConvolutionalLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n ConvolutionalLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The convolutional layer to wrap. </param>\n\n ConvolutionalLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::ConvolutionalLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/ConvolutionalLayerNode.h", "rank": 19, "score": 275093.00055515714 }, { "content": " class BiasLayerNode : public NeuralNetworkLayerNode<BiasLayerNode<ValueType>, predictors::neural::BiasLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::BiasLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<BiasLayerNode<ValueType>, predictors::neural::BiasLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n BiasLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n BiasLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::BiasLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/BiasLayerNode.h", "rank": 20, "score": 275093.0005551572 }, { "content": " class SoftmaxLayerNode : public NeuralNetworkLayerNode<SoftmaxLayerNode<ValueType>, predictors::neural::SoftmaxLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::SoftmaxLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<SoftmaxLayerNode<ValueType>, predictors::neural::SoftmaxLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n SoftmaxLayerNode() = default;\n\n \n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n SoftmaxLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::SoftmaxLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/SoftmaxLayerNode.h", "rank": 21, "score": 275093.0005551572 }, { "content": " class ScalingLayerNode : public NeuralNetworkLayerNode<ScalingLayerNode<ValueType>, predictors::neural::ScalingLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::ScalingLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<ScalingLayerNode<ValueType>, predictors::neural::ScalingLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n ScalingLayerNode() = default;\n\n \n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The layer to wrap. </param>\n\n ScalingLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::ScalingLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/ScalingLayerNode.h", "rank": 22, "score": 275093.0005551572 }, { "content": " class NeuralNetworkLayerNode : public NeuralNetworkLayerNodeBase<ValueType>\n\n {\n\n public:\n\n using LayerType = NodeLayerType;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using NeuralNetworkLayerNodeBase<ValueType>::input;\n\n using NeuralNetworkLayerNodeBase<ValueType>::output;\n\n /// @}\n\n\n\n /// <summary> Default constructor. </summary>\n\n NeuralNetworkLayerNode();\n\n\n\n /// <summary> Constructor </summary>\n\n ///\n\n /// <param name=\"input\"> The input to the layer (typically the output of the previous layer). </param>\n\n /// <param name=\"layer\"> The neural network layer to wrap. </param>\n\n NeuralNetworkLayerNode(const model::PortElements<ValueType>& input, const LayerType& layer);\n\n\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 23, "score": 273928.30558610376 }, { "content": "class InputNode : public Node\n\n{\n\npublic:\n\n InputNode(const InputNode& node);\n\n InputNode(Node node);\n\n using Node::GetInputPort;\n\n using Node::GetOutputPort;\n\n#ifndef SWIG\n\n InputNode() = default;\n\n InputNode(const ell::model::InputNodeBase* other);\n\n const ell::model::InputNodeBase* GetInputNode() const;\n\n#endif\n\n};\n\n\n\n//\n\n// OutputNode\n\n//\n\n\n", "file_path": "interfaces/common/include/ModelInterface.h", "rank": 24, "score": 273478.9144303244 }, { "content": "class OutputNode : public Node\n\n{\n\npublic:\n\n OutputNode(const OutputNode& node);\n\n OutputNode(Node node);\n\n using Node::GetInputPort;\n\n using Node::GetOutputPort;\n\n#ifndef SWIG\n\n OutputNode() = default;\n\n OutputNode(const ell::model::OutputNodeBase* other);\n\n const ell::model::OutputNodeBase* GetOutputNode() const;\n\n#endif\n\n};\n\n\n\n//\n\n// PortElement\n\n//\n\n\n", "file_path": "interfaces/common/include/ModelInterface.h", "rank": 25, "score": 273438.3335833547 }, { "content": "void TestNeuralNetworkPredictorNode6();\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 26, "score": 271145.3198526539 }, { "content": "void TestNeuralNetworkPredictorNode1();\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 27, "score": 271145.31985265383 }, { "content": "void TestNeuralNetworkPredictorNode5();\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 28, "score": 271145.31985265383 }, { "content": "void TestNeuralNetworkPredictorNode2();\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 29, "score": 271145.3198526539 }, { "content": "void TestNeuralNetworkPredictorNode3();\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 30, "score": 271145.31985265383 }, { "content": "void TestNeuralNetworkPredictorNode4();\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 31, "score": 271145.31985265383 }, { "content": " class NeuralNetworkPredictor\n\n {\n\n public:\n\n using Layer = ell::api::predictors::neural::Layer<ElementType>;\n\n using LayerShape = ell::api::math::TensorShape;\n\n using UnderlyingPredictor = ell::predictors::NeuralNetworkPredictor<ElementType>;\n\n using UnderlyingLayer = typename ell::predictors::neural::Layer<ElementType>;\n\n using UnderlyingLayers = typename ell::predictors::NeuralNetworkPredictor<ElementType>::Layers;\n\n using UnderlyingInputParameters = typename ell::predictors::neural::InputLayer<ElementType>::InputParameters;\n\n using UnderlyingInputLayer = typename ell::predictors::neural::InputLayer<ElementType>;\n\n using UnderlyingLayerParameters = typename ell::predictors::neural::Layer<ElementType>::LayerParameters;\n\n\n\n NeuralNetworkPredictor(const std::vector<Layer*>& layers, ElementType scaleFactor=1.0f);\n\n std::vector<ElementType> Predict(const std::vector<ElementType>& input);\n\n void RemoveLastLayers(size_t numLayersToRemove);\n\n LayerShape GetInputShape() const;\n\n LayerShape GetOutputShape() const;\n\n\n\n#ifndef SWIG\n\n const UnderlyingPredictor& GetPredictor() const;\n", "file_path": "interfaces/common/include/NeuralNetworkPredictorInterface.h", "rank": 32, "score": 267582.0155233162 }, { "content": " class BinaryXnorNode : public model::CompilableNode\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n static constexpr const char* inputPaddingMasksPortName = \"inputPaddingMasks\";\n\n static constexpr const char* inputPaddingMaskSumsPortName = \"inputPaddingMaskSums\";\n\n static constexpr const char* filterWeightsPortName = \"filterWeights\";\n\n static constexpr const char* filterMeansPortName = \"filterMeans\";\n\n const model::InputPort<PackedBitsType>& input = _input;\n\n const model::InputPort<PackedBitsType>& inputPaddingMasks = _inputPaddingMasks;\n\n const model::InputPort<int>& inputPaddingMaskSums = _inputPaddingMaskSums;\n\n const model::InputPort<PackedBitsType>& filterWeights = _filterWeights;\n\n const model::InputPort<ValueType>& filterMeans = _filterMeans;\n\n const model::OutputPort<ValueType>& output = _output;\n\n /// @}\n\n\n\n /// <summary> Default contructor. </summary>\n\n BinaryXnorNode();\n\n\n", "file_path": "libraries/nodes/include/BinaryConvolutionalLayerNode.h", "rank": 33, "score": 267340.9261927384 }, { "content": " class FullyConnectedLayerNode : public NeuralNetworkLayerNode<FullyConnectedLayerNode<ValueType>, predictors::neural::FullyConnectedLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::FullyConnectedLayer<ValueType>;\n\n using BaseType = NeuralNetworkLayerNode<FullyConnectedLayerNode<ValueType>, predictors::neural::FullyConnectedLayer<ValueType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n FullyConnectedLayerNode() = default;\n\n \n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n FullyConnectedLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::FullyConnectedLayer<ValueType>& layer);\n\n\n", "file_path": "libraries/nodes/include/FullyConnectedLayerNode.h", "rank": 34, "score": 262040.54337780483 }, { "content": " class RegionDetectionLayerNode : public NeuralNetworkLayerNode<RegionDetectionLayerNode<ValueType>, predictors::neural::RegionDetectionLayer<ValueType>, ValueType>\n\n {\n\n public:\n\n using BaseType = NeuralNetworkLayerNode<RegionDetectionLayerNode<ValueType>, predictors::neural::RegionDetectionLayer<ValueType>, ValueType>;\n\n using typename BaseType::LayerType;\n\n\n\n RegionDetectionLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n RegionDetectionLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::RegionDetectionLayer<ValueType>& layer);\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n static std::string GetTypeName() { return utilities::GetCompositeTypeName<ValueType>(\"RegionDetectionLayerNode\"); }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n", "file_path": "libraries/nodes/include/RegionDetectionLayerNode.h", "rank": 35, "score": 262040.54337780483 }, { "content": " class ForestPredictorNode : public model::Node\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n static constexpr const char* treeOutputsPortName = \"treeOutputs\";\n\n static constexpr const char* edgeIndicatorVectorPortName = \"edgeIndicatorVector\";\n\n const model::InputPort<double>& input = _input;\n\n const model::OutputPort<double>& output = _output;\n\n const model::OutputPort<double>& treeOutputs = _treeOutputs;\n\n const model::OutputPort<bool>& edgeIndicatorVector = _edgeIndicatorVector;\n\n /// @}\n\n\n\n using ForestPredictor = predictors::ForestPredictor<SplitRuleType, EdgePredictorType>;\n\n\n\n /// <summary> Default Constructor </summary>\n\n ForestPredictorNode();\n\n\n\n /// <summary> Constructor </summary>\n\n ///\n", "file_path": "libraries/nodes/include/ForestPredictorNode.h", "rank": 36, "score": 262037.1745479429 }, { "content": " size_t removeLastLayers;\n", "file_path": "tools/trainers/retargetTrainer/include/RetargetArguments.h", "rank": 37, "score": 261364.306652297 }, { "content": " class ActivationLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using ActivationFunction = ActivationFunctionType<ElementType>;\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n\n\n /// <summary> Instantiates an instance of an activation layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n ActivationLayer(const LayerParameters& layerParameters);\n\n\n\n /// <summary> Instantiates an instance of an activation layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"activationFunction\"> The activation function. </param>\n\n ActivationLayer(const LayerParameters& layerParameters, ActivationFunctionType<ElementType> activation);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n ActivationLayer() {}\n", "file_path": "libraries/predictors/neural/include/ActivationLayer.h", "rank": 38, "score": 260742.54951058232 }, { "content": " class LSTMLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using MatrixType = typename Layer<ElementType>::MatrixType;\n\n using ConstMatrixReferenceType = typename Layer<ElementType>::ConstMatrixReferenceType;\n\n using ConstTensorReferenceType = typename Layer<ElementType>::ConstTensorReferenceType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n\n\n /// <summary> Default constructor. </summary>\n\n LSTMLayer();\n\n\n\n /// <summary> Instantiates an instance of a LSTM layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"parameters\"> The weights and biases applicable to an LSTM. Weights should be organised as: [weights, recurrent layer weights] or [W, U].\n", "file_path": "libraries/predictors/neural/include/LSTMLayer.h", "rank": 39, "score": 260742.54951058232 }, { "content": " class ScalingLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::AssignValues;\n\n\n\n /// <summary> Instantiates an instance of a scaling layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"bias\"> The scaling values to apply to input values. </param>\n\n ScalingLayer(const LayerParameters& layerParameters, const VectorType& scales);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n ScalingLayer() {}\n\n\n\n /// <summary> Feeds the input forward through the layer. </summary>\n\n void Compute() override;\n\n\n", "file_path": "libraries/predictors/neural/include/ScalingLayer.h", "rank": 40, "score": 260742.54951058232 }, { "content": " class BiasLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n using Layer<ElementType>::AssignValues;\n\n\n\n /// <summary> Instantiates an instance of a bias layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"bias\"> The bias values to apply to input values. </param>\n\n BiasLayer(const LayerParameters& layerParameters, const VectorType& bias);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n BiasLayer() {}\n\n\n\n /// <summary> Feeds the input forward through the layer and returns a reference to the output. </summary>\n\n void Compute() override;\n", "file_path": "libraries/predictors/neural/include/BiasLayer.h", "rank": 41, "score": 260742.54951058232 }, { "content": " class ConvolutionalLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using MatrixType = typename Layer<ElementType>::MatrixType;\n\n using TensorType = typename Layer<ElementType>::TensorType;\n\n using ConstTensorReferenceType = typename Layer<ElementType>::ConstTensorReferenceType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n\n\n /// <summary> Instantiates an instance of a convolutional layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"convolutionalParameters\"> The hyperparameters for this convolutional layer. </param>\n\n /// <param name=\"weights\"> The set of weights to apply. </param>\n\n ConvolutionalLayer(const LayerParameters& layerParameters, const ConvolutionalParameters& convolutionalParameters, TensorType weights);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n", "file_path": "libraries/predictors/neural/include/ConvolutionalLayer.h", "rank": 42, "score": 260742.54951058232 }, { "content": " class GRULayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using MatrixType = typename Layer<ElementType>::MatrixType;\n\n using ConstMatrixReferenceType = typename Layer<ElementType>::ConstMatrixReferenceType;\n\n using ConstTensorReferenceType = typename Layer<ElementType>::ConstTensorReferenceType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n\n\n /// <summary> Default constructor </summary>\n\n GRULayer();\n\n\n\n /// <summary> Instantiates an instance of a GRU layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"parameters\"> The weights and biases applicable to an GRU. Weights should be organised as: [weights, recurrent layer weights] or [W, U].\n", "file_path": "libraries/predictors/neural/include/GRULayer.h", "rank": 43, "score": 260742.54951058232 }, { "content": " class RecurrentLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using MatrixType = typename Layer<ElementType>::MatrixType;\n\n using MatrixReferenceType = typename Layer<ElementType>::ConstMatrixReferenceType;\n\n using ConstTensorReferenceType = typename Layer<ElementType>::ConstTensorReferenceType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n\n\n /// <summary> Default constructor </summary>\n\n RecurrentLayer();\n\n\n\n /// <summary> Instantiates an instance of a recurrent layer </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"weights\"> Weights for the layers should be in the form [Weights, Recurrent weights]. </param>\n", "file_path": "libraries/predictors/neural/include/RecurrentLayer.h", "rank": 44, "score": 260742.54951058232 }, { "content": " class SoftmaxLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::AssignValues;\n\n\n\n /// <summary> Instantiates an instance of a softmax layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n SoftmaxLayer(const LayerParameters& layerParameters);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n SoftmaxLayer() {}\n\n\n\n /// <summary> Feeds the input forward through the layer and returns a reference to the output. </summary>\n\n void Compute() override;\n\n\n\n /// <summary> Indicates the kind of layer. </summary>\n\n ///\n", "file_path": "libraries/predictors/neural/include/SoftmaxLayer.h", "rank": 45, "score": 260742.54951058232 }, { "content": " class PoolingLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using PoolingFunction = PoolingFunctionType<ElementType>;\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using Layer<ElementType>::GetLayerParameters;\n\n using Layer<ElementType>::GetInput;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::GetInputShapeMinusPadding;\n\n using Layer<ElementType>::GetOutputShapeMinusPadding;\n\n \n\n /// <summary> Instantiates an instance of a pooling layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"poolingParameters\"> Specifies the pooling characteristics of the layer. </param>\n\n PoolingLayer(const LayerParameters& layerParameters, PoolingParameters poolingParameters);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n PoolingLayer() {}\n\n\n", "file_path": "libraries/predictors/neural/include/PoolingLayer.h", "rank": 46, "score": 260742.54951058232 }, { "content": " class ConvolutionalLayer : public Layer<ElementType>\n\n {\n\n public:\n\n ConvolutionalLayer(const LayerParameters& layerParameters, const ConvolutionalParameters& convolutionalParameters, const ell::api::math::Tensor<ElementType>& weightsTensor)\n\n : Layer<ElementType>(layerParameters), weights(weightsTensor.data, weightsTensor.shape.rows, weightsTensor.shape.columns, weightsTensor.shape.channels), convolutionalParameters(convolutionalParameters)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::convolution; }\n\n\n\n API_READONLY(ell::api::math::Tensor<ElementType> weights);\n\n const ConvolutionalParameters convolutionalParameters;\n\n };\n\n\n\n // Api projections for FullyConnectedLayer\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 47, "score": 260573.26697308128 }, { "content": " class PoolingLayer : public Layer<ElementType>\n\n {\n\n public:\n\n PoolingLayer(const LayerParameters& layerParameters, const PoolingParameters& poolingParameters, PoolingType poolingType)\n\n : Layer<ElementType>(layerParameters), poolingType(poolingType), poolingParameters(poolingParameters)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::pooling; }\n\n\n\n const PoolingType poolingType;\n\n const PoolingParameters poolingParameters;\n\n };\n\n\n\n // Api projection for RegionDetectionLayer\n\n using RegionDetectionParameters = ell::predictors::neural::RegionDetectionParameters;\n\n\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 48, "score": 260573.26697308128 }, { "content": " class SoftmaxLayer : public Layer<ElementType>\n\n {\n\n public:\n\n SoftmaxLayer(const LayerParameters& layerParameters)\n\n : Layer<ElementType>(layerParameters)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::softmax; }\n\n };\n\n\n\n // Api projection for ScalingLayer\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 49, "score": 260573.26697308128 }, { "content": " class BiasLayer : public Layer<ElementType>\n\n {\n\n public:\n\n BiasLayer(const LayerParameters& layerParameters, const std::vector<ElementType>& bias)\n\n : Layer<ElementType>(layerParameters), bias(bias)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::bias; }\n\n\n\n const std::vector<ElementType> bias;\n\n };\n\n\n\n // Api projections for BinaryConvolutionalLayer\n\n using BinaryConvolutionMethod = ell::predictors::neural::BinaryConvolutionMethod;\n\n using BinaryConvolutionalParameters = ell::predictors::neural::BinaryConvolutionalParameters;\n\n\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 50, "score": 260573.26697308128 }, { "content": " class GRULayer : public Layer<ElementType>\n\n {\n\n public:\n\n GRULayer(const LayerParameters& layerParameters,\n\n const ell::api::math::Tensor<ElementType>& updateWeightsTensor,\n\n const ell::api::math::Tensor<ElementType>& resetWeightsTensor,\n\n const ell::api::math::Tensor<ElementType>& hiddenWeightsTensor,\n\n const ell::api::math::Tensor<ElementType>& updateBiasTensor,\n\n const ell::api::math::Tensor<ElementType>& resetBiasTensor,\n\n const ell::api::math::Tensor<ElementType>& hiddenBiasTensor,\n\n ActivationType activation,\n\n ActivationType recurrentActivation)\n\n : Layer<ElementType>(layerParameters),\n\n updateWeights(updateWeightsTensor),\n\n resetWeights(resetWeightsTensor),\n\n hiddenWeights(hiddenWeightsTensor),\n\n updateBias(updateBiasTensor),\n\n resetBias(resetBiasTensor),\n\n hiddenBias(hiddenBiasTensor),\n\n activation(activation), recurrentActivation(recurrentActivation)\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 51, "score": 260573.26697308128 }, { "content": " class LSTMLayer : public Layer<ElementType>\n\n {\n\n public:\n\n LSTMLayer(const LayerParameters& layerParameters, const ell::api::math::Tensor<ElementType>& weightsTensor)\n\n : Layer<ElementType>(layerParameters), weights(weightsTensor.data, weightsTensor.shape.rows, weightsTensor.shape.columns, weightsTensor.shape.channels)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::lstm; }\n\n\n\n API_READONLY(ell::api::math::Tensor<ElementType> weights);\n\n };\n\n\n\n // Api projections for PoolingLayer\n\n using PoolingParameters = ell::predictors::neural::PoolingParameters;\n\n\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 52, "score": 260573.26697308128 }, { "content": " class ActivationLayer : public Layer<ElementType>\n\n {\n\n public:\n\n ActivationLayer(const LayerParameters& layerParameters, ActivationType activation)\n\n : Layer<ElementType>(layerParameters), activation(activation)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::activation; }\n\n\n\n const ActivationType activation;\n\n };\n\n\n\n // Api projection for PReLUActivationLayer\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 53, "score": 260573.26697308128 }, { "content": " class ScalingLayer : public Layer<ElementType>\n\n {\n\n public:\n\n ScalingLayer(const LayerParameters& layerParameters, const std::vector<ElementType>& scales)\n\n : Layer<ElementType>(layerParameters), scales(scales)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::scaling; }\n\n\n\n const std::vector<ElementType> scales;\n\n };\n\n}\n\n}\n\n}\n\n}\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 54, "score": 260573.26697308128 }, { "content": " bool isInterleavedOrder;\n\n };\n\n\n\nprotected:\n\n void Compute() const override;\n\n bool Refine(model::ModelTransformer& transformer) const override;\n\n void WriteToArchive(utilities::Archiver& archiver) const override;\n\n void ReadFromArchive(utilities::Unarchiver& archiver) override;\n\n\n\nprivate:\n\n NeuralNetworkLayerNodeBase<ValueType>* AddLayerNode(model::ModelTransformer& transformer, Layer& layer, const model::PortElements<ValueType>& layerInputs, const NetworkCompileOptions& options, NetworkCompileState& state) const;\n\n\n\n // Input\n\n model::InputPort<ValueType> _input;\n\n\n\n // Output\n\n model::OutputPort<ValueType> _output;\n\n\n\n // Pointer to the predictor\n\n PredictorType _predictor;\n\n};\n\n}\n\n}\n\n\n\n#include \"../tcc/NeuralNetworkPredictorNode.tcc\"\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 55, "score": 259017.03643690885 }, { "content": "////////////////////////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Project: Embedded Learning Library (ELL)\n\n// File: NeuralNetworkPredictorNode.h (nodes)\n\n// Authors: Chuck Jacobs, Byron Changuion\n\n//\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n\n\n// model\n\n#include \"Model.h\"\n\n#include \"ModelTransformer.h\"\n\n#include \"Node.h\"\n\n\n\n// nodes\n\n#include \"ActivationLayerNode.h\"\n\n#include \"BatchNormalizationLayerNode.h\"\n\n#include \"BiasLayerNode.h\"\n\n#include \"BinaryConvolutionalLayerNode.h\"\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 56, "score": 259008.0375335537 }, { "content": "// utilities\n\n#include \"TypeName.h\"\n\n\n\n// stl\n\n#include <functional>\n\n#include <string>\n\n#include <type_traits>\n\n\n\nnamespace ell\n\n{\n\nnamespace nodes\n\n{\n\n/// <summary> A node that represents a neural network. </summary>\n\ntemplate <typename ValueType>\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 57, "score": 258991.72538586232 }, { "content": "\n\n /// <summary> Makes a copy of this node in the model being constructed by the transformer </summary>\n\n void Copy(model::ModelTransformer& transformer) const override;\n\n\n\n /// <summary> Options to control how the network is compiled into nodes </summary>\n\n struct NetworkCompileOptions\n\n {\n\n /// <summary> Use diagonal convolution (vs. im2col-based convolution)\n\n bool useDiagonalConvolution;\n\n\n\n /// <summary> Ensure the output of the nodes implementing a layer is in the canonical row, column, channel order </summary>\n\n bool alwaysConvertToInterleaved;\n\n\n\n /// <summary> When using im2col-based convolution, construct the transpose of the receptive field matrix </summary>\n\n bool transposeReceptiveFieldMatrix;\n\n };\n\n\n\n struct NetworkCompileState\n\n {\n\n /// <summary> Indicates the current order of input data. If `true`, it's in the canonical row, column, channel order. </summary>\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 58, "score": 258988.05125744708 }, { "content": "#include \"ConvolutionalLayerNode.h\"\n\n#include \"FullyConnectedLayerNode.h\"\n\n#include \"GRULayerNode.h\"\n\n#include \"LSTMLayerNode.h\"\n\n#include \"PoolingLayerNode.h\"\n\n#include \"RegionDetectionLayerNode.h\"\n\n#include \"ScalingLayerNode.h\"\n\n#include \"SoftmaxLayerNode.h\"\n\n\n\n// predictors\n\n#include \"NeuralNetworkPredictor.h\"\n\n\n\n// activation and pooling functions\n\n#include \"LeakyReLUActivation.h\"\n\n#include \"MaxPoolingFunction.h\"\n\n#include \"MeanPoolingFunction.h\"\n\n#include \"ParametricReLUActivation.h\"\n\n#include \"ReLUActivation.h\"\n\n#include \"SigmoidActivation.h\"\n\n\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 59, "score": 258985.49222832304 }, { "content": "\n\n /// <summary> Returns the underlying predictor </summary>\n\n ///\n\n /// <returns> The predictor wrapped by this node </returns>\n\n const PredictorType& GetPredictor() const { return _predictor; }\n\n\n\n /// <summary> Returns the underlying predictor </summary>\n\n ///\n\n /// <returns> The predictor wrapped by this node </returns>\n\n PredictorType& GetPredictor() { return _predictor; }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n static std::string GetTypeName() { return utilities::GetCompositeTypeName<ValueType>(\"NeuralNetworkPredictorNode\"); }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n std::string GetRuntimeTypeName() const override { return GetTypeName(); }\n", "file_path": "libraries/nodes/include/NeuralNetworkPredictorNode.h", "rank": 60, "score": 258978.9020015295 }, { "content": "\n\n /// <summary> Gets the LayerParameters from the layer wrapped by this node </summary>\n\n virtual typename predictors::neural::Layer<ValueType>::LayerParameters GetLayerParameters() const = 0;\n\n\n\n /// <summary> Get the input padding requested by the layer </summary>\n\n predictors::neural::PaddingParameters GetRequestedInputPadding() const { return GetLayerParameters().inputPaddingParameters; }\n\n\n\n /// <summary> Get the output padding requested by the layer </summary>\n\n predictors::neural::PaddingParameters GetRequestedOutputPadding() const { return GetLayerParameters().inputPaddingParameters; }\n\n\n\n /// <summary> Get the size of the output port </summary>\n\n size_t GetOutputSize() const { return _output.Size(); }\n\n\n\n protected:\n\n NeuralNetworkLayerNodeBase();\n\n NeuralNetworkLayerNodeBase(const model::PortElements<ValueType>& input, const NeuralNetworkLayerNodeParameters& parameters, size_t outputSize);\n\n\n\n void WriteToArchive(utilities::Archiver& archiver) const override;\n\n void ReadFromArchive(utilities::Unarchiver& archiver) override;\n\n\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 61, "score": 258797.04883073023 }, { "content": " model::PortMemoryLayout CalculateMemoryLayout(size_t padding, typename predictors::neural::Layer<ValueType>::Shape dataBufferSize);\n\n void Copy(model::ModelTransformer& transformer) const override;\n\n void Compute() const override;\n\n utilities::ArchiveVersion GetArchiveVersion() const override;\n\n bool CanReadArchiveVersion(const utilities::ArchiveVersion& version) const override;\n\n void WriteToArchive(utilities::Archiver& archiver) const override;\n\n void ReadFromArchive(utilities::Unarchiver& archiver) override;\n\n\n\n using NeuralNetworkLayerNodeBase<ValueType>::_input;\n\n using NeuralNetworkLayerNodeBase<ValueType>::_output;\n\n\n\n mutable typename LayerType::TensorType _inputTensor;\n\n mutable LayerType _layer; // mutable to get around Compute being non-const\n\n bool HasState() const override { return true; } // stored state: inputLayout, outputLayout\n\n\n\n private:\n\n model::PortMemoryLayout _inputLayout;\n\n model::PortMemoryLayout _outputLayout;\n\n math::TensorShape _inputShape;\n\n };\n\n\n\n // helper:\n\n template <typename LayerType>\n\n typename LayerType::LayerParameters GetLayerNodeParameters(const typename LayerType::TensorType& inputTensor, const typename LayerType::LayerParameters& layerParameters);\n\n}\n\n}\n\n\n\n#include \"../tcc/NeuralNetworkLayerNode.tcc\"\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 62, "score": 258796.93298120855 }, { "content": " // Input\n\n model::InputPort<ValueType> _input;\n\n\n\n // Output\n\n model::OutputPort<ValueType> _output;\n\n\n\n NeuralNetworkLayerNodeParameters _parameters;\n\n };\n\n\n\n /// <summary> Base class for neural network layer nodes. </summary\n\n template <typename DerivedType, typename NodeLayerType, typename ValueType>\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 63, "score": 258794.33529668953 }, { "content": "\n\n// stl\n\n#include <string>\n\n#include <type_traits>\n\n\n\nnamespace ell\n\n{\n\nnamespace nodes\n\n{\n\n /// <summary> Parameters to influence how neural network layers behave when embedded as nodes in a graph </summary>\n\n struct NeuralNetworkLayerNodeParameters\n\n {\n\n bool includePaddingInInputData;\n\n };\n\n\n\n /// <summary> Base class for neural network layer nodes. </summary\n\n template <typename ValueType>\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 64, "score": 258789.98696103969 }, { "content": "////////////////////////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Project: Embedded Learning Library (ELL)\n\n// File: NeuralNetworkLayerNode.h (nodes)\n\n// Authors: Chuck Jacobs\n\n//\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n\n\n// model\n\n#include \"CompilableNode.h\"\n\n#include \"IRMapCompiler.h\"\n\n#include \"Model.h\"\n\n#include \"ModelTransformer.h\"\n\n#include \"Node.h\"\n\n#include \"PortMemoryLayout.h\"\n\n\n\n// predictors\n\n#include \"Layer.h\"\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 65, "score": 258786.72888685885 }, { "content": " /// <summary> Gets the layer being wrapped </summary>\n\n const LayerType& GetLayer() const { return _layer; }\n\n\n\n /// <summary> Gets information about the input memory layout </summary>\n\n model::PortMemoryLayout& GetInputMemoryLayout() override { return _inputLayout; }\n\n\n\n /// <summary> Gets information about the input memory layout </summary>\n\n const model::PortMemoryLayout& GetInputMemoryLayout() const override { return _inputLayout; }\n\n\n\n /// <summary> Gets information about the output memory layout </summary>\n\n const model::PortMemoryLayout& GetOutputMemoryLayout() const override { return _outputLayout; }\n\n\n\n /// <summary> Gets information about the output memory layout </summary>\n\n model::PortMemoryLayout& GetOutputMemoryLayout() override { return _outputLayout; }\n\n\n\n /// <summary> Gets the LayerParameters from the layer wrapped by this node </summary>\n\n typename predictors::neural::Layer<ValueType>::LayerParameters GetLayerParameters() const override { return _layer.GetLayerParameters(); }\n\n\n\n protected:\n\n size_t NumInputDimensions() const { return _inputLayout.NumDimensions(); }\n", "file_path": "libraries/nodes/include/NeuralNetworkLayerNode.h", "rank": 66, "score": 258780.22991951753 }, { "content": " class BinaryReceptiveFieldMatrixNode : public model::CompilableNode\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n const model::InputPort<ValueType>& input = _input;\n\n const model::OutputPort<PackedBitsType>& output = _output;\n\n /// @}\n\n\n\n /// <summary></summary>\n\n BinaryReceptiveFieldMatrixNode();\n\n\n\n /// <summary></summary>\n\n BinaryReceptiveFieldMatrixNode(const model::PortElements<ValueType>& input,\n\n const predictors::neural::BinaryConvolutionalParameters& convolutionalParameters,\n\n const model::PortMemoryLayout& inputMemoryLayout,\n\n const model::PortMemoryLayout& outputMemoryLayout);\n\n\n\n /// <summary> Gets information about the input memory layout </summary>\n\n const model::PortMemoryLayout& GetInputMemoryLayout() const { return _inputMemoryLayout; }\n", "file_path": "libraries/nodes/include/BinaryConvolutionalLayerNode.h", "rank": 67, "score": 257942.98407392 }, { "content": " class Model;\n\n\n", "file_path": "libraries/model/include/PortElements.h", "rank": 68, "score": 255467.4513407666 }, { "content": " class RegionDetectionLayer : public Layer<ElementType>\n\n {\n\n public:\n\n RegionDetectionLayer(const LayerParameters& layerParameters, const RegionDetectionParameters& detectionParameters)\n\n : Layer<ElementType>(layerParameters), detectionParameters(detectionParameters)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::region; }\n\n\n\n const RegionDetectionParameters detectionParameters;\n\n };\n\n\n\n // Api projection for SoftmaxLayer\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 69, "score": 255039.67817572076 }, { "content": " class FullyConnectedLayer : public Layer<ElementType>\n\n {\n\n public:\n\n FullyConnectedLayer(const LayerParameters& layerParameters, const ell::api::math::Tensor<ElementType>& weightsTensor)\n\n : Layer<ElementType>(layerParameters), weights(weightsTensor.data, weightsTensor.shape.rows, weightsTensor.shape.columns, weightsTensor.shape.channels)\n\n {\n\n }\n\n\n\n LayerType GetLayerType() const override { return LayerType::fullyConnected; }\n\n\n\n API_READONLY(ell::api::math::Tensor<ElementType> weights);\n\n };\n\n\n\n // Api projections for GRULayer\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 70, "score": 255039.67817572076 }, { "content": "////////////////////////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Project: Embedded Learning Library (ELL)\n\n// File: InputLayer.h (neural)\n\n// Authors: Byron Changuion\n\n//\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n#include \"Layer.h\"\n\n\n\n// stl\n\n#include <vector>\n\n\n\nnamespace ell\n\n{\n\nnamespace predictors\n\n{\n\nnamespace neural\n\n{\n\n \n\n\n\n /// <summary> An input layer in a neural network. This is the only layer type that takes input from an external source, and not from the output of another layer.\n\n /// This must be the first layer in the list of layers that get set on a Neural Predictor.\n\n /// </summary>\n\n template <typename ElementType>\n", "file_path": "libraries/predictors/neural/include/InputLayer.h", "rank": 71, "score": 254735.86130036027 }, { "content": "\n\n protected:\n\n void WriteToArchive(utilities::Archiver& archiver) const override;\n\n void ReadFromArchive(utilities::Unarchiver& archiver) override;\n\n\n\n private:\n\n using Layer<ElementType>::_layerParameters;\n\n using Layer<ElementType>::_output;\n\n\n\n VectorType _scale;\n\n TensorType _data;\n\n };\n\n\n\n}\n\n}\n\n}\n\n\n\n#include \"../tcc/InputLayer.tcc\"\n\n\n", "file_path": "libraries/predictors/neural/include/InputLayer.h", "rank": 72, "score": 254716.47098053718 }, { "content": "\n\n /// <summary> The padding requirements for the input. </summary>\n\n PaddingParameters inputPaddingParameters;\n\n\n\n /// <summary> The extents of the tensor in logical order (row, column, channel). This size includes padding. </summary>\n\n Shape outputShape;\n\n\n\n /// <summary> The padding requirements for the output. </summary>\n\n PaddingParameters outputPaddingParameters;\n\n\n\n /// <summary> The scale factor to apply to each input value. Default is undefined. </summary>\n\n ElementType scale;\n\n };\n\n\n\n /// <summary> Instantiates an instance of an input layer. </summary>\n\n ///\n\n /// <param name=\"inputParameters\"> The parameters for the input layer. </param>\n\n /// <param name=\"inputParameters\"> </param>\n\n InputLayer(const InputParameters& inputParameters);\n\n\n", "file_path": "libraries/predictors/neural/include/InputLayer.h", "rank": 73, "score": 254711.70863190823 }, { "content": " /// <returns> The output tensor. </returns>\n\n const TensorType& GetInput() const { return _data; }\n\n\n\n /// <summary> Feeds the input forward through the layer. </summary>\n\n void Compute() override;\n\n\n\n /// <summary> Indicates the kind of layer. </summary>\n\n ///\n\n /// <returns> An enum indicating the layer type. </returns>\n\n LayerType GetLayerType() const override { return LayerType::input; }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n static std::string GetTypeName() { return utilities::GetCompositeTypeName<ElementType>(\"InputLayer\"); }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n std::string GetRuntimeTypeName() const override { return GetTypeName(); }\n", "file_path": "libraries/predictors/neural/include/InputLayer.h", "rank": 74, "score": 254709.8260373206 }, { "content": " /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n InputLayer() : _data(0, 0, 0) {}\n\n\n\n /// <summary> Sets the input. </summary>\n\n ///\n\n /// <param name=\"input\"> Copies the input vector to the input tensor. </param>\n\n void SetInput(const DataVectorType& input);\n\n\n\n /// <summary> Sets the input. </summary>\n\n ///\n\n /// <param name=\"input\"> Copies the input vector to the input tensor. </param>\n\n void SetInput(const std::vector<ElementType>& input);\n\n\n\n /// <summary> Gets a writeable reference to the input. </summary>\n\n ///\n\n /// <returns> The output tensor. </returns>\n\n TensorType& GetInput() { return _data; }\n\n\n\n /// <summary> Gets a const reference to the input. </summary>\n\n ///\n", "file_path": "libraries/predictors/neural/include/InputLayer.h", "rank": 75, "score": 254705.3382576544 }, { "content": " class L2NormSquaredNode : public model::Node\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n const model::InputPort<ValueType>& input = _input;\n\n const model::OutputPort<ValueType>& output = _output;\n\n /// @}\n\n\n\n /// <summary> Default Constructor </summary>\n\n L2NormSquaredNode();\n\n\n\n /// <summary> Constructor </summary>\n\n /// <param name=\"input\"> The signal to take the squared magnitude of </param>\n\n L2NormSquaredNode(const model::PortElements<ValueType>& input);\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n static std::string GetTypeName() { return utilities::GetCompositeTypeName<ValueType>(\"L2NormSquaredNode\"); }\n", "file_path": "libraries/nodes/include/L2NormSquaredNode.h", "rank": 76, "score": 254299.1378680695 }, { "content": " /// <summary> A node that represents a single-element threshold predictor. </summary>\n\n class SingleElementThresholdNode : public model::Node\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n const model::InputPort<double>& input = _input;\n\n const model::OutputPort<bool>& output = _output;\n\n /// @}\n\n\n\n using SingleElementThresholdPredictor = predictors::SingleElementThresholdPredictor;\n\n\n\n /// <summary> Default Constructor </summary>\n\n SingleElementThresholdNode();\n\n\n\n /// <summary> Constructor </summary>\n\n ///\n\n /// <param name=\"input\"> The signal to predict from </param>\n\n /// <param name=\"predictor\"> The linear predictor to use when making the prediction. </param>\n\n SingleElementThresholdNode(const model::PortElements<double>& input, const SingleElementThresholdPredictor& predictor);\n\n\n", "file_path": "libraries/nodes/include/SingleElementThresholdNode.h", "rank": 77, "score": 254186.84043733255 }, { "content": " class RecurrentLayerNode : public NeuralNetworkLayerNode<RecurrentLayerNode<ValueType, ActivationFunctionType>, predictors::neural::RecurrentLayer<ValueType, ActivationFunctionType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::RecurrentLayer<ValueType, ActivationFunctionType>;\n\n using BaseType = NeuralNetworkLayerNode<RecurrentLayerNode<ValueType, ActivationFunctionType>, predictors::neural::RecurrentLayer<ValueType, ActivationFunctionType>, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n RecurrentLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n RecurrentLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::RecurrentLayer<ValueType, ActivationFunctionType>& layer);\n\n\n", "file_path": "libraries/nodes/include/RecurrentLayerNode.h", "rank": 78, "score": 254150.15071432496 }, { "content": " class PoolingLayerNode : public NeuralNetworkLayerNode<PoolingLayerNode<ValueType, PoolingFunctionType>, predictors::neural::PoolingLayer<ValueType, PoolingFunctionType>, ValueType>\n\n {\n\n public:\n\n using LayerType = predictors::neural::PoolingLayer<ValueType, PoolingFunctionType>;\n\n using BaseType = NeuralNetworkLayerNode<PoolingLayerNode<ValueType, PoolingFunctionType>, LayerType, ValueType>;\n\n\n\n /// @name Input and Output Ports\n\n /// @{\n\n using BaseType::input;\n\n using BaseType::output;\n\n /// @}\n\n\n\n PoolingLayerNode() = default;\n\n\n\n /// <summary> Constructor from a layer. </summary>\n\n ///\n\n /// <param name=\"input\"> The input to the layer. </param>\n\n /// <param name=\"layer\"> The bias layer to wrap. </param>\n\n PoolingLayerNode(const model::PortElements<ValueType>& input, const predictors::neural::PoolingLayer<ValueType, PoolingFunctionType>& layer);\n\n\n", "file_path": "libraries/nodes/include/PoolingLayerNode.h", "rank": 79, "score": 254150.150714325 }, { "content": " /// <summary> A node that represents a ProtoNN predictor. </summary>\n\n class ProtoNNPredictorNode : public model::Node\n\n {\n\n public:\n\n /// @name Input and Output Ports\n\n /// @{\n\n const model::InputPort<double>& input = _input;\n\n const model::OutputPort<double>& output = _output;\n\n\n\n /// @}\n\n\n\n using ProtoNNPredictor = predictors::ProtoNNPredictor;\n\n\n\n /// <summary> Default Constructor </summary>\n\n ProtoNNPredictorNode();\n\n\n\n /// <summary> Constructor </summary>\n\n ///\n\n /// <param name=\"input\"> The signal to predict from </param>\n\n /// <param name=\"outputSize\">The size of the output vector</param>\n\n /// <param name=\"predictor\"> The ProtoNN predictor to use when making the prediction. </param>\n", "file_path": "libraries/nodes/include/ProtoNNPredictorNode.h", "rank": 80, "score": 254034.8906439876 }, { "content": "void TestInputLayerNode(size_t outputPadding = 0);\n", "file_path": "libraries/model/test/include/CompilableNodesTest.h", "rank": 81, "score": 252353.92819993934 }, { "content": " class Layer\n\n {\n\n public:\n\n Layer(const LayerParameters& layerParameters)\n\n : parameters(layerParameters) {}\n\n virtual ~Layer() {}\n\n\n\n virtual LayerType GetLayerType() const = 0;\n\n\n\n template <class LayerType>\n\n LayerType& As()\n\n {\n\n return *(dynamic_cast<LayerType*>(this));\n\n }\n\n\n\n template <class LayerType>\n\n bool Is()\n\n {\n\n return dynamic_cast<LayerType*>(this) != nullptr;\n\n }\n\n\n\n const LayerParameters parameters;\n\n };\n\n\n", "file_path": "interfaces/common/include/NeuralLayersInterface.h", "rank": 82, "score": 250020.44971598458 }, { "content": " class RegionDetectionLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using Base = Layer<ElementType>;\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n\n\n /// <summary> Instantiates an instance of a region detection layer. </summary>\n\n ///\n\n /// <param name=\"regionDetectionParams\"> The parameters desribing the configuration of this layer. </param>\n\n /// <param name=\"anchorScales\"> The values to scale the width and height for each of the anchor regions.\n\n /// The number of elements should equal 2 x numBoxesPerCell. </param>\n\n RegionDetectionLayer(const LayerParameters& layerParameters, RegionDetectionParameters regionDetectionParamss);\n\n\n\n /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n RegionDetectionLayer() : _regionDetectionParams({}) {}\n\n\n\n /// <summary> Feeds the input forward through the layer </summary>\n\n void Compute() override;\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n", "file_path": "libraries/predictors/neural/include/RegionDetectionLayer.h", "rank": 83, "score": 249938.1486966953 }, { "content": " class FullyConnectedLayer : public Layer<ElementType>\n\n {\n\n public:\n\n using LayerParameters = typename Layer<ElementType>::LayerParameters;\n\n using VectorType = typename Layer<ElementType>::VectorType;\n\n using MatrixType = typename Layer<ElementType>::MatrixType;\n\n using ConstMatrixReferenceType = typename Layer<ElementType>::ConstMatrixReferenceType;\n\n using ConstTensorReferenceType = typename Layer<ElementType>::ConstTensorReferenceType;\n\n using Layer<ElementType>::GetOutputMinusPadding;\n\n using Layer<ElementType>::NumOutputRowsMinusPadding;\n\n using Layer<ElementType>::NumOutputColumnsMinusPadding;\n\n using Layer<ElementType>::NumOutputChannels;\n\n\n\n /// <summary> Instantiates an instance of a fully connected layer. </summary>\n\n ///\n\n /// <param name=\"layerParameters\"> The parameters common to every layer. </param>\n\n /// <param name=\"weights\"> The weights to apply as a matrix in rowMajor order, where number of rows equals output neurons\n\n /// and columns represent input (in logical Tensor order: row, column, channel). </param>\n\n FullyConnectedLayer(const LayerParameters& layerParameters, ConstMatrixReferenceType& weights);\n\n\n", "file_path": "libraries/predictors/neural/include/FullyConnectedLayer.h", "rank": 84, "score": 249938.1486966953 }, { "content": " class Port;\n\n\n", "file_path": "libraries/model/include/Node.h", "rank": 85, "score": 248437.84052759103 }, { "content": " class Node;\n\n\n", "file_path": "libraries/model/include/Port.h", "rank": 86, "score": 248382.663799053 }, { "content": " def get_output_port_elements_for_node(self, ell_node: ell.nodes.Node,\n\n output_label: str = \"output\"):\n\n \"\"\"\n\n Returns an ell.nodes.PortElements for the corresponding ELL node's \n\n output port that corresponds to 'output_label'.\n\n \"\"\"\n\n try:\n\n output_link = ell_node.GetOutputPort(output_label)\n\n except BaseException as exception:\n\n raise Exception(\"Cannot get output port {} for {}\".format(output_label, ell_node.GetId()))\n", "file_path": "tools/importers/common/converters.py", "rank": 87, "score": 247306.19235321108 }, { "content": "////////////////////////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Project: Embedded Learning Library (ELL)\n\n// File: BatchNormalizationLayer.h (neural)\n\n// Authors: Byron Changuion\n\n//\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n#include \"Layer.h\"\n\n\n\nnamespace ell\n\n{\n\nnamespace predictors\n\n{\n\n namespace neural\n\n {\n\n /// <summary> Indicates what term the epsilon will be added to in the denominator. </summary>\n", "file_path": "libraries/predictors/neural/include/BatchNormalizationLayer.h", "rank": 88, "score": 246411.36310892765 }, { "content": " /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n BatchNormalizationLayer() {}\n\n\n\n /// <summary> Feeds the input forward through the layer and returns a reference to the output. </summary>\n\n void Compute() override;\n\n\n\n /// <summary> Indicates the kind of layer. </summary>\n\n ///\n\n /// <returns> An enum indicating the layer type. </returns>\n\n LayerType GetLayerType() const override { return LayerType::batchNormalization; }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n static std::string GetTypeName() { return utilities::GetCompositeTypeName<ElementType>(\"BatchNormalizationLayer\"); }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n std::string GetRuntimeTypeName() const override { return GetTypeName(); }\n", "file_path": "libraries/predictors/neural/include/BatchNormalizationLayer.h", "rank": 89, "score": 246403.32705876481 }, { "content": "\n\n /// <summary> Returns the value to scale the output by. </summary>\n\n ///\n\n /// <returns> The value to scale the output by. </returns>\n\n const VectorType& GetScale() const { return _multiplicationValues; }\n\n\n\n /// <summary> Returns the value to offset the output by. </summary>\n\n ///\n\n /// <returns> The value to offset the output by. </returns>\n\n const VectorType& GetBias() const { return _additionValues; }\n\n\n\n protected:\n\n void WriteToArchive(utilities::Archiver& archiver) const override;\n\n void ReadFromArchive(utilities::Unarchiver& archiver) override;\n\n\n\n private:\n\n using Layer<ElementType>::_layerParameters;\n\n using Layer<ElementType>::_output;\n\n\n\n VectorType _multiplicationValues;\n", "file_path": "libraries/predictors/neural/include/BatchNormalizationLayer.h", "rank": 90, "score": 246394.6067342252 }, { "content": " VectorType _additionValues;\n\n ElementType _epsilon; // To ensure non-zero division, this is added to denominator\n\n EpsilonSummand _epsilonSummand;\n\n };\n\n }\n\n}\n\n}\n\n\n\n#include \"../tcc/BatchNormalizationLayer.tcc\"\n", "file_path": "libraries/predictors/neural/include/BatchNormalizationLayer.h", "rank": 91, "score": 246383.3648508628 }, { "content": "#include \"NeuralLayersInterface.h\"\n\n#endif\n\n\n\nnamespace ell\n\n{\n\nnamespace api\n\n{\n\nnamespace predictors\n\n{\n\n //\n\n // API classes for the neural predictor\n\n //\n\n template <typename ElementType>\n", "file_path": "interfaces/common/include/NeuralNetworkPredictorInterface.h", "rank": 92, "score": 246360.73054694297 }, { "content": "////////////////////////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Project: Embedded Learning Library (ELL)\n\n// File: NeuralNetworkPredictorInterface.h (interfaces)\n\n// Authors: Byron Changuion\n\n//\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#pragma once\n\n\n\n#ifndef SWIG\n\n\n\n// neural network predictor\n\n#include \"NeuralNetworkPredictor.h\"\n\n\n\n// stl\n\n#include <string>\n\n#include <vector>\n\n\n\n// apis\n\n#include \"MathInterface.h\"\n", "file_path": "interfaces/common/include/NeuralNetworkPredictorInterface.h", "rank": 93, "score": 246350.66987462575 }, { "content": "#endif\n\n\n\nprivate:\n\n \n\n#ifndef SWIG\n\n template <typename DerivedLayer>\n\n static auto& LayerAs(Layer* layer);\n\n\n\n static void AddLayer(Layer* layer, const std::unique_ptr<UnderlyingInputLayer>& underlyingInputLayer, UnderlyingLayers& underlyingLayers);\n\n\n\n // Specific layer factory functions\n\n static std::unique_ptr<UnderlyingLayer> CreateActivationLayer(neural::ActivationLayer<ElementType>& layer, const UnderlyingLayerParameters& parameters);\n\n\n\n template <template <typename> class ActivationFunctionType, template <typename> class RecurrentActivationFunctionType>\n\n static std::unique_ptr<UnderlyingLayer> CreateGRULayer(neural::GRULayer<ElementType>& layer, const UnderlyingLayerParameters& parameters);\n\n \n\n template <template <typename> class ActivationFunctionType>\n\n static std::unique_ptr<UnderlyingLayer> CreateGRULayer(neural::GRULayer<ElementType>& layer, const UnderlyingLayerParameters& parameters);\n\n \n\n static std::unique_ptr<UnderlyingLayer> CreateGRULayer(neural::GRULayer<ElementType>& layer, const UnderlyingLayerParameters& parameters);\n", "file_path": "interfaces/common/include/NeuralNetworkPredictorInterface.h", "rank": 94, "score": 246350.60898738066 }, { "content": "\n\n#endif\n\n\n\n std::shared_ptr<UnderlyingPredictor> _predictor;\n\n };\n\n}\n\n}\n\n}\n\n\n\n#include \"../tcc/NeuralNetworkPredictorInterface.tcc\"\n", "file_path": "interfaces/common/include/NeuralNetworkPredictorInterface.h", "rank": 95, "score": 246338.749038451 }, { "content": "////////////////////////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Project: Embedded Learning Library (ELL)\n\n// File: BinaryConvolutionalLayer.h (neural)\n\n// Authors: Byron Changuion\n\n//\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n#include \"Layer.h\"\n\n#include \"ConvolutionalLayer.h\"\n\n\n\n// math\n\n#include \"Matrix.h\"\n\n\n\nnamespace ell\n\n{\n\nnamespace predictors\n\n{\n\nnamespace neural\n\n{\n\n /// <summary> The method for performing binary convolutions. </summary>\n", "file_path": "libraries/predictors/neural/include/BinaryConvolutionalLayer.h", "rank": 96, "score": 246325.99409837704 }, { "content": " // Fills a matrix (backed by the array outputMatrix) where the columns the set of input values corresponding to a filter, stretched into a vector.\n\n // The number of columns is equal to the number of locations that a filter is slide over the input tensor.\n\n void ReceptiveFieldToColumns(ConstTensorReferenceType input, MatrixType& shapedInput);\n\n\n\n // Returns whether input zero padding is enabled\n\n bool HasInputZeroPadding() const;\n\n\n\n // Returns whether the row, column indices correspond to input zero padding\n\n bool IsInputZeroPadding(size_t row, size_t column) const;\n\n\n\n void ComputeWeightsMatrices(const ConstTensorReferenceType& weights);\n\n void ComputeRealValuedWeightsMatrix();\n\n void ComputeShapedInputPaddingMask();\n\n void InitializeIOMatrices();\n\n\n\n using Layer<ElementType>::_layerParameters;\n\n using Layer<ElementType>::_output;\n\n\n\n constexpr static size_t _binaryElementSize = 64;\n\n BinaryConvolutionalParameters _convolutionalParameters;\n", "file_path": "libraries/predictors/neural/include/BinaryConvolutionalLayer.h", "rank": 97, "score": 246325.30653484084 }, { "content": " /// <summary> Instantiates a blank instance. Used for unarchiving purposes only. </summary>\n\n BinaryConvolutionalLayer() : _realValuedShapedInputMatrix(0, 0), _realValuedWeightsMatrix(0, 0), _realValuedOutputMatrix(0, 0) {}\n\n\n\n /// <summary> Feeds the input forward through the layer and returns a reference to the output. </summary>\n\n void Compute() override;\n\n\n\n /// <summary> Indicates the kind of layer. </summary>\n\n ///\n\n /// <returns> An enum indicating the layer type. </returns>\n\n LayerType GetLayerType() const override { return LayerType::binaryConvolution; }\n\n\n\n /// <summary> Get the parameters used to control convolution. </summary>\n\n ///\n\n /// <returns> A BinaryConvolutionalParameters struct. </returns>\n\n const BinaryConvolutionalParameters& GetConvolutionalParameters() const { return _convolutionalParameters; }\n\n\n\n /// <summary> Get the weights for the convolution filters. </summary>\n\n ///\n\n /// <returns> The weights, packed into a Tensor. </returns>\n\n const MatrixType& GetRealFilterWeights() const { return _realValuedWeightsMatrix; }\n", "file_path": "libraries/predictors/neural/include/BinaryConvolutionalLayer.h", "rank": 98, "score": 246314.58751283484 }, { "content": "\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n static std::string GetTypeName() { return utilities::GetCompositeTypeName<ElementType>(\"BinaryConvolutionalLayer\"); }\n\n\n\n /// <summary> Gets the name of this type (for serialization). </summary>\n\n ///\n\n /// <returns> The name of this type. </returns>\n\n std::string GetRuntimeTypeName() const override { return GetTypeName(); }\n\n\n\n protected:\n\n void WriteToArchive(utilities::Archiver& archiver) const override;\n\n void ReadFromArchive(utilities::Unarchiver& archiver) override;\n\n\n\n private:\n\n // Fills a vector of vectors where each row is the set of input values corresponding to a filter, stretched into a vector.\n\n // The number of vectors is equal to the number of locations that the filter is slid over the input tensor.\n\n void ReceptiveFieldToBinaryRows(ConstTensorReferenceType input, std::vector<std::vector<uint64_t>>& shapedInput);\n\n\n", "file_path": "libraries/predictors/neural/include/BinaryConvolutionalLayer.h", "rank": 99, "score": 246307.67780630264 } ]
C++
src/Titon/Io/Node.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
<?hh namespace Titon\Io; use Titon\Io\Exception\MissingFileException; use Titon\Io\Exception\ExistingFileException; use Titon\Utility\Path; abstract class Node { const int OVERWRITE = 0; const int MERGE = 1; const int SKIP = 2; protected ?Folder $parent; protected string $path = ''; public function __construct(string $path, bool $create = false, int $mode = 0755) { $this->reset($path); if ($create) { $this->create($mode); } } public function accessTime(): int { if ($this->exists()) { return fileatime($this->path()); } return 0; } public function basename(): string { return pathinfo($this->path(), PATHINFO_BASENAME); } public function changeTime(): int { if ($this->exists()) { return filectime($this->path()); } return 0; } public function chgrp(int $group, bool $recursive = false): bool { if (!$this->exists()) { return false; } $path = $this->path(); $this->reset(); if (is_link($path)) { return lchgrp($path, $group); } return chgrp($path, $group); } public function chmod(int $mode, bool $recursive = false): bool { if (!$this->exists()) { return false; } $this->reset(); return chmod($this->path(), $mode); } public function chown(int $user, bool $recursive = false): bool { if (!$this->exists()) { return false; } $path = $this->path(); $this->reset(); if (is_link($path)) { return lchown($path, $user); } return chown($path, $user); } abstract public function copy(string $target, int $process = self::OVERWRITE, int $mode = 0755): ?Node; abstract public function create(int $mode = 0755): bool; abstract public function delete(): bool; public static function destroy(string $path): bool { if (!file_exists($path)) { return false; } return static::load($path)->delete(); } public function dir(): string { return dirname($this->path()) . '/'; } public function executable(): bool { return is_executable($this->path()); } public function exists(): bool { return file_exists($this->path()); } public function group(): int { if ($this->exists()) { return filegroup($this->path()); } return 0; } public function isAbsolute(): bool { return Path::isAbsolute($this->path()); } public function isRelative(): bool { return Path::isRelative($this->path()); } public static function load(string $path): Node { if (!file_exists($path)) { throw new MissingFileException(sprintf('No file or folder found at %s', $path)); } if (is_dir($path)) { return new Folder($path); } return new File($path); } public function modifyTime(): int { if ($this->exists()) { return filemtime($this->path()); } return 0; } public function move(string $target, bool $overwrite = true): bool { if (!$this->exists()) { return false; } if (file_exists($target)) { if ($overwrite) { static::destroy($target); } else { throw new ExistingFileException('Cannot move file as the target already exists'); } } if (rename($this->path(), $target)) { $this->reset($target); return true; } return false; } public function name(): string { return pathinfo($this->path(), PATHINFO_FILENAME); } public function owner(): int { if ($this->exists()) { return fileowner($this->path()); } return 0; } public function path(): string { return $this->pwd(); } public function parent(): ?Folder { if ($this->parent) { return $this->parent; } $folder = str_replace('\\', '/', dirname($this->path())); if ($folder !== '.' && $folder !== '/') { $this->parent = new Folder($folder); } return $this->parent; } public function permissions(): string { if ($this->exists()) { return substr(sprintf('%o', fileperms($this->path())), -4); } return ''; } public function pwd(): string { return $this->path; } public function readable(): bool { return is_readable($this->path()); } public function rename(string $name, bool $overwrite = true): bool { if (!$this->exists()) { return false; } $name = preg_replace('/[^_\-\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/imu', '-', basename($name)); if ($name === $this->name()) { return true; } $target = $this->dir() . $name; if (file_exists($target)) { if ($overwrite) { static::destroy($target); } else { throw new ExistingFileException('Cannot rename file as the target already exists'); } } if (rename($this->path(), $target)) { $this->reset($target); return true; } return false; } public function reset(string $path = ''): this { if ($path) { $this->path = str_replace('\\', '/', $path); } clearstatcache(); return $this; } abstract public function size(): int; public function writable(): bool { return is_writable($this->path()); } }
<?hh namespace Titon\Io; use Titon\Io\Exception\MissingFileException; use Titon\Io\Exception\ExistingFileException; use Titon\Utility\Path; abstract class Node { const int OVERWRITE = 0; const int MERGE = 1; const int SKIP = 2; protected ?Folder $parent; protected string $path = ''; public function __construct(string $path, bool $create = false, int $mode = 0755) { $this->reset($path); if ($create) { $this->create($mode); } } public function accessTime(): int { if ($this->exists()) { return fileatime($this->path()); } return 0; } public function basename(): string { return pathinfo($this->path(), PATHINFO_BASENAME); } public function changeTime(): int { if ($this->exists()) { return filectime($this->path()); } return 0; } public function chgrp(int $group, bool $recursive = false): bool { if (!$this->exists()) { return false; } $path = $this->path(); $this->reset(); if (is_link($path)) { return lchgrp($path, $group); } return chgrp($path, $group); } public function chmod(int $mode, bool $recursive = false): bool { if (!$this->exists()) { return false; } $this->reset(); return chmod($this
public function modifyTime(): int { if ($this->exists()) { return filemtime($this->path()); } return 0; } public function move(string $target, bool $overwrite = true): bool { if (!$this->exists()) { return false; } if (file_exists($target)) { if ($overwrite) { static::destroy($target); } else { throw new ExistingFileException('Cannot move file as the target already exists'); } } if (rename($this->path(), $target)) { $this->reset($target); return true; } return false; } public function name(): string { return pathinfo($this->path(), PATHINFO_FILENAME); } public function owner(): int { if ($this->exists()) { return fileowner($this->path()); } return 0; } public function path(): string { return $this->pwd(); } public function parent(): ?Folder { if ($this->parent) { return $this->parent; } $folder = str_replace('\\', '/', dirname($this->path())); if ($folder !== '.' && $folder !== '/') { $this->parent = new Folder($folder); } return $this->parent; } public function permissions(): string { if ($this->exists()) { return substr(sprintf('%o', fileperms($this->path())), -4); } return ''; } public function pwd(): string { return $this->path; } public function readable(): bool { return is_readable($this->path()); } public function rename(string $name, bool $overwrite = true): bool { if (!$this->exists()) { return false; } $name = preg_replace('/[^_\-\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/imu', '-', basename($name)); if ($name === $this->name()) { return true; } $target = $this->dir() . $name; if (file_exists($target)) { if ($overwrite) { static::destroy($target); } else { throw new ExistingFileException('Cannot rename file as the target already exists'); } } if (rename($this->path(), $target)) { $this->reset($target); return true; } return false; } public function reset(string $path = ''): this { if ($path) { $this->path = str_replace('\\', '/', $path); } clearstatcache(); return $this; } abstract public function size(): int; public function writable(): bool { return is_writable($this->path()); } }
->path(), $mode); } public function chown(int $user, bool $recursive = false): bool { if (!$this->exists()) { return false; } $path = $this->path(); $this->reset(); if (is_link($path)) { return lchown($path, $user); } return chown($path, $user); } abstract public function copy(string $target, int $process = self::OVERWRITE, int $mode = 0755): ?Node; abstract public function create(int $mode = 0755): bool; abstract public function delete(): bool; public static function destroy(string $path): bool { if (!file_exists($path)) { return false; } return static::load($path)->delete(); } public function dir(): string { return dirname($this->path()) . '/'; } public function executable(): bool { return is_executable($this->path()); } public function exists(): bool { return file_exists($this->path()); } public function group(): int { if ($this->exists()) { return filegroup($this->path()); } return 0; } public function isAbsolute(): bool { return Path::isAbsolute($this->path()); } public function isRelative(): bool { return Path::isRelative($this->path()); } public static function load(string $path): Node { if (!file_exists($path)) { throw new MissingFileException(sprintf('No file or folder found at %s', $path)); } if (is_dir($path)) { return new Folder($path); } return new File($path); }
random
[ { "content": " public function copy(string $target, int $process = self::MERGE, int $mode = 0755): ?Node {\n\n if (!$this->exists()) {\n\n return null;\n\n }\n\n\n\n // Delete the target folder if overwrite is true\n\n if ($process === self::OVERWRITE && file_exists($target)) {\n\n static::destroy($target);\n\n }\n\n\n\n // Create the target folder and reset folder path\n\n $destination = new Folder($target, true, $mode);\n\n $target = $destination->path();\n\n\n\n // Recursively copy over contents to new destination\n\n if ($contents = $this->read()) {\n\n foreach ($contents as $file) {\n\n $to = str_replace($this->path(), $target, $file->path());\n\n\n\n // Skip copy if target exists\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 1, "score": 657572.9135432713 }, { "content": " public function create(int $mode = 0755): bool {\n\n if (!$this->exists()) {\n\n return mkdir($this->path(), $mode, true);\n\n }\n\n\n\n return false;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n *\n\n * @return \\Titon\\Io\\Folder\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 2, "score": 633753.2711682812 }, { "content": " public function create(int $mode = 0755): bool {\n\n $folder = $this->parent();\n\n\n\n if (!$folder) {\n\n return false;\n\n }\n\n\n\n if (!$folder->exists()) {\n\n $folder->create();\n\n }\n\n\n\n if (!$this->exists() && $folder->writable()) {\n\n if (touch($this->path())) {\n\n if ($mode) {\n\n $this->chmod($mode);\n\n }\n\n\n\n return true;\n\n }\n\n }\n\n\n\n return false;\n\n }\n\n\n\n /**\n\n * Remove the file if it exists.\n\n *\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Io/File.hh", "rank": 3, "score": 582697.5168604227 }, { "content": " public function matches(string $pattern, bool $return = false, int $flags = 0): mixed {\n\n $matches = [];\n\n $regex = preg_match($pattern, $this->value(), $matches, $flags);\n\n\n\n return $return ? $matches : $regex;\n\n }\n\n\n\n /**\n\n * Pad the string with a defined character for a specific length.\n\n *\n\n * @param int $length\n\n * @param string $value\n\n * @param int $type\n\n * @return \\Titon\\Type\\StringBuffer\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 4, "score": 559230.532892925 }, { "content": " public function chgrp(int $group, bool $recursive = false): bool {\n\n if ($recursive) {\n\n if ($contents = $this->read()) {\n\n foreach ($contents as $file) {\n\n $file->chgrp($group, true);\n\n }\n\n }\n\n }\n\n\n\n return parent::chgrp($group);\n\n }\n\n\n\n /**\n\n * Change the permissions mode of the file.\n\n * If $recursive is true, set the mode on all children.\n\n *\n\n * @param int $mode\n\n * @param bool $recursive\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 7, "score": 530309.5617393558 }, { "content": " public function chmod(int $mode, bool $recursive = false): bool {\n\n if ($recursive) {\n\n if ($contents = $this->read()) {\n\n foreach ($contents as $file) {\n\n $file->chmod($mode, true);\n\n }\n\n }\n\n }\n\n\n\n return parent::chmod($mode);\n\n }\n\n\n\n /**\n\n * Change the owner of the file.\n\n * If $recursive is true, set the owner on all children.\n\n *\n\n * @param int $user\n\n * @param bool $recursive\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 8, "score": 530304.6112638105 }, { "content": " public function copy(string $target, int $process = self::OVERWRITE, int $mode = 0755): ?File {\n\n if (!$this->exists()) {\n\n return null;\n\n }\n\n\n\n if (file_exists($target) && $process !== self::OVERWRITE) {\n\n throw new ExistingFileException('Cannot copy file as the target already exists');\n\n }\n\n\n\n if (copy($this->path(), $target)) {\n\n $file = new File($target);\n\n $file->chmod($mode);\n\n\n\n return $file;\n\n }\n\n\n\n return null;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Io/File.hh", "rank": 9, "score": 528213.5038988425 }, { "content": " public function read(int $length = -1, string $mode = 'rb'): string {\n\n if (!$this->open($mode)) {\n\n return '';\n\n }\n\n\n\n if ($this->lock()) {\n\n if ($length === -1) {\n\n $length = $this->size() ?: 1;\n\n }\n\n\n\n $content = fread($this->handle, $length);\n\n\n\n $this->close();\n\n\n\n return $content;\n\n }\n\n\n\n return '';\n\n }\n\n\n\n /**\n\n * Reset the cache and path.\n\n *\n\n * @param string $path\n\n * @return $this\n\n * @throws \\Titon\\Io\\Exception\\InvalidPathException\n\n */\n", "file_path": "src/Titon/Io/File.hh", "rank": 10, "score": 515143.9477853278 }, { "content": " public function decrement(string $key, int $step = 1, int $initial = 0): int {\n\n $item = $this->getItem($key);\n\n\n\n $value = ((int) $item->get() ?: $initial) - $step;\n\n\n\n $item->set($value);\n\n\n\n $this->save($item);\n\n\n\n return $value;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Cache/Storage/AbstractStorage.hh", "rank": 11, "score": 501724.6770829136 }, { "content": " public function increment(string $key, int $step = 1, int $initial = 0): int {\n\n $item = $this->getItem($key);\n\n\n\n $value = ((int) $item->get() ?: $initial) + $step;\n\n\n\n $item->set($value);\n\n\n\n $this->save($item);\n\n\n\n return $value;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Cache/Storage/AbstractStorage.hh", "rank": 12, "score": 501724.6770829136 }, { "content": " public function indexOf(string $needle, bool $strict = true, int $offset = 0): int {\n\n return Str::indexOf($this->value(), $needle, $strict, $offset);\n\n }\n\n\n\n /**\n\n * Checks to see if the value is empty.\n\n *\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 13, "score": 501458.848874884 }, { "content": " public function contains(string $needle, bool $strict = true, int $offset = 0): bool {\n\n return Str::contains($this->value(), $needle, $strict, $offset);\n\n }\n\n\n\n /**\n\n * Checks to see if the string ends with a specific value.\n\n *\n\n * @uses Titon\\Utility\\Str\n\n *\n\n * @param string $value\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 14, "score": 501379.07805661275 }, { "content": " public function lastIndexOf(string $needle, bool $strict = true, int $offset = 0): int {\n\n return Str::lastIndexOf($this->value(), $needle, $strict, $offset);\n\n }\n\n\n\n /**\n\n * Return the string length.\n\n *\n\n * @return int\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 15, "score": 497501.66525776667 }, { "content": " public function toString(bool $indent = true, int $depth = 0): string {\n\n $xml = '';\n\n\n\n // Set root XML tag\n\n if ($this->isRoot()) {\n\n $xml = sprintf('<?xml%s?>', $this->formatAttributes($this->getDeclaration())) . PHP_EOL;\n\n }\n\n\n\n // Apply indenting for nested elements\n\n if ($indent) {\n\n $xml .= str_repeat(' ', $depth);\n\n }\n\n\n\n // Build the tag, its attributes and namespaces\n\n $xml .= sprintf('<%s%s%s',\n\n $this->getName(),\n\n $this->formatNamespaces($this->getNamespaces()),\n\n $this->formatAttributes($this->getAttributes())\n\n );\n\n\n", "file_path": "src/Titon/Type/Xml/Element.hh", "rank": 16, "score": 497149.5390655238 }, { "content": " public function open(string $mode): bool {\n\n if (!$this->exists()) {\n\n return false;\n\n }\n\n\n\n if (is_resource($this->handle)) {\n\n if ($mode === $this->mode) {\n\n return true;\n\n } else {\n\n $this->close();\n\n }\n\n }\n\n\n\n $this->reset();\n\n\n\n $this->handle = fopen($this->path(), $mode);\n\n $this->mode = $mode;\n\n\n\n return is_resource($this->handle);\n\n }\n\n\n\n /**\n\n * Prepend data to the beginning of a file.\n\n *\n\n * @param string $data\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Io/File.hh", "rank": 17, "score": 491216.34999441914 }, { "content": " public function move(string $target, bool $overwrite = true): bool {\n\n if (Path::ds($target, true) === Path::ds($this->path(), true)) {\n\n return true; // Don't move to the same location\n\n }\n\n\n\n return parent::move($target, $overwrite);\n\n }\n\n\n\n /**\n\n * Scan the folder and return a list of File and Folder objects.\n\n *\n\n * @param bool $sort\n\n * @param bool $recursive\n\n * @param int $filter\n\n * @return Vector<Node>\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 20, "score": 485370.45086465625 }, { "content": " public function provides(string $class): bool;\n\n\n\n /**\n\n * The `register` method is where any necessary retrieving and registering\n\n * with the Depository container will happen that is necessary for the\n\n * Service Provider.\n\n *\n\n * @return void\n\n */\n", "file_path": "src/Titon/Context/ServiceProvider.hh", "rank": 21, "score": 484672.25943253795 }, { "content": " public function find(string $pattern, int $filter = self::ALL): Vector<Node> {\n\n $contents = Vector {};\n\n\n\n if (!$this->exists()) {\n\n return $contents;\n\n }\n\n\n\n try {\n\n $iterator = new GlobIterator($this->path() . $pattern, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS);\n\n } catch (Exception $e) {\n\n return $contents;\n\n }\n\n\n\n /** @var \\SPLFileInfo $file */\n\n foreach ($iterator as $file) {\n\n if ($file->isDir() && ($filter === self::ALL || $filter === self::FOLDERS)) {\n\n $contents[] = new Folder($file->getPathname());\n\n\n\n } else if ($file->isFile() && ($filter === self::ALL || $filter === self::FILES)) {\n\n $contents[] = new File($file->getPathname());\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 22, "score": 484554.103676194 }, { "content": " public function write(string $data, string $mode = 'w', bool $close = true): bool {\n\n if (!$this->open($mode)) {\n\n return false;\n\n }\n\n\n\n if ($this->lock(LOCK_EX)) {\n\n $result = fwrite($this->handle, $data);\n\n\n\n $this->unlock();\n\n\n\n if ($close) {\n\n $this->close();\n\n }\n\n\n\n return (bool) $result;\n\n }\n\n\n\n return false;\n\n }\n\n\n\n}\n", "file_path": "src/Titon/Io/File.hh", "rank": 23, "score": 479974.3228687397 }, { "content": " public function __construct(string $path, string $mode = 'r+b') {\n\n if (!file_exists($path)) {\n\n throw new MissingFileException(sprintf('File does not exist at path %s', $path));\n\n }\n\n\n\n $this->setStream(fopen($path, $mode));\n\n }\n\n\n\n}", "file_path": "src/Titon/Http/Stream/FileStream.hh", "rank": 24, "score": 479923.02217158605 }, { "content": " public function lock(int $mode = LOCK_SH): bool {\n\n if (is_resource($this->handle)) {\n\n return flock($this->handle, $mode);\n\n }\n\n\n\n return false;\n\n }\n\n\n\n /**\n\n * Return an MD5 checksum of the file.\n\n *\n\n * @param bool $raw\n\n * @return string\n\n */\n", "file_path": "src/Titon/Io/File.hh", "rank": 25, "score": 475143.79627577425 }, { "content": " public function read(bool $sort = false, bool $recursive = false, int $filter = self::ALL): Vector<Node> {\n\n $contents = Vector {};\n\n\n\n if (!$this->exists()) {\n\n return $contents;\n\n }\n\n\n\n try {\n\n $flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;\n\n\n\n if ($recursive) {\n\n $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path(), $flags), RecursiveIteratorIterator::CHILD_FIRST);\n\n } else {\n\n $iterator = new FilesystemIterator($this->path(), $flags);\n\n }\n\n } catch (Exception $e) {\n\n return $contents;\n\n }\n\n\n\n /** @var \\SPLFileInfo $file */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 26, "score": 472585.59348630364 }, { "content": " public function __construct(string $name, string $value, mixed $expires = 0, string $path = '/', string $domain = '', bool $httpOnly = true, bool $secure = false) {\n\n $this->setName($name);\n\n $this->setValue($value);\n\n $this->setExpires($expires);\n\n $this->setPath($path);\n\n $this->setDomain($domain);\n\n $this->setHttpOnly($httpOnly);\n\n $this->setSecure($secure);\n\n }\n\n\n\n /**\n\n * Return the cookie as a valid HTTP cookie string.\n\n *\n\n * @return string\n\n */\n", "file_path": "src/Titon/Http/Cookie.hh", "rank": 29, "score": 470693.43244014843 }, { "content": " public function provides(string $className): bool {\n\n return $this->provides->linearSearch($className) >= 0;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Context/ServiceProvider/AbstractServiceProvider.hh", "rank": 31, "score": 464877.70467098895 }, { "content": " public function __construct(public string $string, public int $int = 0): void {}\n\n}\n", "file_path": "tests/Titon/Test/Stub/Annotation/BarAnnotationStub.hh", "rank": 32, "score": 464348.57019086985 }, { "content": " public function decrement(string $key, int $step = 1, int $initial = 0): int;\n\n\n\n /**\n\n * Delete a single item from the pool.\n\n *\n\n * @param string $key\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Cache/Storage.hh", "rank": 33, "score": 462916.3581825262 }, { "content": " public function increment(string $key, int $step = 1, int $initial = 0): int;\n\n\n\n /**\n\n * Remove the item if it exists and return true, else return false.\n\n *\n\n * @param string $key\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Cache/Storage.hh", "rank": 34, "score": 462916.3581825262 }, { "content": " public function decrement(string $key, int $step = 1, int $initial = 0, string $storage = 'default'): int {\n\n return $this->getStorage($storage)->decrement($key, $step, $initial);\n\n }\n\n\n\n /**\n\n * Empty the cache.\n\n *\n\n * @param string $storage\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Cache/Cache.hh", "rank": 35, "score": 462189.8326259864 }, { "content": " public function increment(string $key, int $step = 1, int $initial = 0, string $storage = 'default'): int {\n\n return $this->getStorage($storage)->increment($key, $step, $initial);\n\n }\n\n\n\n /**\n\n * Remove the item if it exists and return true, else return false.\n\n *\n\n * @param string $key\n\n * @param string $storage\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Cache/Cache.hh", "rank": 36, "score": 462189.8326259864 }, { "content": " public function setCookie(string $name, string $value, mixed $expires = 0, string $path = '/', string $domain = '', bool $httpOnly = true, bool $secure = false): this {\n\n return $this->addHeader('Set-Cookie', (string) new Cookie($name, $value, $expires, $path, $domain, $httpOnly, $secure));\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Http/Server/Response.hh", "rank": 37, "score": 460488.21151778 }, { "content": " public function removeCookie(string $name, string $path = '/', string $domain = '', bool $httpOnly = true, bool $secure = false): this {\n\n return $this->setCookie($name, '', time(), $path, $domain, $httpOnly, $secure);\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Http/Server/Response.hh", "rank": 38, "score": 452202.0425341915 }, { "content": " public function addPath(string $domain, string $path): this {\n\n if (!$this->getPaths()->contains($domain)) {\n\n $this->paths[$domain] = Set {};\n\n }\n\n\n\n $this->paths[$domain][] = Path::ds($path, true);\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Io/Bundle/AbstractBundle.hh", "rank": 39, "score": 450481.6169861552 }, { "content": " public function reset(string $path = ''): this {\n\n if ($path) {\n\n if (file_exists($path) && is_file($path)) {\n\n throw new InvalidPathException(sprintf('Invalid folder path %s, files are not allowed', $path));\n\n }\n\n\n\n if (substr($path, -1) !== '/') {\n\n $path .= '/';\n\n }\n\n }\n\n\n\n return parent::reset($path);\n\n }\n\n\n\n /**\n\n * Return the number of files in the current folder.\n\n *\n\n * @return int\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 41, "score": 449093.42119674175 }, { "content": " public function cd(string $path): this {\n\n return $this->reset($path);\n\n }\n\n\n\n /**\n\n * Change the group of the file.\n\n * If $recursive is true, set the group on all children.\n\n *\n\n * @param int $group\n\n * @param bool $recursive\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 42, "score": 449093.42119674175 }, { "content": " function str_contains(string $string, string $needle, bool $strict = true, int $offset = 0): bool {\n\n return Str::contains($string, $needle, $strict, $offset);\n\n }\n\n\n\n /**\n\n * @see Titon\\Utility\\Str::endsWith()\n\n */\n", "file_path": "src/Titon/Utility/bootstrap.hh", "rank": 43, "score": 446384.05456120276 }, { "content": " public function addPath(string $path): this {\n\n $this->paths[] = Path::ds($path, true);\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/View/Locator/AbstractLocator.hh", "rank": 44, "score": 446077.5942289059 }, { "content": " public function compare(string $value, int $length = 0): int {\n\n return Str::compare($this->value(), $value, $length);\n\n }\n\n\n\n /**\n\n * Concatenate two strings and return a new string object.\n\n *\n\n * @param string $string\n\n * @param bool $append\n\n * @return \\Titon\\Type\\StringBuffer\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 45, "score": 444906.18739608605 }, { "content": " public function __construct(string $path, int $status = Http::OK) {\n\n parent::__construct(null, $status);\n\n\n\n if (!file_exists($path)) {\n\n throw new MissingFileException(sprintf('File %s does not exist', basename($path)));\n\n\n\n } else if (!is_readable($path)) {\n\n throw new InvalidFileException(sprintf('File %s is not readable', basename($path)));\n\n }\n\n\n\n $this->path = $path;\n\n $this->contentDisposition(basename($path));\n\n }\n\n\n\n /**\n\n * Return the file path.\n\n *\n\n * @return string\n\n */\n", "file_path": "src/Titon/Http/Server/DownloadResponse.hh", "rank": 46, "score": 444862.9543540175 }, { "content": " public function __construct(string $path = '') {\n\n if ($path && !file_exists($path)) {\n\n throw new MissingFileException(sprintf('File %s does not exist', $path));\n\n }\n\n\n\n parent::__construct($path);\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Io/Reader/AbstractReader.hh", "rank": 47, "score": 444832.1226173101 }, { "content": " public function write($string): ?int {\n\n if (!$this->isWritable()) {\n\n return null;\n\n }\n\n\n\n $write = fwrite($this->getStream(), $string);\n\n\n\n return ($write === false) ? null : $write;\n\n }\n\n\n\n}\n", "file_path": "src/Titon/Http/Stream/AbstractStream.hh", "rank": 48, "score": 444710.85052697756 }, { "content": " public function set(string $key, mixed $value, int $expires): bool;\n\n\n\n /**\n\n * Set the unique cache key prefix.\n\n *\n\n * @param string $prefix\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Cache/Storage.hh", "rank": 49, "score": 442599.3402497653 }, { "content": " public function chown(int $user, bool $recursive = false): bool {\n\n if ($recursive) {\n\n if ($contents = $this->read()) {\n\n foreach ($contents as $file) {\n\n $file->chown($user, true);\n\n }\n\n }\n\n }\n\n\n\n return parent::chown($user);\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Io/Folder.hh", "rank": 51, "score": 439002.6636521898 }, { "content": " public function hasNamespace(string $key): bool {\n\n return $this->getNamespaces()->contains($key);\n\n }\n\n\n\n /**\n\n * Return true if the element has any namespaces.\n\n *\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Type/Xml/Element.hh", "rank": 52, "score": 438141.1368581663 }, { "content": " public function set(string $key, mixed $value, int $expires): bool {\n\n $this->setCache($this->getPrefix() . $key, $value);\n\n\n\n return true;\n\n }\n\n\n\n}\n", "file_path": "src/Titon/Cache/Storage/MemoryStorage.hh", "rank": 53, "score": 433756.3334236911 }, { "content": " public function set(string $key, mixed $value, int $expires): bool {\n\n return $this->getRedis()->setex($this->getPrefix() . $key, $expires - time(), serialize($value)); // Redis is TTL\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Cache/Storage/RedisStorage.hh", "rank": 54, "score": 433756.33342369116 }, { "content": " public function set(string $key, mixed $value, int $expires): bool {\n\n return $this->getMemcache()->set($this->getPrefix() . $key, $value, $expires);\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Cache/Storage/MemcacheStorage.hh", "rank": 55, "score": 433756.3334236911 }, { "content": " public function set(string $key, mixed $value, int $expires): bool {\n\n return apc_store($this->getPrefix() . $key, $value, $expires - time()); // APC uses TTL\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Cache/Storage/ApcStorage.hh", "rank": 56, "score": 433756.3334236911 }, { "content": " public function isInServiceProvider(string $className): bool {\n\n foreach ($this->providers as $provider) {\n\n if ($provider->provides($className)) {\n\n $provider->initialize();\n\n\n\n return true;\n\n }\n\n }\n\n\n\n return false;\n\n }\n\n\n\n /**\n\n * Return whether or not an alias has been registered in the container.\n\n *\n\n * @param string $alias Registered key or class name\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Context/Depository.hh", "rank": 57, "score": 432570.86731232016 }, { "content": " public function toJson(int $options = 0): string;\n\n\n\n}", "file_path": "src/Titon/Common/Jsonable.hh", "rank": 58, "score": 432402.20227716723 }, { "content": " public function set(string $key, mixed $value, int $expires): bool {\n\n return $this->loadCache($key)->write($expires . \"\\n\" . serialize($value));\n\n }\n\n\n\n /**\n\n * Build an absolute path to the cache on the file system using the defined key.\n\n *\n\n * @param string $key\n\n * @return string\n\n */\n\n <<__Memoize>>\n", "file_path": "src/Titon/Cache/Storage/FileSystemStorage.hh", "rank": 59, "score": 429560.8481722774 }, { "content": " public function toJson(int $options = 0): string {\n\n return json_encode($this, $options);\n\n }\n\n\n\n /**\n\n * Return the list as a map.\n\n *\n\n * @return Map<int, Tv>\n\n */\n", "file_path": "src/Titon/Type/ArrayList.hh", "rank": 60, "score": 428152.41661493725 }, { "content": " public function toJson(int $options = 0): string {\n\n return json_encode($this, $options);\n\n }\n\n\n\n /**\n\n * Return the map as a Map.\n\n *\n\n * @return Map<Tk, Tv>\n\n */\n", "file_path": "src/Titon/Type/HashMap.hh", "rank": 61, "score": 428152.41661493725 }, { "content": " public function split(string $delimiter = '', int $length = 0): Vector<string> {\n\n if ($delimiter !== '') {\n\n if ($length !== 0) {\n\n $chars = explode($delimiter, $this->value(), $length);\n\n } else {\n\n $chars = explode($delimiter, $this->value());\n\n }\n\n } else {\n\n $chars = str_split($this->value(), $length ?: 1);\n\n }\n\n\n\n return new Vector($chars);\n\n }\n\n\n\n /**\n\n * Converts the string to a camel case form.\n\n *\n\n * @uses Titon\\Utility\\Inflector\n\n *\n\n * @return \\Titon\\Type\\StringBuffer\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 62, "score": 427726.9020788524 }, { "content": " public function escape(string $value, ?bool $escape = null): string {\n\n if ($escape === null) {\n\n $escape = $this->getEscaping();\n\n }\n\n\n\n if ($escape) {\n\n $value = Sanitize::escape($value);\n\n }\n\n\n\n return $value;\n\n }\n\n\n\n /**\n\n * Return the automatic escaping setting.\n\n *\n\n * @return bool\n\n */\n", "file_path": "src/Titon/View/Helper/AbstractHelper.hh", "rank": 63, "score": 427379.3232415163 }, { "content": " public function __construct(string $event, int $priority = Emitter::AUTO_PRIORITY, bool $once = false) {\n\n $this->event = $event;\n\n $this->priority = $priority;\n\n $this->once = $once;\n\n }\n\n\n\n /**\n\n * Return the event key.\n\n *\n\n * @return string\n\n */\n", "file_path": "src/Titon/Event/Annotation/Observer.hh", "rank": 64, "score": 417950.896958671 }, { "content": " public function some((function(int, Tv): bool) $callback): bool {\n\n return Col::some($this->value(), $callback);\n\n }\n\n\n\n /**\n\n * Sort the items in the list using a custom callback or the default sorting mechanism.\n\n *\n\n * @param (function(Tv, Tv): int) $callback\n\n * @param int $flags\n\n * @return \\Titon\\Type\\ArrayList<Tv>\n\n */\n", "file_path": "src/Titon/Type/ArrayList.hh", "rank": 66, "score": 412422.2323519788 }, { "content": " public function preparePath(string $path, string $ext): string {\n\n\n\n // Don't modify external assets\n\n if (substr($path, 0, 2) === '//' || preg_match('/^https?:/i', $path)) {\n\n return $path;\n\n }\n\n\n\n // Remove query string\n\n $parts = explode('?', $path);\n\n $path = $parts[0];\n\n $query = array_key_exists(1, $parts) ? $parts[1] : '';\n\n\n\n // Apply extension\n\n if (substr($path, -(strlen($ext) + 1)) !== '.' . $ext) {\n\n $path .= '.' . $ext;\n\n }\n\n\n\n // Apply query\n\n if ($query) {\n\n $path .= '?' . $query;\n", "file_path": "src/Titon/View/Helper/AssetHelper.hh", "rank": 67, "score": 412169.34944833536 }, { "content": " public function addPath(string $domain, string $path): this;\n\n\n\n /**\n\n * Add multiple resource paths.\n\n *\n\n * @param string $domain\n\n * @param \\Titon\\Io\\PathList $paths\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Io/Bundle.hh", "rank": 68, "score": 410437.3137149102 }, { "content": " public function every((function(int, Tv): bool) $callback): bool {\n\n return Col::every($this->value(), $callback);\n\n }\n\n\n\n /**\n\n * Return the first item in the list.\n\n *\n\n * @return ?Tv\n\n */\n", "file_path": "src/Titon/Type/ArrayList.hh", "rank": 69, "score": 408913.03246565594 }, { "content": " public function __construct(string $path, string $action) {\n\n $this->action = Router::parseAction($action);\n\n $this->append($path);\n\n }\n\n\n\n /**\n\n * Append onto the path. This must be done before compilation.\n\n *\n\n * @param string $path\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Route/Route.hh", "rank": 70, "score": 406865.00437979423 }, { "content": " public function addMessagePath(string $domain, string $path): this {\n\n $this->getMessageBundle()->addPath($domain, $path . '/' . $this->getCode());\n\n\n\n // Pass it to the parent also\n\n $this->getParentLocale()?->addMessagePath($domain, $path);\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * Add multiple message lookup paths.\n\n *\n\n * @param string $domain\n\n * @param \\Titon\\Io\\PathList $paths\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Intl/Locale.hh", "rank": 71, "score": 406845.42530025716 }, { "content": " public function addResourcePath(string $domain, string $path): this {\n\n $path = rtrim($path, '/');\n\n\n\n $this->addLocalePath(sprintf('%s/locales', $path));\n\n $this->addMessagePath($domain, sprintf('%s/messages', $path));\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * Add multiple resource lookup paths.\n\n *\n\n * @param string $domain\n\n * @param \\Titon\\Io\\PathList $paths\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Intl/Locale.hh", "rank": 72, "score": 406845.4253002571 }, { "content": " public function parent(): string {\n\n return $this->get($this->active());\n\n }\n\n\n\n /**\n\n * Prepend a string to a block.\n\n * If a block does not exist, create it.\n\n *\n\n * @param string $key\n\n * @param string $value\n\n * @return $this\n\n */\n", "file_path": "src/Titon/View/Helper/BlockHelper.hh", "rank": 73, "score": 406782.18757007853 }, { "content": " public function getMode(): string {\n\n return $this->mode;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n\n public static function getSupportedMethods(): Vector<string> {\n\n return Vector {\n\n self::AES_128_CBC,\n\n self::AES_128_CFB,\n\n self::AES_128_OFB,\n\n self::AES_192_CBC,\n\n self::AES_192_CFB,\n\n self::AES_192_OFB,\n\n self::AES_256_CBC,\n\n self::AES_256_CFB,\n\n self::AES_256_OFB,\n\n self::BLOWFISH_CBC,\n\n self::BLOWFISH_CFB,\n", "file_path": "src/Titon/Crypto/AbstractCipher.hh", "rank": 74, "score": 405722.3609044758 }, { "content": " public function setPath(string $path): this {\n\n $this->path = $path ?: '/';\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * Set the secure HTTPS flag.\n\n *\n\n * @param bool $secure\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Http/Cookie.hh", "rank": 75, "score": 405140.435522363 }, { "content": " public function addPath(string $path): this;\n\n\n\n /**\n\n * Add multiple lookup paths.\n\n *\n\n * @param \\Titon\\View\\PathList $paths\n\n * @return $this\n\n */\n", "file_path": "src/Titon/View/Locator.hh", "rank": 76, "score": 405140.435522363 }, { "content": " public function __construct(string $path) {\n\n $this->lookupPath = rtrim($path, '/') . '/';\n\n }\n\n\n\n /**\n\n * Return the name of the environment.\n\n *\n\n * @return string\n\n */\n", "file_path": "src/Titon/Environment/Detector.hh", "rank": 77, "score": 403698.01011840184 }, { "content": " public function addLocalePath(string $path): this {\n\n $this->getLocaleBundle()->addPath(MessageLoader::DEFAULT_DOMAIN, $path . '/' . $this->getCode());\n\n\n\n // Pass it to the parent also\n\n $this->getParentLocale()?->addLocalePath($path);\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * Add multiple locale lookup paths.\n\n *\n\n * @param \\Titon\\Io\\PathList $paths\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Intl/Locale.hh", "rank": 78, "score": 401102.59418474184 }, { "content": " public function charAt(int $index): ?string {\n\n return Str::charAt($this->value(), $index);\n\n }\n\n\n\n /**\n\n * Removes all extraneous whitespace from a string and trims it.\n\n *\n\n * @return \\Titon\\Type\\StringBuffer\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 79, "score": 400761.0928409145 }, { "content": " public function getMode(): string {\n\n return (string) $this->cache['mode'];\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Http/Stream/AbstractStream.hh", "rank": 80, "score": 400506.39790838695 }, { "content": " public function endsWith(string $value): bool {\n\n return Str::endsWith($this->value(), $value);\n\n }\n\n\n\n /**\n\n * Checks to see if both values are equal.\n\n *\n\n * @param string $value\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 81, "score": 400474.60651399137 }, { "content": " public function equals(string $value): bool {\n\n return ($this->value() === $value);\n\n }\n\n\n\n /**\n\n * Escape the string.\n\n *\n\n * @uses Titon\\Utility\\Sanitize\n\n *\n\n * @param int $flags\n\n * @return \\Titon\\Type\\StringBuffer\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 82, "score": 400474.60651399137 }, { "content": " public function startsWith(string $value): bool {\n\n return Str::startsWith($this->value(), $value);\n\n }\n\n\n\n /**\n\n * Strips the string of its tags and anything in between them.\n\n *\n\n * @return \\Titon\\Type\\StringBuffer\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 83, "score": 400474.60651399137 }, { "content": " public function getPath(): string {\n\n return $this->path();\n\n }\n\n\n\n}\n", "file_path": "src/Titon/Io/Reader/AbstractReader.hh", "rank": 84, "score": 400342.37383910466 }, { "content": " public function getPath(): string {\n\n return $this->path();\n\n }\n\n\n\n}", "file_path": "src/Titon/Io/Writer/AbstractWriter.hh", "rank": 85, "score": 400342.37383910466 }, { "content": " public function __construct(string $key, string $class, string $function, Depository $depository) {\n\n parent::__construct($key, $depository);\n\n\n\n $this->class = $class;\n\n $this->function = $function;\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Context/Definition/CallableDefinition.hh", "rank": 86, "score": 399950.8159078739 }, { "content": " public function extract(int $offset, int $length = 0): StringBuffer {\n\n return new static(Str::extract($this->value(), $offset, $length));\n\n }\n\n\n\n /**\n\n * Grab the index of the first matched character.\n\n *\n\n * @uses Titon\\Utility\\Str\n\n *\n\n * @param string $needle\n\n * @param bool $strict\n\n * @param int $offset\n\n * @return int\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 87, "score": 399780.77589634643 }, { "content": " public function addScript(string $script, string $location = 'footer', int $order = 0, string $env = ''): this {\n\n $scripts = $this->getScripts();\n\n\n\n if (!$scripts->contains($location)) {\n\n $this->scripts[$location] = Map {};\n\n }\n\n\n\n if ($order === 0) {\n\n $order = count($scripts[$location]);\n\n }\n\n\n\n while ($scripts[$location]->contains($order)) {\n\n $order++;\n\n }\n\n\n\n $this->scripts[$location][$order] = shape(\n\n 'path' => $this->preparePath($script, 'js'),\n\n 'attributes' => Map {},\n\n 'env' => $env\n\n );\n", "file_path": "src/Titon/View/Helper/AssetHelper.hh", "rank": 88, "score": 397273.89727538987 }, { "content": " public function reset(string $path = ''): this;\n\n\n\n /**\n\n * Truncate the resource file and write data to it.\n\n *\n\n * @param \\Titon\\Io\\ResourceMap $data\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Io/Writer.hh", "rank": 89, "score": 397030.4077990041 }, { "content": " public function reset(string $path = ''): this;\n\n\n\n}", "file_path": "src/Titon/Io/Reader.hh", "rank": 90, "score": 397030.4077990041 }, { "content": " public function prepend(string $path): this {\n\n $this->path = '/' . trim($path, '/') . rtrim($this->path, '/');\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * Serialize the compiled route for increasing performance when caching mapped routes.\n\n */\n", "file_path": "src/Titon/Route/Route.hh", "rank": 91, "score": 397030.4077990041 }, { "content": " public function reset(string $path = ''): this {\n\n if ($path && file_exists($path) && is_dir($path)) {\n\n throw new InvalidPathException(sprintf('Invalid file path %s, folders are not allowed', $path));\n\n }\n\n\n\n return parent::reset($path);\n\n }\n\n\n\n /**\n\n * Return the current file size.\n\n *\n\n * @return int\n\n */\n", "file_path": "src/Titon/Io/File.hh", "rank": 92, "score": 397030.4077990041 }, { "content": " public function append(string $path): this {\n\n $this->path .= '/' . trim($path, '/');\n\n\n\n return $this;\n\n }\n\n\n\n /**\n\n * Compile the given path into a detectable regex pattern.\n\n *\n\n * @return string\n\n * @throws \\Titon\\Route\\Exception\\MissingPatternException\n\n */\n", "file_path": "src/Titon/Route/Route.hh", "rank": 93, "score": 397030.4077990041 }, { "content": " public function wordCount(string $inherit = ''): int {\n\n return str_word_count($this->value(), 0, $inherit);\n\n }\n\n\n\n /**\n\n * Set or overwrite the value.\n\n *\n\n * @param string $value\n\n * @return $this\n\n */\n", "file_path": "src/Titon/Type/StringBuffer.hh", "rank": 94, "score": 396859.4090498277 }, { "content": " public function is(string $type): bool {\n\n return ($this->getEnvironment() === $type);\n\n }\n\n\n\n}\n", "file_path": "src/Titon/Environment/Detector.hh", "rank": 95, "score": 396624.66362884594 }, { "content": " public function has(string $key): bool;\n\n\n\n /**\n\n * Increment a value within the cache and return the new number.\n\n * If the item does not exist, it will create the item with an initial value.\n\n *\n\n * @param string $key\n\n * @param int $step\n\n * @param int $initial\n\n * @return int\n\n */\n", "file_path": "src/Titon/Cache/Storage.hh", "rank": 96, "score": 396624.66362884594 }, { "content": " public function is(string $code): bool {\n\n $currentCode = $this->current()?->getCode();\n\n\n\n return ($currentCode === $code || Locale::canonicalize($code) === $currentCode);\n\n }\n\n\n\n /**\n\n * Globalization will be enabled if more than 1 locale has been setup.\n\n *\n\n * @return bool\n\n */\n", "file_path": "src/Titon/Intl/Translator.hh", "rank": 97, "score": 396624.66362884594 }, { "content": " public function wire(string $class): this {\n\n $reader = new Reader($class);\n\n\n\n // Map resource routes if the annotation is on the class\n\n foreach ($reader->getClassAnnotations() as $annotation) {\n\n if ($annotation instanceof RouteAnnotation) {\n\n $this->resource($annotation->getKey(), $annotation->toRoute($class));\n\n }\n\n }\n\n\n\n // Map regular routes if the annotation is on a method\n\n foreach ($reader->getAnnotatedMethods() as $method => $annotations) {\n\n foreach ($annotations as $annotation) {\n\n if ($annotation instanceof RouteAnnotation) {\n\n $this->map($annotation->getKey(), $annotation->toRoute($class, $method));\n\n }\n\n }\n\n }\n\n\n\n return $this;\n\n }\n\n\n\n}\n", "file_path": "src/Titon/Route/Router.hh", "rank": 98, "score": 395932.6065484842 }, { "content": " public function __construct(string $path, string $prefix = '') {\n\n if (!$path) {\n\n throw new InvalidPathException('Cache directory is required');\n\n }\n\n\n\n $this->folder = new Folder($path, true);\n\n\n\n parent::__construct($prefix);\n\n }\n\n\n\n /**\n\n * {@inheritdoc}\n\n */\n", "file_path": "src/Titon/Cache/Storage/FileSystemStorage.hh", "rank": 99, "score": 395553.5522543218 } ]
C++
net/instaweb/rewriter/webp_optimizer.cc
dimitrilongo/mod_pagespeed
d0d3bc51aa4feddf010b7085872c64cc46b5aae0
#include "net/instaweb/rewriter/public/webp_optimizer.h" #include <csetjmp> #include <cstddef> #include "base/logging.h" #include "pagespeed/kernel/base/basictypes.h" #include "pagespeed/kernel/base/string.h" #include "pagespeed/kernel/image/jpeg_reader.h" #include "pagespeed/kernel/image/jpeg_utils.h" extern "C" { #ifdef USE_SYSTEM_LIBWEBP #include "webp/encode.h" #include "webp/decode.h" #else #include "third_party/libwebp/src/webp/encode.h" #include "third_party/libwebp/src/webp/decode.h" #endif } extern "C" { #ifdef USE_SYSTEM_LIBJPEG #include "jpeglib.h" #else #include "third_party/libjpeg_turbo/src/jpeglib.h" #endif } using pagespeed::image_compression::JpegUtils; namespace net_instaweb { class MessageHandler; namespace { const bool kUseYUV = false; const int kYPlane = 0; const int kUPlane = 1; const int kVPlane = 2; const int kPlanes = 3; #ifdef DCT_IFAST_SUPPORTED const J_DCT_METHOD fastest_dct_method = JDCT_IFAST; #else #ifdef DCT_FLOAT_SUPPORTED #else #endif #endif int GoogleStringWebpWriter(const uint8_t* data, size_t data_size, const WebPPicture* const picture) { GoogleString* compressed_webp = static_cast<GoogleString*>(picture->custom_ptr); compressed_webp->append(reinterpret_cast<const char*>(data), data_size); return 1; } class WebpOptimizer { public: explicit WebpOptimizer(MessageHandler* handler); ~WebpOptimizer(); bool CreateOptimizedWebp(const GoogleString& original_jpeg, int configured_quality, WebpProgressHook progress_hook, void* progress_hook_data, GoogleString* compressed_webp); private: size_t PixelOffset(size_t x, size_t y) const { return (kPlanes * x + y * row_stride_); } int SampleAt(int plane, int source_offset, int x_offset, int y_offset) const { return static_cast<int>(pixels_[plane + source_offset + PixelOffset(x_offset, y_offset)]); } bool DoReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg); bool ReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg); bool WebPImportYUV(WebPPicture* const picture); static int ProgressHook(int percent, const WebPPicture* picture); MessageHandler* message_handler_; pagespeed::image_compression::JpegReader reader_; uint8* pixels_; uint8** rows_; unsigned int width_, height_; size_t row_stride_; WebpProgressHook progress_hook_; void* progress_hook_data_; DISALLOW_COPY_AND_ASSIGN(WebpOptimizer); }; WebpOptimizer::WebpOptimizer(MessageHandler* handler) : message_handler_(handler), reader_(handler), pixels_(NULL), rows_(NULL), width_(0), height_(0), row_stride_(0), progress_hook_(NULL), progress_hook_data_(NULL) { } WebpOptimizer::~WebpOptimizer() { delete[] pixels_; DCHECK(rows_ == NULL); } bool WebpOptimizer::DoReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg) { jmp_buf env; if (setjmp(env)) { return false; } jpeg_decompress_struct* jpeg_decompress = reader_.decompress_struct(); jpeg_decompress->client_data = static_cast<void*>(&env); reader_.PrepareForRead(original_jpeg.data(), original_jpeg.size()); if (jpeg_read_header(jpeg_decompress, TRUE) != JPEG_HEADER_OK) { return false; } jpeg_decompress->out_color_space = color_space; jpeg_decompress->do_fancy_upsampling = TRUE; if (!jpeg_start_decompress(jpeg_decompress) || jpeg_decompress->output_components != kPlanes) { return false; } width_ = jpeg_decompress->output_width; height_ = jpeg_decompress->output_height; row_stride_ = width_ * jpeg_decompress->output_components * sizeof(*pixels_); pixels_ = new uint8[row_stride_ * height_]; rows_ = new uint8*[height_]; for (unsigned int i = 0; i < height_; ++i) { rows_[i] = pixels_ + PixelOffset(0, i); } while (jpeg_decompress->output_scanline < height_) { int rows_read = jpeg_read_scanlines(jpeg_decompress, rows_ + jpeg_decompress->output_scanline, height_ - jpeg_decompress->output_scanline); if (rows_read == 0) { return false; } } return jpeg_finish_decompress(jpeg_decompress); } bool WebpOptimizer::ReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg) { bool read_ok = DoReadJpegPixels(color_space, original_jpeg); delete[] rows_; rows_ = NULL; jpeg_decompress_struct* jpeg_decompress = reader_.decompress_struct(); jpeg_decompress->client_data = NULL; jpeg_destroy_decompress(jpeg_decompress); return read_ok; } bool WebpOptimizer::WebPImportYUV(WebPPicture* const picture) { if (!WebPPictureAlloc(picture)) { return false; } for (size_t y = 0; y < height_; ++y) { for (size_t x = 0; x < width_; ++x) { picture->y[x + y * picture->y_stride] = pixels_[kYPlane + PixelOffset(x, y)]; } } unsigned int half_height = height_ >> 1; unsigned int half_width = width_ >> 1; unsigned int extra_height = height_ & 1; unsigned int extra_width = width_ & 1; size_t x, y; for (y = 0; y < half_height; ++y) { for (x = 0; x < half_width; ++x) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0) + SampleAt(kUPlane, source_offset, 1, 0) + SampleAt(kUPlane, source_offset, 0, 1) + SampleAt(kUPlane, source_offset, 1, 1); picture->u[picture_offset] = (2 + pixel_sum_u) >> 2; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0) + SampleAt(kVPlane, source_offset, 1, 0) + SampleAt(kVPlane, source_offset, 0, 1) + SampleAt(kVPlane, source_offset, 1, 1); picture->v[picture_offset] = (2 + pixel_sum_v) >> 2; } if (extra_width != 0) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0) + SampleAt(kUPlane, source_offset, 0, 1); picture->u[picture_offset] = (1 + pixel_sum_u) >> 1; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0) + SampleAt(kVPlane, source_offset, 0, 1); picture->v[picture_offset] = (1 + pixel_sum_v) >> 1; } } if (extra_height != 0) { for (x = 0; x < half_width; ++x) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0) + SampleAt(kUPlane, source_offset, 1, 0); picture->u[picture_offset] = (1 + pixel_sum_u) >> 1; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0) + SampleAt(kVPlane, source_offset, 1, 0); picture->v[picture_offset] = (1 + pixel_sum_v) >> 1; } if (extra_width != 0) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0); picture->u[picture_offset] = pixel_sum_u; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0); picture->v[picture_offset] = pixel_sum_v; } } return true; } int WebpOptimizer::ProgressHook(int percent, const WebPPicture* picture) { const WebpOptimizer* webp_optimizer = static_cast<WebpOptimizer*>(picture->user_data); return webp_optimizer->progress_hook_(percent, webp_optimizer->progress_hook_data_); } bool WebpOptimizer::CreateOptimizedWebp( const GoogleString& original_jpeg, int configured_quality, WebpProgressHook progress_hook, void* progress_hook_data, GoogleString* compressed_webp) { WebPPicture picture; WebPConfig config; int input_quality = JpegUtils::GetImageQualityFromImage(original_jpeg.data(), original_jpeg.size(), message_handler_); if (!WebPPictureInit(&picture) || !WebPConfigInit(&config)) { return false; } if (configured_quality == kNoQualityGiven) { configured_quality = config.quality; } int output_quality = configured_quality; if (input_quality != kNoQualityGiven && input_quality < configured_quality) { output_quality = input_quality; } else { output_quality = configured_quality; } if (!WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, output_quality)) { return false; } else { config.method = 3; if (!WebPValidateConfig(&config)) { return false; } } J_COLOR_SPACE color_space = kUseYUV ? JCS_YCbCr : JCS_RGB; if (!ReadJpegPixels(color_space, original_jpeg)) { return false; } picture.writer = &GoogleStringWebpWriter; picture.custom_ptr = static_cast<void*>(compressed_webp); picture.width = width_; picture.height = height_; if (progress_hook != NULL) { picture.progress_hook = ProgressHook; picture.user_data = this; progress_hook_ = progress_hook; progress_hook_data_ = progress_hook_data; } if (kUseYUV) { if (!WebPImportYUV(&picture)) { return false; } } else if (!WebPPictureImportRGB(&picture, pixels_, row_stride_)) { return false; } delete[] pixels_; pixels_ = NULL; bool result = WebPEncode(&config, &picture); WebPPictureFree(&picture); return result; } } bool OptimizeWebp(const GoogleString& original_jpeg, int configured_quality, WebpProgressHook progress_hook, void* progress_hook_data, GoogleString* compressed_webp, MessageHandler* message_handler) { WebpOptimizer optimizer(message_handler); return optimizer.CreateOptimizedWebp(original_jpeg, configured_quality, progress_hook, progress_hook_data, compressed_webp); } static bool WebPDecBufferToPicture(const WebPDecBuffer* const buf, WebPPicture* const picture) { const WebPYUVABuffer* const yuva = &buf->u.YUVA; if ((yuva->u_stride != yuva->v_stride) || (buf->colorspace != MODE_YUVA)) { return false; } picture->width = buf->width; picture->height = buf->height; picture->y = yuva->y; picture->u = yuva->u; picture->v = yuva->v; picture->a = yuva->a; picture->y_stride = yuva->y_stride; picture->uv_stride = yuva->u_stride; picture->a_stride = yuva->a_stride; picture->colorspace = WEBP_YUV420A; return true; } bool ReduceWebpImageQuality(const GoogleString& original_webp, int quality, GoogleString* compressed_webp) { if (quality < 1) { *compressed_webp = original_webp; return true; } else if (quality > 100) { quality = 100; } const uint8* webp = reinterpret_cast<const uint8*>(original_webp.data()); const int webp_size = original_webp.size(); WebPConfig config; if (WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, quality) == 0) { return false; } WebPPicture picture; if (WebPPictureInit(&picture) == 0) { return false; } WebPDecoderConfig dec_config; WebPInitDecoderConfig(&dec_config); WebPDecBuffer* const output_buffer = &dec_config.output; output_buffer->colorspace = MODE_YUVA; bool success = ((WebPDecode(webp, webp_size, &dec_config) == VP8_STATUS_OK) && WebPDecBufferToPicture(output_buffer, &picture)); if (success) { picture.writer = &GoogleStringWebpWriter; picture.custom_ptr = reinterpret_cast<void*>(compressed_webp); success = WebPEncode(&config, &picture); } WebPFreeDecBuffer(output_buffer); return success; } }
#include "net/instaweb/rewriter/public/webp_optimizer.h" #include <csetjmp> #include <cstddef> #include "base/logging.h" #include "pagespeed/kernel/base/basictypes.h" #include "pagespeed/kernel/base/string.h" #include "pagespeed/kernel/image/jpeg_reader.h" #include "pagespeed/kernel/image/jpeg_utils.h" extern "C" { #ifdef USE_SYSTEM_LIBWEBP #include "webp/encode.h" #include "webp/decode.h" #else #include "third_party/libwebp/src/webp/encode.h" #include "third_party/libwebp/src/webp/decode.h" #endif } extern "C" { #ifdef USE_SYSTEM_LIBJPEG #include "jpeglib.h" #else #include "third_party/libjpeg_turbo/src/jpeglib.h" #endif } using pagespeed::image_compression::JpegUtils; namespace net_instaweb { class MessageHandler; namespace { const bool kUseYUV = false; const int kYPlane = 0; const int kUPlane = 1; const int kVPlane = 2; const int kPlanes = 3; #ifdef DCT_IFAST_SUPPORTED const J_DCT_METHOD fastest_dct_method = JDCT_IFAST; #else #ifdef DCT_FLOAT_SUPPORTED #else #endif #endif
class WebpOptimizer { public: explicit WebpOptimizer(MessageHandler* handler); ~WebpOptimizer(); bool CreateOptimizedWebp(const GoogleString& original_jpeg, int configured_quality, WebpProgressHook progress_hook, void* progress_hook_data, GoogleString* compressed_webp); private: size_t PixelOffset(size_t x, size_t y) const { return (kPlanes * x + y * row_stride_); } int SampleAt(int plane, int source_offset, int x_offset, int y_offset) const { return static_cast<int>(pixels_[plane + source_offset + PixelOffset(x_offset, y_offset)]); } bool DoReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg); bool ReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg); bool WebPImportYUV(WebPPicture* const picture); static int ProgressHook(int percent, const WebPPicture* picture); MessageHandler* message_handler_; pagespeed::image_compression::JpegReader reader_; uint8* pixels_; uint8** rows_; unsigned int width_, height_; size_t row_stride_; WebpProgressHook progress_hook_; void* progress_hook_data_; DISALLOW_COPY_AND_ASSIGN(WebpOptimizer); }; WebpOptimizer::WebpOptimizer(MessageHandler* handler) : message_handler_(handler), reader_(handler), pixels_(NULL), rows_(NULL), width_(0), height_(0), row_stride_(0), progress_hook_(NULL), progress_hook_data_(NULL) { } WebpOptimizer::~WebpOptimizer() { delete[] pixels_; DCHECK(rows_ == NULL); } bool WebpOptimizer::DoReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg) { jmp_buf env; if (setjmp(env)) { return false; } jpeg_decompress_struct* jpeg_decompress = reader_.decompress_struct(); jpeg_decompress->client_data = static_cast<void*>(&env); reader_.PrepareForRead(original_jpeg.data(), original_jpeg.size()); if (jpeg_read_header(jpeg_decompress, TRUE) != JPEG_HEADER_OK) { return false; } jpeg_decompress->out_color_space = color_space; jpeg_decompress->do_fancy_upsampling = TRUE; if (!jpeg_start_decompress(jpeg_decompress) || jpeg_decompress->output_components != kPlanes) { return false; } width_ = jpeg_decompress->output_width; height_ = jpeg_decompress->output_height; row_stride_ = width_ * jpeg_decompress->output_components * sizeof(*pixels_); pixels_ = new uint8[row_stride_ * height_]; rows_ = new uint8*[height_]; for (unsigned int i = 0; i < height_; ++i) { rows_[i] = pixels_ + PixelOffset(0, i); } while (jpeg_decompress->output_scanline < height_) { int rows_read = jpeg_read_scanlines(jpeg_decompress, rows_ + jpeg_decompress->output_scanline, height_ - jpeg_decompress->output_scanline); if (rows_read == 0) { return false; } } return jpeg_finish_decompress(jpeg_decompress); } bool WebpOptimizer::ReadJpegPixels(J_COLOR_SPACE color_space, const GoogleString& original_jpeg) { bool read_ok = DoReadJpegPixels(color_space, original_jpeg); delete[] rows_; rows_ = NULL; jpeg_decompress_struct* jpeg_decompress = reader_.decompress_struct(); jpeg_decompress->client_data = NULL; jpeg_destroy_decompress(jpeg_decompress); return read_ok; } bool WebpOptimizer::WebPImportYUV(WebPPicture* const picture) { if (!WebPPictureAlloc(picture)) { return false; } for (size_t y = 0; y < height_; ++y) { for (size_t x = 0; x < width_; ++x) { picture->y[x + y * picture->y_stride] = pixels_[kYPlane + PixelOffset(x, y)]; } } unsigned int half_height = height_ >> 1; unsigned int half_width = width_ >> 1; unsigned int extra_height = height_ & 1; unsigned int extra_width = width_ & 1; size_t x, y; for (y = 0; y < half_height; ++y) { for (x = 0; x < half_width; ++x) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0) + SampleAt(kUPlane, source_offset, 1, 0) + SampleAt(kUPlane, source_offset, 0, 1) + SampleAt(kUPlane, source_offset, 1, 1); picture->u[picture_offset] = (2 + pixel_sum_u) >> 2; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0) + SampleAt(kVPlane, source_offset, 1, 0) + SampleAt(kVPlane, source_offset, 0, 1) + SampleAt(kVPlane, source_offset, 1, 1); picture->v[picture_offset] = (2 + pixel_sum_v) >> 2; } if (extra_width != 0) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0) + SampleAt(kUPlane, source_offset, 0, 1); picture->u[picture_offset] = (1 + pixel_sum_u) >> 1; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0) + SampleAt(kVPlane, source_offset, 0, 1); picture->v[picture_offset] = (1 + pixel_sum_v) >> 1; } } if (extra_height != 0) { for (x = 0; x < half_width; ++x) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0) + SampleAt(kUPlane, source_offset, 1, 0); picture->u[picture_offset] = (1 + pixel_sum_u) >> 1; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0) + SampleAt(kVPlane, source_offset, 1, 0); picture->v[picture_offset] = (1 + pixel_sum_v) >> 1; } if (extra_width != 0) { int source_offset = PixelOffset(2 * x, 2 * y); int picture_offset = x + y * picture->uv_stride; int pixel_sum_u = SampleAt(kUPlane, source_offset, 0, 0); picture->u[picture_offset] = pixel_sum_u; int pixel_sum_v = SampleAt(kVPlane, source_offset, 0, 0); picture->v[picture_offset] = pixel_sum_v; } } return true; } int WebpOptimizer::ProgressHook(int percent, const WebPPicture* picture) { const WebpOptimizer* webp_optimizer = static_cast<WebpOptimizer*>(picture->user_data); return webp_optimizer->progress_hook_(percent, webp_optimizer->progress_hook_data_); } bool WebpOptimizer::CreateOptimizedWebp( const GoogleString& original_jpeg, int configured_quality, WebpProgressHook progress_hook, void* progress_hook_data, GoogleString* compressed_webp) { WebPPicture picture; WebPConfig config; int input_quality = JpegUtils::GetImageQualityFromImage(original_jpeg.data(), original_jpeg.size(), message_handler_); if (!WebPPictureInit(&picture) || !WebPConfigInit(&config)) { return false; } if (configured_quality == kNoQualityGiven) { configured_quality = config.quality; } int output_quality = configured_quality; if (input_quality != kNoQualityGiven && input_quality < configured_quality) { output_quality = input_quality; } else { output_quality = configured_quality; } if (!WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, output_quality)) { return false; } else { config.method = 3; if (!WebPValidateConfig(&config)) { return false; } } J_COLOR_SPACE color_space = kUseYUV ? JCS_YCbCr : JCS_RGB; if (!ReadJpegPixels(color_space, original_jpeg)) { return false; } picture.writer = &GoogleStringWebpWriter; picture.custom_ptr = static_cast<void*>(compressed_webp); picture.width = width_; picture.height = height_; if (progress_hook != NULL) { picture.progress_hook = ProgressHook; picture.user_data = this; progress_hook_ = progress_hook; progress_hook_data_ = progress_hook_data; } if (kUseYUV) { if (!WebPImportYUV(&picture)) { return false; } } else if (!WebPPictureImportRGB(&picture, pixels_, row_stride_)) { return false; } delete[] pixels_; pixels_ = NULL; bool result = WebPEncode(&config, &picture); WebPPictureFree(&picture); return result; } } bool OptimizeWebp(const GoogleString& original_jpeg, int configured_quality, WebpProgressHook progress_hook, void* progress_hook_data, GoogleString* compressed_webp, MessageHandler* message_handler) { WebpOptimizer optimizer(message_handler); return optimizer.CreateOptimizedWebp(original_jpeg, configured_quality, progress_hook, progress_hook_data, compressed_webp); } static bool WebPDecBufferToPicture(const WebPDecBuffer* const buf, WebPPicture* const picture) { const WebPYUVABuffer* const yuva = &buf->u.YUVA; if ((yuva->u_stride != yuva->v_stride) || (buf->colorspace != MODE_YUVA)) { return false; } picture->width = buf->width; picture->height = buf->height; picture->y = yuva->y; picture->u = yuva->u; picture->v = yuva->v; picture->a = yuva->a; picture->y_stride = yuva->y_stride; picture->uv_stride = yuva->u_stride; picture->a_stride = yuva->a_stride; picture->colorspace = WEBP_YUV420A; return true; } bool ReduceWebpImageQuality(const GoogleString& original_webp, int quality, GoogleString* compressed_webp) { if (quality < 1) { *compressed_webp = original_webp; return true; } else if (quality > 100) { quality = 100; } const uint8* webp = reinterpret_cast<const uint8*>(original_webp.data()); const int webp_size = original_webp.size(); WebPConfig config; if (WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, quality) == 0) { return false; } WebPPicture picture; if (WebPPictureInit(&picture) == 0) { return false; } WebPDecoderConfig dec_config; WebPInitDecoderConfig(&dec_config); WebPDecBuffer* const output_buffer = &dec_config.output; output_buffer->colorspace = MODE_YUVA; bool success = ((WebPDecode(webp, webp_size, &dec_config) == VP8_STATUS_OK) && WebPDecBufferToPicture(output_buffer, &picture)); if (success) { picture.writer = &GoogleStringWebpWriter; picture.custom_ptr = reinterpret_cast<void*>(compressed_webp); success = WebPEncode(&config, &picture); } WebPFreeDecBuffer(output_buffer); return success; } }
int GoogleStringWebpWriter(const uint8_t* data, size_t data_size, const WebPPicture* const picture) { GoogleString* compressed_webp = static_cast<GoogleString*>(picture->custom_ptr); compressed_webp->append(reinterpret_cast<const char*>(data), data_size); return 1; }
function_block-full_function
[ { "content": "// Bool that is auto-initialized to false\n\nclass Bool {\n\n public:\n\n Bool() : value_(false) {}\n\n Bool(bool value) : value_(value) {} // Copy constructor // NOLINT\n\n const bool Test() const { return value_; }\n\n\n\n private:\n\n bool value_;\n\n};\n\n\n", "file_path": "pagespeed/kernel/html/html_parse_test.cc", "rank": 0, "score": 215474.80556840266 }, { "content": "class IntVector : public std::vector<int> {\n\n public:\n\n void Merge(const IntVector& src) {\n\n for (int i = 0, n = src.size(); i < n; ++i) {\n\n push_back(src[i]);\n\n }\n\n }\n\n\n\n // Copy and assign OK.\n\n};\n\n\n", "file_path": "pagespeed/kernel/util/copy_on_write_test.cc", "rank": 1, "score": 190563.19677330507 }, { "content": "class MemberFunction2 : public MemberFunctionBase<C> {\n\n public:\n\n typedef void (C::*Func)(T1, T2);\n\n\n\n // Constructor supplying a Run method, but no Cancel method.\n\n MemberFunction2(Func f, C* c, T1 v1, T2 v2)\n\n : MemberFunctionBase<C>(c), run_(f), cancel_(NULL), v1_(v1), v2_(v2) {}\n\n\n\n // Constructor supplying a Run method and a Cancel method.\n\n MemberFunction2(Func f, Func cancel,\n\n C* c, T1 v1, T2 v2)\n\n : MemberFunctionBase<C>(c),\n\n run_(f), cancel_(cancel),\n\n v1_(v1), v2_(v2) {}\n\n\n\n protected:\n\n virtual void Run() { CALL_MEMBER_FN(object_, run_)(v1_, v2_); }\n\n virtual void Cancel() {\n\n if (cancel_ != NULL) {\n\n CALL_MEMBER_FN(object_, cancel_)(v1_, v2_);\n", "file_path": "pagespeed/kernel/base/function.h", "rank": 2, "score": 184722.84189115115 }, { "content": "class MemberFunction0 : public MemberFunctionBase<C> {\n\n public:\n\n typedef void (C::*Func)();\n\n\n\n // Constructor supplying a Run method, but no Cancel method.\n\n MemberFunction0(Func f, C* c) : MemberFunctionBase<C>(c), run_(f),\n\n cancel_(NULL) {\n\n }\n\n\n\n // Constructor supplying a Run method and a Cancel method.\n\n MemberFunction0(Func f, Func cancel, C* c)\n\n : MemberFunctionBase<C>(c), run_(f), cancel_(cancel) {}\n\n\n\n protected:\n\n virtual void Run() { CALL_MEMBER_FN(object_, run_)(); }\n\n virtual void Cancel() {\n\n if (cancel_ != NULL) {\n\n CALL_MEMBER_FN(object_, cancel_)();\n\n }\n\n }\n\n\n\n private:\n\n Func run_;\n\n Func cancel_;\n\n};\n\n\n\n// Captures a delayed call to a 1-arg member function as a closure.\n\ntemplate<class C, typename T1>\n", "file_path": "pagespeed/kernel/base/function.h", "rank": 3, "score": 184722.84189115115 }, { "content": "class MemberFunction1 : public MemberFunctionBase<C> {\n\n public:\n\n typedef void (C::*Func)(T1);\n\n\n\n // Constructor supplying a Run method, but no Cancel method.\n\n MemberFunction1(Func f, C* c, T1 v1)\n\n : MemberFunctionBase<C>(c), run_(f), cancel_(NULL), v1_(v1) {}\n\n\n\n // Constructor supplying a Run method and a Cancel method.\n\n MemberFunction1(Func f, Func cancel,\n\n C* c, T1 v1)\n\n : MemberFunctionBase<C>(c), run_(f), cancel_(cancel), v1_(v1) {}\n\n\n\n protected:\n\n virtual void Run() { CALL_MEMBER_FN(object_, run_)(v1_); }\n\n virtual void Cancel() {\n\n if (cancel_ != NULL) {\n\n CALL_MEMBER_FN(object_, cancel_)(v1_);\n\n }\n\n }\n\n\n\n private:\n\n Func run_;\n\n Func cancel_;\n\n T1 v1_;\n\n};\n\n\n\n// Captures a delayed call to a 2-arg member function as a closure.\n\ntemplate<class C, typename T1, typename T2>\n", "file_path": "pagespeed/kernel/base/function.h", "rank": 4, "score": 184722.84189115115 }, { "content": "class MemberFunction4 : public MemberFunctionBase<C> {\n\n public:\n\n typedef void (C::*Func)(T1, T2, T3, T4);\n\n\n\n // Constructor supplying a Run method, but no Cancel method.\n\n MemberFunction4(Func f, C* c, T1 v1, T2 v2, T3 v3, T4 v4)\n\n : MemberFunctionBase<C>(c), run_(f), cancel_(NULL), v1_(v1), v2_(v2),\n\n v3_(v3), v4_(v4) {\n\n }\n\n\n\n // Constructor supplying a Run method and a Cancel method.\n\n MemberFunction4(Func f, Func cancel,\n\n C* c, T1 v1, T2 v2, T3 v3, T4 v4)\n\n : MemberFunctionBase<C>(c),\n\n run_(f), cancel_(cancel),\n\n v1_(v1), v2_(v2), v3_(v3), v4_(v4) {}\n\n\n\n protected:\n\n virtual void Run() { CALL_MEMBER_FN(object_, run_)(v1_, v2_, v3_, v4_); }\n\n virtual void Cancel() {\n", "file_path": "pagespeed/kernel/base/function.h", "rank": 5, "score": 184722.84189115115 }, { "content": "class MemberFunction3 : public MemberFunctionBase<C> {\n\n public:\n\n typedef void (C::*Func)(T1, T2, T3);\n\n\n\n // Constructor supplying a Run method, but no Cancel method.\n\n MemberFunction3(Func f, C* c, T1 v1, T2 v2, T3 v3)\n\n : MemberFunctionBase<C>(c), run_(f), cancel_(NULL), v1_(v1), v2_(v2),\n\n v3_(v3) {\n\n }\n\n\n\n // Constructor supplying a Run method and a Cancel method.\n\n MemberFunction3(Func f, Func cancel,\n\n C* c, T1 v1, T2 v2, T3 v3)\n\n : MemberFunctionBase<C>(c),\n\n run_(f), cancel_(cancel),\n\n v1_(v1), v2_(v2), v3_(v3) {}\n\n\n\n protected:\n\n virtual void Run() { CALL_MEMBER_FN(object_, run_)(v1_, v2_, v3_); }\n\n virtual void Cancel() {\n", "file_path": "pagespeed/kernel/base/function.h", "rank": 6, "score": 184722.84189115115 }, { "content": "// A boolean flag that can be set atomically and be visible to other\n\n// threads. Please be extra careful with this --- it can go wrong in\n\n// incomprehensible ways; most of the time, you probably want to use a mutex\n\n// instead.\n\nclass AtomicBool {\n\n public:\n\n // Guaranteed to be initialized to false.\n\n AtomicBool() {\n\n set_value(false);\n\n }\n\n\n\n ~AtomicBool() {}\n\n\n\n bool value() const {\n\n return base::subtle::Acquire_Load(&value_);\n\n }\n\n\n\n void set_value(bool v) {\n\n base::subtle::Release_Store(&value_, v);\n\n }\n\n\n\n private:\n\n base::subtle::AtomicWord value_;\n\n DISALLOW_COPY_AND_ASSIGN(AtomicBool);\n\n};\n\n\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // PAGESPEED_KERNEL_BASE_ATOMIC_BOOL_H_\n", "file_path": "pagespeed/kernel/base/atomic_bool.h", "rank": 7, "score": 181459.79622440366 }, { "content": "// Three-way return type for distinguishing Errors from boolean answer.\n\n//\n\n// This is physically just an enum, but is wrapped in a class to prevent\n\n// accidental usage in an if- or ternary-condition without explicitly indicating\n\n// whether you are looking for true, false, or error.\n\nclass BoolOrError {\n\n enum Choice {\n\n kIsFalse,\n\n kIsTrue,\n\n kIsError\n\n };\n\n\n\n public:\n\n BoolOrError() : choice_(kIsError) { }\n\n explicit BoolOrError(bool t_or_f) : choice_(t_or_f ? kIsTrue : kIsFalse) { }\n\n\n\n // Intended to be passed by value; explicitly support copy & assign\n\n BoolOrError(const BoolOrError& src) : choice_(src.choice_) { }\n\n BoolOrError& operator=(const BoolOrError& src) {\n\n if (&src != this) {\n\n choice_ = src.choice_;\n\n }\n\n return *this;\n\n }\n\n\n\n bool is_false() const { return choice_ == kIsFalse; }\n\n bool is_true() const { return choice_ == kIsTrue; }\n\n bool is_error() const { return choice_ == kIsError; }\n\n void set_error() { choice_ = kIsError; }\n\n void set(bool t_or_f) { choice_ = t_or_f ? kIsTrue : kIsFalse; }\n\n\n\n private:\n\n Choice choice_;\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/file_system.h", "rank": 8, "score": 167059.56092995856 }, { "content": "class MessageHandler;\n", "file_path": "net/instaweb/http/public/external_url_fetcher.h", "rank": 9, "score": 161381.44374063134 }, { "content": "class RequestHeaders;\n\n\n\n// Runs an external command ('wget' by default, or 'curl') via popen\n\n// for blocking URL fetches.\n\n\n", "file_path": "net/instaweb/http/public/external_url_fetcher.h", "rank": 10, "score": 161381.44374063134 }, { "content": "class AsyncFetch;\n", "file_path": "net/instaweb/http/public/external_url_fetcher.h", "rank": 11, "score": 161381.44374063134 }, { "content": "// TODO(vchudnov): Incorporate NetcatUrlFetcher functionality into\n\n// this class.\n\nclass ExternalUrlFetcher : public UrlAsyncFetcher {\n\n public:\n\n ExternalUrlFetcher() {}\n\n virtual ~ExternalUrlFetcher() {}\n\n\n\n // TODO(sligocki): Allow protocol version number (e.g. HTTP/1.1)\n\n // and request type (e.g. GET, POST, etc.) to be specified.\n\n virtual void Fetch(const GoogleString& url,\n\n MessageHandler* message_handler,\n\n AsyncFetch* fetch);\n\n\n\n // Default user agent to use.\n\n static const char kDefaultUserAgent[];\n\n\n\n // Sets the path to \"binary\" when fetching using \"how\".\n\n void set_binary(const GoogleString& binary);\n\n\n\n\n\n protected:\n\n // Appends to escaped_headers one header line for each Name, Value\n", "file_path": "net/instaweb/http/public/external_url_fetcher.h", "rank": 12, "score": 157641.08858691936 }, { "content": "// Pool element containing an int, for test purposes.\n\nclass IntElement : public PoolElement<IntElement> {\n\n public:\n\n IntElement() { }\n\n\n\n const int num() const { return num_; }\n\n void set_num(int num) { num_ = num; }\n\n\n\n private:\n\n int num_;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(IntElement);\n\n};\n\n\n\ntypedef Pool<IntElement> IntPool;\n\ntypedef PoolElement<IntElement>::Position PoolPosition;\n\n\n", "file_path": "pagespeed/kernel/base/pool_test.cc", "rank": 13, "score": 156725.46802342575 }, { "content": " class const_iterator;\n\n\n\n typedef char32 value_type;\n\n\n\n // Constructors. These always produce owners.\n\n UnicodeText(); // Create an empty text.\n\n UnicodeText(const UnicodeText& src); // copy constructor\n\n // Construct a substring (copies the data).\n\n UnicodeText(const const_iterator& first, const const_iterator& last);\n\n\n\n // Assignment operator. This copies the data and produces an owner\n\n // unless this == &src, e.g., \"x = x;\", which is a no-op.\n\n UnicodeText& operator=(const UnicodeText& src);\n\n\n\n // x.Copy(y) copies the data from y into x.\n\n UnicodeText& Copy(const UnicodeText& src);\n\n inline UnicodeText& assign(const UnicodeText& src) { return Copy(src); }\n\n\n\n // x.PointTo(y) changes x so that it points to y's data.\n\n // It does not copy y or take ownership of y's data.\n", "file_path": "third_party/css_parser/src/util/utf8/public/unicodetext.h", "rank": 14, "score": 156237.4690349783 }, { "content": " class const_iterator {\n\n typedef const_iterator CI;\n\n public:\n\n typedef std::bidirectional_iterator_tag iterator_category;\n\n typedef char32 value_type;\n\n typedef ptrdiff_t difference_type;\n\n typedef void pointer; // (Not needed.)\n\n typedef const char32 reference; // (Needed for const_reverse_iterator)\n\n\n\n // Iterators are default-constructible.\n\n const_iterator();\n\n\n\n char32 operator*() const; // Dereference\n\n\n\n const_iterator& operator++(); // Advance (++iter)\n\n const_iterator operator++(int) { // (iter++)\n\n const_iterator result(*this);\n\n ++*this;\n\n return result;\n\n }\n", "file_path": "third_party/css_parser/src/util/utf8/public/unicodetext.h", "rank": 15, "score": 156237.4690349783 }, { "content": "class ExternalServerSpecTestInvalid : public ::testing::Test {\n\n protected:\n\n void TestInvalidSpec(const GoogleString &value) {\n\n GoogleString msg;\n\n ExternalServerSpec spec(\"old.com\", 4321);\n\n EXPECT_FALSE(spec.SetFromString(value, kDefaultPortForTesting, &msg));\n\n EXPECT_NE(\"\", msg);\n\n EXPECT_EQ(\"old.com\", spec.host);\n\n EXPECT_EQ(4321, spec.port);\n\n }\n\n};\n\n\n\nTEST_F(ExternalServerSpecTestInvalid, NonNumericPort) {\n\n TestInvalidSpec(\"host:1port\");\n\n}\n\n\n\nTEST_F(ExternalServerSpecTestInvalid, InvalidPortNumber1) {\n\n TestInvalidSpec(\"host:0\");\n\n}\n\n\n", "file_path": "pagespeed/system/external_server_spec_test.cc", "rank": 16, "score": 152688.19921436472 }, { "content": " // Read-only iterator type; cannot be used for deletion or to modify\n\n // the contained items.\n\n class ConstIterator : public IterBase {\n\n public:\n\n ConstIterator& operator++() {\n\n this->Advance();\n\n return *this;\n\n }\n\n\n\n const T* Get() { return this->Data(); }\n\n const T* operator->() { return this->Data(); }\n\n const T& operator*() { return *this->Data(); }\n\n bool operator==(const ConstIterator& other) const {\n\n return this->Equals(other);\n\n }\n\n bool operator!=(const ConstIterator& other) const {\n\n return !this->Equals(other);\n\n }\n\n // default copy op, dtor are OK.\n\n\n\n private:\n\n friend class InlineSList<T>;\n", "file_path": "pagespeed/kernel/base/inline_slist.h", "rank": 17, "score": 150987.95657517356 }, { "content": " class HistC = CountHistogram, // Histogram\n", "file_path": "pagespeed/kernel/base/statistics_template.h", "rank": 18, "score": 150980.39909271104 }, { "content": "class IntElement : public InlineSListElement<IntElement> {\n\n public:\n\n explicit IntElement(int n) : num_(n) { }\n\n\n\n const int num() const { return num_; }\n\n void set_num(int num) { num_ = num; }\n\n\n\n private:\n\n int num_;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(IntElement);\n\n};\n\n\n\ntypedef InlineSList<IntElement> IntList;\n\n\n", "file_path": "pagespeed/kernel/base/inline_slist_test.cc", "rank": 19, "score": 150795.9760467823 }, { "content": " class const_reverse_iterator : public std::reverse_iterator<const_iterator> {\n\n public:\n\n explicit const_reverse_iterator(const_iterator it) :\n\n std::reverse_iterator<const_iterator>(it) {}\n\n const char* utf8_data() const {\n\n const_iterator tmp_it = base();\n\n return (--tmp_it).utf8_data();\n\n }\n\n int get_utf8(char* buf) const {\n\n const_iterator tmp_it = base();\n\n return (--tmp_it).get_utf8(buf);\n\n }\n\n string get_utf8_string() const {\n\n const_iterator tmp_it = base();\n\n return (--tmp_it).get_utf8_string();\n\n }\n\n int utf8_length() const {\n\n const_iterator tmp_it = base();\n\n return (--tmp_it).utf8_length();\n\n }\n", "file_path": "third_party/css_parser/src/util/utf8/public/unicodetext.h", "rank": 20, "score": 144629.03804211903 }, { "content": "// Creates an AsyncFetch object using an existing Writer* object,\n\n// which is used to delegate Write and Flush operations. This\n\n// class is still abstract, and requires inheritors to implement Done().\n\nclass AsyncFetchUsingWriter : public AsyncFetch {\n\n public:\n\n AsyncFetchUsingWriter(const RequestContextPtr& request_context,\n\n Writer* writer)\n\n : AsyncFetch(request_context),\n\n writer_(writer) {}\n\n virtual ~AsyncFetchUsingWriter();\n\n\n\n protected:\n\n virtual bool HandleWrite(const StringPiece& sp, MessageHandler* handler);\n\n virtual bool HandleFlush(MessageHandler* handler);\n\n\n\n private:\n\n Writer* writer_;\n\n DISALLOW_COPY_AND_ASSIGN(AsyncFetchUsingWriter);\n\n};\n\n\n", "file_path": "net/instaweb/http/public/async_fetch.h", "rank": 21, "score": 143758.39228944064 }, { "content": " class HTTPValueFetch : public AsyncFetchUsingWriter {\n\n public:\n\n HTTPValueFetch(const RequestContextPtr& request_context, HTTPValue* value)\n\n : AsyncFetchUsingWriter(request_context, value) {}\n\n virtual void HandleDone(bool /*ok*/) {}\n\n virtual void HandleHeadersComplete() {}\n\n };\n\n\n\n bool IsIproContentType(ResponseHeaders* response_headers);\n\n\n\n void DroppedDueToSize();\n\n void DroppedAsUncacheable();\n\n\n\n const GoogleString url_;\n\n const GoogleString fragment_;\n\n const RequestHeaders::Properties request_properties_;\n\n const HttpOptions http_options_;\n\n\n\n int64 max_response_bytes_;\n\n const int max_concurrent_recordings_;\n", "file_path": "pagespeed/system/in_place_resource_recorder.h", "rank": 22, "score": 143743.99753642658 }, { "content": " class TVarC = FakeTimedVariable> // TimeDVariable\n", "file_path": "pagespeed/kernel/base/statistics_template.h", "rank": 23, "score": 141535.16432343514 }, { "content": "class WgetUrlFetcher : public ExternalUrlFetcher {\n\n public:\n\n WgetUrlFetcher();\n\n virtual ~WgetUrlFetcher() {}\n\n\n\n private:\n\n virtual GoogleString ConstructFetchCommand(\n\n const GoogleString& escaped_url,\n\n const char* user_agent,\n\n const StringVector& escaped_headers);\n\n virtual const char* GetFetchLabel();\n\n\n\n DISALLOW_COPY_AND_ASSIGN(WgetUrlFetcher);\n\n};\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // NET_INSTAWEB_HTTP_PUBLIC_WGET_URL_FETCHER_H_\n", "file_path": "net/instaweb/http/public/wget_url_fetcher.h", "rank": 24, "score": 141525.14600070452 }, { "content": " class ExternalServersOption : public OptionTemplateBase<Spec> {\n\n public:\n\n bool SetFromString(StringPiece value_string,\n\n GoogleString* error_detail) override {\n\n return this->mutable_value().SetFromString(value_string, default_port,\n\n error_detail);\n\n }\n\n GoogleString ToString() const override {\n\n return this->value().ToString();\n\n }\n\n GoogleString Signature(const Hasher* hasher) const override {\n\n return hasher->Hash(ToString());\n\n }\n\n };\n\n\n", "file_path": "pagespeed/system/system_rewrite_options.h", "rank": 25, "score": 140762.09030382178 }, { "content": "class IntegerToStringToIntTest : public testing::Test {\n\n protected:\n\n void ValidateIntegerToString(int i, GoogleString s) {\n\n EXPECT_EQ(s, IntegerToString(i));\n\n ValidateInteger64ToString(static_cast<int64>(i), s);\n\n }\n\n\n\n void ValidateStringToInt(GoogleString s, int i) {\n\n int i2;\n\n EXPECT_TRUE(StringToInt(s, &i2));\n\n EXPECT_EQ(i, i2);\n\n ValidateStringToInt64(s, static_cast<int64>(i));\n\n }\n\n\n\n void InvalidStringToInt(GoogleString s, int expected) {\n\n int i = -50;\n\n EXPECT_FALSE(StringToInt(s, &i));\n\n EXPECT_EQ(expected, i);\n\n InvalidStringToInt64(s);\n\n }\n", "file_path": "pagespeed/kernel/base/string_util_test.cc", "rank": 26, "score": 138562.922375203 }, { "content": "// This class is not template for several reasons:\n\n// 1. There is currently no need in having different types depending on what\n\n// external cache are we testing.\n\n// 2. Templates add complexity and boilerplate when defining functions outside\n\n// of the class.\n\n// 3. When you have a class derived from template class, you cannot access\n\n// member functions and fields without explicitly writing `this->` or\n\n// something similar. It's explained in Google Test documentation and here:\n\n// http://stackoverflow.com/questions/1120833/derived-template-class-access-to-base-class-member-data\n\nclass SystemCachesExternalCacheTestBase : public SystemCachesTest {\n\n protected:\n\n virtual bool SkipExternalCacheTests() = 0;\n\n\n\n virtual GoogleString AssembledAsyncCacheWithStats() = 0;\n\n\n\n virtual GoogleString AssembledBlockingCacheWithStats() = 0;\n\n\n\n virtual void SetUpExternalCache(SystemRewriteOptions* options) = 0;\n\n\n\n // Test helpers\n\n void TestBasicCacheAndLru();\n\n\n\n void TestBasicCacheLruShm();\n\n\n\n void TestBasicCacheShmNoLru();\n\n\n\n void StressTestHelper(bool do_deletes) {\n\n if (SkipExternalCacheTests()) {\n\n return;\n", "file_path": "pagespeed/system/system_caches_test.cc", "rank": 27, "score": 137385.4316443914 }, { "content": "class DequeUsingStdVector : public std::vector<T> {\n\n public:\n\n void push_front(const T& value) { this->insert(this->begin(), value); }\n\n void pop_front() { this->erase(this->begin()); }\n\n};\n\n\n\ntemplate<class Deque> static void FourElementWorkout(int iters,\n\n int num_elements) {\n\n for (int iter = 0; iter < iters; ++iter) {\n\n Deque deque;\n\n\n\n // Simple usage as pure stack or queue, but not at the same time.\n\n for (int i = 0; i < num_elements; ++i) { deque.push_back(i); }\n\n for (int i = 0; i < num_elements; ++i) {\n\n CHECK_EQ(i, deque.front());\n\n deque.pop_front();\n\n }\n\n for (int i = 0; i < num_elements; ++i) { deque.push_front(i); }\n\n for (int i = num_elements - 1; i >= 0; --i) {\n\n CHECK_EQ(i, deque.front());\n", "file_path": "pagespeed/kernel/util/deque_speed_test.cc", "rank": 28, "score": 133900.35030399702 }, { "content": "class SystemCachesRedisCacheTest : public SystemCachesExternalCacheTestBase {\n\n protected:\n\n // TODO(yeputons): share this code with SystemCachesMemCacheTest or move it to\n\n // the base class.\n\n bool SkipExternalCacheTests() override {\n\n return ServerSpec().empty();\n\n }\n\n\n\n // TODO(yeputons): share this code with SystemCachesMemCacheTest or move it to\n\n // the base class.\n\n ExternalServerSpec ServerSpec() {\n\n if (server_spec_.empty()) {\n\n // This matches the logic in apr_mem_cache_test.\n\n const char* port_string = getenv(\"REDIS_PORT\");\n\n int port;\n\n if (port_string == NULL || !StringToInt(port_string, &port)) {\n\n LOG(ERROR) << \"SystemCachesRedisCacheTest is skipped because env var \"\n\n << \"$REDIS_PORT is not set to a valid integer. Set that to \"\n\n << \"the port number where redis is running to enable the \"\n\n << \"tests. See install/run_program_with_redis.sh\";\n", "file_path": "pagespeed/system/system_caches_test.cc", "rank": 29, "score": 133537.00130616734 }, { "content": "class SystemCachesMemCacheTest : public SystemCachesExternalCacheTestBase {\n\n protected:\n\n bool SkipExternalCacheTests() override {\n\n return ServerSpec().empty();\n\n }\n\n\n\n ExternalClusterSpec ServerSpec() {\n\n if (cluster_spec_.empty()) {\n\n // This matches the logic in apr_mem_cache_test.\n\n const char* port_string = getenv(\"MEMCACHED_PORT\");\n\n int port;\n\n if (port_string == nullptr || !StringToInt(port_string, &port)) {\n\n LOG(ERROR) << \"SystemCachesMemCacheTest is skipped because env var \"\n\n << \"$MEMCACHED_PORT is not set to a valid integer. Set that \"\n\n << \"to the port number where memcached is running to enable \"\n\n << \"the tests. See install/run_program_with_memcached.sh\";\n\n return cluster_spec_;\n\n }\n\n cluster_spec_.servers.push_back(ExternalServerSpec(\"localhost\", port));\n\n }\n", "file_path": "pagespeed/system/system_caches_test.cc", "rank": 30, "score": 133537.00130616734 }, { "content": " // Functions added to a Sequence will be run sequentially, though not\n\n // necessarily always from the same worker thread. The scheduler will\n\n // continue to schedule new work added to the sequence until\n\n // FreeSequence is called.\n\n //\n\n // TODO(jmarantz): Make this subclass private (or just move it to the .cc\n\n // file) and change NewSequence to return a net_instaweb::Sequence*.\n\n class Sequence : public net_instaweb::Sequence {\n\n public:\n", "file_path": "pagespeed/kernel/thread/queued_worker_pool.h", "rank": 31, "score": 128989.95549028544 }, { "content": "class TestMessageHandler : public net_instaweb::MessageHandler {\n\n public:\n\n const StringVector& messages() { return messages_; }\n\n\n\n protected:\n\n virtual void MessageVImpl(MessageType type, const char* msg, va_list args);\n\n virtual void MessageSImpl(MessageType type, const GoogleString& message);\n\n\n\n virtual void FileMessageVImpl(MessageType type, const char* filename,\n\n int line, const char* msg, va_list args);\n\n virtual void FileMessageSImpl(MessageType type, const char* filename,\n\n int line, const GoogleString& message);\n\n\n\n private:\n\n StringVector messages_;\n\n};\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // PAGESPEED_KERNEL_BASE_MESSAGE_HANDLER_TEST_BASE_H_\n", "file_path": "pagespeed/kernel/base/message_handler_test_base.h", "rank": 32, "score": 124500.57099137842 }, { "content": "// Implements a sequence which is run directly from RunTasksUntil,\n\n// rather than running in a background thread.\n\nclass Scheduler::Sequence : public net_instaweb::Sequence {\n\n public:\n\n // The scheduler is used for doing timed-waits so that any pending\n\n // scheduler alarms fire before the wait-period ends.\n\n explicit Sequence(Scheduler* scheduler);\n\n virtual ~Sequence();\n\n\n\n void Add(Function* function) override LOCKS_EXCLUDED(scheduler_->mutex());\n\n\n\n // Runs functions for this sequence directly, until *done is true or\n\n // the timeout expires. Returns 'false' if the timeout expired prior\n\n // to 'done' getting set to true. 'done' must be protected\n\n // by scheduler_->mutex(), and is expected to be set by one of the sequence\n\n // tasks.\n\n bool RunTasksUntil(int64 timeout_ms, bool* done)\n\n EXCLUSIVE_LOCKS_REQUIRED(scheduler_->mutex());\n\n\n\n // Atomically forwards all activity to an alternative Sequence.\n\n // Any pending functions in the work_queue_ are transferred into\n\n // the sequence, and new functions passed to Add are added to\n", "file_path": "pagespeed/kernel/thread/scheduler_sequence.h", "rank": 33, "score": 123599.32645941089 }, { "content": " class TimedVar> class StatisticsTemplate\n\n : public Statistics {\n\n public:\n\n StatisticsTemplate() {}\n\n virtual ~StatisticsTemplate() {\n\n STLDeleteContainerPointers(variables_.begin(), variables_.end());\n\n STLDeleteContainerPointers(up_downs_.begin(), up_downs_.end());\n\n STLDeleteContainerPointers(histograms_.begin(), histograms_.end());\n\n STLDeleteContainerPointers(timed_vars_.begin(), timed_vars_.end());\n\n }\n\n\n\n // Implementations of Statistics API --- see base class docs for\n\n // description.\n\n virtual Var* AddVariable(const StringPiece& name) {\n\n Var* var = FindVariable(name);\n\n if (var == NULL) {\n\n var = NewVariable(name);\n\n variables_.push_back(var);\n\n variable_names_.push_back(name.as_string());\n\n variable_map_[name.as_string()] = var;\n", "file_path": "pagespeed/kernel/base/statistics_template.h", "rank": 34, "score": 121491.54189442613 }, { "content": "class TestClass {\n\n public:\n\n TestClass()\n\n : x_(0),\n\n runs_(0) {\n\n }\n\n\n\n void Method1(int x) {\n\n x_ = x;\n\n ++runs_;\n\n }\n\n\n\n void Method1ConstRefArg(const int& x) {\n\n x_ = 2 * x;\n\n ++runs_;\n\n }\n\n\n\n void Method2(int a, int b) {\n\n x_ = a + b;\n\n ++runs_;\n", "file_path": "pagespeed/kernel/base/callback_test.cc", "rank": 35, "score": 118997.96761353404 }, { "content": "class EmptyCallback : public net_instaweb::CacheInterface::Callback {\n\n public:\n\n EmptyCallback() {}\n\n virtual ~EmptyCallback() {}\n\n virtual void Done(net_instaweb::CacheInterface::KeyState state) {}\n\n\n\n private:\n\n DISALLOW_COPY_AND_ASSIGN(EmptyCallback);\n\n};\n\n\n\nvoid TestCachePayload(int payload_size, int chunk_size, int iters) {\n\n GoogleString value;\n\n net_instaweb::SimpleRandom random(new net_instaweb::NullMutex);\n\n GoogleString chunk = random.GenerateHighEntropyString(chunk_size);\n\n while (static_cast<int>(value.size()) < payload_size) {\n\n value += chunk;\n\n }\n\n net_instaweb::scoped_ptr<net_instaweb::ThreadSystem> thread_system(\n\n net_instaweb::Platform::CreateThreadSystem());\n\n net_instaweb::SimpleStats stats(thread_system.get());\n", "file_path": "pagespeed/kernel/cache/compressed_cache_speed_test.cc", "rank": 36, "score": 118100.08789390538 }, { "content": "class EmptyCallback : public net_instaweb::CacheInterface::Callback {\n\n public:\n\n EmptyCallback() {}\n\n virtual ~EmptyCallback() {}\n\n virtual void Done(net_instaweb::CacheInterface::KeyState state) {}\n\n\n\n private:\n\n DISALLOW_COPY_AND_ASSIGN(EmptyCallback);\n\n};\n\n\n", "file_path": "pagespeed/kernel/cache/lru_cache_speed_test.cc", "rank": 37, "score": 118100.08789390538 }, { "content": "class SimpleClass {\n\n public:\n\n SimpleClass() : index_(counter++) {}\n\n int index() const { return index_; }\n\n\n\n private:\n\n int index_;\n\n DISALLOW_COPY_AND_ASSIGN(SimpleClass);\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/ref_counted_ptr_test.cc", "rank": 38, "score": 116878.50327090279 }, { "content": "namespace net_instaweb {\n\n\n\nstruct ExternalServerSpec {\n\n ExternalServerSpec() : host(), port(0) {}\n\n ExternalServerSpec(GoogleString host_, int port_)\n\n : host(host_), port(port_) {}\n\n bool SetFromString(StringPiece value_string, int default_port,\n\n GoogleString* error_detail);\n\n\n\n bool empty() const { return host.empty() && port == 0; }\n\n GoogleString ToString() const {\n\n // Should be 1:1 representation of value held, used to generate signature.\n\n return empty() ? \"\" : StrCat(host, \":\", IntegerToString(port));\n\n }\n\n\n\n GoogleString host;\n\n int port;\n", "file_path": "pagespeed/system/external_server_spec.h", "rank": 39, "score": 112778.93965911199 }, { "content": "class BaseClass : public RefCounted<BaseClass> {\n\n public:\n\n BaseClass() {}\n\n int index() const { return simple_.index(); }\n\n\n\n protected:\n\n virtual ~BaseClass() {}\n\n REFCOUNT_FRIEND_DECLARATION(BaseClass);\n\n\n\n private:\n\n SimpleClass simple_;\n\n DISALLOW_COPY_AND_ASSIGN(BaseClass);\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/ref_counted_ptr_test.cc", "rank": 40, "score": 109203.3094428851 }, { "content": "// This class is a base for various mechanisms of running things in background.\n\n//\n\n// If you just want to run something in background, you want to use a subclass\n\n// of this, such as a SlowWorker or QueuedWorker instance.\n\n//\n\n// Subclasses should implement bool PermitQueue() and provide an appropriate\n\n// wrapper around QueueIfPermitted().\n\nclass Worker {\n\n public:\n\n // Tries to start the work thread (if it hasn't been started already).\n\n void Start();\n\n\n\n // Returns true if there was a job running or any jobs queued at the time\n\n // this function was called.\n\n bool IsBusy();\n\n\n\n // Finishes the currently running jobs, and deletes any queued jobs.\n\n // No further jobs will be accepted after this call either; they will\n\n // just be canceled. It is safe to call this method multiple times.\n\n void ShutDown();\n\n\n\n // Sets up a timed-variable statistic indicating the current queue depth.\n\n //\n\n // This must be called prior to starting the thread.\n\n void set_queue_size_stat(Waveform* x) { queue_size_ = x; }\n\n\n\n protected:\n", "file_path": "pagespeed/kernel/thread/worker.h", "rank": 41, "score": 109034.40973974376 }, { "content": "// Encapsulates a task to be run in response to some event, such as\n\n// a Timer callback, an fetch, or a cache lookup.\n\n//\n\n// Users of interfaces requiring a Function* can either derive a new\n\n// class from Function, or use one of the helper template-classes or\n\n// MakeFunction variants below, which create delayed calls to class\n\n// methods.\n\n//\n\n// Note that Functions by default are self-deleting after call, but\n\n// you can override that with set_delete_after_callback(false).\n\n//\n\n// A Function will always have its Run method or its Cancel method\n\n// called, never both. A Function should never be deleted without its\n\n// Run/Cancel method being called (except if\n\n// set_delete_after_callback(false)).\n\n//\n\n// Note that classes calling Functions use the CallRun or CallCancel methods,\n\n// rather than calling Run or Cancel directly. This allows the Function class\n\n// to enforce policy on making run & cancel mutually exclusive and implement\n\n// delete-after-run.\n\nclass Function {\n\n public:\n\n Function();\n\n virtual ~Function();\n\n\n\n // Functions used as Worker tasks can help the system shut down cleanly\n\n // by calling quit_requested() periodically. To support this, Worker\n\n // calls set_quit_requested_pointer so the Function object can access\n\n // the atomic bool.\n\n //\n\n // Note that a strategy of allocating the AtomicBool inside the Function\n\n // object exposes a shutdown race when the function completes and deletes\n\n // itself.\n\n void set_quit_requested_pointer(AtomicBool* x) { quit_requested_ = x; }\n\n\n\n // Allows an infrastructure (e.g. Worker or Alarm) to request that\n\n // a running Function stop soon, as it is being shut down.\n\n //\n\n // This can should only be called during the Run() method.\n\n bool quit_requested() const {\n", "file_path": "pagespeed/kernel/base/function.h", "rank": 42, "score": 109030.05000108486 }, { "content": "// Base class for implementations of monitoring statistics.\n\nclass Statistics {\n\n public:\n\n // Default group for use with AddTimedVariable.\n\n static const char kDefaultGroup[];\n\n\n\n Statistics() {}\n\n virtual ~Statistics();\n\n\n\n // Add a new variable, or returns an existing one of that name.\n\n // The UpDownCounter* is owned by the Statistics class -- it should\n\n // not be deleted by the caller.\n\n virtual UpDownCounter* AddUpDownCounter(const StringPiece& name) = 0;\n\n\n\n // Like AddVariable, but asks the implementation to scope the variable to the\n\n // entire process, even if statistics are generally partitioned by domains or\n\n // the like. Default implementation simply forwards to AddVariable.\n\n virtual UpDownCounter* AddGlobalUpDownCounter(const StringPiece& name);\n\n\n\n // Find a variable from a name, returning NULL if not found.\n\n virtual UpDownCounter* FindUpDownCounter(const StringPiece& name) const = 0;\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 43, "score": 109023.0330942476 }, { "content": "// Displays a waveform of values over time. This can run\n\n// continuously, in which case it will only display waveforms for a\n\n// bounded number of samples. Or it can be run as a trigger.\n\n//\n\n// However the average, min, and max values will account for all the\n\n// values seen by the waveform since it was cleared.\n\n//\n\n// This class is threadsafe.\n\nclass Waveform {\n\n public:\n\n Waveform(ThreadSystem* thread_system, Timer* timer, int capacity,\n\n UpDownCounter* metric);\n\n\n\n void Clear();\n\n double Average();\n\n double Maximum();\n\n double Minimum();\n\n int Size();\n\n\n\n // Records a value at the current time using the Timer.\n\n void Add(double value);\n\n\n\n // Records a delta relative to the previous value using the Timer.\n\n // This is equivalent to calling Add(previous_value + delta).\n\n void AddDelta(double delta);\n\n\n\n // Write script and function to web page. Note that this function\n\n // should be called only once for each HTML page, and should not be\n", "file_path": "pagespeed/kernel/base/waveform.h", "rank": 44, "score": 109022.07581341194 }, { "content": "// Implements a simple scheduler that allows a thread to block until either time\n\n// expires, or a condition variable is signaled. Also permits various alarms to\n\n// be scheduled; these are lightweight short-lived callbacks that must be safely\n\n// runnable from any thread in any lock state in which scheduler invocations\n\n// occur. Finally, implements a hybrid between these: a callback that can be\n\n// run when the condition variable is signaled.\n\n//\n\n// This class is designed to be overridden, but only to re-implement its\n\n// internal notion of blocking to permit time to be mocked by MockScheduler.\n\nclass Scheduler {\n\n public:\n", "file_path": "pagespeed/kernel/thread/scheduler.h", "rank": 45, "score": 109021.46927399689 }, { "content": "class Function;\n\n\n", "file_path": "pagespeed/kernel/thread/sequence.h", "rank": 46, "score": 109015.77755732345 }, { "content": "class Writer;\n\n\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 47, "score": 109015.77755732345 }, { "content": "class Hasher {\n\n public:\n\n // The passed in max_chars will be used to limit the length of\n\n // Hash() and HashSizeInChars()\n\n explicit Hasher(int max_chars);\n\n virtual ~Hasher();\n\n\n\n // Computes a web64-encoded hash of a single string. This\n\n // operation is thread-safe.\n\n //\n\n // This is implemented in terms of RawHash, and honors the length limit\n\n // passed in to the constructor.\n\n GoogleString Hash(const StringPiece& content) const;\n\n\n\n // Return string length of hashes produced by this hasher's Hash\n\n // method.\n\n //\n\n // This is implemented in terms of RawHashSizeInBytes() and the length limit\n\n // passed in to the constructor.\n\n int HashSizeInChars() const;\n", "file_path": "pagespeed/kernel/base/hasher.h", "rank": 48, "score": 109015.77755732345 }, { "content": "// UpDownCounters are variables that can also be decreased (e.g. Add\n\n// of a negative number) or Set to an arbitrary value.\n\n//\n\n// TODO(jmarantz): Make this not inherit from Variable, which will simplify the\n\n// 'CheckNotNegative' and its ifndefs, but will require us to do more accurate\n\n// type bookkeeping in tests, etc.\n\n//\n\n// TODO(jmarantz): consider renaming Variable->Counter, UpDownCounter->Variable.\n\nclass UpDownCounter {\n\n public:\n\n virtual ~UpDownCounter();\n\n\n\n virtual int64 Get() const = 0;\n\n // Return some name representing the variable, provided that the specific\n\n // implementation has some sensible way of doing so.\n\n virtual StringPiece GetName() const = 0;\n\n\n\n // Sets the specified value, returning the previous value. This can be\n\n // used to by two competing threads/processes to determine which thread\n\n // modified the value first. The default implementation is non-atomic,\n\n // but implementations can override to provide an atomic version.\n\n //\n\n // Non-atomic implementations may result in multiple concurrent updates\n\n // each returning the old value. In an atomic implementation, only one\n\n // concurrent update will return the old value.\n\n virtual int64 SetReturningPreviousValue(int64 value);\n\n\n\n virtual void Set(int64 value) = 0;\n\n void Clear() { Set(0); }\n\n int64 Add(int64 delta) { return AddHelper(delta); }\n\n\n\n protected:\n\n // This is virtual so that subclasses can add platform-specific atomicity.\n\n virtual int64 AddHelper(int64 delta) = 0;\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 49, "score": 109015.77755732345 }, { "content": "class Callback1 {\n\n public:\n\n Callback1() {}\n\n virtual ~Callback1() {}\n\n virtual void Run(A1) = 0;\n\n};\n\n\n\n// Naming convention is:\n\n// (Member)?Callback_<num-pre-bound-args>_<num-runtime-args>\n\n\n\n// TODO(gee): Fill out other useful specializations.\n\ntemplate<class C, class A1, bool DeleteAfterRun>\n", "file_path": "pagespeed/kernel/base/callback.h", "rank": 50, "score": 109015.77755732345 }, { "content": "class Timer;\n", "file_path": "pagespeed/system/admin_site.h", "rank": 51, "score": 109015.77755732345 }, { "content": "class Waveform;\n\n\n", "file_path": "pagespeed/kernel/thread/worker.h", "rank": 52, "score": 109015.77755732345 }, { "content": "class Statistics;\n", "file_path": "pagespeed/system/system_caches.h", "rank": 53, "score": 109015.77755732345 }, { "content": "// Atoms are idempotent representations of strings, created\n\n// via a symbol table.\n\nclass Atom {\n\n public:\n\n Atom(const Atom& src) : str_(src.str_) {}\n\n Atom();\n\n ~Atom() {} // atoms are memory-managed by SymbolTables.\n\n\n\n Atom& operator=(const Atom& src) {\n\n if (&src != this) {\n\n str_ = src.str_;\n\n }\n\n return *this;\n\n }\n\n\n\n // Returns the address of the canonical StringPiece representing this Atom.\n\n // The underlying StringPiece object (and its data) are owned by the\n\n // SymbolTable.\n\n const StringPiece* Rep() const { return str_; }\n\n\n\n // This is comparing the underlying StringPiece pointers. It is invalid\n\n // to compare Atoms from different symbol tables.\n", "file_path": "pagespeed/kernel/base/atom.h", "rank": 54, "score": 109015.77755732345 }, { "content": " // An implementation of net_instaweb::Sequence that's controlled by the\n\n // scheduler.\n\n class Sequence;\n\n\n\n // Sorting comparator for Alarms, so that they can be retrieved in time\n\n // order. For use by std::set, thus public.\n\n struct CompareAlarms {\n\n bool operator()(const Alarm* a, const Alarm* b) const;\n\n };\n\n\n\n Scheduler(ThreadSystem* thread_system, Timer* timer);\n\n virtual ~Scheduler();\n\n\n\n ThreadSystem::CondvarCapableMutex* mutex() LOCK_RETURNED(mutex_) {\n\n return mutex_.get();\n\n }\n\n\n\n // Optionally check that mutex is locked for debugging purposes.\n\n void DCheckLocked() EXCLUSIVE_LOCKS_REQUIRED(mutex()) {\n\n mutex_->DCheckLocked();\n\n }\n\n\n", "file_path": "pagespeed/kernel/thread/scheduler.h", "rank": 55, "score": 109015.77755732345 }, { "content": "class Statistics;\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 56, "score": 109015.77755732345 }, { "content": "class Signature {\n\n public:\n\n // The passed in max_chars will be used to limit the length of Sign() and\n\n // SignatureSizeInChars().\n\n explicit Signature();\n\n virtual ~Signature();\n\n\n\n // Computes a web64-encoded signature of data under a given key. Takes a\n\n // StringPiece for signing key, which is used for a pointer to the key and the\n\n // length of the signing key, and a StringPiece for the data, which is used\n\n // for a pointer to the data to sign, and the length of the data.\n\n GoogleString Sign(StringPiece key, StringPiece data) const;\n\n\n\n // Returns the string length of the signatures produced by the Sign() method.\n\n virtual int SignatureSizeInChars() const = 0;\n\n\n\n protected:\n\n // Computes a binary signature of a given data under key.\n\n virtual GoogleString RawSign(StringPiece key, StringPiece data) const = 0;\n\n // The number of bytes RawSign will produce.\n", "file_path": "pagespeed/kernel/base/signature.h", "rank": 57, "score": 109015.77755732345 }, { "content": "class Function;\n", "file_path": "pagespeed/kernel/thread/worker.h", "rank": 58, "score": 109015.77755732345 }, { "content": "class Callback2 {\n\n public:\n\n Callback2() {}\n\n virtual ~Callback2() {}\n\n virtual void Run(A1, A2) = 0;\n\n};\n\n\n\n// Naming convention is:\n\n// (Member)?Callback_<num-pre-bound-args>_<num-runtime-args>\n\n\n\n// TODO(gee): Fill out other useful specializations.\n\ntemplate<class C, class A1, class A2, bool DeleteAfterRun>\n", "file_path": "pagespeed/kernel/base/callback.h", "rank": 59, "score": 109015.77755732345 }, { "content": "class Histogram {\n\n public:\n\n virtual ~Histogram();\n\n // Record a value in its bucket.\n\n virtual void Add(double value) = 0;\n\n // Throw away all data.\n\n virtual void Clear() = 0;\n\n // True if the histogram is empty.\n\n bool Empty() {\n\n ScopedMutex hold(lock());\n\n return CountInternal() == 0;\n\n }\n\n // Write Histogram Data to the writer.\n\n // Default implementation does not include histogram graph, but only raw\n\n // histogram data table. It looks like:\n\n // ________________________________________\n\n // | TITLE String |\n\n // | Avg: StdDev: Median: 90%: 95%: 99% |\n\n // | Raw Histogram Data: |\n\n // | [0,1] 1 25% 25% ||||| |\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 60, "score": 109015.77755732345 }, { "content": "class Timer;\n", "file_path": "pagespeed/kernel/base/waveform.h", "rank": 61, "score": 109015.77755732345 }, { "content": "// Interface for writing bytes to an output stream.\n\nclass Writer {\n\n public:\n\n Writer() {}\n\n virtual ~Writer();\n\n\n\n virtual bool Write(const StringPiece& str, MessageHandler* handler) = 0;\n\n virtual bool Flush(MessageHandler* message_handler) = 0;\n\n\n\n // Dumps the contents of what's been written to the Writer. Many\n\n // Writer implementations will not be able to do this, and the default\n\n // implementation will return false. But StringWriter and\n\n // SharedCircularBuffer can dump their contents, and override\n\n // this with implementations that return true.\n\n virtual bool Dump(Writer* writer, MessageHandler* message_handler);\n\n\n\n private:\n\n DISALLOW_COPY_AND_ASSIGN(Writer);\n\n};\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // PAGESPEED_KERNEL_BASE_WRITER_H_\n", "file_path": "pagespeed/kernel/base/writer.h", "rank": 62, "score": 109015.77755732345 }, { "content": "class UpDownCounter;\n", "file_path": "pagespeed/kernel/base/waveform.h", "rank": 63, "score": 109015.77755732345 }, { "content": "class Pool {\n\n public:\n\n // We can iterate over a pool using this iterator type.\n\n typedef typename PoolElement<T>::Position iterator;\n\n typedef typename std::list<T*>::const_iterator const_iterator;\n\n\n\n Pool() { }\n\n\n\n ~Pool() {\n\n DeleteAll();\n\n }\n\n\n\n // Is pool empty?\n\n bool empty() const {\n\n return contents_.empty();\n\n }\n\n\n\n // Size of pool\n\n size_t size() const {\n\n return contents_.size();\n", "file_path": "pagespeed/kernel/base/pool.h", "rank": 64, "score": 109015.77755732345 }, { "content": "class Writer;\n\n\n", "file_path": "pagespeed/kernel/base/waveform.h", "rank": 65, "score": 109015.77755732345 }, { "content": "class Statistics;\n", "file_path": "pagespeed/system/admin_site.h", "rank": 66, "score": 109015.77755732345 }, { "content": "class Statistics;\n", "file_path": "pagespeed/automatic/proxy_interface.h", "rank": 67, "score": 109015.77755732345 }, { "content": "// Interface for a holding and adding to a sequence of tasks.\n\n// The mechanism for executing the tasks must be defined by\n\n// implementations of this interface.\n\nclass Sequence {\n\n public:\n\n Sequence();\n\n virtual ~Sequence();\n\n\n\n // Adds 'function' to a sequence. Note that this can occur at any time\n\n // the sequence is live -- you can add functions to a sequence that has\n\n // already started processing. The caller is expected to ensure Function\n\n // will be cleaned up after Run or Cancel.\n\n //\n\n // 'function' can be called any time after Add(), and may in fact be\n\n // called before Add() returns. It's OK for the function to call Add\n\n // again.\n\n //\n\n // If the sequence is destructed after Add, but before the function has\n\n // been run, function->Cancel() will be called when the Sequence is destroyed.\n\n virtual void Add(Function* function) = 0;\n\n\n\n private:\n\n DISALLOW_COPY_AND_ASSIGN(Sequence);\n\n};\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // PAGESPEED_KERNEL_THREAD_SEQUENCE_H_\n", "file_path": "pagespeed/kernel/thread/sequence.h", "rank": 68, "score": 109015.77755732345 }, { "content": "// CONCEPT!\n\nclass allocator\n\n{\n\npublic:\n\n\texplicit allocator(const char* name = \"DEFAULT\"):\tm_name(name) {}\n\n\t// Copy ctor generated by compiler.\n\n\t// allocator(const allocator&)\n\n\t~allocator() {}\n\n\n\n\t// Generated by compiler.\n\n\t//allocator& operator=(const allocator&)\n\n\n\n\tvoid* allocate(unsigned int bytes, int flags = 0);\n\n\t// Not supported for standard allocator for the time being.\n\n\tvoid* allocate_aligned(unsigned int bytes, unsigned int alignment, int flags = 0);\n\n\tvoid deallocate(void* ptr, unsigned int bytes);\n\n\n\n\tconst char* get_name() const;\n\n\n\nprivate:\n\n\tconst char*\tm_name;\n", "file_path": "third_party/rdestl/allocator.h", "rank": 69, "score": 109015.77755732345 }, { "content": "class Arena {\n\n public:\n\n // All allocations we make will be aligned to this. We will also reserve\n\n // this much room for our work area, as it keeps things simple.\n\n static const size_t kAlign = 8;\n\n\n\n Arena() {\n\n InitEmpty();\n\n }\n\n\n\n ~Arena() {\n\n CHECK(chunks_.empty());\n\n }\n\n\n\n void* Allocate(size_t size) {\n\n size += kAlign; // Need room to link the next object.\n\n size = ExpandToAlign(size);\n\n\n\n DCHECK(sizeof(void*) <= kAlign);\n\n DCHECK(size < Chunk::kSize);\n", "file_path": "pagespeed/kernel/base/arena.h", "rank": 70, "score": 109015.77755732345 }, { "content": "class Writer;\n\n\n\n// Read/write API for HTTP headers (shared base class)\n\ntemplate<class Proto> class Headers {\n\n public:\n\n // typedef's for manipulating the cookie multimap.\n\n typedef std::pair<StringPiece, StringPiece> ValueAndAttributes;\n\n typedef std::multimap<StringPiece, ValueAndAttributes> CookieMultimap;\n\n typedef std::multimap<StringPiece, ValueAndAttributes>::const_iterator\n\n CookieMultimapConstIter;\n\n\n\n Headers();\n\n virtual ~Headers();\n\n\n\n virtual void Clear();\n\n\n\n int major_version() const;\n\n bool has_major_version() const;\n\n int minor_version() const;\n\n void set_major_version(int major_version);\n", "file_path": "pagespeed/kernel/http/headers.h", "rank": 71, "score": 109015.77755732345 }, { "content": "class Writer;\n\n\n", "file_path": "pagespeed/system/admin_site.h", "rank": 72, "score": 109015.77755732345 }, { "content": "class Wildcard {\n\n public:\n\n static const char kMatchAny; // *\n\n static const char kMatchOne; // ?\n\n\n\n // Create a wildcard object with the specification using * and ?\n\n // as wildcards. There is currently no way to quote * or ?.\n\n explicit Wildcard(const StringPiece& wildcard_spec);\n\n\n\n // Determines whether a string matches the wildcard.\n\n bool Match(const StringPiece& str) const;\n\n\n\n // Determines whether this wildcard is just a simple name, lacking\n\n // any wildcard characters.\n\n bool IsSimple() const { return is_simple_; }\n\n\n\n // Returns the original wildcard specification.\n\n const StringPiece spec() const {\n\n return StringPiece(storage_.data(), storage_.size() - 1);\n\n }\n", "file_path": "pagespeed/kernel/base/wildcard.h", "rank": 73, "score": 109015.77755732345 }, { "content": "class Hasher;\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 74, "score": 109015.77755732345 }, { "content": " class Connection {\n\n public:\n\n Connection(RedisCache* redis_cache, StringPiece host, int port);\n\n\n\n void StartUp(bool connect_now = true)\n\n LOCKS_EXCLUDED(redis_mutex_, state_mutex_);\n\n bool IsHealthy() const LOCKS_EXCLUDED(redis_mutex_, state_mutex_);\n\n void ShutDown() LOCKS_EXCLUDED(redis_mutex_, state_mutex_);\n\n\n\n GoogleString ToString() {\n\n return StrCat(host_, \":\", IntegerToString(port_));\n\n }\n\n\n\n AbstractMutex* GetOperationMutex() const LOCK_RETURNED(redis_mutex_) {\n\n return redis_mutex_.get();\n\n }\n\n\n\n // Must be followed by ValidateRedisReply() under the same lock.\n\n RedisReply RedisCommand(const char* format, va_list args)\n\n EXCLUSIVE_LOCKS_REQUIRED(redis_mutex_) LOCKS_EXCLUDED(state_mutex_);\n", "file_path": "pagespeed/system/redis_cache.h", "rank": 75, "score": 109015.77755732345 }, { "content": "// Encapsulates the creation of objects that may have different applications\n\n// across platforms.\n\nclass Platform {\n\n public:\n\n // Creates an appropriate ThreadSystem for the platform.\n\n static ThreadSystem* CreateThreadSystem();\n\n\n\n // Creates an appropriate Timer for the platform.\n\n static Timer* CreateTimer();\n\n};\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // PAGESPEED_KERNEL_UTIL_PLATFORM_H_\n", "file_path": "pagespeed/kernel/util/platform.h", "rank": 76, "score": 109015.77755732345 }, { "content": "class Timer;\n\n\n", "file_path": "pagespeed/kernel/util/platform.h", "rank": 77, "score": 109015.77755732345 }, { "content": " // A callback for a scheduler alarm, with an associated wakeup time (absolute\n\n // time after which the callback will be invoked with Run() by the scheduler).\n\n // Alarm should be treated as an opaque type.\n\n class Alarm;\n\n\n", "file_path": "pagespeed/kernel/thread/scheduler.h", "rank": 78, "score": 109015.77755732345 }, { "content": "// Timer interface, made virtual so it can be mocked for tests.\n\nclass Timer {\n\n public:\n\n // Note: it's important that these stay compile-time constants, to\n\n // avoid weird init order surprises. (Noticed in the wild on Mac).\n\n // If you get a link error due to one of these missing, you're trying\n\n // to pass it in by a const reference. You can do something like * 1 to\n\n // sidestep the issue.\n\n static const int64 kSecondMs = 1000;\n\n static const int64 kMsUs = 1000;\n\n static const int64 kSecondUs = kMsUs * kSecondMs;\n\n static const int64 kSecondNs = 1000 * kSecondUs;\n\n static const int64 kMinuteMs = 60 * kSecondMs;\n\n static const int64 kMinuteUs = 60 * kSecondUs;\n\n static const int64 kHourMs = 60 * kMinuteMs;\n\n static const int64 kDayMs = 24 * kHourMs;\n\n static const int64 kWeekMs = 7 * kDayMs;\n\n static const int64 kMonthMs = 31 * kDayMs;\n\n static const int64 kYearMs = 365 * kDayMs;\n\n\n\n virtual ~Timer();\n", "file_path": "pagespeed/kernel/base/timer.h", "rank": 79, "score": 109015.77755732345 }, { "content": "class Timer;\n\n\n", "file_path": "pagespeed/automatic/proxy_fetch.h", "rank": 80, "score": 109015.77755732345 }, { "content": "// Variables can normally only be increased, not decreased. However, for\n\n// testing, They can also be Cleared.\n\n//\n\n// TODO(jmarantz): consider renaming this to Counter or maybe UpCounter.\n\nclass Variable {\n\n public:\n\n virtual ~Variable();\n\n\n\n virtual int64 Get() const = 0;\n\n // Return some name representing the variable, provided that the specific\n\n // implementation has some sensible way of doing so.\n\n virtual StringPiece GetName() const = 0;\n\n\n\n // Adds 'delta' to the variable's value, returning the result.\n\n int64 Add(int64 non_negative_delta) {\n\n DCHECK_LE(0, non_negative_delta);\n\n return AddHelper(non_negative_delta);\n\n }\n\n\n\n virtual void Clear() = 0;\n\n\n\n protected:\n\n // This is virtual so that subclasses can add platform-specific atomicity.\n\n virtual int64 AddHelper(int64 delta) = 0;\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 81, "score": 109015.77755732345 }, { "content": "#line 22 \"htmlparse/html_name.gperf\"\n\nstruct KeywordMap {const char* name; net_instaweb::HtmlName::Keyword keyword;};\n\n#include <string.h>\n\n\n\n#define TOTAL_KEYWORDS 137\n\n#define MIN_WORD_LENGTH 1\n\n#define MAX_WORD_LENGTH 22\n\n#define MIN_HASH_VALUE 7\n\n#define MAX_HASH_VALUE 209\n\n/* maximum key range = 203, duplicates = 0 */\n\n\n\n#ifndef GPERF_DOWNCASE\n\n#define GPERF_DOWNCASE 1\n\nstatic unsigned char gperf_downcase[256] =\n\n {\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n\n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n\n 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,\n\n 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,\n", "file_path": "net/instaweb/genfiles/htmlparse/html_name.cc", "rank": 82, "score": 107873.87598034886 }, { "content": "// Context for handling a request, computing options and request headers in\n\n// the constructor.\n\n//\n\n// TODO(jmarantz): There are many static methods in this class. Some\n\n// of them need to stay that way as they are used as C entry points.\n\n// Some are helper methods, and we could adopt a policy of requiring\n\n// the static methods to instantiate the class (possibly making its\n\n// constructor lighter weight) and then calling them explicitly. For\n\n// the time being, we'll leave these static methods with the\n\n// non-compliant lower_case_names_with_underscores naming convention\n\n// and fix their naming when we update whether they should be static\n\n// or not.\n\nclass InstawebHandler {\n\n public:\n\n explicit InstawebHandler(request_rec* request);\n\n ~InstawebHandler();\n\n\n\n // Any PageSpeed query params are removed.\n\n const GoogleUrl& stripped_gurl() const { return stripped_gurl_; }\n\n const RequestContextPtr request_context() const { return request_context_; }\n\n bool use_custom_options() const { return custom_options_.get() != NULL; }\n\n const QueryParams& query_params() { return rewrite_query_.query_params(); }\n\n const QueryParams& pagespeed_query_params() {\n\n return rewrite_query_.pagespeed_query_params();\n\n }\n\n const QueryParams& pagespeed_option_cookies() {\n\n return rewrite_query_.pagespeed_option_cookies();\n\n }\n\n\n\n void RemoveStrippedResponseHeadersFromApacheRequest();\n\n\n\n // Makes a driver from the request_context and options. Note that\n", "file_path": "pagespeed/apache/instaweb_handler.h", "rank": 83, "score": 107446.14045519012 }, { "content": "// Scalar value protected by a mutex. Mutex must fully protect access\n\n// to underlying scalar. For example, in mod_pagespeed and\n\n// ngx_pagespeed, variables are stored in shared memory and accessible\n\n// from any process on a machine, so the mutex must provide protection\n\n// across separate processes.\n\n//\n\n// StatisticsLogger depends upon these mutexes being cross-process so that\n\n// several processes using the same file system don't clobber each others logs.\n\n//\n\n// TODO(jmarantz): this could be done using templates rather than using virtual\n\n// methods, as MutexedScalar does not implement an abstract interface.\n\nclass MutexedScalar {\n\n public:\n\n virtual ~MutexedScalar();\n\n\n\n // Subclasses should not define these methods, instead define the *LockHeld()\n\n // methods below.\n\n int64 Get() const;\n\n void Set(int64 value);\n\n int64 SetReturningPreviousValue(int64 value);\n\n int64 AddHelper(int64 delta);\n\n\n\n protected:\n\n friend class StatisticsLogger;\n\n\n\n virtual AbstractMutex* mutex() const = 0;\n\n\n\n // Get/Setters that may only be called if you already hold the mutex.\n\n virtual int64 GetLockHeld() const = 0;\n\n virtual int64 SetReturningPreviousValueLockHeld(int64 value) = 0;\n\n\n\n // These are implemented based on GetLockHeld() and\n\n // SetReturningPreviousLockHeld().\n\n void SetLockHeld(int64 value);\n\n int64 AddLockHeld(int64 delta);\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 84, "score": 107435.4760557193 }, { "content": "// TimedVariable is a statistic class returns the amount added in the\n\n// last interval, which could be last 10 seconds, last minute\n\n// last one hour and total.\n\nclass TimedVariable {\n\n public:\n\n // The intervals for which we keep stats.\n\n enum Levels { TENSEC, MINUTE, HOUR, START };\n\n virtual ~TimedVariable();\n\n // Update the stat value. delta is in milliseconds.\n\n virtual void IncBy(int64 delta) = 0;\n\n // Get the amount added over the last time interval\n\n // specified by \"level\".\n\n virtual int64 Get(int level) = 0;\n\n // Throw away all data.\n\n virtual void Clear() = 0;\n\n};\n\n\n", "file_path": "pagespeed/kernel/base/statistics.h", "rank": 85, "score": 107434.70569898686 }, { "content": " // Limited iterator (not an STL iterator). Example usage:\n\n // for (HtmlName::Iterator iter; !iter.AtEnd(); iter.Next()) {\n\n // use(iter.keyword(), iter.name());\n\n // }\n\n class Iterator {\n\n public:\n\n Iterator() : index_(-1) { Next(); }\n\n bool AtEnd() const;\n\n void Next();\n\n Keyword keyword() const;\n\n const char* name() const;\n\n\n\n private:\n\n int index_;\n\n\n\n // Implicit copy and assign ok. The members can be safely copied by bits.\n\n };\n\n\n\n static int num_keywords();\n\n static Keyword Lookup(const StringPiece& name);\n\n\n\n private:\n\n // Constructs an HTML name given a keyword, which can be\n\n // HtmlName::kNotAKeyword, and 'StringPiece* str'. 'str'\n", "file_path": "pagespeed/kernel/html/html_name.h", "rank": 86, "score": 107434.47452981994 }, { "content": " // Limited iterator (not an STL iterator). Example usage:\n\n // for (JsKeywords::Iterator iter; !iter.AtEnd(); iter.Next()) {\n\n // use(iter.keyword(), iter.name());\n\n // }\n\n class Iterator {\n\n public:\n\n Iterator() : index_(-1) { Next(); }\n\n bool AtEnd() const;\n\n void Next();\n\n Type keyword() const;\n\n const char* name() const;\n\n\n\n private:\n\n int index_;\n\n\n\n // Implicit copy and assign ok. The members can be safely copied by bits.\n\n };\n\n\n\n private:\n\n // TODO(jkarlin): Get rid of the net_instaweb namespace once JsLexer is\n\n // moved into kernel/js.\n\n friend class net_instaweb::JsLexer;\n\n\n\n // Returns the number of keywords recognized by the Lookup function. This is\n\n // used by the Lexer to size the keyword-sring array prior to iterating over\n\n // the keywords to populate it.\n\n static int num_keywords();\n\n};\n\n\n\n} // namespace pagespeed\n\n\n\n#endif // PAGESPEED_KERNEL_JS_JS_KEYWORDS_H_\n", "file_path": "pagespeed/kernel/js/js_keywords.h", "rank": 87, "score": 107434.47452981994 }, { "content": "// This class tries to heuristically detect whether something that claims to\n\n// HTML is likely to be. For now, it merely looks at whether the first\n\n// non-whitespace/non-BOM character is <.\n\n//\n\n// Typical usage:\n\n// HtmlDetector detect_html_;\n\n//\n\n// if (!detect_html_.already_decided() &&\n\n// detect_html_.ConsiderInput(data)) {\n\n// GoogleString buffered;\n\n// detect_html_.ReleaseBuffered(&buffered);\n\n// if (detect_html_.probable_html()) {\n\n// do html-specific bits with buffered\n\n// } else {\n\n// do non-html things with buffered\n\n// }\n\n// }\n\n//\n\n// if (detect_html_.already_decided()) {\n\n// do appropriate things with data based on detect_html_.probable_html()\n\n// }\n\nclass HtmlDetector {\n\n public:\n\n HtmlDetector();\n\n ~HtmlDetector();\n\n\n\n // Processes the data, trying to determine if it's HTML or not. If there is\n\n // enough evidence to make a decision, returns true.\n\n //\n\n // If true is returned, already_decided() will be true as well, and hence\n\n // probable_html() will be accessible. buffered() will not be changed.\n\n //\n\n // If false is returned, data will be accumulated inside buffered().\n\n //\n\n // Precondition: !already_decided()\n\n bool ConsiderInput(const StringPiece& data);\n\n\n\n // Returns true if we have seen enough input to make a guess as to whether\n\n // it's HTML or not.\n\n bool already_decided() const { return already_decided_; }\n\n\n", "file_path": "pagespeed/automatic/html_detector.h", "rank": 88, "score": 107433.25116815642 }, { "content": "// Helps manage setup of cache backends provided by the PSOL library\n\n// (LRU, File, Memcached, and shared memory metadata), as well as named lock\n\n// managers. The expectation is that the RewriteDriverFactory for the server\n\n// will invoke this class's methods in appropriate spots.\n\n//\n\n// It is also expected that the RootInit() method will be called during server\n\n// setup before the server launches any additional processes, and ChildInit()\n\n// will be called on any child process handling requests. If the server\n\n// is single-process, both methods should be called.\n\n//\n\n// Keep in mind, however, that when fork() is involved a process may\n\n// effectively see both calls, in which case the 'ChildInit' call would\n\n// come second and override the previous root status.\n\nclass SystemCaches {\n\n public:\n\n // CacheStats prefixes.\n\n static const char kMemcachedAsync[];\n\n static const char kMemcachedBlocking[];\n\n static const char kRedisAsync[];\n\n static const char kRedisBlocking[];\n\n static const char kShmCache[];\n\n\n\n static const char kDefaultSharedMemoryPath[];\n\n\n\n enum StatFlags {\n\n kDefaultStatFlags = 0,\n\n kGlobalView = 1,\n\n kIncludeMemcached = 2,\n\n kIncludeRedis = 4\n\n };\n\n\n\n // Registers all statistics the cache backends may use.\n\n static void InitStats(Statistics* statistics);\n", "file_path": "pagespeed/system/system_caches.h", "rank": 89, "score": 107433.0744372396 }, { "content": "// Handles forking off a controller process, restarting it if it dies, and\n\n// shutting down the process if the host reloads config or shuts down.\n\n//\n\n// We fork a babysitter process, which forks a controller process. If the\n\n// controller process dies without calling exit(0) the babysitter will fork off\n\n// another controller.\n\n//\n\n// The controller runs a thread that watches for the root process to die, or to\n\n// ask it to quit. We use pipes for communication between the master process\n\n// and the controller. If the master process goes away, the controller reading\n\n// will get EOF. If the master process wants the controller to shut down so it\n\n// can be replaced, it writes a byte.\n\n//\n\n// (All methods in the ControllerManager are static. When you call\n\n// ForkControllerProcess() it keeps running until process exit.)\n\nclass ControllerManager {\n\n public:\n\n // Called on system startup, before forking off any workers. Starts up a\n\n // babysitter process that starts a controller process and restarts the\n\n // controller if it dies. Also called (again) on configuration reloading.\n\n static void ForkControllerProcess(\n\n std::unique_ptr<ControllerProcess>&& process,\n\n SystemRewriteDriverFactory* factory, ThreadSystem* thread_system,\n\n MessageHandler* handler);\n\n\n\n // Relinquishes the reference from us to the controller process. This may be\n\n // needed if our current process is going to go on and do something unrelated.\n\n static void DetachFromControllerProcess();\n\n\n\n private:\n\n // Set us up as a proper daemon, with no stdin/out/err and not process group.\n\n static void Daemonize(MessageHandler* handler);\n\n\n\n // Actually start the ControllerProcess. Returns an exit status.\n\n static int RunController(int controller_read_fd, ControllerProcess* process,\n\n ThreadSystem* thread_system,\n\n MessageHandler* handler);\n\n\n", "file_path": "pagespeed/system/controller_manager.h", "rank": 90, "score": 107432.97416251394 }, { "content": "// Encapsulates the instantiation of a FileRewriter & a simple one-shot\n\n// interface to rewrite some HTML text.\n\nclass StaticRewriter {\n\n public:\n\n StaticRewriter(const ProcessContext& process_context,\n\n int* argc, char*** argv);\n\n explicit StaticRewriter(const ProcessContext& process_context);\n\n ~StaticRewriter();\n\n\n\n bool ParseText(const StringPiece& text,\n\n const StringPiece& url,\n\n const StringPiece& id,\n\n const StringPiece& output_dir,\n\n Writer* writer);\n\n\n\n FileSystem* file_system();\n\n MessageHandler* message_handler();\n\n\n\n private:\n\n RewriteGflags gflags_;\n\n FileRewriter file_rewriter_;\n\n ServerContext* server_context_;\n\n\n\n DISALLOW_COPY_AND_ASSIGN(StaticRewriter);\n\n};\n\n\n\n} // namespace net_instaweb\n\n\n\n#endif // PAGESPEED_AUTOMATIC_STATIC_REWRITER_H_\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 91, "score": 107427.92577306878 }, { "content": "class Timer;\n\n\n", "file_path": "pagespeed/kernel/base/countdown_timer.h", "rank": 92, "score": 107427.92577306878 }, { "content": "class ProcessContext;\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 93, "score": 107427.92577306878 }, { "content": "class ServerContext;\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 94, "score": 107427.92577306878 }, { "content": "class Writer;\n\n\n", "file_path": "pagespeed/kernel/base/message_handler.h", "rank": 95, "score": 107427.92577306878 }, { "content": "class FileSystem;\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 96, "score": 107427.92577306878 }, { "content": "class Timer;\n\n\n", "file_path": "pagespeed/apache/apache_message_handler.h", "rank": 97, "score": 107427.92577306878 }, { "content": "class MessageHandler;\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 98, "score": 107427.92577306878 }, { "content": "class RewriteOptions;\n", "file_path": "pagespeed/automatic/static_rewriter.h", "rank": 99, "score": 107427.92577306878 } ]
C++
lite/tnn/cv/tnn_rvm.cpp
azuredsky/lite.ai
2751a7f0cf0970c1ab94b865b96c2f53ee28d545
#include "tnn_rvm.h" using tnncv::TNNRobustVideoMatting; TNNRobustVideoMatting::TNNRobustVideoMatting( const std::string &_proto_path, const std::string &_model_path, unsigned int _num_threads ) : proto_path(_proto_path.data()), model_path(_model_path.data()), log_id(_proto_path.data()), num_threads(_num_threads) { initialize_instance(); initialize_context(); } TNNRobustVideoMatting::~TNNRobustVideoMatting() { net = nullptr; src_mat = nullptr; r1i_mat = nullptr; r2i_mat = nullptr; r3i_mat = nullptr; r4i_mat = nullptr; instance = nullptr; } void TNNRobustVideoMatting::initialize_instance() { std::string proto_content_buffer, model_content_buffer; proto_content_buffer = BasicTNNHandler::content_buffer_from(proto_path); model_content_buffer = BasicTNNHandler::content_buffer_from(model_path); tnn::ModelConfig model_config; model_config.model_type = tnn::MODEL_TYPE_TNN; model_config.params = {proto_content_buffer, model_content_buffer}; tnn::Status status; net = std::make_shared<tnn::TNN>(); status = net->Init(model_config); if (status != tnn::TNN_OK || !net) { #ifdef LITETNN_DEBUG std::cout << "net->Init failed!\n"; #endif return; } #ifdef __ANDROID__ network_device_type = tnn::DEVICE_ARM; input_device_type = tnn::DEVICE_ARM; output_device_type = tnn::DEVICE_ARM; #else network_device_type = tnn::DEVICE_X86; input_device_type = tnn::DEVICE_X86; output_device_type = tnn::DEVICE_X86; #endif tnn::NetworkConfig network_config; network_config.library_path = {""}; network_config.device_type = network_device_type; instance = net->CreateInst(network_config, status); if (status != tnn::TNN_OK || !instance) { #ifdef LITETNN_DEBUG std::cout << "CreateInst failed!" << status.description().c_str() << "\n"; #endif return; } instance->SetCpuNumThreads((int) num_threads); for (auto &name: input_names) input_shapes[name] = BasicTNNHandler::get_input_shape(instance, name); auto src_shape = input_shapes.at("src"); if (src_shape.size() != 4) { #ifdef LITETNN_DEBUG throw std::runtime_error("Found src_shape.size()!=4, but " "src input only support 4 dims." "Such as NCHW, NHWC ..."); #else return; #endif } input_mat_type = BasicTNNHandler::get_input_mat_type(instance, "src"); input_data_format = BasicTNNHandler::get_input_data_format(instance, "src"); if (input_data_format == tnn::DATA_FORMAT_NCHW) { input_height = src_shape.at(2); input_width = src_shape.at(3); } else if (input_data_format == tnn::DATA_FORMAT_NHWC) { input_height = src_shape.at(1); input_width = src_shape.at(2); } else { #ifdef LITETNN_DEBUG std::cout << "src input only support NCHW and NHWC " "input_data_format, but found others.\n"; #endif return; } src_size = 1 * 3 * input_height * input_width; for (auto &name: output_names) output_shapes[name] = BasicTNNHandler::get_output_shape(instance, name); #ifdef LITETNN_DEBUG this->print_debug_string(); #endif } int TNNRobustVideoMatting::value_size_of(tnn::DimsVector &shape) { if (shape.empty()) return 0; int _size = 1; for (auto &s: shape) _size *= s; return _size; } void TNNRobustVideoMatting::print_debug_string() { std::cout << "LITETNN_DEBUG LogId: " << log_id << "\n"; std::cout << "=============== Input-Dims ==============\n"; for (auto &in: input_shapes) BasicTNNHandler::print_name_shape(in.first, in.second); std::string data_format_string = (input_data_format == tnn::DATA_FORMAT_NCHW) ? "NCHW" : "NHWC"; std::cout << "Input Data Format: " << data_format_string << "\n"; std::cout << "=============== Output-Dims ==============\n"; for (auto &out: output_shapes) BasicTNNHandler::print_name_shape(out.first, out.second); std::cout << "========================================\n"; } void TNNRobustVideoMatting::initialize_context() { r1i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r1i") ); r2i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r2i") ); r3i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r3i") ); r4i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r4i") ); r1i_size = this->value_size_of(input_shapes.at("r1i")); r2i_size = this->value_size_of(input_shapes.at("r2i")); r3i_size = this->value_size_of(input_shapes.at("r3i")); r4i_size = this->value_size_of(input_shapes.at("r4i")); std::fill_n((float *) r1i_mat->GetData(), r1i_size, 0.f); std::fill_n((float *) r2i_mat->GetData(), r2i_size, 0.f); std::fill_n((float *) r3i_mat->GetData(), r3i_size, 0.f); std::fill_n((float *) r4i_mat->GetData(), r4i_size, 0.f); context_is_initialized = true; } void TNNRobustVideoMatting::transform(const cv::Mat &mat) { cv::Mat canvas; cv::resize(mat, canvas, cv::Size(input_width, input_height)); cv::cvtColor(canvas, canvas, cv::COLOR_BGR2RGB); src_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::N8UC3, input_shapes.at("src"), (void *) canvas.data ); if (!src_mat->GetData()) { #ifdef LITETNN_DEBUG std::cout << "input_mat == nullptr! transform failed\n"; #endif } } void TNNRobustVideoMatting::detect(const cv::Mat &mat, types::MattingContent &content, bool video_mode) { if (mat.empty()) return; int img_h = mat.rows; int img_w = mat.cols; if (!context_is_initialized) return; this->transform(mat); tnn::MatConvertParam src_cvt_param, ctx_cvt_param; src_cvt_param.scale = scale_vals; src_cvt_param.bias = bias_vals; tnn::Status status_src, status_r1i, status_r2i, status_r3i, status_r4i; status_src = instance->SetInputMat(src_mat, src_cvt_param, "src"); status_r1i = instance->SetInputMat(r1i_mat, ctx_cvt_param, "r1i"); status_r2i = instance->SetInputMat(r2i_mat, ctx_cvt_param, "r2i"); status_r3i = instance->SetInputMat(r3i_mat, ctx_cvt_param, "r3i"); status_r4i = instance->SetInputMat(r4i_mat, ctx_cvt_param, "r4i"); if (status_src != tnn::TNN_OK || status_r1i != tnn::TNN_OK || status_r2i != tnn::TNN_OK || status_r3i != tnn::TNN_OK || status_r4i != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->SetInputMat failed!:" << status_src.description().c_str() << ": " << status_r1i.description().c_str() << ": " << status_r2i.description().c_str() << ": " << status_r3i.description().c_str() << ": " << status_r4i.description().c_str() << "\n"; #endif return; } auto status = instance->Forward(); if (status != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->Forward failed!:" << status.description().c_str() << "\n"; #endif return; } this->generate_matting(instance, content, img_h, img_w); if (video_mode) { context_is_update = false; this->update_context(instance); } } void TNNRobustVideoMatting::detect_video( const std::string &video_path, const std::string &output_path, std::vector<types::MattingContent> &contents, bool save_contents, unsigned int writer_fps) { cv::VideoCapture video_capture(video_path); const unsigned int width = video_capture.get(cv::CAP_PROP_FRAME_WIDTH); const unsigned int height = video_capture.get(cv::CAP_PROP_FRAME_HEIGHT); const unsigned int frame_count = video_capture.get(cv::CAP_PROP_FRAME_COUNT); if (!video_capture.isOpened()) { std::cout << "Can not open video: " << video_path << "\n"; return; } cv::VideoWriter video_writer(output_path, cv::VideoWriter::fourcc('m', 'p', '4', 'v'), writer_fps, cv::Size(width, height)); if (!video_writer.isOpened()) { std::cout << "Can not open writer: " << output_path << "\n"; return; } cv::Mat mat; unsigned int i = 0; while (video_capture.read(mat)) { i += 1; types::MattingContent content; this->detect(mat, content, true); if (content.flag) { if (save_contents) contents.push_back(content); if (!content.merge_mat.empty()) video_writer.write(content.merge_mat); } if (!context_is_update) break; #ifdef LITETNN_DEBUG std::cout << i << "/" << frame_count << " done!" << "\n"; #endif } video_capture.release(); video_writer.release(); } void TNNRobustVideoMatting::generate_matting(std::shared_ptr<tnn::Instance> &_instance, types::MattingContent &content, int img_h, int img_w) { std::shared_ptr<tnn::Mat> fgr_mat; std::shared_ptr<tnn::Mat> pha_mat; tnn::MatConvertParam cvt_param; tnn::Status status_fgr, status_pha; status_fgr = _instance->GetOutputMat(fgr_mat, cvt_param, "fgr", output_device_type); status_pha = _instance->GetOutputMat(pha_mat, cvt_param, "pha", output_device_type); if (status_fgr != tnn::TNN_OK || status_pha != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->GetOutputMat failed!:" << status_fgr.description().c_str() << ": " << status_pha.description().c_str() << "\n"; #endif return; } float *fgr_ptr = (float *) fgr_mat->GetData(); float *pha_ptr = (float *) pha_mat->GetData(); const unsigned int channel_step = input_height * input_width; cv::Mat rmat(input_height, input_width, CV_32FC1, fgr_ptr); cv::Mat gmat(input_height, input_width, CV_32FC1, fgr_ptr + channel_step); cv::Mat bmat(input_height, input_width, CV_32FC1, fgr_ptr + 2 * channel_step); cv::Mat pmat(input_height, input_width, CV_32FC1, pha_ptr); rmat *= 255.f; bmat *= 255.f; gmat *= 255.f; cv::Mat rest = 1.f - pmat; cv::Mat mbmat = bmat.mul(pmat) + rest * 153.f; cv::Mat mgmat = gmat.mul(pmat) + rest * 255.f; cv::Mat mrmat = rmat.mul(pmat) + rest * 120.f; std::vector<cv::Mat> fgr_channel_mats, merge_channel_mats; fgr_channel_mats.push_back(bmat); fgr_channel_mats.push_back(gmat); fgr_channel_mats.push_back(rmat); merge_channel_mats.push_back(mbmat); merge_channel_mats.push_back(mgmat); merge_channel_mats.push_back(mrmat); content.pha_mat = pmat; cv::merge(fgr_channel_mats, content.fgr_mat); cv::merge(merge_channel_mats, content.merge_mat); content.fgr_mat.convertTo(content.fgr_mat, CV_8UC3); content.merge_mat.convertTo(content.merge_mat, CV_8UC3); if (img_w != input_width || img_h != input_height) { cv::resize(content.pha_mat, content.pha_mat, cv::Size(img_w, img_h)); cv::resize(content.fgr_mat, content.fgr_mat, cv::Size(img_w, img_h)); cv::resize(content.merge_mat, content.merge_mat, cv::Size(img_w, img_h)); } content.flag = true; } void TNNRobustVideoMatting::update_context(std::shared_ptr<tnn::Instance> &_instance) { std::shared_ptr<tnn::Mat> r1o_mat; std::shared_ptr<tnn::Mat> r2o_mat; std::shared_ptr<tnn::Mat> r3o_mat; std::shared_ptr<tnn::Mat> r4o_mat; tnn::MatConvertParam cvt_param; tnn::Status status_r1o; tnn::Status status_r2o; tnn::Status status_r3o; tnn::Status status_r4o; status_r1o = _instance->GetOutputMat(r1o_mat, cvt_param, "r1o", output_device_type); status_r2o = _instance->GetOutputMat(r2o_mat, cvt_param, "r2o", output_device_type); status_r3o = _instance->GetOutputMat(r3o_mat, cvt_param, "r3o", output_device_type); status_r4o = _instance->GetOutputMat(r4o_mat, cvt_param, "r4o", output_device_type); if (status_r1o != tnn::TNN_OK || status_r2o != tnn::TNN_OK || status_r3o != tnn::TNN_OK || status_r4o != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->GetOutputMat context failed!:" << status_r1o.description().c_str() << ": " << status_r2o.description().c_str() << ": " << status_r3o.description().c_str() << ": " << status_r4o.description().c_str() << "\n"; #endif return; } void *command_queue = nullptr; auto status_cmd = _instance->GetCommandQueue(&command_queue); if (status_cmd != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->GetCommandQueue failed!:" << status_cmd.description().c_str() << "\n"; #endif return; } tnn::MatUtils::Copy(*r1o_mat, *r1i_mat, command_queue); tnn::MatUtils::Copy(*r2o_mat, *r2i_mat, command_queue); tnn::MatUtils::Copy(*r3o_mat, *r3i_mat, command_queue); tnn::MatUtils::Copy(*r4o_mat, *r4i_mat, command_queue); context_is_update = true; }
#include "tnn_rvm.h" using tnncv::TNNRobustVideoMatting; TNNRobustVideoMatting::TNNRobustVideoMatting( const std::string &_proto_path, const std::string &_model_path, unsigned int _num_threads ) : proto_path(_proto_path.data()), model_path(_model_path.data()), log_id(_proto_path.data()), num_threads(_num_threads) { initialize_instance(); initialize_context(); } TNNRobustVideoMatting::~TNNRobustVideoMatting() { net = nullptr; src_mat = nullptr; r1i_mat = nullptr; r2i_mat = nullptr; r3i_mat = nullptr; r4i_mat = nullptr; instance = nullptr; } void TNNRobustVideoMatting::initialize_instance() { std::string proto_content_buffer, model_content_buffer; proto_content_buffer = BasicTNNHandler::content_buffer_from(proto_path); model_content_buffer = BasicTNNHandler::content_buffer_from(model_path); tnn::ModelConfig model_config; model_config.model_type = tnn::MODEL_TYPE_TNN; model_config.params = {proto_content_buffer, model_content_buffer}; tnn::Status status; net = std::make_shared<tnn::TNN>(); status = net->Init(model_config); if (status != tnn::TNN_OK || !net) { #ifdef LITETNN_DEBUG std::cout << "net->Init failed!\n"; #endif return; } #ifdef __ANDROID__ network_device_type = tnn::DEVICE_ARM; input_device_type = tnn::DEVICE_ARM; output_device_type = tnn::DEVICE_ARM; #else network_device_type = tnn::DEVICE_X86; input_device_type = tnn::DEVICE_X86; output_device_type = tnn::DEVICE_X86; #endif tnn::NetworkConfig network_config; network_config.library_path = {""}; network_config.device_type = network_device_type; instance = net->CreateInst(network_config, status); if (status != tnn::TNN_OK || !instance) { #ifdef LITETNN_DEBUG std::cout << "CreateInst failed!" << status.description().c_str() << "\n"; #endif return; } instance->SetCpuNumThreads((int) num_threads); for (auto &name: input_names) input_shapes[name] = BasicTNNHandler::get_input_shape(instance, name); auto src_shape = input_shapes.at("src"); if (src_shape.size() != 4) { #ifdef LITETNN_DEBUG throw std::runtime_error("Found src_shape.size()!=4, but " "src input only support 4 dims." "Such as NCHW, NHWC ..."); #else return; #endif } input_mat_type = BasicTNNHandler::get_input_mat_type(instance, "src"); input_data_format = BasicTNNHandler::get_input_data_format(instance, "src"); if (input_data_format == tnn::DATA_FORMAT_NCHW) { input_height = src_shape.at(2); input_width = src_shape.at(3); } else if (input_data_format == tnn::DATA_FORMAT_NHWC) { input_height = src_shape.at(1); input_width = src_shape.at(2); }
int TNNRobustVideoMatting::value_size_of(tnn::DimsVector &shape) { if (shape.empty()) return 0; int _size = 1; for (auto &s: shape) _size *= s; return _size; } void TNNRobustVideoMatting::print_debug_string() { std::cout << "LITETNN_DEBUG LogId: " << log_id << "\n"; std::cout << "=============== Input-Dims ==============\n"; for (auto &in: input_shapes) BasicTNNHandler::print_name_shape(in.first, in.second); std::string data_format_string = (input_data_format == tnn::DATA_FORMAT_NCHW) ? "NCHW" : "NHWC"; std::cout << "Input Data Format: " << data_format_string << "\n"; std::cout << "=============== Output-Dims ==============\n"; for (auto &out: output_shapes) BasicTNNHandler::print_name_shape(out.first, out.second); std::cout << "========================================\n"; } void TNNRobustVideoMatting::initialize_context() { r1i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r1i") ); r2i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r2i") ); r3i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r3i") ); r4i_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::NCHW_FLOAT, input_shapes.at("r4i") ); r1i_size = this->value_size_of(input_shapes.at("r1i")); r2i_size = this->value_size_of(input_shapes.at("r2i")); r3i_size = this->value_size_of(input_shapes.at("r3i")); r4i_size = this->value_size_of(input_shapes.at("r4i")); std::fill_n((float *) r1i_mat->GetData(), r1i_size, 0.f); std::fill_n((float *) r2i_mat->GetData(), r2i_size, 0.f); std::fill_n((float *) r3i_mat->GetData(), r3i_size, 0.f); std::fill_n((float *) r4i_mat->GetData(), r4i_size, 0.f); context_is_initialized = true; } void TNNRobustVideoMatting::transform(const cv::Mat &mat) { cv::Mat canvas; cv::resize(mat, canvas, cv::Size(input_width, input_height)); cv::cvtColor(canvas, canvas, cv::COLOR_BGR2RGB); src_mat = std::make_shared<tnn::Mat>( input_device_type, tnn::N8UC3, input_shapes.at("src"), (void *) canvas.data ); if (!src_mat->GetData()) { #ifdef LITETNN_DEBUG std::cout << "input_mat == nullptr! transform failed\n"; #endif } } void TNNRobustVideoMatting::detect(const cv::Mat &mat, types::MattingContent &content, bool video_mode) { if (mat.empty()) return; int img_h = mat.rows; int img_w = mat.cols; if (!context_is_initialized) return; this->transform(mat); tnn::MatConvertParam src_cvt_param, ctx_cvt_param; src_cvt_param.scale = scale_vals; src_cvt_param.bias = bias_vals; tnn::Status status_src, status_r1i, status_r2i, status_r3i, status_r4i; status_src = instance->SetInputMat(src_mat, src_cvt_param, "src"); status_r1i = instance->SetInputMat(r1i_mat, ctx_cvt_param, "r1i"); status_r2i = instance->SetInputMat(r2i_mat, ctx_cvt_param, "r2i"); status_r3i = instance->SetInputMat(r3i_mat, ctx_cvt_param, "r3i"); status_r4i = instance->SetInputMat(r4i_mat, ctx_cvt_param, "r4i"); if (status_src != tnn::TNN_OK || status_r1i != tnn::TNN_OK || status_r2i != tnn::TNN_OK || status_r3i != tnn::TNN_OK || status_r4i != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->SetInputMat failed!:" << status_src.description().c_str() << ": " << status_r1i.description().c_str() << ": " << status_r2i.description().c_str() << ": " << status_r3i.description().c_str() << ": " << status_r4i.description().c_str() << "\n"; #endif return; } auto status = instance->Forward(); if (status != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->Forward failed!:" << status.description().c_str() << "\n"; #endif return; } this->generate_matting(instance, content, img_h, img_w); if (video_mode) { context_is_update = false; this->update_context(instance); } } void TNNRobustVideoMatting::detect_video( const std::string &video_path, const std::string &output_path, std::vector<types::MattingContent> &contents, bool save_contents, unsigned int writer_fps) { cv::VideoCapture video_capture(video_path); const unsigned int width = video_capture.get(cv::CAP_PROP_FRAME_WIDTH); const unsigned int height = video_capture.get(cv::CAP_PROP_FRAME_HEIGHT); const unsigned int frame_count = video_capture.get(cv::CAP_PROP_FRAME_COUNT); if (!video_capture.isOpened()) { std::cout << "Can not open video: " << video_path << "\n"; return; } cv::VideoWriter video_writer(output_path, cv::VideoWriter::fourcc('m', 'p', '4', 'v'), writer_fps, cv::Size(width, height)); if (!video_writer.isOpened()) { std::cout << "Can not open writer: " << output_path << "\n"; return; } cv::Mat mat; unsigned int i = 0; while (video_capture.read(mat)) { i += 1; types::MattingContent content; this->detect(mat, content, true); if (content.flag) { if (save_contents) contents.push_back(content); if (!content.merge_mat.empty()) video_writer.write(content.merge_mat); } if (!context_is_update) break; #ifdef LITETNN_DEBUG std::cout << i << "/" << frame_count << " done!" << "\n"; #endif } video_capture.release(); video_writer.release(); } void TNNRobustVideoMatting::generate_matting(std::shared_ptr<tnn::Instance> &_instance, types::MattingContent &content, int img_h, int img_w) { std::shared_ptr<tnn::Mat> fgr_mat; std::shared_ptr<tnn::Mat> pha_mat; tnn::MatConvertParam cvt_param; tnn::Status status_fgr, status_pha; status_fgr = _instance->GetOutputMat(fgr_mat, cvt_param, "fgr", output_device_type); status_pha = _instance->GetOutputMat(pha_mat, cvt_param, "pha", output_device_type); if (status_fgr != tnn::TNN_OK || status_pha != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->GetOutputMat failed!:" << status_fgr.description().c_str() << ": " << status_pha.description().c_str() << "\n"; #endif return; } float *fgr_ptr = (float *) fgr_mat->GetData(); float *pha_ptr = (float *) pha_mat->GetData(); const unsigned int channel_step = input_height * input_width; cv::Mat rmat(input_height, input_width, CV_32FC1, fgr_ptr); cv::Mat gmat(input_height, input_width, CV_32FC1, fgr_ptr + channel_step); cv::Mat bmat(input_height, input_width, CV_32FC1, fgr_ptr + 2 * channel_step); cv::Mat pmat(input_height, input_width, CV_32FC1, pha_ptr); rmat *= 255.f; bmat *= 255.f; gmat *= 255.f; cv::Mat rest = 1.f - pmat; cv::Mat mbmat = bmat.mul(pmat) + rest * 153.f; cv::Mat mgmat = gmat.mul(pmat) + rest * 255.f; cv::Mat mrmat = rmat.mul(pmat) + rest * 120.f; std::vector<cv::Mat> fgr_channel_mats, merge_channel_mats; fgr_channel_mats.push_back(bmat); fgr_channel_mats.push_back(gmat); fgr_channel_mats.push_back(rmat); merge_channel_mats.push_back(mbmat); merge_channel_mats.push_back(mgmat); merge_channel_mats.push_back(mrmat); content.pha_mat = pmat; cv::merge(fgr_channel_mats, content.fgr_mat); cv::merge(merge_channel_mats, content.merge_mat); content.fgr_mat.convertTo(content.fgr_mat, CV_8UC3); content.merge_mat.convertTo(content.merge_mat, CV_8UC3); if (img_w != input_width || img_h != input_height) { cv::resize(content.pha_mat, content.pha_mat, cv::Size(img_w, img_h)); cv::resize(content.fgr_mat, content.fgr_mat, cv::Size(img_w, img_h)); cv::resize(content.merge_mat, content.merge_mat, cv::Size(img_w, img_h)); } content.flag = true; } void TNNRobustVideoMatting::update_context(std::shared_ptr<tnn::Instance> &_instance) { std::shared_ptr<tnn::Mat> r1o_mat; std::shared_ptr<tnn::Mat> r2o_mat; std::shared_ptr<tnn::Mat> r3o_mat; std::shared_ptr<tnn::Mat> r4o_mat; tnn::MatConvertParam cvt_param; tnn::Status status_r1o; tnn::Status status_r2o; tnn::Status status_r3o; tnn::Status status_r4o; status_r1o = _instance->GetOutputMat(r1o_mat, cvt_param, "r1o", output_device_type); status_r2o = _instance->GetOutputMat(r2o_mat, cvt_param, "r2o", output_device_type); status_r3o = _instance->GetOutputMat(r3o_mat, cvt_param, "r3o", output_device_type); status_r4o = _instance->GetOutputMat(r4o_mat, cvt_param, "r4o", output_device_type); if (status_r1o != tnn::TNN_OK || status_r2o != tnn::TNN_OK || status_r3o != tnn::TNN_OK || status_r4o != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->GetOutputMat context failed!:" << status_r1o.description().c_str() << ": " << status_r2o.description().c_str() << ": " << status_r3o.description().c_str() << ": " << status_r4o.description().c_str() << "\n"; #endif return; } void *command_queue = nullptr; auto status_cmd = _instance->GetCommandQueue(&command_queue); if (status_cmd != tnn::TNN_OK) { #ifdef LITETNN_DEBUG std::cout << "instance->GetCommandQueue failed!:" << status_cmd.description().c_str() << "\n"; #endif return; } tnn::MatUtils::Copy(*r1o_mat, *r1i_mat, command_queue); tnn::MatUtils::Copy(*r2o_mat, *r2i_mat, command_queue); tnn::MatUtils::Copy(*r3o_mat, *r3i_mat, command_queue); tnn::MatUtils::Copy(*r4o_mat, *r4i_mat, command_queue); context_is_update = true; }
else { #ifdef LITETNN_DEBUG std::cout << "src input only support NCHW and NHWC " "input_data_format, but found others.\n"; #endif return; } src_size = 1 * 3 * input_height * input_width; for (auto &name: output_names) output_shapes[name] = BasicTNNHandler::get_output_shape(instance, name); #ifdef LITETNN_DEBUG this->print_debug_string(); #endif }
function_block-function_prefixed
[ { "content": "enum Dimensionformat { NHWC, NC4HW4, NCHW };\n", "file_path": "MNN/expr/Expr.hpp", "rank": 0, "score": 159329.26997513027 }, { "content": "function should be prototyped as void Foo(int,void\\*); , where the first parameter is the trackbar\n\nposition and the second parameter is the user data (see the next parameter). If the callback is\n\nthe NULL pointer, no callbacks are called, but only value is updated.\n\n@param userdata User data that is passed as is to the callback. It can be used to handle trackbar\n\nevents without using global variables.\n\n */\n\nCV_EXPORTS int createTrackbar(const String& trackbarname, const String& winname,\n\n int* value, int count,\n\n TrackbarCallback onChange = 0,\n\n void* userdata = 0);\n\n\n\n/** @brief Returns the trackbar position.\n\n\n\nThe function returns the current position of the specified trackbar.\n\n\n\n@note\n\n\n\n[__Qt Backend Only__] winname can be empty if the trackbar is attached to the control\n\npanel.\n\n\n", "file_path": "opencv2/highgui.hpp", "rank": 1, "score": 142770.72483673278 }, { "content": "function use the rational model and return 8 coefficients. If the flag is not set, the\n", "file_path": "opencv2/calib3d.hpp", "rank": 2, "score": 119248.57970633352 }, { "content": "struct Accumulator<unsigned int> { typedef float Type; };\n\ntemplate<>\n", "file_path": "opencv2/flann/dist.h", "rank": 3, "score": 118857.05111997866 }, { "content": "class NCNN_EXPORT Net\n\n{\n\npublic:\n\n // empty init\n\n Net();\n\n // clear and destroy\n\n virtual ~Net();\n\n\n\npublic:\n\n // option can be changed before loading\n\n Option opt;\n\n\n\n#if NCNN_VULKAN\n\n // set gpu device by index\n\n void set_vulkan_device(int device_index);\n\n\n\n // set gpu device by device handle, no owner transfer\n\n void set_vulkan_device(const VulkanDevice* vkdev);\n\n\n\n const VulkanDevice* vulkan_device() const;\n", "file_path": "ncnn/net.h", "rank": 4, "score": 108503.44064376353 }, { "content": "class Net;\n", "file_path": "ncnn/paramdict.h", "rank": 5, "score": 104565.93619895207 }, { "content": " struct\n\n {\n\n int size;\n\n int step;\n\n }\n", "file_path": "opencv2/core/types_c.h", "rank": 6, "score": 101100.630041141 }, { "content": " halide_dimension_t *dim;\n", "file_path": "MNN/HalideRuntime.h", "rank": 7, "score": 101100.630041141 }, { "content": " DeviceId Id() const {\n\n return device_id;\n", "file_path": "onnxruntime/core/framework/ortdevice.h", "rank": 8, "score": 99323.46716096142 }, { "content": " _In_reads_(input_len) const OrtValue* const* input, size_t input_len,\n", "file_path": "onnxruntime/core/session/onnxruntime_c_api.h", "rank": 9, "score": 97716.76308585136 }, { "content": " ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name,\n", "file_path": "onnxruntime/core/session/onnxruntime_c_api.h", "rank": 10, "score": 97694.09064123848 }, { "content": "struct MemoryAllocation {\n\n MemoryAllocation(OrtAllocator* allocator, void* p, size_t size);\n\n ~MemoryAllocation();\n\n MemoryAllocation(const MemoryAllocation&) = delete;\n\n MemoryAllocation& operator=(const MemoryAllocation&) = delete;\n\n MemoryAllocation(MemoryAllocation&&);\n\n MemoryAllocation& operator=(MemoryAllocation&&);\n\n\n\n void* get() { return p_; }\n", "file_path": "onnxruntime/core/session/onnxruntime_cxx_api.h", "rank": 11, "score": 96172.87408570621 }, { "content": "function return value).\n\n@param flags Flag that can take values of cv::KmeansFlags .\n\n\n\n@return\n\n - Compactness measure that is computed as\n\n\\f[\\sum _i \\| \\texttt{samples} _i - \\texttt{centers} _{ \\texttt{labels} _i} \\| ^2\\f]\n\nafter every attempt. The best (minimum) value is chosen and the corresponding labels and the\n\ncompactness value are returned by the function.\n\n - Integer array that stores the cluster indices for every sample.\n\n - Array of the cluster centers.\n\n*/\n\nGAPI_EXPORTS std::tuple<GOpaque<double>,GMat,GMat>\n\nkmeans(const GMat& data, const int K, const GMat& bestLabels,\n\n const TermCriteria& criteria, const int attempts, const KmeansFlags flags);\n\n\n\n/** @overload\n\n@note\n\n - Function textual ID is \"org.opencv.core.kmeansNDNoInit\"\n\n - #KMEANS_USE_INITIAL_LABELS flag must not be set while using this overload.\n\n */\n", "file_path": "opencv2/gapi/core.hpp", "rank": 12, "score": 91606.9756278658 }, { "content": "function either returns false (when quiet=true) or throws an exception.\n\n@param a input array.\n\n@param quiet a flag, indicating whether the functions quietly return false when the array elements\n\nare out of range or they throw an exception.\n\n@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims\n\nelements.\n\n@param minVal inclusive lower boundary of valid values range.\n\n@param maxVal exclusive upper boundary of valid values range.\n\n*/\n\nCV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,\n\n double minVal = -DBL_MAX, double maxVal = DBL_MAX);\n\n\n\n/** @brief converts NaNs to the given number\n\n@param a input/output matrix (CV_32F type).\n\n@param val value to convert the NaNs\n\n*/\n\nCV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);\n\n\n\n/** @brief Performs generalized matrix multiplication.\n\n\n", "file_path": "opencv2/core.hpp", "rank": 13, "score": 89293.70926575267 }, { "content": " _In_reads_(input_len) const char* const* input_names,\n", "file_path": "onnxruntime/core/session/onnxruntime_c_api.h", "rank": 14, "score": 86245.56047989702 }, { "content": " _Inout_ OrtSessionOptions* options, _In_ const char* dim_name,\n", "file_path": "onnxruntime/core/session/onnxruntime_c_api.h", "rank": 15, "score": 86243.81580132537 }, { "content": " class CV_EXPORTS_W_SIMPLE Net\n\n {\n\n public:\n\n\n\n CV_WRAP Net(); //!< Default constructor.\n\n CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.\n\n\n\n /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR).\n\n * @param[in] xml XML configuration file with network's topology.\n\n * @param[in] bin Binary file with trained weights.\n\n * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine\n\n * backend.\n\n */\n\n CV_WRAP static Net readFromModelOptimizer(const String& xml, const String& bin);\n\n\n\n /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).\n\n * @param[in] bufferModelConfig buffer with model's configuration.\n\n * @param[in] bufferWeights buffer with model's trained weights.\n\n * @returns Net object.\n\n */\n", "file_path": "opencv2/dnn/dnn.hpp", "rank": 16, "score": 85847.97196217277 }, { "content": "#define ONNX_OPERATOR_KERNEL_EX(name, domain, ver, provider, builder, ...) \\\n\n class ONNX_OPERATOR_KERNEL_CLASS_NAME(provider, domain, ver, name); \\\n\n template <> \\\n\n KernelCreateInfo \\\n\n BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(provider, domain, ver, name)>() { \\\n\n return KernelCreateInfo( \\\n\n builder.SetName(#name) \\\n\n .SetDomain(domain) \\\n\n .SinceVersion(ver) \\\n\n .Provider(provider) \\\n\n .Build(), \\\n\n static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \\\n\n }\n\n\n\n#define ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(provider, domain, startver, endver, name) \\\n\n provider##_##name##_##domain##_ver##startver##_##endver\n\n\n\n#define ONNX_CPU_OPERATOR_VERSIONED_KERNEL(name, startver, endver, builder, ...) \\\n\n ONNX_OPERATOR_VERSIONED_KERNEL_EX(name, kOnnxDomain, startver, endver, kCpuExecutionProvider, builder, __VA_ARGS__)\n\n\n\n#define ONNX_CPU_OPERATOR_VERSIONED_ML_KERNEL(name, startver, endver, builder, ...) \\\n\n ONNX_OPERATOR_VERSIONED_KERNEL_EX(name, kMLDomain, startver, endver, kCpuExecutionProvider, builder, __VA_ARGS__)\n\n\n", "file_path": "onnxruntime/core/framework/op_kernel.h", "rank": 17, "score": 84109.61194348108 }, { "content": "function returns the rotated rectangle structure that includes the object position, size, and\n\norientation. The next position of the search window can be obtained with RotatedRect::boundingRect()\n\n\n\nSee the OpenCV sample camshiftdemo.c that tracks colored objects.\n\n\n\n@note\n\n- (Python) A sample explaining the camshift tracking algorithm can be found at\n\n opencv_source_code/samples/python/camshift.py\n\n */\n\nCV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_IN_OUT Rect& window,\n\n TermCriteria criteria );\n\n/** @example samples/cpp/camshiftdemo.cpp\n\nAn example using the mean-shift tracking algorithm\n\n*/\n\n\n\n/** @brief Finds an object on a back projection image.\n\n\n\n@param probImage Back projection of the object histogram. See calcBackProject for details.\n\n@param window Initial search window.\n\n@param criteria Stop criteria for the iterative search algorithm.\n", "file_path": "opencv2/video/tracking.hpp", "rank": 18, "score": 83413.6985961282 }, { "content": " // This enum is utilized mostly by GArray and GOpaque to store and recognize their internal data\n\n // types (aka Host type). Also it is widely used during serialization routine.\n\n enum class OpaqueKind: int\n\n {\n\n CV_UNKNOWN, // Unknown, generic, opaque-to-GAPI data type unsupported in graph seriallization\n\n CV_BOOL, // bool user G-API data\n\n CV_INT, // int user G-API data\n\n CV_DOUBLE, // double user G-API data\n\n CV_FLOAT, // float user G-API data\n\n CV_UINT64, // uint64_t user G-API data\n\n CV_STRING, // std::string user G-API data\n\n CV_POINT, // cv::Point user G-API data\n\n CV_POINT2F, // cv::Point2f user G-API data\n\n CV_SIZE, // cv::Size user G-API data\n\n CV_RECT, // cv::Rect user G-API data\n\n CV_SCALAR, // cv::Scalar user G-API data\n\n CV_MAT, // cv::Mat user G-API data\n\n CV_DRAW_PRIM, // cv::gapi::wip::draw::Prim user G-API data\n\n };\n\n\n\n // Type traits helper which simplifies the extraction of kind from type\n\n template<typename T> struct GOpaqueTraits;\n", "file_path": "opencv2/gapi/gcommon.hpp", "rank": 19, "score": 83204.86074518146 }, { "content": "// This definition is here because it is reused by both public(?) and internal\n\n// modules. Keeping it here wouldn't expose public details (e.g., API-level)\n\n// to components which are internal and operate on a lower-level entities\n\n// (e.g., compiler, backends).\n\n// FIXME: merge with ArgKind?\n\n// FIXME: replace with variant[format desc]?\n\nenum class GShape: int\n\n{\n\n GMAT,\n\n GSCALAR,\n\n GARRAY,\n\n GOPAQUE,\n\n GFRAME,\n\n};\n\n\n\nnamespace gapi {\n\nnamespace s11n {\n\nnamespace detail {\n\ntemplate<typename T> struct wrap_serialize;\n\n} // namespace detail\n\n} // namespace s11n\n\n} // namespace gapi\n\n\n\n\n", "file_path": "opencv2/gapi/gcommon.hpp", "rank": 20, "score": 83199.03222977163 }, { "content": "enum class MediaFormat: int\n\n{\n\n BGR = 0,\n\n NV12,\n\n};\n\n\n\n/**\n\n * \\addtogroup gapi_meta_args\n\n * @{\n\n */\n", "file_path": "opencv2/gapi/gframe.hpp", "rank": 21, "score": 83199.03222977163 }, { "content": "enum class TraitAs: int\n\n{\n\n TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor and passes dimensions as-is\n\n IMAGE //!< G-API traits an associated cv::Mat as an image so creates an \"image\" blob (NCHW/NHWC, etc)\n\n};\n\n\n\nusing IEConfig = std::map<std::string, std::string>;\n\n\n\nnamespace detail {\n\n struct ParamDesc {\n\n std::string model_path;\n\n std::string weights_path;\n\n std::string device_id;\n\n\n\n // NB: Here order follows the `Net` API\n\n std::vector<std::string> input_names;\n\n std::vector<std::string> output_names;\n\n\n\n using ConstInput = std::pair<cv::Mat, TraitAs>;\n\n std::unordered_map<std::string, ConstInput> const_inputs;\n\n\n\n // NB: nun_* may differ from topology's real input/output port numbers\n\n // (e.g. topology's partial execution)\n\n std::size_t num_in; // How many inputs are defined in the operation\n\n std::size_t num_out; // How many outputs are defined in the operation\n\n\n", "file_path": "opencv2/gapi/infer/ie.hpp", "rank": 22, "score": 83199.03222977163 }, { "content": "enum class TraitAs: int {\n\n TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor\n\n // and passes dimensions as-is\n\n IMAGE //!< G-API traits an associated cv::Mat as an image so\n\n // creates an \"image\" blob (NCHW/NHWC, etc)\n\n};\n\n\n\nusing PostProc = std::function<void(const std::unordered_map<std::string, cv::Mat> &,\n\n std::unordered_map<std::string, cv::Mat> &)>;\n\n\n\n\n\nnamespace detail {\n", "file_path": "opencv2/gapi/infer/onnx.hpp", "rank": 23, "score": 83199.03222977163 }, { "content": " // FIXME: These traits and enum and possible numerous switch(kind)\n\n // block may be replaced with a special Handler<T> object or with\n\n // a double dispatch\n\n enum class ArgKind: int\n\n {\n\n OPAQUE_VAL, // Unknown, generic, opaque-to-GAPI data type - STATIC\n\n // Note: OPAQUE is sometimes defined in Win sys headers\n\n#if !defined(OPAQUE) && !defined(CV_DOXYGEN)\n\n OPAQUE = OPAQUE_VAL, // deprecated value used for compatibility, use OPAQUE_VAL instead\n\n#endif\n\n GOBJREF, // <internal> reference to object\n\n GMAT, // a cv::GMat\n\n GMATP, // a cv::GMatP\n\n GFRAME, // a cv::GFrame\n\n GSCALAR, // a cv::GScalar\n\n GARRAY, // a cv::GArrayU (note - exactly GArrayU, not GArray<T>!)\n\n GOPAQUE, // a cv::GOpaqueU (note - exactly GOpaqueU, not GOpaque<T>!)\n\n };\n\n\n\n // Describe G-API types (G-types) with traits. Mostly used by\n\n // cv::GArg to store meta information about types passed into\n\n // operation arguments. Please note that cv::GComputation is\n\n // defined on GProtoArgs, not GArgs!\n", "file_path": "opencv2/gapi/gtype_traits.hpp", "rank": 24, "score": 81444.35000810632 }, { "content": "#define ONNX_OPERATOR_TYPED_KERNEL_EX(name, domain, ver, type, provider, builder, ...) \\\n\n class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type, name); \\\n\n template <> \\\n\n KernelCreateInfo \\\n\n BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type, name)>() { \\\n\n return KernelCreateInfo( \\\n\n builder.SetName(#name) \\\n\n .SetDomain(domain) \\\n\n .SinceVersion(ver) \\\n\n .Provider(provider) \\\n\n .Build(), \\\n\n static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \\\n\n }\n\n\n\n#define ONNX_OPERATOR_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type1, type2, name) \\\n\n provider##_##name##_##domain##_ver##ver##_##type1##_##type2\n\n\n", "file_path": "onnxruntime/core/framework/op_kernel.h", "rank": 25, "score": 79375.74572507264 }, { "content": "#define ONNX_OPERATOR_VERSIONED_KERNEL_EX(name, domain, startver, endver, provider, builder, ...) \\\n\n class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(provider, domain, startver, endver, name); \\\n\n template <> \\\n\n KernelCreateInfo \\\n\n BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(provider, domain, startver, endver, name)>() { \\\n\n return KernelCreateInfo( \\\n\n builder.SetName(#name) \\\n\n .SetDomain(domain) \\\n\n .SinceVersion(startver, endver) \\\n\n .Provider(provider) \\\n\n .Build(), \\\n\n static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \\\n\n }\n\n\n\n#define ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type, name) \\\n\n provider##_##name##_##domain##_ver##ver##_##type\n\n\n\n#define ONNX_CPU_OPERATOR_TYPED_KERNEL(name, ver, type, builder, ...) \\\n\n ONNX_OPERATOR_TYPED_KERNEL_EX(name, kOnnxDomain, ver, type, kCpuExecutionProvider, builder, __VA_ARGS__)\n\n\n\n#define ONNX_CPU_OPERATOR_TYPED_ML_KERNEL(name, ver, type, builder, ...) \\\n\n ONNX_OPERATOR_TYPED_KERNEL_EX(name, kMLDomain, ver, type, kCpuExecutionProvider, builder, __VA_ARGS__)\n\n\n\n#define ONNX_CPU_OPERATOR_TYPED_MS_KERNEL(name, ver, type, builder, ...) \\\n\n ONNX_OPERATOR_TYPED_KERNEL_EX(name, kMSDomain, ver, type, kCpuExecutionProvider, builder, __VA_ARGS__)\n\n\n", "file_path": "onnxruntime/core/framework/op_kernel.h", "rank": 26, "score": 79375.74572507264 }, { "content": " class LITE_EXPORTS BoundingBoxType<int, float>;\n\n\n\n template\n", "file_path": "lite/types.h", "rank": 27, "score": 77891.90458141497 }, { "content": "struct Accumulator<int> { typedef float Type; };\n\n\n\n#undef True\n\n#undef False\n\n\n", "file_path": "opencv2/flann/dist.h", "rank": 28, "score": 76745.9537691839 }, { "content": "#define ONNX_OPERATOR_TWO_TYPED_KERNEL_EX(name, domain, ver, type1, type2, provider, builder, ...) \\\n\n class ONNX_OPERATOR_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type1, type2, name); \\\n\n template <> \\\n\n KernelCreateInfo \\\n\n BuildKernelCreateInfo<ONNX_OPERATOR_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type1, type2, name)>() { \\\n\n return KernelCreateInfo( \\\n\n builder.SetName(#name) \\\n\n .SetDomain(domain) \\\n\n .SinceVersion(ver) \\\n\n .Provider(provider) \\\n\n .Build(), \\\n\n static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \\\n\n }\n\n\n\n#define ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type, name) \\\n\n provider##_##name##_##domain##_ver##startver##_##endver##_##type\n\n\n\n#define ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(name, startver, endver, type, builder, ...) \\\n\n ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, kOnnxDomain, startver, endver, type, kCpuExecutionProvider, builder, \\\n\n __VA_ARGS__)\n\n\n\n#define ONNX_CPU_OPERATOR_VERSIONED_TYPED_ML_KERNEL(name, startver, endver, type, builder, ...) \\\n\n ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, kMLDomain, startver, endver, type, kCpuExecutionProvider, builder, \\\n\n __VA_ARGS__)\n\n\n\n#define ONNX_CPU_OPERATOR_VERSIONED_TYPED_MS_KERNEL(name, startver, endver, type, builder, ...) \\\n\n ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, kMSDomain, startver, endver, type, kCpuExecutionProvider, builder, \\\n\n __VA_ARGS__)\n\n\n", "file_path": "onnxruntime/core/framework/op_kernel.h", "rank": 29, "score": 75202.65131138577 }, { "content": "#define ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, domain, startver, endver, type, provider, builder, ...) \\\n\n class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type, name); \\\n\n template <> \\\n\n KernelCreateInfo \\\n\n BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, \\\n\n type, name)>() { \\\n\n return KernelCreateInfo( \\\n\n builder.SetName(#name) \\\n\n .SetDomain(domain) \\\n\n .SinceVersion(startver, endver) \\\n\n .Provider(provider) \\\n\n .Build(), \\\n\n static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \\\n\n }\n\n\n\n#define ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type1, type2, name) \\\n\n provider##_##name##_##domain##_ver##startver##_##endver##_##type1##_##type2\n\n\n\n#define ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_EX(name, domain, startver, endver, type1, type2, \\\n\n provider, builder, ...) \\\n", "file_path": "onnxruntime/core/framework/op_kernel.h", "rank": 30, "score": 75202.65131138577 }, { "content": " class GAPI_EXPORTS Priv; // internal use only\n\n Priv& priv(); // internal use only\n\n const Priv& priv() const; // internal use only\n\n\n\nprivate:\n\n std::unique_ptr<Priv> m_priv;\n\n const Cache* m_cache;\n\n};\n\n\n\n} // namespace cv::gapi::fluid\n\n} // namespace cv::gapi\n\n} // namespace cv\n\n\n\n#endif // OPENCV_GAPI_FLUID_BUFFER_HPP\n", "file_path": "opencv2/gapi/fluid/gfluidbuffer.hpp", "rank": 31, "score": 73365.80486320899 }, { "content": "type deserialize(const std::vector<char> &p) {\n\n return detail::getRunArgsWithRMats<RMatAdapterType>(p);\n\n}\n\n} // namespace gapi\n\n} // namespace cv\n\n\n\nnamespace cv {\n\nnamespace gapi {\n\nnamespace s11n {\n", "file_path": "opencv2/gapi/s11n.hpp", "rank": 32, "score": 72574.05552337898 }, { "content": "// Variant that only ever allows const access to nodes and optionally allows filtering of the nodes.\n\nclass ConstGraphNodes : public ValidNodes<const std::vector<std::unique_ptr<Node>>> {\n\n public:\n\n ConstGraphNodes(const std::vector<std::unique_ptr<Node>>& nodes) : ValidNodes(nodes) {\n\n }\n\n\n\n ConstGraphNodes(const std::vector<std::unique_ptr<Node>>& nodes,\n\n GraphNodes::NodeFilterFunc&& filter_func)\n\n : ValidNodes(nodes, std::move(filter_func)) {\n\n }\n\n};\n\n\n\n} // namespace onnxruntime\n", "file_path": "onnxruntime/core/graph/graph_nodes.h", "rank": 33, "score": 71944.30663099543 }, { "content": " class ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type1, type2, name); \\\n\n template <> \\\n\n KernelCreateInfo \\\n\n BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, \\\n\n type1, type2, name)>() { \\\n\n return KernelCreateInfo( \\\n\n builder.SetName(#name) \\\n\n .SetDomain(domain) \\\n\n .SinceVersion(startver, endver) \\\n\n .Provider(provider) \\\n\n .Build(), \\\n\n static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \\\n\n }\n\n\n\ntemplate <typename... Types>\n", "file_path": "onnxruntime/core/framework/op_kernel.h", "rank": 34, "score": 71481.9134841609 }, { "content": "class NetPrivate;\n", "file_path": "ncnn/net.h", "rank": 35, "score": 70795.82197608595 }, { "content": "class PUBLIC Instance {\n\npublic:\n\n Instance(NetworkConfig& net_config, ModelConfig& model_config);\n\n\n\n ~Instance();\n\n\n\n // init with model interpeter and inputs shape.\n\n Status Init(std::shared_ptr<AbstractModelInterpreter> interpreter, InputShapesMap inputs_shape);\n\n\n\n // init with model interpeter, min inputs shape and max inputs shape.\n\n Status Init(std::shared_ptr<AbstractModelInterpreter> interpreter, InputShapesMap min_inputs_shape, InputShapesMap max_inputs_shape);\n\n\n\n // deinit, release network\n\n Status DeInit();\n\n\n\n // return memory bytes required for forward\n\n Status GetForwardMemorySize(int& memory_size);\n\n\n\n // set memory to tnn instance. if success, return status code zero.\n\n // only instance created with SHARE_MEMORY_MODE_SET_FROM_EXTERNAL can be set from external.\n", "file_path": "tnn/core/instance.h", "rank": 36, "score": 68960.45406286124 }, { "content": "struct Depth< Range > { enum { value = Depth<int>::value }; };\n\ntemplate<>\n", "file_path": "opencv2/core/types.hpp", "rank": 37, "score": 67388.19123058612 }, { "content": "type for the input array should be either np.int32 or np.float32.\n\n\n\n@sa contourArea, arcLength\n\n */\n\nCV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false );\n\n\n\n/** @brief Calculates seven Hu invariants.\n\n\n\nThe function calculates seven Hu invariants (introduced in @cite Hu62; see also\n\n<http://en.wikipedia.org/wiki/Image_moment>) defined as:\n\n\n\n\\f[\\begin{array}{l} hu[0]= \\eta _{20}+ \\eta _{02} \\\\ hu[1]=( \\eta _{20}- \\eta _{02})^{2}+4 \\eta _{11}^{2} \\\\ hu[2]=( \\eta _{30}-3 \\eta _{12})^{2}+ (3 \\eta _{21}- \\eta _{03})^{2} \\\\ hu[3]=( \\eta _{30}+ \\eta _{12})^{2}+ ( \\eta _{21}+ \\eta _{03})^{2} \\\\ hu[4]=( \\eta _{30}-3 \\eta _{12})( \\eta _{30}+ \\eta _{12})[( \\eta _{30}+ \\eta _{12})^{2}-3( \\eta _{21}+ \\eta _{03})^{2}]+(3 \\eta _{21}- \\eta _{03})( \\eta _{21}+ \\eta _{03})[3( \\eta _{30}+ \\eta _{12})^{2}-( \\eta _{21}+ \\eta _{03})^{2}] \\\\ hu[5]=( \\eta _{20}- \\eta _{02})[( \\eta _{30}+ \\eta _{12})^{2}- ( \\eta _{21}+ \\eta _{03})^{2}]+4 \\eta _{11}( \\eta _{30}+ \\eta _{12})( \\eta _{21}+ \\eta _{03}) \\\\ hu[6]=(3 \\eta _{21}- \\eta _{03})( \\eta _{21}+ \\eta _{03})[3( \\eta _{30}+ \\eta _{12})^{2}-( \\eta _{21}+ \\eta _{03})^{2}]-( \\eta _{30}-3 \\eta _{12})( \\eta _{21}+ \\eta _{03})[3( \\eta _{30}+ \\eta _{12})^{2}-( \\eta _{21}+ \\eta _{03})^{2}] \\\\ \\end{array}\\f]\n\n\n\nwhere \\f$\\eta_{ji}\\f$ stands for \\f$\\texttt{Moments::nu}_{ji}\\f$ .\n\n\n\nThese values are proved to be invariants to the image scale, rotation, and reflection except the\n\nseventh one, whose sign is changed by reflection. This invariance is proved with the assumption of\n\ninfinite image resolution. In case of raster images, the computed Hu invariants for the original and\n\ntransformed images are a bit different.\n\n\n", "file_path": "opencv2/imgproc.hpp", "rank": 38, "score": 64338.868590093596 }, { "content": " function may return even if the copy operation is not finished.\n\n\n\n The copy operation may be overlapped with operations in other non-default streams if \\p stream is\n\n not the default stream and \\p dst is HostMem allocated with HostMem::PAGE_LOCKED option.\n\n */\n\n CV_WRAP void download(OutputArray dst, Stream& stream) const;\n\n\n\n //! returns deep copy of the GpuMat, i.e. the data is copied\n\n CV_WRAP GpuMat clone() const;\n\n\n\n //! copies the GpuMat content to device memory (Blocking call)\n\n CV_WRAP void copyTo(OutputArray dst) const;\n\n\n\n //! copies the GpuMat content to device memory (Non-Blocking call)\n\n CV_WRAP void copyTo(OutputArray dst, Stream& stream) const;\n\n\n\n //! copies those GpuMat elements to \"m\" that are marked with non-zero mask elements (Blocking call)\n\n CV_WRAP void copyTo(OutputArray dst, InputArray mask) const;\n\n\n\n //! copies those GpuMat elements to \"m\" that are marked with non-zero mask elements (Non-Blocking call)\n", "file_path": "opencv2/core/cuda.hpp", "rank": 39, "score": 64338.37061219402 }, { "content": "function does not copy src itself but simply constructs the border, for example:\n\n\n\n@code{.cpp}\n\n // let border be the same in all directions\n\n int border=2;\n\n // constructs a larger image to fit both the image and the border\n\n Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());\n\n // select the middle part of it w/o copying data\n\n Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));\n\n // convert image from RGB to grayscale\n\n cvtColor(rgb, gray, COLOR_RGB2GRAY);\n\n // form a border in-place\n\n copyMakeBorder(gray, gray_buf, border, border,\n\n border, border, BORDER_REPLICATE);\n\n // now do some custom filtering ...\n\n ...\n\n@endcode\n\n@note When the source image is a part (ROI) of a bigger image, the function will try to use the\n\npixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as\n\nif src was not a ROI, use borderType | #BORDER_ISOLATED.\n", "file_path": "opencv2/core.hpp", "rank": 40, "score": 63772.394104729254 }, { "content": " class ConstIterator {\n\n public:\n\n using const_iterator = typename Container::const_iterator;\n\n using iterator_category = std::input_iterator_tag;\n\n using value_type = T*;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T**;\n\n using reference = T*&;\n\n\n\n /** Construct iterator for container that will return const T* entries.*/\n\n explicit ConstIterator(const_iterator position) noexcept : current_{position}, item_{nullptr} {}\n\n ConstIterator(const ConstIterator& other) = default;\n\n ConstIterator& operator=(const ConstIterator& other) = default;\n\n\n\n bool operator==(const ConstIterator& other) const noexcept { return current_ == other.current_; }\n\n bool operator!=(const ConstIterator& other) const noexcept { return current_ != other.current_; }\n\n\n\n ConstIterator& operator++() {\n\n ++current_;\n\n return *this;\n", "file_path": "onnxruntime/core/common/const_pointer_container.h", "rank": 41, "score": 63746.71299371178 }, { "content": "class MNN_PUBLIC AutoTime : Timer {\n\npublic:\n\n AutoTime(int line, const char* func);\n\n ~AutoTime();\n\n AutoTime(const AutoTime&) = delete;\n\n AutoTime(const AutoTime&&) = delete;\n\n AutoTime& operator=(const AutoTime&) = delete;\n\n AutoTime& operator=(const AutoTime&&) = delete;\n\n\n\nprivate:\n\n int mLine;\n\n char* mName;\n\n};\n\n} // namespace MNN\n\n\n\n#ifdef MNN_OPEN_TIME_TRACE\n\n#define AUTOTIME MNN::AutoTime ___t(__LINE__, __func__)\n\n#else\n\n#define AUTOTIME\n\n#endif\n\n\n\n#endif /* AutoTime_hpp */\n", "file_path": "MNN/AutoTime.hpp", "rank": 42, "score": 62193.890287877526 }, { "content": "class PUBLIC DimsVectorUtils {\n\npublic:\n\n // @brief all dims product, [start_index, end_index)\n\n // @param dims\n\n static int Count(const DimsVector &dims, int start_index = 0, int end_index = -1);\n\n\n\n // @brief max of dims0 and dims1, [start_index, end_index)\n\n static DimsVector Max(const DimsVector &dims0, const DimsVector &dims1, int start_index = 0, int end_index = -1);\n\n\n\n // @brief min of dims0 and dims1, [start_index, end_index)\n\n static DimsVector Min(const DimsVector &dims0, const DimsVector &dims1, int start_index = 0, int end_index = -1);\n\n\n\n // @brief equal of dims0 and dims1, [start_index, end_index)\n\n static bool Equal(const DimsVector &dims0, const DimsVector &dims1, int start_index = 0, int end_index = -1);\n\n \n\n // @brief NCHW dims vector to NHWC dims vector\n\n static DimsVector NCHW2NHWC(const DimsVector &dims);\n\n\n\n // @brief NHWC dims vector to NCHW\n\n static DimsVector NHWC2NCHW(const DimsVector &dims);\n\n};\n\n\n\n} // namespace TNN_NS\n\n\n\n#endif // TNN_INCLUDE_TNN_UTILS_DIMS_VECTOR_UTILS_H_\n", "file_path": "tnn/utils/dims_vector_utils.h", "rank": 43, "score": 62188.333772142934 }, { "content": "class ConstPointerContainer {\n\n public:\n\n using T = typename std::remove_pointer<typename Container::value_type>::type;\n\n\n", "file_path": "onnxruntime/core/common/const_pointer_container.h", "rank": 44, "score": 62181.800322964555 }, { "content": "\n\n // convenient load network weight data from android asset model file\n\n int load_model(AAsset* asset);\n\n int load_model(AAssetManager* mgr, const char* assetpath);\n\n#endif // __ANDROID_API__ >= 9\n\n#endif // NCNN_PLATFORM_API\n\n\n\n // unload network structure and weight data\n\n void clear();\n\n\n\n // construct an Extractor from network\n\n Extractor create_extractor() const;\n\n\n\n // get input/output indexes/names\n\n const std::vector<int>& input_indexes() const;\n\n const std::vector<int>& output_indexes() const;\n\n#if NCNN_STRING\n\n const std::vector<const char*>& input_names() const;\n\n const std::vector<const char*>& output_names() const;\n\n#endif\n", "file_path": "ncnn/net.h", "rank": 45, "score": 62116.46463681968 }, { "content": " int extract(int blob_index, Mat& feat, int type = 0);\n\n\n\n#if NCNN_VULKAN\n\n#if NCNN_STRING\n\n // set input by blob name\n\n // return 0 if success\n\n int input(const char* blob_name, const VkMat& in);\n\n\n\n // get result by blob name\n\n // return 0 if success\n\n int extract(const char* blob_name, VkMat& feat, VkCompute& cmd);\n\n\n\n // set input by blob name\n\n // return 0 if success\n\n int input(const char* blob_name, const VkImageMat& in);\n\n\n\n // get result by blob name\n\n // return 0 if success\n\n int extract(const char* blob_name, VkImageMat& feat, VkCompute& cmd);\n\n#endif // NCNN_STRING\n", "file_path": "ncnn/net.h", "rank": 46, "score": 62114.717380012655 }, { "content": "#if NCNN_STRING\n\n // set input by blob name\n\n // return 0 if success\n\n int input(const char* blob_name, const Mat& in);\n\n\n\n // get result by blob name\n\n // return 0 if success\n\n // type = 0, default\n\n // type = 1, do not convert fp16/bf16 or / and packing\n\n int extract(const char* blob_name, Mat& feat, int type = 0);\n\n#endif // NCNN_STRING\n\n\n\n // set input by blob index\n\n // return 0 if success\n\n int input(int blob_index, const Mat& in);\n\n\n\n // get result by blob index\n\n // return 0 if success\n\n // type = 0, default\n\n // type = 1, do not convert fp16/bf16 or / and packing\n", "file_path": "ncnn/net.h", "rank": 47, "score": 62114.29048418305 }, { "content": "\n\n const std::vector<Blob>& blobs() const;\n\n const std::vector<Layer*>& layers() const;\n\n\n\n std::vector<Blob>& mutable_blobs();\n\n std::vector<Layer*>& mutable_layers();\n\n\n\nprotected:\n\n friend class Extractor;\n\n#if NCNN_STRING\n\n int find_blob_index_by_name(const char* name) const;\n\n int find_layer_index_by_name(const char* name) const;\n\n virtual int custom_layer_to_index(const char* type);\n\n virtual Layer* create_custom_layer(const char* type);\n\n#endif // NCNN_STRING\n\n virtual Layer* create_custom_layer(int index);\n\n\n\nprivate:\n\n Net(const Net&);\n\n Net& operator=(const Net&);\n\n\n\nprivate:\n\n NetPrivate* const d;\n\n};\n\n\n", "file_path": "ncnn/net.h", "rank": 48, "score": 62113.91248618529 }, { "content": "// Tencent is pleased to support the open source community by making ncnn available.\n\n//\n\n// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.\n\n//\n\n// Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n\n// in compliance with the License. You may obtain a copy of the License at\n\n//\n\n// https://opensource.org/licenses/BSD-3-Clause\n\n//\n\n// Unless required by applicable law or agreed to in writing, software distributed\n\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n\n// specific language governing permissions and limitations under the License.\n\n\n\n#ifndef NCNN_NET_H\n\n#define NCNN_NET_H\n\n\n\n#include \"blob.h\"\n\n#include \"layer.h\"\n\n#include \"mat.h\"\n", "file_path": "ncnn/net.h", "rank": 49, "score": 62112.293172215635 }, { "content": "\n\n // set input by blob index\n\n // return 0 if success\n\n int input(int blob_index, const VkMat& in);\n\n\n\n // get result by blob index\n\n // return 0 if success\n\n int extract(int blob_index, VkMat& feat, VkCompute& cmd);\n\n\n\n // set input by blob index\n\n // return 0 if success\n\n int input(int blob_index, const VkImageMat& in);\n\n\n\n // get result by blob index\n\n // return 0 if success\n\n int extract(int blob_index, VkImageMat& feat, VkCompute& cmd);\n\n#endif // NCNN_VULKAN\n\n\n\nprotected:\n\n friend Extractor Net::create_extractor() const;\n", "file_path": "ncnn/net.h", "rank": 50, "score": 62111.51672710917 }, { "content": "#endif // NCNN_VULKAN\n\n\n\n#if NCNN_STRING\n\n // register custom layer by layer type name\n\n // return 0 if success\n\n int register_custom_layer(const char* type, layer_creator_func creator, layer_destroyer_func destroyer = 0, void* userdata = 0);\n\n#endif // NCNN_STRING\n\n // register custom layer by layer type\n\n // return 0 if success\n\n int register_custom_layer(int index, layer_creator_func creator, layer_destroyer_func destroyer = 0, void* userdata = 0);\n\n\n\n#if NCNN_STRING\n\n int load_param(const DataReader& dr);\n\n#endif // NCNN_STRING\n\n\n\n int load_param_bin(const DataReader& dr);\n\n\n\n int load_model(const DataReader& dr);\n\n\n\n#if NCNN_STDIO\n", "file_path": "ncnn/net.h", "rank": 51, "score": 62109.298508097534 }, { "content": " // return bytes consumed\n\n int load_param(const unsigned char* mem);\n\n\n\n // reference network weight data from external memory\n\n // weight data is not copied but referenced\n\n // so external memory should be retained when used\n\n // memory pointer must be 32-bit aligned\n\n // return bytes consumed\n\n int load_model(const unsigned char* mem);\n\n\n\n#if NCNN_PLATFORM_API\n\n#if __ANDROID_API__ >= 9\n\n#if NCNN_STRING\n\n // convenient load network structure from android asset plain param file\n\n int load_param(AAsset* asset);\n\n int load_param(AAssetManager* mgr, const char* assetpath);\n\n#endif // NCNN_STRING\n\n // convenient load network structure from android asset binary param file\n\n int load_param_bin(AAsset* asset);\n\n int load_param_bin(AAssetManager* mgr, const char* assetpath);\n", "file_path": "ncnn/net.h", "rank": 52, "score": 62108.475742931245 }, { "content": " // this will overwrite the global setting\n\n // default count is system depended\n\n void set_num_threads(int num_threads);\n\n\n\n // set blob memory allocator\n\n void set_blob_allocator(Allocator* allocator);\n\n\n\n // set workspace memory allocator\n\n void set_workspace_allocator(Allocator* allocator);\n\n\n\n#if NCNN_VULKAN\n\n void set_vulkan_compute(bool enable);\n\n\n\n void set_blob_vkallocator(VkAllocator* allocator);\n\n\n\n void set_workspace_vkallocator(VkAllocator* allocator);\n\n\n\n void set_staging_vkallocator(VkAllocator* allocator);\n\n#endif // NCNN_VULKAN\n\n\n", "file_path": "ncnn/net.h", "rank": 53, "score": 62104.20540597123 }, { "content": " Extractor(const Net* net, size_t blob_count);\n\n\n\nprivate:\n\n ExtractorPrivate* const d;\n\n};\n\n\n\n} // namespace ncnn\n\n\n\n#endif // NCNN_NET_H\n", "file_path": "ncnn/net.h", "rank": 54, "score": 62100.41192088727 }, { "content": "#include \"option.h\"\n\n#include \"platform.h\"\n\n\n\n#if NCNN_PLATFORM_API\n\n#if __ANDROID_API__ >= 9\n\n#include <android/asset_manager.h>\n\n#endif // __ANDROID_API__ >= 9\n\n#endif // NCNN_PLATFORM_API\n\n\n\nnamespace ncnn {\n\n\n\n#if NCNN_VULKAN\n", "file_path": "ncnn/net.h", "rank": 55, "score": 62100.09800414842 }, { "content": "#if NCNN_STRING\n\n // load network structure from plain param file\n\n // return 0 if success\n\n int load_param(FILE* fp);\n\n int load_param(const char* protopath);\n\n int load_param_mem(const char* mem);\n\n#endif // NCNN_STRING\n\n // load network structure from binary param file\n\n // return 0 if success\n\n int load_param_bin(FILE* fp);\n\n int load_param_bin(const char* protopath);\n\n\n\n // load network weight data from model file\n\n // return 0 if success\n\n int load_model(FILE* fp);\n\n int load_model(const char* modelpath);\n\n#endif // NCNN_STDIO\n\n\n\n // load network structure from external memory\n\n // memory pointer must be 32-bit aligned\n", "file_path": "ncnn/net.h", "rank": 56, "score": 62099.87841061977 }, { "content": "struct Type< Range > { enum { value = CV_MAKETYPE(Depth<int>::value, 2) }; };\n\n} // namespace\n\n\n\n\n\n//////////////////////////////// Scalar_ ///////////////////////////////\n\n\n\n/** @brief Template class for a 4-element vector derived from Vec.\n\n\n\nBeing derived from Vec\\<_Tp, 4\\> , Scalar\\_ and Scalar can be used just as typical 4-element\n\nvectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in\n\nOpenCV to pass pixel values.\n\n*/\n\ntemplate<typename _Tp> class Scalar_ : public Vec<_Tp, 4>\n\n{\n\npublic:\n\n //! default constructor\n\n Scalar_();\n\n Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);\n\n Scalar_(_Tp v0);\n\n\n", "file_path": "opencv2/core/types.hpp", "rank": 57, "score": 61382.054358225774 }, { "content": "//! @cond IGNORED\n\n// FIXIT Remove this (especially CV_EXPORTS modifier)\n\nstruct CV_EXPORTS Matx_AddOp { Matx_AddOp() {} Matx_AddOp(const Matx_AddOp&) {} };\n", "file_path": "opencv2/core/matx.hpp", "rank": 58, "score": 60193.23708298516 }, { "content": "struct CV_EXPORTS Matx_TOp { Matx_TOp() {} Matx_TOp(const Matx_TOp&) {} };\n\n//! @endcond\n\n\n\n/** @brief Template class for small matrices whose type and size are known at compilation time\n\n\n\nIf you need a more flexible type, use Mat . The elements of the matrix M are accessible using the\n\nM(i,j) notation. Most of the common matrix operations (see also @ref MatrixExpressions ) are\n\navailable. To do an operation on Matx that is not implemented, you can easily convert the matrix to\n\nMat and backwards:\n\n@code{.cpp}\n\n Matx33f m(1, 2, 3,\n\n 4, 5, 6,\n\n 7, 8, 9);\n\n cout << sum(Mat(m*m.t())) << endl;\n\n@endcode\n\nExcept of the plain constructor which takes a list of elements, Matx can be initialized from a C-array:\n\n@code{.cpp}\n\n float values[] = { 1, 2, 3};\n\n Matx31f m(values);\n\n@endcode\n", "file_path": "opencv2/core/matx.hpp", "rank": 59, "score": 60193.23708298516 }, { "content": "struct CV_EXPORTS Matx_ScaleOp { Matx_ScaleOp() {} Matx_ScaleOp(const Matx_ScaleOp&) {} };\n", "file_path": "opencv2/core/matx.hpp", "rank": 60, "score": 60193.23708298516 }, { "content": "struct CV_EXPORTS Matx_MulOp { Matx_MulOp() {} Matx_MulOp(const Matx_MulOp&) {} };\n", "file_path": "opencv2/core/matx.hpp", "rank": 61, "score": 60193.23708298516 }, { "content": "struct CV_EXPORTS Matx_SubOp { Matx_SubOp() {} Matx_SubOp(const Matx_SubOp&) {} };\n", "file_path": "opencv2/core/matx.hpp", "rank": 62, "score": 60193.23708298516 }, { "content": "struct CV_EXPORTS Matx_DivOp { Matx_DivOp() {} Matx_DivOp(const Matx_DivOp&) {} };\n", "file_path": "opencv2/core/matx.hpp", "rank": 63, "score": 60193.23708298516 }, { "content": " // the memory size need >= GetForwardMemorySize().\n\n // releasing or otherwise using the memory for other purposes during the tnn network run\n\n // will result in undefined behavior.\n\n Status SetForwardMemory(void* memory);\n\n\n\n // reshape instance with new input shapes\n\n Status Reshape(const InputShapesMap& inputs);\n\n\n\n // get tnn command queue\n\n Status GetCommandQueue(void** command_queue);\n\n \n\n // @brief share command queue with another instance\n\n // @param instance to share command queue\n\n Status ShareCommandQueue(Instance *instance);\n\n\n\n // @brief tnn instance network infer, it will wait until all layer infer complete.\n\n Status Forward();\n\n\n\n#ifdef FORWARD_CALLBACK_ENABLE\n\n // tnn instance network infer with callback to get blob info\n", "file_path": "tnn/core/instance.h", "rank": 64, "score": 59288.81088190687 }, { "content": "// Tencent is pleased to support the open source community by making TNN available.\n\n//\n\n// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.\n\n//\n\n// Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n\n// in compliance with the License. You may obtain a copy of the License at\n\n//\n\n// https://opensource.org/licenses/BSD-3-Clause\n\n//\n\n// Unless required by applicable law or agreed to in writing, software distributed\n\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n\n// specific language governing permissions and limitations under the License.\n\n\n\n#ifndef TNN_INCLUDE_TNN_CORE_INSTANCE_H_\n\n#define TNN_INCLUDE_TNN_CORE_INSTANCE_H_\n\n\n\n#include <functional>\n\n#include <memory>\n\n#include <vector>\n", "file_path": "tnn/core/instance.h", "rank": 65, "score": 59286.326370883646 }, { "content": "\n\n#if TNN_PROFILE\n\npublic:\n\n /**start to profile each layer, dont call this func if you only want to profile the whole mode*/\n\n void StartProfile();\n\n /**finish profile each layer and show result*/\n\n std::string FinishProfile(bool do_print = false);\n\n#endif\n\n\n\nprivate:\n\n std::shared_ptr<AbstractModelInterpreter> interpreter_ = nullptr;\n\n std::shared_ptr<AbstractNetwork> network_ = nullptr;\n\n std::shared_ptr<AbstractNetwork> const_folder_ = nullptr;\n\n NetworkConfig net_config_;\n\n ModelConfig model_config_;\n\n \n\n AbstractNetwork *GetNetwork();\n\n \n\n //Mat interface for simple use\n\npublic:\n", "file_path": "tnn/core/instance.h", "rank": 66, "score": 59285.71574162249 }, { "content": " // set input Mat, if input_name is not set, take the first input as default\n\n Status SetInputMat(std::shared_ptr<Mat> mat,\n\n MatConvertParam param,\n\n std::string input_name = \"\");\n\n \n\n // get output Mat, if output_name is not set, take the first output as default\n\n Status GetOutputMat(std::shared_ptr<Mat>& mat,\n\n MatConvertParam param = MatConvertParam(),\n\n std::string output_name = \"\",\n\n DeviceType device = DEVICE_ARM, MatType mat_type = NCHW_FLOAT);\n\n \n\nprivate:\n\n // input converter\n\n std::map<std::string, std::shared_ptr<BlobConverter>> input_converters_ = {};\n\n\n\n // output converter\n\n std::map<std::string, std::shared_ptr<BlobConverter>> output_converters_ = {};\n\n\n\n // output mat\n\n std::map<std::string, std::shared_ptr<Mat>> output_mats_ = {};\n", "file_path": "tnn/core/instance.h", "rank": 67, "score": 59283.260672564684 }, { "content": " // output mat convert status\n\n std::map<std::string, int> output_mats_convert_status_ = {};\n\n};\n\n\n\n} // namespace TNN_NS\n\n\n\n#pragma warning(pop)\n\n\n\n#endif // TNN_INCLUDE_TNN_CORE_INSTANCE_H_\n", "file_path": "tnn/core/instance.h", "rank": 68, "score": 59282.8160712113 }, { "content": " Status ForwardWithCallback(BlobStatisticCallback before, BlobStatisticCallback after);\n\n#endif // end of FORWARD_CALLBACK_ENABLE\n\n\n\n#ifdef GET_INTERP_ENABLE\n\n // get model interpreter\n\n std::shared_ptr<AbstractModelInterpreter> GetInterpreter();\n\n#endif // end of GET_INTERP_ENABLE\n\n\n\n // tnn instance network infer async.\n\n // device gpu, all layer infer complete will call Callback.\n\n Status ForwardAsync(Callback call_back);\n\n\n\n // get all input blobs\n\n Status GetAllInputBlobs(BlobMap& blobs);\n\n\n\n // get all output blobs\n\n Status GetAllOutputBlobs(BlobMap& blobs);\n\n\n\n // set threads run on cpu\n\n Status SetCpuNumThreads(int num_threads);\n", "file_path": "tnn/core/instance.h", "rank": 69, "score": 59279.18429368589 }, { "content": "\n\n#include \"tnn/core/blob.h\"\n\n#include \"tnn/core/common.h\"\n\n#include \"tnn/core/macro.h\"\n\n#include \"tnn/core/status.h\"\n\n#include \"tnn/utils/blob_converter.h\"\n\n\n\n#pragma warning(push)\n\n#pragma warning(disable : 4251)\n\n\n\nnamespace TNN_NS {\n\n\n", "file_path": "tnn/core/instance.h", "rank": 70, "score": 59274.085280534106 }, { "content": "class MatConstIterator_ : public MatConstIterator\n\n{\n\npublic:\n\n typedef _Tp value_type;\n\n typedef ptrdiff_t difference_type;\n\n typedef const _Tp* pointer;\n\n typedef const _Tp& reference;\n\n\n\n typedef std::random_access_iterator_tag iterator_category;\n\n\n\n //! default constructor\n\n MatConstIterator_();\n\n //! constructor that sets the iterator to the beginning of the matrix\n\n MatConstIterator_(const Mat_<_Tp>* _m);\n\n //! constructor that sets the iterator to the specified element of the matrix\n\n MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);\n\n //! constructor that sets the iterator to the specified element of the matrix\n\n MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);\n\n //! constructor that sets the iterator to the specified element of the matrix\n\n MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);\n", "file_path": "opencv2/core/mat.hpp", "rank": 71, "score": 59271.68895543124 }, { "content": "class Extractor;\n", "file_path": "ncnn/net.h", "rank": 72, "score": 59187.11008487533 }, { "content": " class LITE_EXPORTS HRNet; // [67] reference: https://github.com/HRNet/HRNet-Facial-Landmark-Detection\n", "file_path": "lite/ort/core/ort_core.h", "rank": 73, "score": 58294.117268425 }, { "content": "struct CV_EXPORTS Matx_MatMulOp { Matx_MatMulOp() {} Matx_MatMulOp(const Matx_MatMulOp&) {} };\n", "file_path": "opencv2/core/matx.hpp", "rank": 74, "score": 56916.74502884897 }, { "content": "//\n\n// AutoTime.hpp\n\n// MNN\n\n//\n\n// Created by MNN on 2018/07/27.\n\n// Copyright © 2018, Alibaba Group Holding Limited\n\n//\n\n\n\n#ifndef AutoTime_hpp\n\n#define AutoTime_hpp\n\n\n\n#include <stdint.h>\n\n#include <stdio.h>\n\n#include <MNN/MNNDefine.h>\n\n\n\nnamespace MNN {\n\n\n", "file_path": "MNN/AutoTime.hpp", "rank": 75, "score": 56636.51935501077 }, { "content": "#endif // NCNN_VULKAN\n\nclass DataReader;\n", "file_path": "ncnn/net.h", "rank": 76, "score": 56548.446825630796 }, { "content": "#if NCNN_VULKAN\n\nclass VkCompute;\n", "file_path": "ncnn/net.h", "rank": 77, "score": 56541.51605871881 }, { "content": "class ExtractorPrivate;\n", "file_path": "ncnn/net.h", "rank": 78, "score": 56541.51605871881 }, { "content": "# include <opencv2/gapi/own/mat.hpp>\n\n// replacement of cv's structures:\n\nnamespace cv {\n\n using Rect = gapi::own::Rect;\n\n using Size = gapi::own::Size;\n\n using Point = gapi::own::Point;\n\n using Point2f = gapi::own::Point2f;\n\n using Scalar = gapi::own::Scalar;\n\n using Mat = gapi::own::Mat;\n\n} // namespace cv\n\n#endif // !defined(GAPI_STANDALONE)\n\n\n\n#endif // OPENCV_GAPI_OPENCV_INCLUDES_HPP\n", "file_path": "opencv2/gapi/opencv_includes.hpp", "rank": 79, "score": 54213.659508752935 }, { "content": "// Tencent is pleased to support the open source community by making TNN available.\n\n//\n\n// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.\n\n//\n\n// Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n\n// in compliance with the License. You may obtain a copy of the License at\n\n//\n\n// https://opensource.org/licenses/BSD-3-Clause\n\n//\n\n// Unless required by applicable law or agreed to in writing, software distributed\n\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n\n// specific language governing permissions and limitations under the License.\n\n\n\n#ifndef TNN_INCLUDE_TNN_UTILS_DIMS_VECTOR_UTILS_H_\n\n#define TNN_INCLUDE_TNN_UTILS_DIMS_VECTOR_UTILS_H_\n\n\n\n#include <algorithm>\n\n\n\n#include \"tnn/core/common.h\"\n\n#include \"tnn/core/macro.h\"\n\n#include \"tnn/core/status.h\"\n\n\n\nnamespace TNN_NS {\n\n\n", "file_path": "tnn/utils/dims_vector_utils.h", "rank": 80, "score": 54213.534685270264 }, { "content": "// This file is part of OpenCV project.\n\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n\n// of this distribution and at http://opencv.org/license.html.\n\n//\n\n// Copyright (C) 2018 Intel Corporation\n\n\n\n\n\n#ifndef OPENCV_GAPI_UTIL_THROW_HPP\n\n#define OPENCV_GAPI_UTIL_THROW_HPP\n\n\n\n#include <utility> // std::forward\n\n\n\n#if !defined(__EXCEPTIONS)\n\n#include <stdlib.h>\n\n#include <stdio.h>\n\n#endif\n\n\n\nnamespace cv\n\n{\n\nnamespace util\n", "file_path": "opencv2/gapi/util/throw.hpp", "rank": 81, "score": 54212.61694712113 }, { "content": "{\n\ntemplate <class ExceptionType>\n\n[[noreturn]] void throw_error(ExceptionType &&e)\n\n{\n\n#if defined(__EXCEPTIONS) || defined(_CPPUNWIND)\n\n throw std::forward<ExceptionType>(e);\n\n#else\n\n fprintf(stderr, \"An exception thrown! %s\\n\" , e.what());\n\n fflush(stderr);\n\n abort();\n\n#endif\n\n}\n\n} // namespace util\n\n} // namespace cv\n\n\n\n#endif // OPENCV_GAPI_UTIL_THROW_HPP\n", "file_path": "opencv2/gapi/util/throw.hpp", "rank": 82, "score": 54210.06956052039 }, { "content": "// This file is part of OpenCV project.\n\n\n\n// It is subject to the license terms in the LICENSE file found in the top-level directory\n\n// of this distribution and at http://opencv.org/license.html.\n\n//\n\n// Copyright (C) 2018 Intel Corporation\n\n\n\n\n\n#ifndef OPENCV_GAPI_OPENCV_INCLUDES_HPP\n\n#define OPENCV_GAPI_OPENCV_INCLUDES_HPP\n\n\n\n#if !defined(GAPI_STANDALONE)\n\n# include <opencv2/core/mat.hpp>\n\n# include <opencv2/core/cvdef.h>\n\n# include <opencv2/core/types.hpp>\n\n# include <opencv2/core/base.hpp>\n\n#else // Without OpenCV\n\n# include <opencv2/gapi/own/cvdefs.hpp>\n\n# include <opencv2/gapi/own/types.hpp> // cv::gapi::own::Rect/Size/Point\n\n# include <opencv2/gapi/own/scalar.hpp> // cv::gapi::own::Scalar\n", "file_path": "opencv2/gapi/opencv_includes.hpp", "rank": 83, "score": 54207.296511486944 }, { "content": "struct LayerInfo;\n\n\n\n#ifdef FORWARD_CALLBACK_ENABLE\n\ntypedef std::function<void(std::vector<Blob*>& blobs, LayerInfo* info)> BlobStatisticCallback;\n\n#endif // end of FORWARD_CALLBACK_ENABLE\n\n\n", "file_path": "tnn/core/instance.h", "rank": 84, "score": 54194.48420536921 }, { "content": "class AbstractNetwork;\n", "file_path": "tnn/core/instance.h", "rank": 85, "score": 54194.48420536921 }, { "content": "class NCNN_EXPORT Extractor\n\n{\n\npublic:\n\n virtual ~Extractor();\n\n\n\n // copy\n\n Extractor(const Extractor&);\n\n\n\n // assign\n\n Extractor& operator=(const Extractor&);\n\n\n\n // clear blob mats and alloctors\n\n void clear();\n\n\n\n // enable light mode\n\n // intermediate blob will be recycled when enabled\n\n // enabled by default\n\n void set_light_mode(bool enable);\n\n\n\n // set thread count for this extractor\n", "file_path": "ncnn/net.h", "rank": 86, "score": 54122.31251157698 }, { "content": " }\n\n\n\n ConstIterator operator++(int) {\n\n ConstIterator tmp{*this};\n\n ++(*this);\n\n return tmp;\n\n }\n\n\n\n const T*& operator*() const {\n\n item_ = *current_;\n\n return item_;\n\n }\n\n\n\n const T** operator->() const { return &(operator*()); };\n\n\n\n private:\n\n const_iterator current_;\n\n mutable const T* item_;\n\n };\n\n\n", "file_path": "onnxruntime/core/common/const_pointer_container.h", "rank": 87, "score": 51977.77755741198 }, { "content": "// Copyright (c) Microsoft Corporation. All rights reserved.\n\n// Licensed under the MIT License.\n\n\n\n#pragma once\n\n\n\n#include <type_traits>\n\n\n\nnamespace onnxruntime {\n\n/**\n\n Container has T* entries. e.g. std::vector<T*>, and this class provides const access to those\n\n via iterators and direct access, as the standard behavior only makes the pointer constant,\n\n and not what is pointed too. i.e. you get a const pointer to T not a pointer to const T without this wrapper.\n\n See https://stackoverflow.com/questions/8017036/understanding-const-iterator-with-pointers\n\n*/\n\ntemplate <typename Container>\n", "file_path": "onnxruntime/core/common/const_pointer_container.h", "rank": 88, "score": 51974.47695941491 }, { "content": " /**\n\n Construct wrapper class that will provide const access to the pointers in a container of non-const pointers.\n\n @param data Container with non-const pointers. e.g. std::vector<T*>\n\n */\n\n explicit ConstPointerContainer(const Container& data) noexcept : data_(data) {}\n\n\n\n size_t size() const noexcept { return data_.size(); }\n\n bool empty() const noexcept { return data_.empty(); }\n\n\n\n ConstIterator cbegin() const noexcept { return ConstIterator(data_.cbegin()); }\n\n ConstIterator cend() const noexcept { return ConstIterator(data_.cend()); }\n\n\n\n ConstIterator begin() const noexcept { return ConstIterator(data_.cbegin()); }\n\n ConstIterator end() const noexcept { return ConstIterator(data_.cend()); }\n\n\n\n const T* operator[](size_t index) const { return data_[index]; }\n\n\n\n const T* at(size_t index) const {\n\n ORT_ENFORCE(index < data_.size());\n\n return data_[index];\n\n }\n\n\n\n private:\n\n const Container& data_;\n\n};\n\n} // namespace onnxruntime\n", "file_path": "onnxruntime/core/common/const_pointer_container.h", "rank": 89, "score": 51972.97142582076 }, { "content": "```\n\n\n\n* 实现 `transform` 和 `detect` 方法.\n\n\n\n```c++\n\n#include \"age_googlenet.h\"\n\n#include \"ort/core/ort_utils.h\"\n\n\n\nusing ortcv::AgeGoogleNet;\n\n\n\nort::Value AgeGoogleNet::transform(const cv::Mat &mat)\n\n{\n\n cv::Mat canva = mat.clone();\n\n cv::resize(canva, canva, cv::Size(input_node_dims.at(3), input_node_dims.at(2)));\n\n cv::cvtColor(canva, canva, cv::COLOR_BGR2RGB);\n\n // (1,3,224,224)\n\n ortcv::utils::transform::normalize_inplace(canva, mean_val, scale_val); // float32\n\n \n\n return ortcv::utils::transform::create_tensor(\n\n canva, input_node_dims, memory_info_handler,\n\n input_values_handler, ortcv::utils::transform::CHW);\n\n}\n\n\n\nvoid AgeGoogleNet::detect(const cv::Mat &mat, types::Age &age)\n\n{\n\n if (mat.empty()) return;\n\n // 1. make input tensor\n\n ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n ort::Value &age_logits = output_tensors.at(0); // (1,8)\n\n auto age_dims = output_node_dims.at(0);\n\n unsigned int interval = 0;\n\n const unsigned int num_intervals = age_dims.at(1); // 8\n\n const float *pred_logits = age_logits.GetTensorMutableData<float>();\n\n auto softmax_probs = ortcv::utils::math::softmax<float>(pred_logits, num_intervals, interval);\n\n const float pred_age = static_cast<float>(age_intervals[interval][0] + age_intervals[interval][1]) / 2.0f;\n\n age.age = pred_age;\n\n age.age_interval[0] = age_intervals[interval][0];\n\n age.age_interval[1] = age_intervals[interval][1];\n\n age.interval_prob = softmax_probs[interval];\n\n age.flag = true;\n\n}\n\n```\n\n\n\n\n\n\n", "file_path": "docs/ort/ort_handler.zh.md", "rank": 91, "score": 52.56817515439065 }, { "content": "using ortcv::AgeGoogleNet;\n\n\n\nort::Value AgeGoogleNet::transform(const cv::Mat &mat)\n\n{\n\n cv::Mat canva = mat.clone();\n\n cv::resize(canva, canva, cv::Size(input_node_dims.at(3), input_node_dims.at(2)));\n\n cv::cvtColor(canva, canva, cv::COLOR_BGR2RGB);\n\n // (1,3,224,224)\n\n ortcv::utils::transform::normalize_inplace(canva, mean_val, scale_val); // float32\n\n \n\n return ortcv::utils::transform::create_tensor(\n\n canva, input_node_dims, memory_info_handler,\n\n input_values_handler, ortcv::utils::transform::CHW);\n\n}\n\n\n\nvoid AgeGoogleNet::detect(const cv::Mat &mat, types::Age &age)\n\n{\n\n if (mat.empty()) return;\n\n // 1. make input tensor\n\n ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n ort::Value &age_logits = output_tensors.at(0); // (1,8)\n\n auto age_dims = output_node_dims.at(0);\n\n unsigned int interval = 0;\n\n const unsigned int num_intervals = age_dims.at(1); // 8\n\n const float *pred_logits = age_logits.GetTensorMutableData<float>();\n\n auto softmax_probs = ortcv::utils::math::softmax<float>(pred_logits, num_intervals, interval);\n\n const float pred_age = static_cast<float>(age_intervals[interval][0] + age_intervals[interval][1]) / 2.0f;\n\n age.age = pred_age;\n\n age.age_interval[0] = age_intervals[interval][0];\n\n age.age_interval[1] = age_intervals[interval][1];\n\n age.interval_prob = softmax_probs[interval];\n\n age.flag = true;\n\n}\n", "file_path": "docs/ort/ort_handler.md", "rank": 92, "score": 47.22921457483278 }, { "content": "\n\nvoid FastStyleTransfer::detect(const cv::Mat &mat, types::StyleContent &style_content)\n\n{\n\n // 1. make input tensor\n\n Ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n Ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n Ort::Value &pred_tensor = output_tensors.at(0); // (1,3,224,224)\n\n auto pred_dims = output_node_dims.at(0);\n\n const unsigned int rows = pred_dims.at(2); // H\n\n const unsigned int cols = pred_dims.at(3); // W\n\n\n\n style_content.mat.create(rows, cols, CV_8UC3); // release & create\n\n\n\n // time cost!\n\n for (unsigned int i = 0; i < rows; ++i)\n\n {\n", "file_path": "lite/ort/cv/fast_style_transfer.cpp", "rank": 94, "score": 44.64732430933586 }, { "content": " return Ort::Value::CreateTensor<uchar>(memory_info_handler, input_values_handler.data(),\n\n input_tensor_sizes.at(0),\n\n input_node_dims.at(0).data(),\n\n input_node_dims.at(0).size());\n\n\n\n}\n\n\n\n\n\nvoid SSDMobileNetV1::detect(const cv::Mat &mat, std::vector<types::Boxf> &detected_boxes,\n\n float score_threshold, float iou_threshold,\n\n unsigned int topk, unsigned int nms_type)\n\n{\n\n if (mat.empty()) return;\n\n const unsigned int img_height = mat.rows;\n\n const unsigned int img_width = mat.cols;\n\n // 1. make input tensor\n\n Ort::Value input_tensor = this->transform(mat);\n\n // 2. inference nums & boxes & scores & classes.\n\n auto output_tensors = ort_session->Run(\n\n Ort::RunOptions{nullptr}, input_node_names.data(),\n", "file_path": "lite/ort/cv/ssd_mobilenetv1.cpp", "rank": 95, "score": 44.431514223245614 }, { "content": " canvas, input_node_dims, memory_info_handler,\n\n input_values_handler, ortcv::utils::transform::HWC);\n\n}\n\n\n\nvoid EfficientNetLite4::detect(const cv::Mat &mat, types::ImageNetContent &content, unsigned int top_k)\n\n{\n\n if (mat.empty()) return;\n\n // 1. make input tensor\n\n Ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n Ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n Ort::Value &scores_tensor = output_tensors.at(0); // (1,1000)\n\n const unsigned int num_classes = output_node_dims.at(0).at(1);\n\n const float *scores = scores_tensor.GetTensorMutableData<float>(); // float\n\n std::vector<unsigned int> sorted_indices = lite::utils::math::argsort<float>(scores, num_classes);\n\n if (top_k > num_classes) top_k = num_classes;\n\n\n", "file_path": "lite/ort/cv/efficientnet_lite4.cpp", "rank": 96, "score": 44.11565119581444 }, { "content": " canvas, input_node_dims, memory_info_handler,\n\n input_values_handler, ortcv::utils::transform::CHW);\n\n}\n\n\n\nvoid ShuffleNetV2::detect(const cv::Mat &mat, types::ImageNetContent &content, unsigned int top_k)\n\n{\n\n if (mat.empty()) return;\n\n // 1. make input tensor\n\n Ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n Ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n Ort::Value &logits_tensor = output_tensors.at(0); // (1,1000)\n\n const unsigned int num_classes = output_node_dims.at(0).at(1);\n\n const float *logits = logits_tensor.GetTensorMutableData<float>(); // float\n\n unsigned int max_id;\n\n std::vector<float> scores = lite::utils::math::softmax<float>(logits, num_classes, max_id);\n\n std::vector<unsigned int> sorted_indices = lite::utils::math::argsort<float>(scores);\n", "file_path": "lite/ort/cv/shufflenetv2.cpp", "rank": 97, "score": 43.848575563868394 }, { "content": " return ortcv::utils::transform::create_tensor(\n\n canvas, input_node_dims, memory_info_handler,\n\n input_values_handler, ortcv::utils::transform::CHW);\n\n}\n\n\n\nvoid GhostNet::detect(const cv::Mat &mat, types::ImageNetContent &content, unsigned int top_k)\n\n{\n\n if (mat.empty()) return;\n\n // 1. make input tensor\n\n Ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n Ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n Ort::Value &logits_tensor = output_tensors.at(0); // (1,1000)\n\n const unsigned int num_classes = output_node_dims.at(0).at(1);\n\n const float *logits = logits_tensor.GetTensorMutableData<float>(); // float\n\n unsigned int max_id;\n\n std::vector<float> scores = lite::utils::math::softmax<float>(logits, num_classes, max_id);\n", "file_path": "lite/ort/cv/ghostnet.cpp", "rank": 98, "score": 43.82395921161442 }, { "content": " return ortcv::utils::transform::create_tensor(\n\n canvas, input_node_dims, memory_info_handler,\n\n input_values_handler, ortcv::utils::transform::CHW);\n\n}\n\n\n\nvoid ResNet::detect(const cv::Mat &mat, types::ImageNetContent &content, unsigned int top_k)\n\n{\n\n if (mat.empty()) return;\n\n // 1. make input tensor\n\n Ort::Value input_tensor = this->transform(mat);\n\n // 2. inference\n\n auto output_tensors = ort_session->Run(\n\n Ort::RunOptions{nullptr}, input_node_names.data(),\n\n &input_tensor, 1, output_node_names.data(), num_outputs\n\n );\n\n Ort::Value &logits_tensor = output_tensors.at(0); // (1,1000)\n\n const unsigned int num_classes = output_node_dims.at(0).at(1);\n\n const float *logits = logits_tensor.GetTensorMutableData<float>(); // float\n\n unsigned int max_id;\n\n std::vector<float> scores = lite::utils::math::softmax<float>(logits, num_classes, max_id);\n", "file_path": "lite/ort/cv/resnet.cpp", "rank": 99, "score": 43.82395921161442 } ]
C++
stlio.hpp
legokangpalla/FileSTL
675b2cc1364e8d70be43ec09423dbc45b7b574b0
#pragma once #include <vector> #include <type_traits> #include <utility> #include <fstream> #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/fusion/include/adapt_struct.hpp> namespace tyti { namespace stl { template<typename T> struct basic_vec3 { using scalar_type = T; static_assert(std::is_floating_point<scalar_type>::value, "T must be a floating point"); T data[3]; basic_vec3():data{T(0),T(0),T(0)}{} basic_vec3(T x, T y, T z):data{x,y,z}{} T operator[](size_t i)const {return data[i];} const T &operator[](size_t i) { return data[i]; } }; using dvec3 = basic_vec3<double>; using vec3 = basic_vec3<float>; template<typename T> struct basic_solid { using vec3 = basic_vec3<T>; using scalar_type = T; std::string header; std::vector<vec3> normals; std::vector<vec3> vertices; std::vector<std::uint16_t> attributes; }; using dsolid = basic_solid<double>; using solid = basic_solid<float>; template <typename T, typename Iterator> struct stl_parser_ascii : boost::spirit::qi::grammar<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> { stl_parser_ascii() : stl_parser_ascii::base_type(start) { namespace qi = boost::spirit::qi; namespace ql = qi::labels; namespace ascii = boost::spirit::ascii; namespace fusion = boost::fusion; namespace px = boost::phoenix; startSolid %= qi::lexeme[qi::lit("solid ") >> (+(ascii::char_ - qi::eol) | qi::attr(""))]; endSolid = qi::lexeme[qi::lit("endsolid ") >> ascii::string(ql::_r1)]; vector %= qi::float_ >> qi::float_ >> qi::float_; start = startSolid[px::at_c<0>(ql::_val) = ql::_1] >> *(qi::lit("facet") >> qi::lit("normal") >> vector[px::push_back(px::at_c<1>(ql::_val), ql::_1)] >> qi::lit("outer loop") >> qi::repeat(3)[qi::lit("vertex") >> vector[px::push_back(px::at_c<2>(ql::_val), ql::_1)]] >> qi::lit("endloop") >> qi::lit("endfacet") ) >> endSolid(px::at_c<0>(ql::_val)) ; } boost::spirit::qi::rule<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> start; boost::spirit::qi::rule<Iterator, std::string(), boost::spirit::ascii::space_type> startSolid; boost::spirit::qi::rule<Iterator, basic_vec3<T>(), boost::spirit::ascii::space_type> vector; boost::spirit::qi::rule<Iterator, void(std::string), boost::spirit::ascii::space_type> endSolid; }; template <typename T, typename Iterator> struct stl_parser_binary : boost::spirit::qi::grammar<Iterator, basic_solid<T>()> { stl_parser_binary() : stl_parser_binary::base_type(start) { namespace spirit = boost::spirit; namespace qi = boost::spirit::qi; namespace ql = qi::labels; namespace ascii = boost::spirit::ascii; namespace px = boost::phoenix; vector %= spirit::little_bin_float >> spirit::little_bin_float >> spirit::little_bin_float; start = qi::repeat(80)[spirit::byte_[px::at_c<0>(ql::_val) += ql::_1]] >> spirit::little_dword[px::reserve(px::at_c<1>(ql::_val), ql::_1), px::reserve(px::at_c<2>(ql::_val), 3 * ql::_1), px::reserve(px::at_c<3>(ql::_val), ql::_1)] >> *(vector[px::push_back(px::at_c<1>(ql::_val), ql::_1)] >> spirit::repeat(3)[vector[px::push_back(px::at_c<2>(ql::_val), ql::_1)]] >> spirit::little_word[px::push_back(px::at_c<3>(ql::_val), ql::_1)] ) ; } boost::spirit::qi::rule<Iterator, basic_solid<T>()> start; boost::spirit::qi::rule<Iterator, basic_vec3<T>()> vector; boost::spirit::qi::rule<Iterator, void(std::string)> endSolid; }; template <typename T, typename Iterator> struct stl_parser : boost::spirit::qi::grammar<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> { stl_parser() : stl_parser::base_type(start) { start %= stl_ascii_ | boost::spirit::qi::lexeme[stl_binary_]; } stl_parser_ascii<T, Iterator> stl_ascii_; stl_parser_binary<T, Iterator> stl_binary_; boost::spirit::qi::rule<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> start; }; template<typename T, typename IterT> inline bool read(basic_solid<T>& out, IterT begin, IterT end) { stl_parser< T, IterT > p; return boost::spirit::qi::phrase_parse(begin, end, p, boost::spirit::ascii::space, out); } template<typename T, typename IterT> inline std::pair< basic_solid<T>, bool > read(IterT begin, IterT end) { basic_solid<T> o; bool r = read(o, begin, end); return std::make_pair<basic_solid<T>, bool>(std::move(o), std::move(r)); } template<typename IterT> inline std::pair< solid, bool > read(IterT begin, IterT end) { return read<float>(begin, end); } template<typename T> inline bool read(basic_solid<T>& out, const std::string& fileName) { std::ifstream f(fileName, std::ios::binary); std::string str; f.seekg(0, std::ios::end); str.resize((unsigned)f.tellg()); f.seekg(0, std::ios::beg); f.read(&str[0], str.size()); f.close(); return read<T>(out, str.cbegin(), str.cend()); } template<typename T> inline std::pair<basic_solid<T>, bool> read(const std::string& fileName) { basic_solid<T> out; bool r = read(out, fileName); return std::make_pair<basic_solid<T>, bool>(std::move(out), std::move(r)); } inline std::pair<solid, bool> read(const std::string& fileName) { return read<float>(fileName); } template<typename T, typename streamT> void write_ascii(streamT& out, const basic_solid<T>&s) { out << "solid " << s.header << "\n"; for (size_t i = 0; i < s.normals.size(); ++i) { out << "\tfacet normal " << s.normals[i][0] << " " << s.normals[i][1] << " " << s.normals[i][2] << " " << "\n"; out << "\t\touter loop\n"; for (size_t j = 0; j < 3; ++j) { out << "\t\t\tvertex " << s.vertices[3 * i + j][0] << " " << s.vertices[3 * i + j][1] << " " << s.vertices[3 * i + j][2] << " " << "\n"; } out << "\t\tendloop\n" << "\tendfacet\n"; } out << "endsolid " << s.header << "\n"; } namespace detail { template<typename streamT> inline void write_vectorF32(streamT& out, const double* p) { for (size_t i = 0; i < 3; ++i) { const float f = static_cast<float>(p[i]); out.write(reinterpret_cast<const char *>(p), sizeof(float)); } } template<typename streamT> inline void write_vectorF32(streamT& out, const float* p) { out.write(reinterpret_cast<const char*>(p), sizeof(float) * 3); } } template<typename T, typename streamT> void write_binary(streamT& out, basic_solid<T>&s) { s.header.resize(80); out.write(&s.header[0], 80); const size_t num_triangles{ s.normals.size() }; s.attributes.resize(num_triangles); out.write(reinterpret_cast<const char*>(&num_triangles), 4); out << num_triangles; for (size_t i = 0; i < num_triangles; ++i) { detail::write_vectorF32(out, s.normals[i].data); for (size_t j = 0; j < 3; ++j) detail::write_vectorF32(out, s.vertices[3 * i + j].data); out.write(reinterpret_cast<const char*>(&s.attributes[i]), sizeof(uint16_t)); } } template<typename T, typename streamT> void write(streamT& out, basic_solid<T>& s, bool binary) { s.vertices.resize(3 * s.normals.size()); if (binary) write_binary(out, s); else write_ascii(out, s); } } } BOOST_FUSION_ADAPT_TPL_STRUCT( (T), (tyti::stl::basic_solid)(T), (std::string, header), (std::vector< tyti::stl::basic_vec3<T> >, normals), (std::vector< tyti::stl::basic_vec3<T> >, vertices), (std::vector<std::uint16_t>, attributes) ); BOOST_FUSION_ADAPT_TPL_STRUCT( (T), (tyti::stl::basic_vec3)(T), (T, data[0]) (T, data[1]) (T, data[2]) );
#pragma once #include <vector> #include <type_traits> #include <utility> #include <fstream> #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/fusion/include/adapt_struct.hpp> namespace tyti { namespace stl { template<typename T> struct basic_vec3 { using scalar_type = T; static_assert(std::is_floating_point<scalar_type>::value, "T must be a floating point"); T data[3]; basic_vec3():data{T(0),T(0),T(0)}{} basic_vec3(T x, T y, T z):data{x,y,z}{} T operator[](size_t i)const {return data[i];} const T &operator[](size_t i) { return data[i]; } }; using dvec3 = basic_vec3<double>; using vec3 = basic_vec3<float>; template<typename T> struct basic_solid { using vec3 = basic_vec3<T>; using scalar_type = T; std::string header; std::vector<vec3> normals; std::vector<vec3> vertices; std::vector<std::uint16_t> attributes; }; using dsolid = basic_solid<double>; using solid = basic_solid<float>; template <typename T, typename Iterator> struct stl_parser_ascii : boost::spirit::qi::grammar<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> { stl_parser_ascii() : stl_parser_ascii::base_type(start) { namespace qi = boost::spirit::qi; namespace ql = qi::labels; namespace ascii = boost::spirit::ascii; namespace fusion = boost::fusion; namespace px = boost::phoenix; startSolid %= qi::lexeme[qi::lit("solid ") >> (+(ascii::char_ - qi::eol) | qi::attr(""))]; endSolid = qi::lexeme[qi::lit("endsolid ") >> ascii::string(ql::_r1)]; vector %= qi::float_ >> qi::float_ >> qi::float_; start = startSolid[px::at_c<0>(ql::_val) = ql::_1] >> *(qi::lit("facet") >> qi::lit("normal") >> vector[px::push_back(px::at_c<1>(ql::_val), ql::_1)] >> qi::lit("outer loop") >> qi::repeat(3)[qi::lit("vertex") >> vector[px::push_back(px::at_c<2>(ql::_val), ql::_1)]] >> qi::lit("endloop") >> qi::lit("endfacet") ) >> endSolid(px::at_c<0>(ql::_val)) ; } boost::spirit::qi::rule<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> start; boost::spirit::qi::rule<Iterator, std::string(), boost::spirit::ascii::space_type> startSolid; boost::spirit::qi::rule<Iterator, basic_vec3<T>(), boost::spirit::ascii::space_type> vector; boost::spirit::qi::rule<Iterator, void(std::string), boost::spirit::ascii::space_type> endSolid; }; template <typename T, typename Iterator> struct stl_parser_binary : boost::spirit::qi::grammar<Iterator, basic_solid<T>()> { stl_parser_binary() : stl_parser_binary::base_type(start) { namespace spirit = boost::spirit; namespace qi = boost::spirit::qi; namespace ql = qi::labels; namespace ascii = boost::spirit::ascii; namespace px = boost::phoenix; vector %= spirit::little_bin_float >> spirit::little_bin_float >> spirit::little_bin_float; start = qi::repeat(80)[spirit::byte_[px::at_c<0>(ql::_val) += ql::_1]] >> spirit::little_dword[px::reserve(px::at_c<1>(ql::_val), ql::_1), px::reserve(px::at_c<2>(ql::_val), 3 * ql::_1), px::reserve(px::at_c<3>(ql::_val), ql::_1)] >> *(vector[px::push_back(px::at_c<1>(ql::_val), ql::_1)] >> spirit::repeat(3)[vector[px::push_back(px::at_c<2>(ql::_val), ql::_1)]] >> spirit::little_word[px::push_back(px::at_c<3>(ql::_val), ql::_1)] ) ; } boost::spirit::qi::rule<Iterator, basic_solid<T>()> start; boost::spirit::qi::rule<Iterator, basic_vec3<T>()> vector; boost::spirit::qi::rule<Iterator, void(std::string)> endSolid; }; template <typename T, typename Iterator> struct stl_parser : boost::spirit::qi::grammar<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> { stl_parser() : stl_parser::base_type(start) { start %= stl_ascii_ | boost::spirit::qi::lexeme[stl_binary_]; } stl_parser_ascii<T, Iterator> stl_ascii_; stl_parser_binary<T, Iterator> stl_binary_; boost::spirit::qi::rule<Iterator, basic_solid<T>(), boost::spirit::ascii::space_type> start; }; template<typename T, typename IterT> inline bool read(basic_solid<T>& out, IterT begin, IterT end) { stl_parser< T, IterT > p; return boost::spirit::qi::phrase_parse(begin, end, p, boost::spirit::ascii::space, out); } template<typename T, typename IterT> inline std::pair< basic_solid<T>, bool > read(IterT begin, IterT end) { basic_solid<T> o; bool r = read(o, begin, end); return std::make_pair<basic_solid<T>, bool>(std::move(o), std::move(r)); } template<typename IterT>
const size_t num_triangles{ s.normals.size() }; s.attributes.resize(num_triangles); out.write(reinterpret_cast<const char*>(&num_triangles), 4); out << num_triangles; for (size_t i = 0; i < num_triangles; ++i) { detail::write_vectorF32(out, s.normals[i].data); for (size_t j = 0; j < 3; ++j) detail::write_vectorF32(out, s.vertices[3 * i + j].data); out.write(reinterpret_cast<const char*>(&s.attributes[i]), sizeof(uint16_t)); } } template<typename T, typename streamT> void write(streamT& out, basic_solid<T>& s, bool binary) { s.vertices.resize(3 * s.normals.size()); if (binary) write_binary(out, s); else write_ascii(out, s); } } } BOOST_FUSION_ADAPT_TPL_STRUCT( (T), (tyti::stl::basic_solid)(T), (std::string, header), (std::vector< tyti::stl::basic_vec3<T> >, normals), (std::vector< tyti::stl::basic_vec3<T> >, vertices), (std::vector<std::uint16_t>, attributes) ); BOOST_FUSION_ADAPT_TPL_STRUCT( (T), (tyti::stl::basic_vec3)(T), (T, data[0]) (T, data[1]) (T, data[2]) );
inline std::pair< solid, bool > read(IterT begin, IterT end) { return read<float>(begin, end); } template<typename T> inline bool read(basic_solid<T>& out, const std::string& fileName) { std::ifstream f(fileName, std::ios::binary); std::string str; f.seekg(0, std::ios::end); str.resize((unsigned)f.tellg()); f.seekg(0, std::ios::beg); f.read(&str[0], str.size()); f.close(); return read<T>(out, str.cbegin(), str.cend()); } template<typename T> inline std::pair<basic_solid<T>, bool> read(const std::string& fileName) { basic_solid<T> out; bool r = read(out, fileName); return std::make_pair<basic_solid<T>, bool>(std::move(out), std::move(r)); } inline std::pair<solid, bool> read(const std::string& fileName) { return read<float>(fileName); } template<typename T, typename streamT> void write_ascii(streamT& out, const basic_solid<T>&s) { out << "solid " << s.header << "\n"; for (size_t i = 0; i < s.normals.size(); ++i) { out << "\tfacet normal " << s.normals[i][0] << " " << s.normals[i][1] << " " << s.normals[i][2] << " " << "\n"; out << "\t\touter loop\n"; for (size_t j = 0; j < 3; ++j) { out << "\t\t\tvertex " << s.vertices[3 * i + j][0] << " " << s.vertices[3 * i + j][1] << " " << s.vertices[3 * i + j][2] << " " << "\n"; } out << "\t\tendloop\n" << "\tendfacet\n"; } out << "endsolid " << s.header << "\n"; } namespace detail { template<typename streamT> inline void write_vectorF32(streamT& out, const double* p) { for (size_t i = 0; i < 3; ++i) { const float f = static_cast<float>(p[i]); out.write(reinterpret_cast<const char *>(p), sizeof(float)); } } template<typename streamT> inline void write_vectorF32(streamT& out, const float* p) { out.write(reinterpret_cast<const char*>(p), sizeof(float) * 3); } } template<typename T, typename streamT> void write_binary(streamT& out, basic_solid<T>&s) { s.header.resize(80); out.write(&s.header[0], 80);
random
[ { "content": "#define BOOST_TEST_MODULE STL_IO\n\n\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <boost/mpl/list.hpp>\n\n\n\n#include <sstream>\n\n\n\n#include \"../stlio.hpp\"\n\n\n\nusing test_types = boost::mpl::list<float, double>;\n\n\n\nusing namespace tyti;\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(read_ascii_from_string, T, test_types)\n\n{\n\n using solid = stl::basic_solid<T>;\n\n std::string str = \"solid Hi you\\n \\\n\n facet normal 0.5 0.6 0.7\\n\\\n\n outer loop\\n\\\n\n vertex 0.5 0.6 0.7\\n\\\n", "file_path": "test/stl_parser_test.cpp", "rank": 0, "score": 11115.289688987395 }, { "content": " vertex 0.5 0.6 0.7\\n\\\n\n vertex 0.5 0.6 0.7\\n\\\n\n endloop\\n\\\n\n endfacet\\n\\\n\n endsolid Hi you\\n\";\n\n\n\n auto out = stl::read<T>(str.begin(), str.end());\n\n\n\n BOOST_TEST(out.second);\n\n solid& s = out.first;\n\n BOOST_TEST(s.header == \"Hi you\");\n\n BOOST_TEST(s.normals.size() == 1);\n\n BOOST_TEST(s.vertices.size() == 3);\n\n BOOST_TEST(s.attributes.size() == 0);\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(read_ascii_from_file, T, test_types)\n\n{\n\n const std::string test_data{ SOURCE_DIR \"/testdata/cube_ascii.stl\" };\n\n\n", "file_path": "test/stl_parser_test.cpp", "rank": 1, "score": 11112.840945052321 }, { "content": "}\n\n\n\ntemplate<typename T>\n\nvoid simple_read_test(bool binary)\n\n{\n\n using solid = stl::basic_solid<T>;\n\n using vec3 = stl::basic_vec3<T>;\n\n\n\n T n = T(1.0);\n\n vec3 vec_n(n, n, n);\n\n\n\n solid to_write;\n\n to_write.vertices.push_back(vec_n);\n\n to_write.vertices.push_back(vec_n);\n\n to_write.vertices.push_back(vec_n);\n\n to_write.normals.push_back(vec_n);\n\n\n\n std::stringstream sstream;\n\n stl::write(sstream, to_write, binary);\n\n\n", "file_path": "test/stl_parser_test.cpp", "rank": 2, "score": 11112.578891802792 }, { "content": " std::string str_w = sstream.str();\n\n auto out = stl::read<T>(str_w.begin(), str_w.end());\n\n BOOST_TEST(out.second);\n\n\n\n solid cmp = out.first;\n\n BOOST_TEST(to_write.header == cmp.header);\n\n BOOST_TEST(to_write.vertices.size() == cmp.vertices.size());\n\n BOOST_TEST(to_write.normals.size() == cmp.normals.size());\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(write_binary, T, test_types)\n\n{\n\n simple_read_test<T>(true);\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(write_ascii, T, test_types)\n\n{\n\n simple_read_test<T>(false);\n\n}", "file_path": "test/stl_parser_test.cpp", "rank": 3, "score": 11110.098238485776 }, { "content": " auto out = stl::read<T>(test_data);\n\n BOOST_TEST(out.second);\n\n stl::basic_solid<T>& s = out.first;\n\n\n\n BOOST_TEST(s.normals.size() == 12);\n\n BOOST_TEST(s.vertices.size() == 3*12);\n\n BOOST_TEST(s.attributes.size() == 0);\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(read_binary_from_file, T, test_types)\n\n{\n\n const std::string test_data{ SOURCE_DIR \"/testdata/cube_binary.stl\" };\n\n\n\n auto out = stl::read<T>(test_data);\n\n BOOST_TEST(out.second);\n\n stl::basic_solid<T>& s = out.first;\n\n\n\n BOOST_TEST(s.normals.size() == 12);\n\n BOOST_TEST(s.vertices.size() == 3 * 12);\n\n BOOST_TEST(s.attributes.size() == 12);\n", "file_path": "test/stl_parser_test.cpp", "rank": 4, "score": 11108.96588228026 }, { "content": "# STL File Reader and Writer\n\nReads and writes STL files for 3D Geometry.\n\n\n\n## Install\n\nHeader only\n\n\n\n## Dependencies:\n\n - [Boost.Spirit](http://www.boost.org/)\n\n - [Boost.Test (for tests)](http://www.boost.org/)\n\n\n\n## Small and Fast Reference\n\nUse one of the read functions in namespace `tyti::stl`.\n\n\n\nPossible scalar values for the template `float, double`, default is `float`.\n\n\n\n```c++\n\n//////////////////////////////////////////////////////////////\n\n// Reader Functions:\n\ntemplate<typename T, typename IterT>\n\ninline bool read(basic_solid<T>& out, IterT begin, IterT end)\n\ntemplate<typename T, typename IterT>\n\ninline std::pair< basic_solid<T>, bool > read(IterT begin, IterT end)\n\ntemplate<typename IterT>\n\ninline std::pair< solid, bool > read(IterT begin, IterT end)\n\n\n\n//////////////////////////////////////////////////////////////\n\n// Writer Functions: (streamT is an output stream type)\n\ntemplate<typename T, typename streamT>\n\nvoid write(streamT& out, basic_solid<T>& s, bool binary)\n\ntemplate<typename T, typename streamT>\n\nvoid write_binary(streamT& out, basic_solid<T>&s)\n\ntemplate<typename T, typename streamT>\n\nvoid write_ascii(streamT& out, basic_solid<T>&s)\n\n\n\n// Remark: the solid parameter is not constant to ensure the correct size of the containers.\n\n// You may want to rewrite those functions corresponding on your error-checking presumptions\n\n\n\n// The write functions were just written as a proof of concept and you may want to avoid them\n\n\n\n//////////////////////////////////////////////////////////////\n\n// Output DataType:\n\ntemplate<typename T>\n\nstruct basic_solid\n\n{\n\n using vec3 = basic_vec3<T>;\n\n using scalar_type = T;\n\n std::string header; //solid name or header\n\n std::vector<vec3> normals;\n\n std::vector<vec3> vertices;\n\n std::vector<std::uint16_t> attributes; //only available in binary files\n\n};\n\n\n\ntypedef basic_solid<float> solid;\n\ntypedef basic_solid<float> dsolid;\n\n\n\ntemplate<typename T>\n\nstruct basic_vec3\n\n{\n\n using scalar_type = T;\n\n T data[3];\n\n};\n\n\n\ntypedef basic_vec3<float> vec3;\n\ntypedef basic_vec3<float> dvec3;\n\n```\n\n\n\n\n\n## License\n\n\n\n[MIT License](./LICENSE) © Matthias Möller. Made with ♥ in Germany.\n", "file_path": "Readme.md", "rank": 5, "score": 6357.771984835941 } ]
C++
mxflib/vbi.cpp
Jamaika1/mxflib
7eefe6da1f76f7de4f2de48322311533369f8ba5
#include <mxflib/mxflib.h> using namespace mxflib; int ANCVBISource::Field2Offset(void) { if(F2Offset >= 0) return F2Offset; MDObjectPtr Descriptor = MasterSource->GetDescriptor(); if(!Descriptor) { error("EssenceDescriptor not defined for master source of ANCVBISource before calling Field2Offset()\n"); F2Offset = 0; return F2Offset; } if(Descriptor->IsA(MultipleDescriptor_UL)) { MDObject::iterator it = Descriptor->begin(); while(it != Descriptor->end()) { if((*it).second->IsA(GenericPictureEssenceDescriptor_UL)) { Descriptor = (*it).second; break; } it++; } } if(Descriptor->IsDValue(FrameLayout_UL)) { warning("EssenceDescriptor for ANCVBISource does not have a valid FrameLayout\n"); F2Offset = 0; return F2Offset; } if(Descriptor->GetInt(FrameLayout_UL) != 1) { F2Offset = 0; return F2Offset; } MDObjectPtr VideoLineMap = Descriptor->Child(VideoLineMap_UL); if(!VideoLineMap) { error("EssenceDescriptor for ANCVBISource does not have a valid VideoLineMap\n"); F2Offset = 0; return F2Offset; } MDObjectPtr F1Entry = VideoLineMap->Child(0); MDObjectPtr F2Entry = VideoLineMap->Child(1); if((!F1Entry) || (!F2Entry)) { error("EssenceDescriptor for ANCVBISource does not have a valid VideoLineMap\n"); F2Offset = 0; return F2Offset; } F2Offset = static_cast<int>(F2Entry->GetInt() - F1Entry->GetInt()); return F2Offset; } DataChunkPtr ANCVBISource::BuildChunk(void) { ANCVBILineSourceList::iterator LS_it = Sources.begin(); while(LS_it != Sources.end()) { int LineNumber = (*LS_it)->GetLineNumber(); if((*LS_it)->GetField() == 2) LineNumber += Field2Offset(); Lines.insert(ANCLineMap::value_type( LineNumber, new ANCLine(LineNumber, (*LS_it)->GetWrappingType(), (*LS_it)->GetSampleCoding(), (*LS_it)->GetLineData(), (*LS_it)->GetDID(), (*LS_it)->GetSDID()))); LS_it++; } if(Lines.empty()) { DataChunkPtr Ret = new DataChunk(2); PutU16(0, Ret->Data); return Ret; } VBILineMap::iterator it = Lines.begin(); size_t BufferSize = ((*it).second->GetFullDataSize() * Lines.size()) + 2; DataChunkPtr Ret = new DataChunk(BufferSize); UInt8 *pBuffer = Ret->Data; PutU16(static_cast<UInt16>(Lines.size()), Ret->Data); pBuffer += 2; BufferSize -= 2; while(it != Lines.end()) { size_t RequiredBytes = (*it).second->GetFullDataSize(); if(RequiredBytes > BufferSize) { size_t CurrentPos = pBuffer - Ret->Data; Ret->Resize(static_cast<UInt32>(CurrentPos + RequiredBytes)); BufferSize = RequiredBytes; pBuffer = &Ret->Data[CurrentPos]; } (*it).second->WriteData(pBuffer); pBuffer += RequiredBytes; BufferSize -= RequiredBytes; it++; } Ret->Resize(static_cast<UInt32>(pBuffer - Ret->Data)); Lines.clear(); return Ret; } void ANCVBILine::WriteData(UInt8 *Buffer) { PutU16( LineNumber, Buffer); Buffer[2] = static_cast<UInt8>(WrappingType); Buffer[3] = static_cast<UInt8>(SampleCoding); PutU16(static_cast<UInt16>(SampleCount), &Buffer[4]); if(Data.Data) { PutU32(static_cast<UInt32>(Data.Size), &Buffer[6]); PutU32(1, &Buffer[10]); memcpy(&Buffer[14], Data.Data, Data.Size); } else { PutU32(0, &Buffer[6]); PutU32(1, &Buffer[10]); } } bool ANCVBISource::EndSignalled(void) { if(EndAtPosition < 0) { if(!MasterSource) return true; if(MasterSource->EndOfData()) EndAtPosition = MasterSource->GetCurrentPosition(); else EndAtPosition = 0; CurrentPosition = 0; } if(EndAtPosition) { if(CurrentPosition >= EndAtPosition) return true; else return false; } return MasterSource->EndOfData(); } size_t ANCVBISource::GetEssenceDataSize(void) { if(BufferedData.empty()) { if(EndSignalled()) return 0; BufferedData.push_back(BuildChunk()); } return static_cast<size_t>(BufferedData.front()->Size); } DataChunkPtr ANCVBISource::GetEssenceData(size_t Size , size_t MaxSize ) { if(BodyParent) CurrentPosition = BodyParent->GetPosition(); else if(MasterSource) CurrentPosition = MasterSource->GetCurrentPosition() - 1; if(BufferedData.empty()) { if(EndSignalled()) return NULL; BufferedData.push_back(BuildChunk()); } if(IndexMan) IndexMan->OfferEditUnit(IndexStreamID, CurrentPosition, 0, 0x80); CurrentPosition++; if((BufferOffset == 0) && ((MaxSize == 0) || (BufferedData.front()->Size <= MaxSize))) { DataChunkPtr Ret = BufferedData.front(); BufferedData.pop_front(); return Ret; } size_t Bytes = BufferedData.front()->Size - BufferOffset; if(Bytes <= MaxSize) { DataChunkPtr Ret = new DataChunk(Bytes); Ret->Set(static_cast<UInt32>(Bytes), BufferedData.front()->Data); BufferedData.pop_front(); BufferOffset = 0; return Ret; } DataChunkPtr Ret = new DataChunk(MaxSize); Ret->Set(static_cast<UInt32>(MaxSize), BufferedData.front()->Data); BufferOffset -= MaxSize; return Ret; } EssenceParser::WrappingConfigPtr ANCVBISource::MakeWrappingConfig(WrappingConfigPtr MasterCfg) { EssenceParser::WrappingConfigPtr SubCfg; if(MasterCfg->WrapOpt->ThisWrapType != WrappingOption::Frame) return SubCfg; if(Sources.empty()) return SubCfg; std::string Description; ANCVBILineSourceList::iterator it = Sources.begin(); while(it != Sources.end()) { std::string ThisDesc = (*it)->ValidateConfig(MasterCfg); if(ThisDesc.empty()) return SubCfg; if(!Description.empty()) Description += ", plus "; Description += ThisDesc; it++; } SubCfg = new EssenceParser::WrappingConfig(); SubCfg->Parser = MasterCfg->Parser; SubCfg->WrapOpt = new WrappingOption(); SubCfg->WrapOpt->Handler = SubCfg->Parser; SubCfg->WrapOpt->Name = ""; SubCfg->WrapOpt->Description = Description; SubCfg->WrapOpt->GCEssenceType = GetGCEssenceType(); SubCfg->WrapOpt->GCElementType = GetGCElementType(); SubCfg->WrapOpt->ThisWrapType = MasterCfg->WrapOpt->ThisWrapType; SubCfg->WrapOpt->CanSlave = false; SubCfg->WrapOpt->CanIndex = true; SubCfg->WrapOpt->CBRIndex = false; SubCfg->WrapOpt->BERSize = 4; SubCfg->WrapOpt->BytesPerEditUnit = 0; SubCfg->WrapOpt->WrappingUL = GetWrappingUL(); SubCfg->EssenceDescriptor = new MDObject(ANCDataDescriptor_UL); MDObjectPtr SampleRate = SubCfg->EssenceDescriptor->AddChild(SampleRate_UL); SampleRate->SetInt("Numerator", MasterCfg->EditRate.Numerator); SampleRate->SetInt("Denominator", MasterCfg->EditRate.Denominator); SubCfg->EssenceDescriptor->SetValue(EssenceContainer_UL, DataChunk(16,SubCfg->WrapOpt->WrappingUL->GetValue())); SubCfg->Stream = 0; SubCfg->EditRate = MasterCfg->EditRate; SubCfg->StartTimecode = 0; return SubCfg; } std::string SimpleAFDSource::ValidateConfig(WrappingConfigPtr MasterCfg) { if(FieldNum == 1) return "Fixed F1 AFD of 0x" + Int64toHexString(CurrentAFD); return "Fixed F2 AFD of 0x" + Int64toHexString(CurrentAFD); } UInt8 SimpleAFDSource::TextToAFD(std::string Text) { bool Wide = false; UInt8 Ret = 0; std::string::iterator it = Text.begin(); while(it != Text.end()) { if(*it == '1') Ret = (Ret << 1) | 1; else if(*it == '0') Ret = (Ret << 1); else if(tolower(*it) == 'w') Wide = true; it++; } return Wide ? (Ret << 3) | 4 : (Ret << 3); }
#include <mxflib/mxflib.h> using namespace mxflib; int ANCVBISource::Field2Offset(void) { if(F2Offset >= 0) return F2Offset; MDObjectPtr Descriptor = MasterSource->GetDescriptor(); if(!Descriptor) { error("EssenceDescriptor not defined for master source of ANCVBISource before calling Field2Offset()\n"); F2Offset = 0; return F2Offset; } if(Descriptor->IsA(MultipleDescriptor_UL)) { MDObject::iterator it = Descriptor->begin(); while(it != Descriptor->end()) { if((*it).second->IsA(GenericPictureEssenceDescriptor_UL)) { Descriptor = (*it).second; break; } it++; } } if(Descriptor->IsDValue(FrameLayout_UL)) { warning("EssenceDescriptor for ANCVBISource does not have a valid FrameLayout\n"); F2Offset = 0; return F2Offset; } if(Descriptor->GetInt(FrameLayout_UL) != 1) { F2Offset = 0; return F2Offset; } MDObjectPtr VideoLineMap = Descriptor->Child(VideoLineMap_UL); if(!VideoLineMap) { error("EssenceDescriptor for ANCVBISource does not have a valid VideoLineMap\n"); F2Offset = 0; return F2Offset; } MDObjectPtr F1Entry = VideoLineMap->Child(0); MDObjectPtr F2Entry = VideoLineMap->Child(1); if((!F1Entry) || (!F2Entry)) { error("EssenceDescriptor for ANCVBISource does not have a valid VideoLineMap\n"); F2Offset = 0; return F2Offset; } F2Offset = static_cast<int>(F2Entry->GetInt() - F1Entry->GetInt()); return F2Offset; } DataChunkPtr ANCVBISource::BuildChunk(void) { ANCVBILineSourceList::iterator LS_it = Sources.begin(); while(LS_it != Sources.end()) { int LineNumber = (*LS_it)->GetLineNumber(); if((*LS_it)->GetField() == 2) LineNumber += Field2Offset(); Lines.insert(
); LS_it++; } if(Lines.empty()) { DataChunkPtr Ret = new DataChunk(2); PutU16(0, Ret->Data); return Ret; } VBILineMap::iterator it = Lines.begin(); size_t BufferSize = ((*it).second->GetFullDataSize() * Lines.size()) + 2; DataChunkPtr Ret = new DataChunk(BufferSize); UInt8 *pBuffer = Ret->Data; PutU16(static_cast<UInt16>(Lines.size()), Ret->Data); pBuffer += 2; BufferSize -= 2; while(it != Lines.end()) { size_t RequiredBytes = (*it).second->GetFullDataSize(); if(RequiredBytes > BufferSize) { size_t CurrentPos = pBuffer - Ret->Data; Ret->Resize(static_cast<UInt32>(CurrentPos + RequiredBytes)); BufferSize = RequiredBytes; pBuffer = &Ret->Data[CurrentPos]; } (*it).second->WriteData(pBuffer); pBuffer += RequiredBytes; BufferSize -= RequiredBytes; it++; } Ret->Resize(static_cast<UInt32>(pBuffer - Ret->Data)); Lines.clear(); return Ret; } void ANCVBILine::WriteData(UInt8 *Buffer) { PutU16( LineNumber, Buffer); Buffer[2] = static_cast<UInt8>(WrappingType); Buffer[3] = static_cast<UInt8>(SampleCoding); PutU16(static_cast<UInt16>(SampleCount), &Buffer[4]); if(Data.Data) { PutU32(static_cast<UInt32>(Data.Size), &Buffer[6]); PutU32(1, &Buffer[10]); memcpy(&Buffer[14], Data.Data, Data.Size); } else { PutU32(0, &Buffer[6]); PutU32(1, &Buffer[10]); } } bool ANCVBISource::EndSignalled(void) { if(EndAtPosition < 0) { if(!MasterSource) return true; if(MasterSource->EndOfData()) EndAtPosition = MasterSource->GetCurrentPosition(); else EndAtPosition = 0; CurrentPosition = 0; } if(EndAtPosition) { if(CurrentPosition >= EndAtPosition) return true; else return false; } return MasterSource->EndOfData(); } size_t ANCVBISource::GetEssenceDataSize(void) { if(BufferedData.empty()) { if(EndSignalled()) return 0; BufferedData.push_back(BuildChunk()); } return static_cast<size_t>(BufferedData.front()->Size); } DataChunkPtr ANCVBISource::GetEssenceData(size_t Size , size_t MaxSize ) { if(BodyParent) CurrentPosition = BodyParent->GetPosition(); else if(MasterSource) CurrentPosition = MasterSource->GetCurrentPosition() - 1; if(BufferedData.empty()) { if(EndSignalled()) return NULL; BufferedData.push_back(BuildChunk()); } if(IndexMan) IndexMan->OfferEditUnit(IndexStreamID, CurrentPosition, 0, 0x80); CurrentPosition++; if((BufferOffset == 0) && ((MaxSize == 0) || (BufferedData.front()->Size <= MaxSize))) { DataChunkPtr Ret = BufferedData.front(); BufferedData.pop_front(); return Ret; } size_t Bytes = BufferedData.front()->Size - BufferOffset; if(Bytes <= MaxSize) { DataChunkPtr Ret = new DataChunk(Bytes); Ret->Set(static_cast<UInt32>(Bytes), BufferedData.front()->Data); BufferedData.pop_front(); BufferOffset = 0; return Ret; } DataChunkPtr Ret = new DataChunk(MaxSize); Ret->Set(static_cast<UInt32>(MaxSize), BufferedData.front()->Data); BufferOffset -= MaxSize; return Ret; } EssenceParser::WrappingConfigPtr ANCVBISource::MakeWrappingConfig(WrappingConfigPtr MasterCfg) { EssenceParser::WrappingConfigPtr SubCfg; if(MasterCfg->WrapOpt->ThisWrapType != WrappingOption::Frame) return SubCfg; if(Sources.empty()) return SubCfg; std::string Description; ANCVBILineSourceList::iterator it = Sources.begin(); while(it != Sources.end()) { std::string ThisDesc = (*it)->ValidateConfig(MasterCfg); if(ThisDesc.empty()) return SubCfg; if(!Description.empty()) Description += ", plus "; Description += ThisDesc; it++; } SubCfg = new EssenceParser::WrappingConfig(); SubCfg->Parser = MasterCfg->Parser; SubCfg->WrapOpt = new WrappingOption(); SubCfg->WrapOpt->Handler = SubCfg->Parser; SubCfg->WrapOpt->Name = ""; SubCfg->WrapOpt->Description = Description; SubCfg->WrapOpt->GCEssenceType = GetGCEssenceType(); SubCfg->WrapOpt->GCElementType = GetGCElementType(); SubCfg->WrapOpt->ThisWrapType = MasterCfg->WrapOpt->ThisWrapType; SubCfg->WrapOpt->CanSlave = false; SubCfg->WrapOpt->CanIndex = true; SubCfg->WrapOpt->CBRIndex = false; SubCfg->WrapOpt->BERSize = 4; SubCfg->WrapOpt->BytesPerEditUnit = 0; SubCfg->WrapOpt->WrappingUL = GetWrappingUL(); SubCfg->EssenceDescriptor = new MDObject(ANCDataDescriptor_UL); MDObjectPtr SampleRate = SubCfg->EssenceDescriptor->AddChild(SampleRate_UL); SampleRate->SetInt("Numerator", MasterCfg->EditRate.Numerator); SampleRate->SetInt("Denominator", MasterCfg->EditRate.Denominator); SubCfg->EssenceDescriptor->SetValue(EssenceContainer_UL, DataChunk(16,SubCfg->WrapOpt->WrappingUL->GetValue())); SubCfg->Stream = 0; SubCfg->EditRate = MasterCfg->EditRate; SubCfg->StartTimecode = 0; return SubCfg; } std::string SimpleAFDSource::ValidateConfig(WrappingConfigPtr MasterCfg) { if(FieldNum == 1) return "Fixed F1 AFD of 0x" + Int64toHexString(CurrentAFD); return "Fixed F2 AFD of 0x" + Int64toHexString(CurrentAFD); } UInt8 SimpleAFDSource::TextToAFD(std::string Text) { bool Wide = false; UInt8 Ret = 0; std::string::iterator it = Text.begin(); while(it != Text.end()) { if(*it == '1') Ret = (Ret << 1) | 1; else if(*it == '0') Ret = (Ret << 1); else if(tolower(*it) == 'w') Wide = true; it++; } return Wide ? (Ret << 3) | 4 : (Ret << 3); }
ANCLineMap::value_type( LineNumber, new ANCLine(LineNumber, (*LS_it)->GetWrappingType(), (*LS_it)->GetSampleCoding(), (*LS_it)->GetLineData(), (*LS_it)->GetDID(), (*LS_it)->GetSDID()))
call_expression
[ { "content": "namespace mxflib {}\n", "file_path": "mxflib/mxflib.h", "rank": 0, "score": 89973.22926212748 }, { "content": "namespace mxflib\n\n{\n\n\n\n\t//! Load classes and types from a Metadictionary object\n\n\t/*! At the point where this function is called, you need to have all the component parts loaded and\n\n\t * all the strong references within the metadictionary need to be satisfied\n\n\t */\n\n\tbool LoadMetadictionary(MDObjectPtr &Meta, SymbolSpacePtr &SymSpace);\n\n\n\n\t//! Build a metadictionary from current classes and types used in a given list of metadata trees\n\n\t/*! If Meta is supplied, then all classes in the trees strongly linked from it are written to the metadictionary, \n\n\t * including all properties of those classes (whether used or not) and any types used by those properties\n\n\t */\n\n\tMDObjectPtr BuildMetadictionary(MDObjectList &MetaList, Primer *UsePrimer);\n", "file_path": "mxflib/metadict.h", "rank": 1, "score": 86374.1332027388 }, { "content": "\tnamespace mxflib\n\n\t{\n\n\t\tconst UInt8 AES3PCMDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x47, 0x00 };\n\n\t\tconst UL AES3PCMDescriptor_UL(AES3PCMDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 ANCDataDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x5c, 0x00 };\n\n\t\tconst UL ANCDataDescriptor_UL(ANCDataDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 ATSCA52_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x04, 0x02, 0x02, 0x02, 0x03, 0x02, 0x01, 0x00 };\n\n\t\tconst UL ATSCA52_UL(ATSCA52_UL_Data);\n\n\n\n\t\tconst UInt8 AUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AUID_UL(AUID_UL_Data);\n\n\n\n\t\tconst UInt8 AUIDArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AUIDArray_UL(AUIDArray_UL_Data);\n\n\n\n\t\tconst UInt8 AUIDSet_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AUIDSet_UL(AUIDSet_UL_Data);\n\n\n\n\t\tconst UInt8 AUL_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AUL_UL(AUL_UL_Data);\n\n\n\n\t\tconst UInt8 AbstractObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x7f, 0x00 };\n\n\t\tconst UL AbstractObject_UL(AbstractObject_UL_Data);\n\n\n\n\t\tconst UInt8 ActiveFormatDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x03, 0x02, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ActiveFormatDescriptor_UL(ActiveFormatDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 AlphaMaxRef_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x05, 0x03, 0x0d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AlphaMaxRef_UL(AlphaMaxRef_UL_Data);\n\n\n\n\t\tconst UInt8 AlphaMinRef_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x05, 0x03, 0x0e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AlphaMinRef_UL(AlphaMinRef_UL_Data);\n\n\n\n\t\tconst UInt8 AlphaSampleDepth_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AlphaSampleDepth_UL(AlphaSampleDepth_UL_Data);\n\n\n\n\t\tconst UInt8 AlphaTransparency_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AlphaTransparency_UL(AlphaTransparency_UL_Data);\n\n\n\n\t\tconst UInt8 AnnotationSource_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x0a, 0x00, 0x00 };\n\n\t\tconst UL AnnotationSource_UL(AnnotationSource_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationEnvironmentID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x0f, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ApplicationEnvironmentID_UL(ApplicationEnvironmentID_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x66, 0x00 };\n\n\t\tconst UL ApplicationObject_UL(ApplicationObject_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationPluginBatch_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x06, 0x01, 0x01, 0x04, 0x02, 0x0e, 0x00, 0x00 };\n\n\t\tconst UL ApplicationPluginBatch_UL(ApplicationPluginBatch_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationPluginInstanceID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x0d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ApplicationPluginInstanceID_UL(ApplicationPluginInstanceID_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationPluginObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x61, 0x00 };\n\n\t\tconst UL ApplicationPluginObject_UL(ApplicationPluginObject_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationReferencedObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x62, 0x00 };\n\n\t\tconst UL ApplicationReferencedObject_UL(ApplicationReferencedObject_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationScheme_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x04, 0x06, 0x08, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ApplicationScheme_UL(ApplicationScheme_UL_Data);\n\n\n\n\t\tconst UInt8 ApplicationSchemesBatch_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x01, 0x02, 0x02, 0x10, 0x02, 0x03, 0x00, 0x00 };\n\n\t\tconst UL ApplicationSchemesBatch_UL(ApplicationSchemesBatch_UL_Data);\n\n\n\n\t\tconst UInt8 AspectRatio_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AspectRatio_UL(AspectRatio_UL_Data);\n\n\n\n\t\tconst UInt8 AudioRefLevel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AudioRefLevel_UL(AudioRefLevel_UL_Data);\n\n\n\n\t\tconst UInt8 AudioSamplingRate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00 };\n\n\t\tconst UL AudioSamplingRate_UL(AudioSamplingRate_UL_Data);\n\n\n\n\t\tconst UInt8 AuxBitsMode_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x05, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AuxBitsMode_UL(AuxBitsMode_UL_Data);\n\n\n\n\t\tconst UInt8 AvgBps_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x03, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL AvgBps_UL(AvgBps_UL_Data);\n\n\n\n\t\tconst UInt8 BPictureCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x09, 0x00, 0x00 };\n\n\t\tconst UL BPictureCount_UL(BPictureCount_UL_Data);\n\n\n\n\t\tconst UInt8 BaseClass_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x06, 0x01, 0x01, 0x04, 0x01, 0x0b, 0x00, 0x00 };\n\n\t\tconst UL BaseClass_UL(BaseClass_UL_Data);\n\n\n\n\t\tconst UInt8 BitRate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x0b, 0x00, 0x00 };\n\n\t\tconst UL BitRate_UL(BitRate_UL_Data);\n\n\n\n\t\tconst UInt8 BlackRefLevel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x03, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL BlackRefLevel_UL(BlackRefLevel_UL_Data);\n\n\n\n\t\tconst UInt8 BlockAlign_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL BlockAlign_UL(BlockAlign_UL_Data);\n\n\n\n\t\tconst UInt8 BlockStartOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x02, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL BlockStartOffset_UL(BlockStartOffset_UL_Data);\n\n\n\n\t\tconst UInt8 BodyOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x08, 0x01, 0x02, 0x01, 0x03, 0x00, 0x00 };\n\n\t\tconst UL BodyOffset_UL(BodyOffset_UL_Data);\n\n\n\n\t\tconst UInt8 BodySID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x01, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL BodySID_UL(BodySID_UL_Data);\n\n\n\n\t\tconst UInt8 Boolean_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Boolean_UL(Boolean_UL_Data);\n\n\n\n\t\tconst UInt8 Build_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Build_UL(Build_UL_Data);\n\n\n\n\t\tconst UInt8 ByteOrder_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ByteOrder_UL(ByteOrder_UL_Data);\n\n\n\n\t\tconst UInt8 CDCIEssenceDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x28, 0x00 };\n\n\t\tconst UL CDCIEssenceDescriptor_UL(CDCIEssenceDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 ChannelAssignment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x07, 0x04, 0x02, 0x01, 0x01, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChannelAssignment_UL(ChannelAssignment_UL_Data);\n\n\n\n\t\tconst UInt8 ChannelCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x01, 0x01, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChannelCount_UL(ChannelCount_UL_Data);\n\n\n\n\t\tconst UInt8 ChannelIDs_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x07, 0x06, 0x01, 0x01, 0x03, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChannelIDs_UL(ChannelIDs_UL_Data);\n\n\n\n\t\tconst UInt8 ChannelStatusMode_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChannelStatusMode_UL(ChannelStatusMode_UL_Data);\n\n\n\n\t\tconst UInt8 ChannelStatusModeType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x25, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChannelStatusModeType_UL(ChannelStatusModeType_UL_Data);\n\n\n\n\t\tconst UInt8 ChunkData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x07, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChunkData_UL(ChunkData_UL_Data);\n\n\n\n\t\tconst UInt8 ChunkID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x06, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChunkID_UL(ChunkID_UL_Data);\n\n\n\n\t\tconst UInt8 ChunkLength_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x06, 0x09, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ChunkLength_UL(ChunkLength_UL_Data);\n\n\n\n\t\tconst UInt8 CipherAlgorithm_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x02, 0x09, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL CipherAlgorithm_UL(CipherAlgorithm_UL_Data);\n\n\n\n\t\tconst UInt8 CipherAlgorithmAES128CBC_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x07, 0x02, 0x09, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL CipherAlgorithmAES128CBC_UL(CipherAlgorithmAES128CBC_UL_Data);\n\n\n\n\t\tconst UInt8 ClassDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL ClassDefinition_UL(ClassDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 ClassDefinitions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ClassDefinitions_UL(ClassDefinitions_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedBodyPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x03, 0x02, 0x00 };\n\n\t\tconst UL ClosedBodyPartition_UL(ClosedBodyPartition_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedCompleteBodyPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x03, 0x04, 0x00 };\n\n\t\tconst UL ClosedCompleteBodyPartition_UL(ClosedCompleteBodyPartition_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedCompleteHeader_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02, 0x04, 0x00 };\n\n\t\tconst UL ClosedCompleteHeader_UL(ClosedCompleteHeader_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedGOP_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x06, 0x00, 0x00 };\n\n\t\tconst UL ClosedGOP_UL(ClosedGOP_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedHeader_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02, 0x02, 0x00 };\n\n\t\tconst UL ClosedHeader_UL(ClosedHeader_UL_Data);\n\n\n\n\t\tconst UInt8 Codec_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x01, 0x03, 0x00, 0x00 };\n\n\t\tconst UL Codec_UL(Codec_UL_Data);\n\n\n\n\t\tconst UInt8 CodecDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1f, 0x00 };\n\n\t\tconst UL CodecDefinition_UL(CodecDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 CodecDefinitions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x07, 0x00, 0x00 };\n\n\t\tconst UL CodecDefinitions_UL(CodecDefinitions_UL_Data);\n\n\n\n\t\tconst UInt8 CodedContentType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x04, 0x00, 0x00 };\n\n\t\tconst UL CodedContentType_UL(CodedContentType_UL_Data);\n\n\n\n\t\tconst UInt8 CodingEquations_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x02, 0x01, 0x01, 0x03, 0x01, 0x00 };\n\n\t\tconst UL CodingEquations_UL(CodingEquations_UL_Data);\n\n\n\n\t\tconst UInt8 CodingStyleDefault_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL CodingStyleDefault_UL(CodingStyleDefault_UL_Data);\n\n\n\n\t\tconst UInt8 ColorPrimaries_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x02, 0x01, 0x01, 0x06, 0x01, 0x00 };\n\n\t\tconst UL ColorPrimaries_UL(ColorPrimaries_UL_Data);\n\n\n\n\t\tconst UInt8 ColorRange_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ColorRange_UL(ColorRange_UL_Data);\n\n\n\n\t\tconst UInt8 ColorSiting_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ColorSiting_UL(ColorSiting_UL_Data);\n\n\n\n\t\tconst UInt8 CommentMarker_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x00 };\n\n\t\tconst UL CommentMarker_UL(CommentMarker_UL_Data);\n\n\n\n\t\tconst UInt8 CompanyName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL CompanyName_UL(CompanyName_UL_Data);\n\n\n\n\t\tconst UInt8 CompleteFooter_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x04, 0x04, 0x00 };\n\n\t\tconst UL CompleteFooter_UL(CompleteFooter_UL_Data);\n\n\n\n\t\tconst UInt8 ComponentDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ComponentDataDefinition_UL(ComponentDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 ComponentDepth_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ComponentDepth_UL(ComponentDepth_UL_Data);\n\n\n\n\t\tconst UInt8 ComponentLength_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x02, 0x01, 0x01, 0x03, 0x00, 0x00 };\n\n\t\tconst UL ComponentLength_UL(ComponentLength_UL_Data);\n\n\n\n\t\tconst UInt8 ComponentMaxRef_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x05, 0x03, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ComponentMaxRef_UL(ComponentMaxRef_UL_Data);\n\n\n\n\t\tconst UInt8 ComponentMinRef_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x05, 0x03, 0x0c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ComponentMinRef_UL(ComponentMinRef_UL_Data);\n\n\n\n\t\tconst UInt8 ConstantBFrames_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x03, 0x00, 0x00 };\n\n\t\tconst UL ConstantBFrames_UL(ConstantBFrames_UL_Data);\n\n\n\n\t\tconst UInt8 ContainerDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00 };\n\n\t\tconst UL ContainerDefinition_UL(ContainerDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 ContainerDefinitions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x08, 0x00, 0x00 };\n\n\t\tconst UL ContainerDefinitions_UL(ContainerDefinitions_UL_Data);\n\n\n\n\t\tconst UInt8 ContainerDuration_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x06, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ContainerDuration_UL(ContainerDuration_UL_Data);\n\n\n\n\t\tconst UInt8 ContentStorage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, 0x00 };\n\n\t\tconst UL ContentStorage_UL(ContentStorage_UL_Data);\n\n\n\n\t\tconst UInt8 ContentStorageObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL ContentStorageObject_UL(ContentStorageObject_UL_Data);\n\n\n\n\t\tconst UInt8 ContextID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x01, 0x01, 0x15, 0x11, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ContextID_UL(ContextID_UL_Data);\n\n\n\n\t\tconst UInt8 ContextIDLink_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x06, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ContextIDLink_UL(ContextIDLink_UL_Data);\n\n\n\n\t\tconst UInt8 ContextSR_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x04, 0x02, 0x0d, 0x00, 0x00 };\n\n\t\tconst UL ContextSR_UL(ContextSR_UL_Data);\n\n\n\n\t\tconst UInt8 CryptographicContext_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x04, 0x01, 0x02, 0x02, 0x00, 0x00 };\n\n\t\tconst UL CryptographicContext_UL(CryptographicContext_UL_Data);\n\n\n\n\t\tconst UInt8 CryptographicFramework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x04, 0x01, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL CryptographicFramework_UL(CryptographicFramework_UL_Data);\n\n\n\n\t\tconst UInt8 CryptographicFrameworkLabel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x07, 0x0d, 0x01, 0x04, 0x01, 0x02, 0x01, 0x01, 0x00 };\n\n\t\tconst UL CryptographicFrameworkLabel_UL(CryptographicFrameworkLabel_UL_Data);\n\n\n\n\t\tconst UInt8 CryptographicKeyID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x02, 0x09, 0x03, 0x01, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL CryptographicKeyID_UL(CryptographicKeyID_UL_Data);\n\n\n\n\t\tconst UInt8 Csiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Csiz_UL(Csiz_UL_Data);\n\n\n\n\t\tconst UInt8 DCinemaTimedText_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x0a, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x13, 0x01, 0x01 };\n\n\t\tconst UL DCinemaTimedText_UL(DCinemaTimedText_UL_Data);\n\n\n\n\t\tconst UInt8 DMFramework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x06, 0x01, 0x01, 0x04, 0x02, 0x0c, 0x00, 0x00 };\n\n\t\tconst UL DMFramework_UL(DMFramework_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DMS1_UL(DMS1_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1Clip_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x04, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x02, 0x02, 0x01 };\n\n\t\tconst UL DMS1Clip_UL(DMS1Clip_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1ClipExtended_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x04, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x02, 0x02, 0x02 };\n\n\t\tconst UL DMS1ClipExtended_UL(DMS1ClipExtended_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1Production_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x04, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01 };\n\n\t\tconst UL DMS1Production_UL(DMS1Production_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1ProductionExtended_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x04, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x02, 0x01, 0x02 };\n\n\t\tconst UL DMS1ProductionExtended_UL(DMS1ProductionExtended_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1Scene_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x04, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x01 };\n\n\t\tconst UL DMS1Scene_UL(DMS1Scene_UL_Data);\n\n\n\n\t\tconst UInt8 DMS1SceneExtended_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x04, 0x0d, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x02 };\n\n\t\tconst UL DMS1SceneExtended_UL(DMS1SceneExtended_UL_Data);\n\n\n\n\t\tconst UInt8 DMSCrypto_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x07, 0x0d, 0x01, 0x04, 0x01, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DMSCrypto_UL(DMSCrypto_UL_Data);\n\n\n\n\t\tconst UInt8 DMSchemes_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x02, 0x02, 0x10, 0x02, 0x02, 0x00, 0x00 };\n\n\t\tconst UL DMSchemes_UL(DMSchemes_UL_Data);\n\n\n\n\t\tconst UInt8 DMSegment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x41, 0x00 };\n\n\t\tconst UL DMSegment_UL(DMSegment_UL_Data);\n\n\n\n\t\tconst UInt8 DMSourceClip_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x45, 0x00 };\n\n\t\tconst UL DMSourceClip_UL(DMSourceClip_UL_Data);\n\n\n\n\t\tconst UInt8 DMSourceClipTrackIDs_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x07, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DMSourceClipTrackIDs_UL(DMSourceClipTrackIDs_UL_Data);\n\n\n\n\t\tconst UInt8 DM_Framework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DM_Framework_UL(DM_Framework_UL_Data);\n\n\n\n\t\tconst UInt8 DM_Set_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DM_Set_UL(DM_Set_UL_Data);\n\n\n\n\t\tconst UInt8 DataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1b, 0x00 };\n\n\t\tconst UL DataDefinition_UL(DataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 DataDefinitions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x05, 0x00, 0x00 };\n\n\t\tconst UL DataDefinitions_UL(DataDefinitions_UL_Data);\n\n\n\n\t\tconst UInt8 DataEssenceCoding_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x03, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DataEssenceCoding_UL(DataEssenceCoding_UL_Data);\n\n\n\n\t\tconst UInt8 DataEssenceTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DataEssenceTrack_UL(DataEssenceTrack_UL_Data);\n\n\n\n\t\tconst UInt8 DataValue_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DataValue_UL(DataValue_UL_Data);\n\n\n\n\t\tconst UInt8 DateStruct_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DateStruct_UL(DateStruct_UL_Data);\n\n\n\n\t\tconst UInt8 Day_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x05, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Day_UL(Day_UL_Data);\n\n\n\n\t\tconst UInt8 DefinitionObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1a, 0x00 };\n\n\t\tconst UL DefinitionObject_UL(DefinitionObject_UL_Data);\n\n\n\n\t\tconst UInt8 DefinitionObjectDescription_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x02, 0x03, 0x01, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL DefinitionObjectDescription_UL(DefinitionObjectDescription_UL_Data);\n\n\n\n\t\tconst UInt8 DefinitionObjectIdentification_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x15, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DefinitionObjectIdentification_UL(DefinitionObjectIdentification_UL_Data);\n\n\n\n\t\tconst UInt8 DefinitionObjectName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x07, 0x01, 0x02, 0x03, 0x01, 0x00, 0x00 };\n\n\t\tconst UL DefinitionObjectName_UL(DefinitionObjectName_UL_Data);\n\n\n\n\t\tconst UInt8 DeltaEntryArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x04, 0x04, 0x01, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DeltaEntryArray_UL(DeltaEntryArray_UL_Data);\n\n\n\n\t\tconst UInt8 Denominator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Denominator_UL(Denominator_UL_Data);\n\n\n\n\t\tconst UInt8 DescriptiveMetadataApplicationEnvironmentID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x10, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DescriptiveMetadataApplicationEnvironmentID_UL(DescriptiveMetadataApplicationEnvironmentID_UL_Data);\n\n\n\n\t\tconst UInt8 DescriptiveMetadataPluginID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x0e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DescriptiveMetadataPluginID_UL(DescriptiveMetadataPluginID_UL_Data);\n\n\n\n\t\tconst UInt8 DescriptiveMetadataScheme_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x04, 0x06, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DescriptiveMetadataScheme_UL(DescriptiveMetadataScheme_UL_Data);\n\n\n\n\t\tconst UInt8 DescriptiveMetadataTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x10, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DescriptiveMetadataTrack_UL(DescriptiveMetadataTrack_UL_Data);\n\n\n\n\t\tconst UInt8 Descriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x03, 0x00, 0x00 };\n\n\t\tconst UL Descriptor_UL(Descriptor_UL_Data);\n\n\n\n\t\tconst UInt8 DialNorm_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DialNorm_UL(DialNorm_UL_Data);\n\n\n\n\t\tconst UInt8 DictReferenceCodecDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DictReferenceCodecDefinition_UL(DictReferenceCodecDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 DictReferenceContainerDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DictReferenceContainerDefinition_UL(DictReferenceContainerDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 DictReferenceDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DictReferenceDataDefinition_UL(DictReferenceDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 DictReferenceVectorDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DictReferenceVectorDataDefinition_UL(DictReferenceVectorDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 Dictionaries_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x02, 0x00, 0x00 };\n\n\t\tconst UL Dictionaries_UL(Dictionaries_UL_Data);\n\n\n\n\t\tconst UInt8 Dictionary_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x22, 0x00 };\n\n\t\tconst UL Dictionary_UL(Dictionary_UL_Data);\n\n\n\n\t\tconst UInt8 DisplayF2Offset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x03, 0x02, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DisplayF2Offset_UL(DisplayF2Offset_UL_Data);\n\n\n\n\t\tconst UInt8 DisplayHeight_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DisplayHeight_UL(DisplayHeight_UL_Data);\n\n\n\n\t\tconst UInt8 DisplayWidth_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x0c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DisplayWidth_UL(DisplayWidth_UL_Data);\n\n\n\n\t\tconst UInt8 DisplayXOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x0d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DisplayXOffset_UL(DisplayXOffset_UL_Data);\n\n\n\n\t\tconst UInt8 DisplayYOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x0e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DisplayYOffset_UL(DisplayYOffset_UL_Data);\n\n\n\n\t\tconst UInt8 DropFrame_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04, 0x01, 0x01, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DropFrame_UL(DropFrame_UL_Data);\n\n\n\n\t\tconst UInt8 EditRate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x30, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL EditRate_UL(EditRate_UL_Data);\n\n\n\n\t\tconst UInt8 EditUnitByteCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL EditUnitByteCount_UL(EditUnitByteCount_UL_Data);\n\n\n\n\t\tconst UInt8 ElectroSpatialFormulation_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ElectroSpatialFormulation_UL(ElectroSpatialFormulation_UL_Data);\n\n\n\n\t\tconst UInt8 ElementCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ElementCount_UL(ElementCount_UL_Data);\n\n\n\n\t\tconst UInt8 ElementNames_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ElementNames_UL(ElementNames_UL_Data);\n\n\n\n\t\tconst UInt8 ElementOf_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x21, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ElementOf_UL(ElementOf_UL_Data);\n\n\n\n\t\tconst UInt8 ElementType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ElementType_UL(ElementType_UL_Data);\n\n\n\n\t\tconst UInt8 ElementValues_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ElementValues_UL(ElementValues_UL_Data);\n\n\n\n\t\tconst UInt8 Emphasis_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x05, 0x01, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Emphasis_UL(Emphasis_UL_Data);\n\n\n\n\t\tconst UInt8 EncryptedContainerLabel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x07, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0b, 0x01, 0x00 };\n\n\t\tconst UL EncryptedContainerLabel_UL(EncryptedContainerLabel_UL_Data);\n\n\n\n\t\tconst UInt8 EncryptedSourceValue_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x02, 0x09, 0x03, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL EncryptedSourceValue_UL(EncryptedSourceValue_UL_Data);\n\n\n\n\t\tconst UInt8 EncryptedTriplet_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x04, 0x01, 0x07, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x7e, 0x01, 0x00 };\n\n\t\tconst UL EncryptedTriplet_UL(EncryptedTriplet_UL_Data);\n\n\n\n\t\tconst UInt8 EssenceContainer_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x01, 0x02, 0x00, 0x00 };\n\n\t\tconst UL EssenceContainer_UL(EssenceContainer_UL_Data);\n\n\n\n\t\tconst UInt8 EssenceContainerData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x00 };\n\n\t\tconst UL EssenceContainerData_UL(EssenceContainerData_UL_Data);\n\n\n\n\t\tconst UInt8 EssenceContainers_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x02, 0x02, 0x10, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL EssenceContainers_UL(EssenceContainers_UL_Data);\n\n\n\n\t\tconst UInt8 EssenceDataObjects_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x02, 0x00, 0x00 };\n\n\t\tconst UL EssenceDataObjects_UL(EssenceDataObjects_UL_Data);\n\n\n\n\t\tconst UInt8 EssenceIsIdentified_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x02, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL EssenceIsIdentified_UL(EssenceIsIdentified_UL_Data);\n\n\n\n\t\tconst UInt8 Event_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x06, 0x00 };\n\n\t\tconst UL Event_UL(Event_UL_Data);\n\n\n\n\t\tconst UInt8 EventComment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x30, 0x04, 0x04, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL EventComment_UL(EventComment_UL_Data);\n\n\n\n\t\tconst UInt8 EventEditRate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x30, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL EventEditRate_UL(EventEditRate_UL_Data);\n\n\n\n\t\tconst UInt8 EventOrigin_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x07, 0x02, 0x01, 0x03, 0x01, 0x0b, 0x00, 0x00 };\n\n\t\tconst UL EventOrigin_UL(EventOrigin_UL_Data);\n\n\n\n\t\tconst UInt8 EventStartPosition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x03, 0x03, 0x00, 0x00 };\n\n\t\tconst UL EventStartPosition_UL(EventStartPosition_UL_Data);\n\n\n\n\t\tconst UInt8 EventTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x39, 0x00 };\n\n\t\tconst UL EventTrack_UL(EventTrack_UL_Data);\n\n\n\n\t\tconst UInt8 ExtElementNames_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ExtElementNames_UL(ExtElementNames_UL_Data);\n\n\n\n\t\tconst UInt8 ExtElementValues_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ExtElementValues_UL(ExtElementValues_UL_Data);\n\n\n\n\t\tconst UInt8 ExtendibleEnumerationElement_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x7e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ExtendibleEnumerationElement_UL(ExtendibleEnumerationElement_UL_Data);\n\n\n\n\t\tconst UInt8 ExtensionDescription_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x1e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ExtensionDescription_UL(ExtensionDescription_UL_Data);\n\n\n\n\t\tconst UInt8 ExtensionScheme_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x26, 0x00, 0x00 };\n\n\t\tconst UL ExtensionScheme_UL(ExtensionScheme_UL_Data);\n\n\n\n\t\tconst UInt8 ExtensionSchemeID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x1b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ExtensionSchemeID_UL(ExtensionSchemeID_UL_Data);\n\n\n\n\t\tconst UInt8 FieldDominance_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x03, 0x01, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL FieldDominance_UL(FieldDominance_UL_Data);\n\n\n\n\t\tconst UInt8 FileDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x25, 0x00 };\n\n\t\tconst UL FileDescriptor_UL(FileDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 FileDescriptors_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x01, 0x01, 0x04, 0x06, 0x0b, 0x00, 0x00 };\n\n\t\tconst UL FileDescriptors_UL(FileDescriptors_UL_Data);\n\n\n\n\t\tconst UInt8 Filler_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x09, 0x00 };\n\n\t\tconst UL Filler_UL(Filler_UL_Data);\n\n\n\n\t\tconst UInt8 FixedArrayElementType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x0c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL FixedArrayElementType_UL(FixedArrayElementType_UL_Data);\n\n\n\n\t\tconst UInt8 FixedChannelStatusData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x05, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL FixedChannelStatusData_UL(FixedChannelStatusData_UL_Data);\n\n\n\n\t\tconst UInt8 FixedUserData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x05, 0x01, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL FixedUserData_UL(FixedUserData_UL_Data);\n\n\n\n\t\tconst UInt8 Float32_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Float32_UL(Float32_UL_Data);\n\n\n\n\t\tconst UInt8 Float64_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Float64_UL(Float64_UL_Data);\n\n\n\n\t\tconst UInt8 Footer_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x04, 0x02, 0x00 };\n\n\t\tconst UL Footer_UL(Footer_UL_Data);\n\n\n\n\t\tconst UInt8 FooterPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x10, 0x10, 0x05, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL FooterPartition_UL(FooterPartition_UL_Data);\n\n\n\n\t\tconst UInt8 FrameLayout_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x03, 0x01, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL FrameLayout_UL(FrameLayout_UL_Data);\n\n\n\n\t\tconst UInt8 GenerationUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL GenerationUID_UL(GenerationUID_UL_Data);\n\n\n\n\t\tconst UInt8 GenericDataEssenceDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x43, 0x00 };\n\n\t\tconst UL GenericDataEssenceDescriptor_UL(GenericDataEssenceDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 GenericDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x24, 0x00 };\n\n\t\tconst UL GenericDescriptor_UL(GenericDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 GenericEssenceContainerMultipleWrappings_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x03, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x7f, 0x01, 0x00 };\n\n\t\tconst UL GenericEssenceContainerMultipleWrappings_UL(GenericEssenceContainerMultipleWrappings_UL_Data);\n\n\n\n\t\tconst UInt8 GenericPackage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x34, 0x00 };\n\n\t\tconst UL GenericPackage_UL(GenericPackage_UL_Data);\n\n\n\n\t\tconst UInt8 GenericPictureEssenceDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x27, 0x00 };\n\n\t\tconst UL GenericPictureEssenceDescriptor_UL(GenericPictureEssenceDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 GenericSoundEssenceDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x42, 0x00 };\n\n\t\tconst UL GenericSoundEssenceDescriptor_UL(GenericSoundEssenceDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 GenericStreamPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x03, 0x11, 0x00 };\n\n\t\tconst UL GenericStreamPartition_UL(GenericStreamPartition_UL_Data);\n\n\n\n\t\tconst UInt8 GenericTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x38, 0x00 };\n\n\t\tconst UL GenericTrack_UL(GenericTrack_UL_Data);\n\n\n\n\t\tconst UInt8 GlobalAUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x03, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL GlobalAUID_UL(GlobalAUID_UL_Data);\n\n\n\n\t\tconst UInt8 HMACAlgorithmSHA1128_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x07, 0x02, 0x09, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL HMACAlgorithmSHA1128_UL(HMACAlgorithmSHA1128_UL_Data);\n\n\n\n\t\tconst UInt8 HeaderByteCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x06, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL HeaderByteCount_UL(HeaderByteCount_UL_Data);\n\n\n\n\t\tconst UInt8 HorizontalSubsampling_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL HorizontalSubsampling_UL(HorizontalSubsampling_UL_Data);\n\n\n\n\t\tconst UInt8 Hours_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Hours_UL(Hours_UL_Data);\n\n\n\n\t\tconst UInt8 ISO7_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x10, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ISO7_UL(ISO7_UL_Data);\n\n\n\n\t\tconst UInt8 ISO7String_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ISO7String_UL(ISO7String_UL_Data);\n\n\n\n\t\tconst UInt8 IdenticalGOP_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x07, 0x00, 0x00 };\n\n\t\tconst UL IdenticalGOP_UL(IdenticalGOP_UL_Data);\n\n\n\n\t\tconst UInt8 Identification_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x30, 0x00 };\n\n\t\tconst UL Identification_UL(Identification_UL_Data);\n\n\n\n\t\tconst UInt8 Identifications_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x06, 0x04, 0x00, 0x00 };\n\n\t\tconst UL Identifications_UL(Identifications_UL_Data);\n\n\n\n\t\tconst UInt8 ImageAlignmentOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x18, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ImageAlignmentOffset_UL(ImageAlignmentOffset_UL_Data);\n\n\n\n\t\tconst UInt8 ImageEndOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x18, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ImageEndOffset_UL(ImageEndOffset_UL_Data);\n\n\n\n\t\tconst UInt8 ImageStartOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x18, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ImageStartOffset_UL(ImageStartOffset_UL_Data);\n\n\n\n\t\tconst UInt8 IndexByteCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IndexByteCount_UL(IndexByteCount_UL_Data);\n\n\n\n\t\tconst UInt8 IndexDuration_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x07, 0x02, 0x02, 0x01, 0x01, 0x02, 0x00, 0x00 };\n\n\t\tconst UL IndexDuration_UL(IndexDuration_UL_Data);\n\n\n\n\t\tconst UInt8 IndexEditRate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x05, 0x30, 0x04, 0x06, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IndexEditRate_UL(IndexEditRate_UL_Data);\n\n\n\n\t\tconst UInt8 IndexEntryArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x04, 0x04, 0x02, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IndexEntryArray_UL(IndexEntryArray_UL_Data);\n\n\n\n\t\tconst UInt8 IndexSID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x01, 0x03, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IndexSID_UL(IndexSID_UL_Data);\n\n\n\n\t\tconst UInt8 IndexStartPosition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x07, 0x02, 0x01, 0x03, 0x01, 0x0a, 0x00, 0x00 };\n\n\t\tconst UL IndexStartPosition_UL(IndexStartPosition_UL_Data);\n\n\n\n\t\tconst UInt8 IndexTableSegment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x10, 0x01, 0x00 };\n\n\t\tconst UL IndexTableSegment_UL(IndexTableSegment_UL_Data);\n\n\n\n\t\tconst UInt8 Indirect_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x10, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Indirect_UL(Indirect_UL_Data);\n\n\n\n\t\tconst UInt8 InstanceUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x15, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL InstanceUID_UL(InstanceUID_UL_Data);\n\n\n\n\t\tconst UInt8 Int16_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Int16_UL(Int16_UL_Data);\n\n\n\n\t\tconst UInt8 Int32_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Int32_UL(Int32_UL_Data);\n\n\n\n\t\tconst UInt8 Int32Batch_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Int32Batch_UL(Int32Batch_UL_Data);\n\n\n\n\t\tconst UInt8 Int64_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Int64_UL(Int64_UL_Data);\n\n\n\n\t\tconst UInt8 Int64Array_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Int64Array_UL(Int64Array_UL_Data);\n\n\n\n\t\tconst UInt8 Int8_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Int8_UL(Int8_UL_Data);\n\n\n\n\t\tconst UInt8 InterchangeObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00 };\n\n\t\tconst UL InterchangeObject_UL(InterchangeObject_UL_Data);\n\n\n\n\t\tconst UInt8 IsConcrete_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IsConcrete_UL(IsConcrete_UL_Data);\n\n\n\n\t\tconst UInt8 IsOptional_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IsOptional_UL(IsOptional_UL_Data);\n\n\n\n\t\tconst UInt8 IsSigned_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IsSigned_UL(IsSigned_UL_Data);\n\n\n\n\t\tconst UInt8 IsUniqueIdentifier_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL IsUniqueIdentifier_UL(IsUniqueIdentifier_UL_Data);\n\n\n\n\t\tconst UInt8 JPEG2000PictureSubDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x5a, 0x00 };\n\n\t\tconst UL JPEG2000PictureSubDescriptor_UL(JPEG2000PictureSubDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 KAGSize_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x03, 0x01, 0x02, 0x01, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL KAGSize_UL(KAGSize_UL_Data);\n\n\n\n\t\tconst UInt8 KLVFill_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x10, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL KLVFill_UL(KLVFill_UL_Data);\n\n\n\n\t\tconst UInt8 LastModifiedDate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x02, 0x04, 0x00, 0x00 };\n\n\t\tconst UL LastModifiedDate_UL(LastModifiedDate_UL_Data);\n\n\n\n\t\tconst UInt8 LayoutType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LayoutType_UL(LayoutType_UL_Data);\n\n\n\n\t\tconst UInt8 Length_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x06, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Length_UL(Length_UL_Data);\n\n\n\n\t\tconst UInt8 LengthType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x20, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LengthType_UL(LengthType_UL_Data);\n\n\n\n\t\tconst UInt8 LinkedApplicationPluginInstanceID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LinkedApplicationPluginInstanceID_UL(LinkedApplicationPluginInstanceID_UL_Data);\n\n\n\n\t\tconst UInt8 LinkedDescriptiveFrameworkPluginID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x0c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LinkedDescriptiveFrameworkPluginID_UL(LinkedDescriptiveFrameworkPluginID_UL_Data);\n\n\n\n\t\tconst UInt8 LinkedDescriptiveObjectPluginID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x05, 0x20, 0x07, 0x01, 0x11, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LinkedDescriptiveObjectPluginID_UL(LinkedDescriptiveObjectPluginID_UL_Data);\n\n\n\n\t\tconst UInt8 LinkedPackageUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x06, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LinkedPackageUID_UL(LinkedPackageUID_UL_Data);\n\n\n\n\t\tconst UInt8 LinkedTrackID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x06, 0x01, 0x01, 0x03, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LinkedTrackID_UL(LinkedTrackID_UL_Data);\n\n\n\n\t\tconst UInt8 LocalIdentification_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LocalIdentification_UL(LocalIdentification_UL_Data);\n\n\n\n\t\tconst UInt8 LocalTag_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x03, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LocalTag_UL(LocalTag_UL_Data);\n\n\n\n\t\tconst UInt8 LocalTagEntries_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x06, 0x01, 0x01, 0x07, 0x15, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LocalTagEntries_UL(LocalTagEntries_UL_Data);\n\n\n\n\t\tconst UInt8 LocalTagType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x20, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LocalTagType_UL(LocalTagType_UL_Data);\n\n\n\n\t\tconst UInt8 Locator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x31, 0x00 };\n\n\t\tconst UL Locator_UL(Locator_UL_Data);\n\n\n\n\t\tconst UInt8 LocatorName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x04, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL LocatorName_UL(LocatorName_UL_Data);\n\n\n\n\t\tconst UInt8 Locators_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x06, 0x03, 0x00, 0x00 };\n\n\t\tconst UL Locators_UL(Locators_UL_Data);\n\n\n\n\t\tconst UInt8 Locked_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x02, 0x03, 0x01, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Locked_UL(Locked_UL_Data);\n\n\n\n\t\tconst UInt8 LowDelay_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x05, 0x00, 0x00 };\n\n\t\tconst UL LowDelay_UL(LowDelay_UL_Data);\n\n\n\n\t\tconst UInt8 MIC_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x02, 0x09, 0x03, 0x02, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MIC_UL(MIC_UL_Data);\n\n\n\n\t\tconst UInt8 MICAlgorithm_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x02, 0x09, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MICAlgorithm_UL(MICAlgorithm_UL_Data);\n\n\n\n\t\tconst UInt8 MPEG2VideoDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x51, 0x00 };\n\n\t\tconst UL MPEG2VideoDescriptor_UL(MPEG2VideoDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 MXFEC_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MXFEC_UL(MXFEC_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGC_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MXFGC_UL(MXFGC_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCAESBWF_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x06, 0x00, 0x00 };\n\n\t\tconst UL MXFGCAESBWF_UL(MXFGCAESBWF_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCALaw_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0a, 0x00, 0x00 };\n\n\t\tconst UL MXFGCALaw_UL(MXFGCALaw_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCD10_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL MXFGCD10_UL(MXFGCD10_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCD11_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x03, 0x00, 0x00 };\n\n\t\tconst UL MXFGCD11_UL(MXFGCD11_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCDV_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x02, 0x00, 0x00 };\n\n\t\tconst UL MXFGCDV_UL(MXFGCDV_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCEncrypted_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0b, 0x00, 0x00 };\n\n\t\tconst UL MXFGCEncrypted_UL(MXFGCEncrypted_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCJP2K_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0c, 0x00, 0x00 };\n\n\t\tconst UL MXFGCJP2K_UL(MXFGCJP2K_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCMPEGES_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x04, 0x00, 0x00 };\n\n\t\tconst UL MXFGCMPEGES_UL(MXFGCMPEGES_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCMPEGPES_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x07, 0x00, 0x00 };\n\n\t\tconst UL MXFGCMPEGPES_UL(MXFGCMPEGPES_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCMPEGPS_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x08, 0x00, 0x00 };\n\n\t\tconst UL MXFGCMPEGPS_UL(MXFGCMPEGPS_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCMPEGTS_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x09, 0x00, 0x00 };\n\n\t\tconst UL MXFGCMPEGTS_UL(MXFGCMPEGTS_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCMultiple_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x03, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x7f, 0x01, 0x00 };\n\n\t\tconst UL MXFGCMultiple_UL(MXFGCMultiple_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCUncompressed_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x05, 0x00, 0x00 };\n\n\t\tconst UL MXFGCUncompressed_UL(MXFGCUncompressed_UL_Data);\n\n\n\n\t\tconst UInt8 MXFGCVBI_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0d, 0x00, 0x00 };\n\n\t\tconst UL MXFGCVBI_UL(MXFGCVBI_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP1a_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x00 };\n\n\t\tconst UL MXFOP1a_UL(MXFOP1a_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP1b_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x00 };\n\n\t\tconst UL MXFOP1b_UL(MXFOP1b_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP1c_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x03, 0x01, 0x00 };\n\n\t\tconst UL MXFOP1c_UL(MXFOP1c_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP1x_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x00 };\n\n\t\tconst UL MXFOP1x_UL(MXFOP1x_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP2a_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x01, 0x01, 0x00 };\n\n\t\tconst UL MXFOP2a_UL(MXFOP2a_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP2b_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x00 };\n\n\t\tconst UL MXFOP2b_UL(MXFOP2b_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP2c_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x03, 0x01, 0x00 };\n\n\t\tconst UL MXFOP2c_UL(MXFOP2c_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP3a_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x03, 0x01, 0x01, 0x00 };\n\n\t\tconst UL MXFOP3a_UL(MXFOP3a_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP3b_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x03, 0x02, 0x01, 0x00 };\n\n\t\tconst UL MXFOP3b_UL(MXFOP3b_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOP3c_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x03, 0x03, 0x01, 0x00 };\n\n\t\tconst UL MXFOP3c_UL(MXFOP3c_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOPAtom_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x02, 0x0d, 0x01, 0x02, 0x01, 0x10, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MXFOPAtom_UL(MXFOPAtom_UL_Data);\n\n\n\n\t\tconst UInt8 MXFOPSpecialized_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x00, 0x0d, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MXFOPSpecialized_UL(MXFOPSpecialized_UL_Data);\n\n\n\n\t\tconst UInt8 Major_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Major_UL(Major_UL_Data);\n\n\n\n\t\tconst UInt8 MajorVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x03, 0x01, 0x02, 0x01, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MajorVersion_UL(MajorVersion_UL_Data);\n\n\n\n\t\tconst UInt8 MaterialPackage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x36, 0x00 };\n\n\t\tconst UL MaterialPackage_UL(MaterialPackage_UL_Data);\n\n\n\n\t\tconst UInt8 MaxGOP_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x08, 0x00, 0x00 };\n\n\t\tconst UL MaxGOP_UL(MaxGOP_UL_Data);\n\n\n\n\t\tconst UInt8 MemberNames_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MemberNames_UL(MemberNames_UL_Data);\n\n\n\n\t\tconst UInt8 MemberTypes_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x11, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MemberTypes_UL(MemberTypes_UL_Data);\n\n\n\n\t\tconst UInt8 MetaDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x24, 0x00, 0x00 };\n\n\t\tconst UL MetaDefinition_UL(MetaDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 MetaDefinitionDescription_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x14, 0x01, 0x00, 0x00 };\n\n\t\tconst UL MetaDefinitionDescription_UL(MetaDefinitionDescription_UL_Data);\n\n\n\n\t\tconst UInt8 MetaDefinitionIdentification_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x13, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MetaDefinitionIdentification_UL(MetaDefinitionIdentification_UL_Data);\n\n\n\n\t\tconst UInt8 MetaDefinitionName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x02, 0x04, 0x01, 0x02, 0x01, 0x00, 0x00 };\n\n\t\tconst UL MetaDefinitionName_UL(MetaDefinitionName_UL_Data);\n\n\n\n\t\tconst UInt8 MetaDefinitions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x1f, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MetaDefinitions_UL(MetaDefinitions_UL_Data);\n\n\n\n\t\tconst UInt8 MetaDictionary_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x25, 0x00, 0x00 };\n\n\t\tconst UL MetaDictionary_UL(MetaDictionary_UL_Data);\n\n\n\n\t\tconst UInt8 MetaReferenceClassDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MetaReferenceClassDefinition_UL(MetaReferenceClassDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 MetaReferenceTypeDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MetaReferenceTypeDefinition_UL(MetaReferenceTypeDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 Minor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Minor_UL(Minor_UL_Data);\n\n\n\n\t\tconst UInt8 MinorVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x03, 0x01, 0x02, 0x01, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MinorVersion_UL(MinorVersion_UL_Data);\n\n\n\n\t\tconst UInt8 Minutes_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Minutes_UL(Minutes_UL_Data);\n\n\n\n\t\tconst UInt8 ModificationDate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x02, 0x03, 0x00, 0x00 };\n\n\t\tconst UL ModificationDate_UL(ModificationDate_UL_Data);\n\n\n\n\t\tconst UInt8 MonoSourceTrackIDs_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x06, 0x01, 0x01, 0x03, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL MonoSourceTrackIDs_UL(MonoSourceTrackIDs_UL_Data);\n\n\n\n\t\tconst UInt8 Month_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Month_UL(Month_UL_Data);\n\n\n\n\t\tconst UInt8 MultipleDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x44, 0x00 };\n\n\t\tconst UL MultipleDescriptor_UL(MultipleDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 NetworkLocator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x32, 0x00 };\n\n\t\tconst UL NetworkLocator_UL(NetworkLocator_UL_Data);\n\n\n\n\t\tconst UInt8 Numerator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Numerator_UL(Numerator_UL_Data);\n\n\n\n\t\tconst UInt8 ObjectClass_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00 };\n\n\t\tconst UL ObjectClass_UL(ObjectClass_UL_Data);\n\n\n\n\t\tconst UInt8 ObjectModelVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x01, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ObjectModelVersion_UL(ObjectModelVersion_UL_Data);\n\n\n\n\t\tconst UInt8 Opaque_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Opaque_UL(Opaque_UL_Data);\n\n\n\n\t\tconst UInt8 OpenBodyPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x03, 0x01, 0x00 };\n\n\t\tconst UL OpenBodyPartition_UL(OpenBodyPartition_UL_Data);\n\n\n\n\t\tconst UInt8 OpenCompleteBodyPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x03, 0x03, 0x00 };\n\n\t\tconst UL OpenCompleteBodyPartition_UL(OpenCompleteBodyPartition_UL_Data);\n\n\n\n\t\tconst UInt8 OpenCompleteHeader_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02, 0x03, 0x00 };\n\n\t\tconst UL OpenCompleteHeader_UL(OpenCompleteHeader_UL_Data);\n\n\n\n\t\tconst UInt8 OpenHeader_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02, 0x01, 0x00 };\n\n\t\tconst UL OpenHeader_UL(OpenHeader_UL_Data);\n\n\n\n\t\tconst UInt8 OperationalPattern_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL OperationalPattern_UL(OperationalPattern_UL_Data);\n\n\n\n\t\tconst UInt8 Origin_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x01, 0x03, 0x00, 0x00 };\n\n\t\tconst UL Origin_UL(Origin_UL_Data);\n\n\n\n\t\tconst UInt8 OriginalProperty_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x20, 0x00, 0x00, 0x00 };\n\n\t\tconst UL OriginalProperty_UL(OriginalProperty_UL_Data);\n\n\n\n\t\tconst UInt8 PackageCreationDate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x01, 0x03, 0x00, 0x00 };\n\n\t\tconst UL PackageCreationDate_UL(PackageCreationDate_UL_Data);\n\n\n\n\t\tconst UInt8 PackageID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PackageID_UL(PackageID_UL_Data);\n\n\n\n\t\tconst UInt8 PackageMarkInPosition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x07, 0x02, 0x01, 0x03, 0x01, 0x0e, 0x00, 0x00 };\n\n\t\tconst UL PackageMarkInPosition_UL(PackageMarkInPosition_UL_Data);\n\n\n\n\t\tconst UInt8 PackageMarkOutPosition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x07, 0x02, 0x01, 0x03, 0x02, 0x04, 0x00, 0x00 };\n\n\t\tconst UL PackageMarkOutPosition_UL(PackageMarkOutPosition_UL_Data);\n\n\n\n\t\tconst UInt8 PackageMarker_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x06, 0x01, 0x01, 0x04, 0x02, 0x0f, 0x00, 0x00 };\n\n\t\tconst UL PackageMarker_UL(PackageMarker_UL_Data);\n\n\n\n\t\tconst UInt8 PackageMarkerObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x60, 0x00 };\n\n\t\tconst UL PackageMarkerObject_UL(PackageMarkerObject_UL_Data);\n\n\n\n\t\tconst UInt8 PackageModifiedDate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x10, 0x02, 0x05, 0x00, 0x00 };\n\n\t\tconst UL PackageModifiedDate_UL(PackageModifiedDate_UL_Data);\n\n\n\n\t\tconst UInt8 PackageName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PackageName_UL(PackageName_UL_Data);\n\n\n\n\t\tconst UInt8 PackageUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x15, 0x10, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PackageUID_UL(PackageUID_UL_Data);\n\n\n\n\t\tconst UInt8 Packages_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x05, 0x01, 0x00, 0x00 };\n\n\t\tconst UL Packages_UL(Packages_UL_Data);\n\n\n\n\t\tconst UInt8 PaddingBits_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x18, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PaddingBits_UL(PaddingBits_UL_Data);\n\n\n\n\t\tconst UInt8 Palette_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Palette_UL(Palette_UL_Data);\n\n\n\n\t\tconst UInt8 PaletteLayout_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PaletteLayout_UL(PaletteLayout_UL_Data);\n\n\n\n\t\tconst UInt8 ParentClass_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ParentClass_UL(ParentClass_UL_Data);\n\n\n\n\t\tconst UInt8 PartitionArray_UL_Data[16] = { 0x80, 0x62, 0xc1, 0x08, 0xa8, 0x0d, 0xeb, 0xfe, 0x3a, 0x9d, 0xc8, 0xe1, 0x7e, 0x83, 0xb6, 0x4b };\n\n\t\tconst UL PartitionArray_UL(PartitionArray_UL_Data);\n\n\n\n\t\tconst UInt8 PartitionMetadata_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x06, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PartitionMetadata_UL(PartitionMetadata_UL_Data);\n\n\n\n\t\tconst UInt8 Patch_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Patch_UL(Patch_UL_Data);\n\n\n\n\t\tconst UInt8 PeakChannels_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakChannels_UL(PeakChannels_UL_Data);\n\n\n\n\t\tconst UInt8 PeakEnvelopeBlockSize_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakEnvelopeBlockSize_UL(PeakEnvelopeBlockSize_UL_Data);\n\n\n\n\t\tconst UInt8 PeakEnvelopeData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x01, 0x0e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakEnvelopeData_UL(PeakEnvelopeData_UL_Data);\n\n\n\n\t\tconst UInt8 PeakEnvelopeFormat_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakEnvelopeFormat_UL(PeakEnvelopeFormat_UL_Data);\n\n\n\n\t\tconst UInt8 PeakEnvelopeTimestamp_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x0d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakEnvelopeTimestamp_UL(PeakEnvelopeTimestamp_UL_Data);\n\n\n\n\t\tconst UInt8 PeakEnvelopeVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakEnvelopeVersion_UL(PeakEnvelopeVersion_UL_Data);\n\n\n\n\t\tconst UInt8 PeakFrames_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakFrames_UL(PeakFrames_UL_Data);\n\n\n\n\t\tconst UInt8 PeakOfPeaksPosition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x0c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PeakOfPeaksPosition_UL(PeakOfPeaksPosition_UL_Data);\n\n\n\n\t\tconst UInt8 PictureComponentSizing_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PictureComponentSizing_UL(PictureComponentSizing_UL_Data);\n\n\n\n\t\tconst UInt8 PictureEssenceCoding_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PictureEssenceCoding_UL(PictureEssenceCoding_UL_Data);\n\n\n\n\t\tconst UInt8 PictureEssenceTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PictureEssenceTrack_UL(PictureEssenceTrack_UL_Data);\n\n\n\n\t\tconst UInt8 PixelLayout_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x03, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PixelLayout_UL(PixelLayout_UL_Data);\n\n\n\n\t\tconst UInt8 PlaintextOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x09, 0x02, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PlaintextOffset_UL(PlaintextOffset_UL_Data);\n\n\n\n\t\tconst UInt8 Platform_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x06, 0x01, 0x00, 0x00 };\n\n\t\tconst UL Platform_UL(Platform_UL_Data);\n\n\n\n\t\tconst UInt8 PointsPerPeakValue_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x08, 0x04, 0x02, 0x03, 0x01, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PointsPerPeakValue_UL(PointsPerPeakValue_UL_Data);\n\n\n\n\t\tconst UInt8 PosTableCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x04, 0x04, 0x01, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PosTableCount_UL(PosTableCount_UL_Data);\n\n\n\n\t\tconst UInt8 Position_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Position_UL(Position_UL_Data);\n\n\n\n\t\tconst UInt8 Preface_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x2f, 0x00 };\n\n\t\tconst UL Preface_UL(Preface_UL_Data);\n\n\n\n\t\tconst UInt8 PreferredPrefix_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x1d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PreferredPrefix_UL(PreferredPrefix_UL_Data);\n\n\n\n\t\tconst UInt8 PreviousPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x10, 0x10, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PreviousPartition_UL(PreviousPartition_UL_Data);\n\n\n\n\t\tconst UInt8 PrimaryPackage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x01, 0x01, 0x04, 0x01, 0x08, 0x00, 0x00 };\n\n\t\tconst UL PrimaryPackage_UL(PrimaryPackage_UL_Data);\n\n\n\n\t\tconst UInt8 Primer_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00 };\n\n\t\tconst UL Primer_UL(Primer_UL_Data);\n\n\n\n\t\tconst UInt8 ProductName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x03, 0x01, 0x00, 0x00 };\n\n\t\tconst UL ProductName_UL(ProductName_UL_Data);\n\n\n\n\t\tconst UInt8 ProductUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ProductUID_UL(ProductUID_UL_Data);\n\n\n\n\t\tconst UInt8 ProductVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ProductVersion_UL(ProductVersion_UL_Data);\n\n\n\n\t\tconst UInt8 ProductVersionType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ProductVersionType_UL(ProductVersionType_UL_Data);\n\n\n\n\t\tconst UInt8 ProfileAndLevel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x0a, 0x00, 0x00 };\n\n\t\tconst UL ProfileAndLevel_UL(ProfileAndLevel_UL_Data);\n\n\n\n\t\tconst UInt8 Properties_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Properties_UL(Properties_UL_Data);\n\n\n\n\t\tconst UInt8 PropertyDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x02, 0x00, 0x00 };\n\n\t\tconst UL PropertyDefinition_UL(PropertyDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 PropertyType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL PropertyType_UL(PropertyType_UL_Data);\n\n\n\n\t\tconst UInt8 PropertyWrapperDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x27, 0x00, 0x00 };\n\n\t\tconst UL PropertyWrapperDefinition_UL(PropertyWrapperDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 QuantizationBits_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x02, 0x03, 0x03, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL QuantizationBits_UL(QuantizationBits_UL_Data);\n\n\n\n\t\tconst UInt8 QuantizationDefault_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x0d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL QuantizationDefault_UL(QuantizationDefault_UL_Data);\n\n\n\n\t\tconst UInt8 RGBACode_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x0e, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RGBACode_UL(RGBACode_UL_Data);\n\n\n\n\t\tconst UInt8 RGBAEssenceDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x29, 0x00 };\n\n\t\tconst UL RGBAEssenceDescriptor_UL(RGBAEssenceDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 RGBALayout_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RGBALayout_UL(RGBALayout_UL_Data);\n\n\n\n\t\tconst UInt8 RGBALayoutItem_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RGBALayoutItem_UL(RGBALayoutItem_UL_Data);\n\n\n\n\t\tconst UInt8 RandomIndexMetadata_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x11, 0x01, 0x00 };\n\n\t\tconst UL RandomIndexMetadata_UL(RandomIndexMetadata_UL_Data);\n\n\n\n\t\tconst UInt8 RandomIndexMetadataV10_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x11, 0x00, 0x00 };\n\n\t\tconst UL RandomIndexMetadataV10_UL(RandomIndexMetadataV10_UL_Data);\n\n\n\n\t\tconst UInt8 Rational_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Rational_UL(Rational_UL_Data);\n\n\n\n\t\tconst UInt8 RationalArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RationalArray_UL(RationalArray_UL_Data);\n\n\n\n\t\tconst UInt8 ReferencedType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ReferencedType_UL(ReferencedType_UL_Data);\n\n\n\n\t\tconst UInt8 Release_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Release_UL(Release_UL_Data);\n\n\n\n\t\tconst UInt8 RenamedType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x12, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RenamedType_UL(RenamedType_UL_Data);\n\n\n\n\t\tconst UInt8 ReversedByteOrder_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x03, 0x01, 0x02, 0x01, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ReversedByteOrder_UL(ReversedByteOrder_UL_Data);\n\n\n\n\t\tconst UInt8 Root_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Root_UL(Root_UL_Data);\n\n\n\n\t\tconst UInt8 RootExtensions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x06, 0x01, 0x01, 0x07, 0x7f, 0x01, 0x00, 0x00 };\n\n\t\tconst UL RootExtensions_UL(RootExtensions_UL_Data);\n\n\n\n\t\tconst UInt8 RootFormatVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x06, 0x01, 0x01, 0x07, 0x19, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RootFormatVersion_UL(RootFormatVersion_UL_Data);\n\n\n\n\t\tconst UInt8 RootPreface_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x06, 0x01, 0x01, 0x07, 0x17, 0x00, 0x00, 0x00 };\n\n\t\tconst UL RootPreface_UL(RootPreface_UL_Data);\n\n\n\n\t\tconst UInt8 RoundedTimecodeBase_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x04, 0x01, 0x01, 0x02, 0x06, 0x00, 0x00 };\n\n\t\tconst UL RoundedTimecodeBase_UL(RoundedTimecodeBase_UL_Data);\n\n\n\n\t\tconst UInt8 Rsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Rsiz_UL(Rsiz_UL_Data);\n\n\n\n\t\tconst UInt8 SMPTE12MTimecodeActiveUserBitsTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SMPTE12MTimecodeActiveUserBitsTrack_UL(SMPTE12MTimecodeActiveUserBitsTrack_UL_Data);\n\n\n\n\t\tconst UInt8 SMPTE12MTimecodeTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SMPTE12MTimecodeTrack_UL(SMPTE12MTimecodeTrack_UL_Data);\n\n\n\n\t\tconst UInt8 SMPTE309MTimecodeTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SMPTE309MTimecodeTrack_UL(SMPTE309MTimecodeTrack_UL_Data);\n\n\n\n\t\tconst UInt8 SampleRate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x06, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SampleRate_UL(SampleRate_UL_Data);\n\n\n\n\t\tconst UInt8 SampledHeight_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SampledHeight_UL(SampledHeight_UL_Data);\n\n\n\n\t\tconst UInt8 SampledWidth_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SampledWidth_UL(SampledWidth_UL_Data);\n\n\n\n\t\tconst UInt8 SampledXOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SampledXOffset_UL(SampledXOffset_UL_Data);\n\n\n\n\t\tconst UInt8 SampledYOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x01, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SampledYOffset_UL(SampledYOffset_UL_Data);\n\n\n\n\t\tconst UInt8 ScanningDirection_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x04, 0x04, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ScanningDirection_UL(ScanningDirection_UL_Data);\n\n\n\n\t\tconst UInt8 Seconds_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Seconds_UL(Seconds_UL_Data);\n\n\n\n\t\tconst UInt8 Segment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x00 };\n\n\t\tconst UL Segment_UL(Segment_UL_Data);\n\n\n\n\t\tconst UInt8 Sequence_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x0f, 0x00 };\n\n\t\tconst UL Sequence_UL(Sequence_UL_Data);\n\n\n\n\t\tconst UInt8 SequenceNumber_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x10, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SequenceNumber_UL(SequenceNumber_UL_Data);\n\n\n\n\t\tconst UInt8 SequenceOffset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x03, 0x02, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SequenceOffset_UL(SequenceOffset_UL_Data);\n\n\n\n\t\tconst UInt8 SetElementType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x0e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SetElementType_UL(SetElementType_UL_Data);\n\n\n\n\t\tconst UInt8 SignalStandard_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x05, 0x01, 0x13, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SignalStandard_UL(SignalStandard_UL_Data);\n\n\n\n\t\tconst UInt8 SingleSequence_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x06, 0x02, 0x01, 0x02, 0x00, 0x00 };\n\n\t\tconst UL SingleSequence_UL(SingleSequence_UL_Data);\n\n\n\n\t\tconst UInt8 Size_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Size_UL(Size_UL_Data);\n\n\n\n\t\tconst UInt8 SliceCount_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x04, 0x04, 0x04, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SliceCount_UL(SliceCount_UL_Data);\n\n\n\n\t\tconst UInt8 SoundEssenceCompression_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x02, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SoundEssenceCompression_UL(SoundEssenceCompression_UL_Data);\n\n\n\n\t\tconst UInt8 SoundEssenceTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SoundEssenceTrack_UL(SoundEssenceTrack_UL_Data);\n\n\n\n\t\tconst UInt8 SourceClip_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x11, 0x00 };\n\n\t\tconst UL SourceClip_UL(SourceClip_UL_Data);\n\n\n\n\t\tconst UInt8 SourceEssenceContainer_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x02, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SourceEssenceContainer_UL(SourceEssenceContainer_UL_Data);\n\n\n\n\t\tconst UInt8 SourceKey_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SourceKey_UL(SourceKey_UL_Data);\n\n\n\n\t\tconst UInt8 SourceLength_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x04, 0x06, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SourceLength_UL(SourceLength_UL_Data);\n\n\n\n\t\tconst UInt8 SourcePackage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x37, 0x00 };\n\n\t\tconst UL SourcePackage_UL(SourcePackage_UL_Data);\n\n\n\n\t\tconst UInt8 SourcePackageID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x03, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SourcePackageID_UL(SourcePackageID_UL_Data);\n\n\n\n\t\tconst UInt8 SourceReference_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00 };\n\n\t\tconst UL SourceReference_UL(SourceReference_UL_Data);\n\n\n\n\t\tconst UInt8 SourceTrackID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x03, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SourceTrackID_UL(SourceTrackID_UL_Data);\n\n\n\n\t\tconst UInt8 StartPosition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x01, 0x04, 0x00, 0x00 };\n\n\t\tconst UL StartPosition_UL(StartPosition_UL_Data);\n\n\n\n\t\tconst UInt8 StartTimecode_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x01, 0x05, 0x00, 0x00 };\n\n\t\tconst UL StartTimecode_UL(StartTimecode_UL_Data);\n\n\n\n\t\tconst UInt8 StaticTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x3a, 0x00 };\n\n\t\tconst UL StaticTrack_UL(StaticTrack_UL_Data);\n\n\n\n\t\tconst UInt8 StoredF2Offset_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x01, 0x03, 0x02, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StoredF2Offset_UL(StoredF2Offset_UL_Data);\n\n\n\n\t\tconst UInt8 StoredHeight_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StoredHeight_UL(StoredHeight_UL_Data);\n\n\n\n\t\tconst UInt8 StoredWidth_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x02, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StoredWidth_UL(StoredWidth_UL_Data);\n\n\n\n\t\tconst UInt8 Stream_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Stream_UL(Stream_UL_Data);\n\n\n\n\t\tconst UInt8 StringArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StringArray_UL(StringArray_UL_Data);\n\n\n\n\t\tconst UInt8 StringElementType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x0f, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StringElementType_UL(StringElementType_UL_Data);\n\n\n\n\t\tconst UInt8 StrongRef_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongRef_UL(StrongRef_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceCodecDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceCodecDefinition_UL(StrongReferenceCodecDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceComponent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceComponent_UL(StrongReferenceComponent_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceContainerDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceContainerDefinition_UL(StrongReferenceContainerDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceContentStorage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceContentStorage_UL(StrongReferenceContentStorage_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceDataDefinition_UL(StrongReferenceDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceDictionary_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceDictionary_UL(StrongReferenceDictionary_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceEssenceData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceEssenceData_UL(StrongReferenceEssenceData_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceEssenceDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceEssenceDescriptor_UL(StrongReferenceEssenceDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceIdentification_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceIdentification_UL(StrongReferenceIdentification_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceInterpolationDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceInterpolationDefinition_UL(StrongReferenceInterpolationDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceKLVData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceKLVData_UL(StrongReferenceKLVData_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceKLVDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceKLVDataDefinition_UL(StrongReferenceKLVDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceLocator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceLocator_UL(StrongReferenceLocator_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceNetworkLocator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceNetworkLocator_UL(StrongReferenceNetworkLocator_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferencePackage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferencePackage_UL(StrongReferencePackage_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceParameter_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceParameter_UL(StrongReferenceParameter_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceParameterDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceParameterDefinition_UL(StrongReferenceParameterDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferencePluginDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferencePluginDefinition_UL(StrongReferencePluginDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferencePropertyDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferencePropertyDefinition_UL(StrongReferencePropertyDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSegment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSegment_UL(StrongReferenceSegment_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetClassDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetClassDefinition_UL(StrongReferenceSetClassDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetCodecDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetCodecDefinition_UL(StrongReferenceSetCodecDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetContainerDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetContainerDefinition_UL(StrongReferenceSetContainerDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetDataDefinition_UL(StrongReferenceSetDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetEssenceData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetEssenceData_UL(StrongReferenceSetEssenceData_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetInterpolationDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetInterpolationDefinition_UL(StrongReferenceSetInterpolationDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetKLVDataDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetKLVDataDefinition_UL(StrongReferenceSetKLVDataDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetPackage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetPackage_UL(StrongReferenceSetPackage_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetParameterDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetParameterDefinition_UL(StrongReferenceSetParameterDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetPluginDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetPluginDefinition_UL(StrongReferenceSetPluginDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetPropertyDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetPropertyDefinition_UL(StrongReferenceSetPropertyDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetTaggedValueDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetTaggedValueDefinition_UL(StrongReferenceSetTaggedValueDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSetTypeDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x05, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSetTypeDefinition_UL(StrongReferenceSetTypeDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceSourceReference_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceSourceReference_UL(StrongReferenceSourceReference_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceTaggedValueDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceTaggedValueDefinition_UL(StrongReferenceTaggedValueDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x02, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceTrack_UL(StrongReferenceTrack_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorComponent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorComponent_UL(StrongReferenceVectorComponent_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorFileDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorFileDescriptor_UL(StrongReferenceVectorFileDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorIdentification_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorIdentification_UL(StrongReferenceVectorIdentification_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorKLVData_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorKLVData_UL(StrongReferenceVectorKLVData_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorLocator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorLocator_UL(StrongReferenceVectorLocator_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorParameter_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorParameter_UL(StrongReferenceVectorParameter_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorSegment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorSegment_UL(StrongReferenceVectorSegment_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorSubDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorSubDescriptor_UL(StrongReferenceVectorSubDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 StrongReferenceVectorTrack_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x06, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL StrongReferenceVectorTrack_UL(StrongReferenceVectorTrack_UL_Data);\n\n\n\n\t\tconst UInt8 StructuralComponent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00 };\n\n\t\tconst UL StructuralComponent_UL(StructuralComponent_UL_Data);\n\n\n\n\t\tconst UInt8 StructuralComponents_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x06, 0x09, 0x00, 0x00 };\n\n\t\tconst UL StructuralComponents_UL(StructuralComponents_UL_Data);\n\n\n\n\t\tconst UInt8 SubDescriptors_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x04, 0x06, 0x10, 0x00, 0x00 };\n\n\t\tconst UL SubDescriptors_UL(SubDescriptors_UL_Data);\n\n\n\n\t\tconst UInt8 SymbolSpaceURI_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x06, 0x01, 0x01, 0x07, 0x1c, 0x00, 0x00, 0x00 };\n\n\t\tconst UL SymbolSpaceURI_UL(SymbolSpaceURI_UL_Data);\n\n\n\n\t\tconst UInt8 TargetSet_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x03, 0x0b, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TargetSet_UL(TargetSet_UL_Data);\n\n\n\n\t\tconst UInt8 TextLocator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x33, 0x00 };\n\n\t\tconst UL TextLocator_UL(TextLocator_UL_Data);\n\n\n\n\t\tconst UInt8 ThisGenerationUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ThisGenerationUID_UL(ThisGenerationUID_UL_Data);\n\n\n\n\t\tconst UInt8 ThisPartition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x06, 0x10, 0x10, 0x03, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ThisPartition_UL(ThisPartition_UL_Data);\n\n\n\n\t\tconst UInt8 TimeStruct_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TimeStruct_UL(TimeStruct_UL_Data);\n\n\n\n\t\tconst UInt8 TimebaseReferenceTrackID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0c, 0x06, 0x01, 0x01, 0x03, 0x0e, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TimebaseReferenceTrackID_UL(TimebaseReferenceTrackID_UL_Data);\n\n\n\n\t\tconst UInt8 TimecodeComponent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x14, 0x00 };\n\n\t\tconst UL TimecodeComponent_UL(TimecodeComponent_UL_Data);\n\n\n\n\t\tconst UInt8 Timestamp_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Timestamp_UL(Timestamp_UL_Data);\n\n\n\n\t\tconst UInt8 ToolkitVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ToolkitVersion_UL(ToolkitVersion_UL_Data);\n\n\n\n\t\tconst UInt8 Track_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x3b, 0x00 };\n\n\t\tconst UL Track_UL(Track_UL_Data);\n\n\n\n\t\tconst UInt8 TrackFileID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x09, 0x06, 0x01, 0x01, 0x06, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TrackFileID_UL(TrackFileID_UL_Data);\n\n\n\n\t\tconst UInt8 TrackID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TrackID_UL(TrackID_UL_Data);\n\n\n\n\t\tconst UInt8 TrackIDs_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x04, 0x01, 0x07, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TrackIDs_UL(TrackIDs_UL_Data);\n\n\n\n\t\tconst UInt8 TrackName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x07, 0x01, 0x02, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TrackName_UL(TrackName_UL_Data);\n\n\n\n\t\tconst UInt8 TrackNumber_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x01, 0x04, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TrackNumber_UL(TrackNumber_UL_Data);\n\n\n\n\t\tconst UInt8 TrackSegment_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x02, 0x04, 0x00, 0x00 };\n\n\t\tconst UL TrackSegment_UL(TrackSegment_UL_Data);\n\n\n\n\t\tconst UInt8 Tracks_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x04, 0x06, 0x05, 0x00, 0x00 };\n\n\t\tconst UL Tracks_UL(Tracks_UL_Data);\n\n\n\n\t\tconst UInt8 TransferCharacteristic_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x00 };\n\n\t\tconst UL TransferCharacteristic_UL(TransferCharacteristic_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x03, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinition_UL(TypeDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionCharacter_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x23, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionCharacter_UL(TypeDefinitionCharacter_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionEnumeration_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x07, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionEnumeration_UL(TypeDefinitionEnumeration_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionExtendibleEnumeration_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x20, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionExtendibleEnumeration_UL(TypeDefinitionExtendibleEnumeration_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionFixedArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x08, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionFixedArray_UL(TypeDefinitionFixedArray_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionIndirect_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x21, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionIndirect_UL(TypeDefinitionIndirect_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionInteger_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x04, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionInteger_UL(TypeDefinitionInteger_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionOpaque_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x22, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionOpaque_UL(TypeDefinitionOpaque_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionRecord_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x0d, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionRecord_UL(TypeDefinitionRecord_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionRename_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x0e, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionRename_UL(TypeDefinitionRename_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionSet_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x0a, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionSet_UL(TypeDefinitionSet_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionStream_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x0c, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionStream_UL(TypeDefinitionStream_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionString_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x0b, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionString_UL(TypeDefinitionString_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionStrongObjectReference_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x05, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionStrongObjectReference_UL(TypeDefinitionStrongObjectReference_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionVariableArray_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x09, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionVariableArray_UL(TypeDefinitionVariableArray_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitionWeakObjectReference_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x02, 0x06, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitionWeakObjectReference_UL(TypeDefinitionWeakObjectReference_UL_Data);\n\n\n\n\t\tconst UInt8 TypeDefinitions_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL TypeDefinitions_UL(TypeDefinitions_UL_Data);\n\n\n\n\t\tconst UInt8 UInt16_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt16_UL(UInt16_UL_Data);\n\n\n\n\t\tconst UInt8 UInt32_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt32_UL(UInt32_UL_Data);\n\n\n\n\t\tconst UInt8 UInt32Array_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x01, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt32Array_UL(UInt32Array_UL_Data);\n\n\n\n\t\tconst UInt8 UInt32Batch_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt32Batch_UL(UInt32Batch_UL_Data);\n\n\n\n\t\tconst UInt8 UInt64_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt64_UL(UInt64_UL_Data);\n\n\n\n\t\tconst UInt8 UInt8_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt8_UL(UInt8_UL_Data);\n\n\n\n\t\tconst UInt8 UInt8Array_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x04, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UInt8Array_UL(UInt8Array_UL_Data);\n\n\n\n\t\tconst UInt8 UL_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UL_UL(UL_UL_Data);\n\n\n\n\t\tconst UInt8 UMID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x30, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UMID_UL(UMID_UL_Data);\n\n\n\n\t\tconst UInt8 URLString_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL URLString_UL(URLString_UL_Data);\n\n\n\n\t\tconst UInt8 UTF16_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UTF16_UL(UTF16_UL_Data);\n\n\n\n\t\tconst UInt8 UTF16String_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UTF16String_UL(UTF16String_UL_Data);\n\n\n\n\t\tconst UInt8 UTF7String_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x20, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UTF7String_UL(UTF7String_UL_Data);\n\n\n\n\t\tconst UInt8 UUID_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UUID_UL(UUID_UL_Data);\n\n\n\n\t\tconst UInt8 UnknownChunk_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x4f, 0x00 };\n\n\t\tconst UL UnknownChunk_UL(UnknownChunk_UL_Data);\n\n\n\n\t\tconst UInt8 UserDataMode_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x05, 0x04, 0x02, 0x05, 0x01, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UserDataMode_UL(UserDataMode_UL_Data);\n\n\n\n\t\tconst UInt8 VBIDataDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x5b, 0x00 };\n\n\t\tconst UL VBIDataDescriptor_UL(VBIDataDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 VariableArrayElementType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x0d, 0x00, 0x00, 0x00 };\n\n\t\tconst UL VariableArrayElementType_UL(VariableArrayElementType_UL_Data);\n\n\n\n\t\tconst UInt8 Version_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Version_UL(Version_UL_Data);\n\n\n\n\t\tconst UInt8 VersionString_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x05, 0x20, 0x07, 0x01, 0x05, 0x01, 0x00, 0x00 };\n\n\t\tconst UL VersionString_UL(VersionString_UL_Data);\n\n\n\n\t\tconst UInt8 VersionType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL VersionType_UL(VersionType_UL_Data);\n\n\n\n\t\tconst UInt8 VerticalSubsampling_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x05, 0x01, 0x10, 0x00, 0x00, 0x00 };\n\n\t\tconst UL VerticalSubsampling_UL(VerticalSubsampling_UL_Data);\n\n\n\n\t\tconst UInt8 VideoLineMap_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x04, 0x01, 0x03, 0x02, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL VideoLineMap_UL(VideoLineMap_UL_Data);\n\n\n\n\t\tconst UInt8 WaveAudioDescriptor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x01, 0x01, 0x01, 0x01, 0x48, 0x00 };\n\n\t\tconst UL WaveAudioDescriptor_UL(WaveAudioDescriptor_UL_Data);\n\n\n\n\t\tconst UInt8 WeakRef_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL WeakRef_UL(WeakRef_UL_Data);\n\n\n\n\t\tconst UInt8 WeakReferenceArrayTypeDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL WeakReferenceArrayTypeDefinition_UL(WeakReferenceArrayTypeDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 WeakReferenceParameterDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL WeakReferenceParameterDefinition_UL(WeakReferenceParameterDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 WeakReferenceSetParameterDefinition_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x05, 0x03, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL WeakReferenceSetParameterDefinition_UL(WeakReferenceSetParameterDefinition_UL_Data);\n\n\n\n\t\tconst UInt8 WeakReferencedType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x02, 0x06, 0x01, 0x01, 0x07, 0x0a, 0x00, 0x00, 0x00 };\n\n\t\tconst UL WeakReferencedType_UL(WeakReferencedType_UL_Data);\n\n\n\n\t\tconst UInt8 WhiteReflevel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x05, 0x03, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL WhiteReflevel_UL(WhiteReflevel_UL_Data);\n\n\n\n\t\tconst UInt8 XOsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x04, 0x00, 0x00, 0x00 };\n\n\t\tconst UL XOsiz_UL(XOsiz_UL_Data);\n\n\n\n\t\tconst UInt8 XTOsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x08, 0x00, 0x00, 0x00 };\n\n\t\tconst UL XTOsiz_UL(XTOsiz_UL_Data);\n\n\n\n\t\tconst UInt8 XTsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x06, 0x00, 0x00, 0x00 };\n\n\t\tconst UL XTsiz_UL(XTsiz_UL_Data);\n\n\n\n\t\tconst UInt8 Xsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x02, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Xsiz_UL(Xsiz_UL_Data);\n\n\n\n\t\tconst UInt8 YOsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x05, 0x00, 0x00, 0x00 };\n\n\t\tconst UL YOsiz_UL(YOsiz_UL_Data);\n\n\n\n\t\tconst UInt8 YTOsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x09, 0x00, 0x00, 0x00 };\n\n\t\tconst UL YTOsiz_UL(YTOsiz_UL_Data);\n\n\n\n\t\tconst UInt8 YTsiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x07, 0x00, 0x00, 0x00 };\n\n\t\tconst UL YTsiz_UL(YTsiz_UL_Data);\n\n\n\n\t\tconst UInt8 Year_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Year_UL(Year_UL_Data);\n\n\n\n\t\tconst UInt8 Ysiz_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0a, 0x04, 0x01, 0x06, 0x03, 0x03, 0x00, 0x00, 0x00 };\n\n\t\tconst UL Ysiz_UL(Ysiz_UL_Data);\n\n\n\n\t\tconst UInt8 msBy4_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x06, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL msBy4_UL(msBy4_UL_Data);\n\n\n", "file_path": "mxflib/ulmap.h", "rank": 2, "score": 86361.94720784588 }, { "content": "namespace mxflib\n\n{\n\n\t/* Standard library features (bits 0 to 30) */\n\n\n\n\tconst UInt64 FeatureVersion1KLVFill\t = UINT64_C(1) << 0;\t//!< MXFLib feature: Write KLVFill items with the version 1 key\n\n\tconst UInt64 FeatureUnknownsByUL2Name = UINT64_C(1) << 1;\t//!< MXFLib feature: If an unknown UL is converted to a name during MDObject construction, using UL2NameFunc, check if this name is a known type\n\n\n\n\tconst UInt64 FeatureFullDescriptors = UINT64_C(1) << 2;\t//!< MXFLib feature: Fill in ALL Descriptor properties\n\n\tconst UInt64 FeatureStreamZeroBase = UINT64_C(1) << 3;\t//!< MXFLib feature: Set GC Essence Element Key StreamBase = 0, not 1\n\n\tconst UInt64 FeatureForceAES\t\t = UINT64_C(1) << 4;\t//!< MXFLib feature: Force PCM to act like AES\n\n\tconst UInt64 FeatureAlignAllStreams\t = UINT64_C(1) << 5;\t//!< MXFLib feature: Add alignment between GC Elements of same Type\n\n\n\n\t/* This sub-range is currently used by temporary fixes (bits 16 to 30) */\n\n\n\n\tconst UInt64 FeatureNegPrechargeIndex = UINT64_C(1) << 16;\t//!< MXFLib feature: Use -ve indexing for precharge\n\n\tconst UInt64 FeatureRDD9Properties = UINT64_C(1) << 17;\t//!< MXFLib feature: Do bad things to Descriptor properties\n\n\n\n\t/* Reserve a sub-range for user-extensions */\n\n\n\n\tconst UInt64 UserExtension = UINT64_C(1) << 31;\t//!< MXFLib feature: Reserved to allow user extensions\n\n\n\n\t/* Non-Standard library functions - may cause non-compliant behaviour (bits 32 to 63) */\n\n\n\n\n\n\n\n\tconst UInt64 FeatureLoadMetadict =\tUINT64_C(1) << 48;\t//!< Load any metadict when reading metadata\n\n\tconst UInt64 FeatureSaveMetadict = UINT64_C(1) << 49;\t//!< Add a KLV metadict when writing metadata (Only contains extension data)\n\n\tconst UInt64 FeatureUsedMetadict = UINT64_C(1) << 50;\t//!< Write any metadict as a complete version holding all types and sets used in the file along with all known properties of those sets\n\n\tconst UInt64 FeatureFullMetadict = UINT64_C(1) << 51;\t//!< Write any metadict as a full version holding all known types, sets and properties\n\n\tconst UInt64 FeatureKXSMetadict = UINT64_C(1) << 52;\t//!< Use version 1b of KLV Encoded Extension Syntax for any metadict\n\n\tconst UInt64 FeatureForceVBRIndex =\tUINT64_C(1) << 54;\t//!< Where possible write a VBR index even though CBR makes sense\n\n\tconst UInt64 FeatureNoHeaderIndex = UINT64_C(1) << 55;\t//!< Do not write index in header, mimic avid files\n\n\n\n\n\n\n\n\t// Declare the features bitmap\n\n\textern UInt64 Features;\n\n\n\n\n\n\t//! Set an MXFLib library feature (or multiple features)\n\n\t/*! \\return true if features set as requested\n\n\t * \\note If multiple features are requested and any one is unavailable none will be set\n\n\t *\n\n\t * DRAGONS: This code is written so that it will fold to:\n\n\t * - a simple bit-set if the value of SetValue is known at compile-time and it is enabled and unlocked\n\n\t * - an error message if the value of SetValue is known at compile-time and it is disabled or locked off\n\n\t * - a simple bit-set if the value of SetValue is non known at compile time, but no features are disabled or locked off\n\n\t * - the full function in all other cases\n\n\t */\n\n\tinline bool SetFeature(const UInt64 SetValue)\n\n\t{\n\n\t\t// Fail if any of the features are disabled\n\n\t\tif((SetValue & MXFLIB_FEATURE_MASK) != SetValue)\n\n\t\t{\n\n\t\t\terror(\"Feature 0x%s is not enabled in the current library\\n\", Int64toHexString(SetValue).c_str());\n\n\t\t\treturn false;\n\n\t\t}\n\n\n\n\t\t// Fail if any of the features are locked (unless they are locked enabled!)\n\n\t\tif(SetValue & MXFLIB_FEATURE_LOCK)\n\n\t\t{\n\n\t\t\t// Check if the locked bits are a problem (the locked value may be \"on\", which is fine)\n\n\t\t\tUInt64 Locked = SetValue & MXFLIB_FEATURE_LOCK;\n\n\t\t\tif(Locked & (~MXFLIB_FEATURE_DEFAULT))\n\n\t\t\t{\n\n\t\t\t\terror(\"Feature 0x%s is locked off in the current library\\n\", Int64toHexString(SetValue).c_str());\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\t// Set the feature or features\n\n\t\tFeatures |= SetValue;\n\n\n\n\t\t// All OK\n\n\t\treturn true;\n\n\t}\n\n\n\n\n\n\t//! Clear an MXFLib library feature (or multiple features)\n\n\t/*! \\return true if features cleared as requested\n\n\t * \\note If clearing of multiple features is requested and any one is locked on none will be cleared\n\n\t *\n\n\t * DRAGONS: This code is written so that it will fold to:\n\n\t * - a simple bit-clear if the value of SetValue is known at compile-time and it is unlocked\n\n\t * - an error message if the value of SetValue is known at compile-time and it is locked on\n\n\t * - a simple bit-clear if the value of SetValue is non known at compile time, but no features are locked on\n\n\t * - the full function in all other cases\n\n\t */\n\n\tinline bool ClearFeature(const UInt64 ClearValue)\n\n\t{\n\n\t\t// Fail if any of the features are locked (and they are locked enabled!)\n\n\t\tif(ClearValue & MXFLIB_FEATURE_LOCK)\n\n\t\t{\n\n\t\t\t// Check if the locked bits are a problem (the locked value may be \"off\", which is fine)\n\n\t\t\tUInt64 Locked = ClearValue & MXFLIB_FEATURE_LOCK;\n\n\t\t\tif(Locked & MXFLIB_FEATURE_DEFAULT)\n\n\t\t\t{\n\n\t\t\t\terror(\"Feature 0x%s is locked on in the current library\\n\", Int64toHexString(ClearValue).c_str());\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\t// Clear the feature or features\n\n\t\tFeatures &= ~ClearValue;\n\n\n\n\t\t// All OK\n\n\t\treturn true;\n\n\t}\n\n\n\n\n\n\t//! Determine if an MXFLibrary feature is selected (or combination of features are all selected)\n\n\t/* DRAGONS: This code is written so that it will fold to:\n\n\t * - a compile-time result if the value of Value is known at compile-time and it is disabled or locked (on or off)\n\n\t * - a simple bit-test if the value of SetValue is non known at compile time, but no features are disabled or locked\n\n\t * - the full function in all other cases\n\n\t */\n\n\tinline bool Feature(const UInt64 Value)\n\n\t{\n\n\t\t// If any of the features are disabled don't bother to read it\n\n\t\tif((Value & MXFLIB_FEATURE_MASK) != Value) return false;\n\n\n\n\t\t// If all of the features are locked simply return the compile-time setting\n\n\t\tif(Value & MXFLIB_FEATURE_LOCK)\n\n\t\t{\n\n\t\t\tif((Value & MXFLIB_FEATURE_DEFAULT) == Value) return true; else return false;\n\n\t\t}\n\n\n\n\t\t// Run-time test\n\n\t\tif((Value & Features) == Value) return true; else return false;\n\n\t}\n", "file_path": "mxflib/features.h", "rank": 3, "score": 86356.08929983043 }, { "content": "namespace mxflib\n\n{\n\n\ttypedef struct sopSAXHandlerStruct sopSAXHandler;\n\n\ttypedef sopSAXHandler *sopSAXHandlerPtr;\n\n\n\n\n\n\t/* Function pointer definitions */\n\n\ttypedef void (*startElementSAXFunc) (void *, const char *, const char **);\n\n\ttypedef void (*endElementSAXFunc) (void *, const char *);\n\n\ttypedef void (*warningSAXFunc) (void *, const char *msg, ...);\n\n\ttypedef void (*errorSAXFunc) (void *, const char *msg, ...);\n\n\ttypedef void (*fatalErrorSAXFunc) (void *, const char *msg, ...);\n\n\n\n\n\n\t/* Handler structure */\n\n\tstruct sopSAXHandlerStruct\n\n\t{\n\n\t\tstartElementSAXFunc startElement;\t\t/* startElement */\n\n\t\tendElementSAXFunc endElement;\t\t\t/* endElement */\n\n\t\twarningSAXFunc warning;\t\t\t\t\t/* warning */\n\n\t\terrorSAXFunc error;\t\t\t\t\t\t/* error */\n\n\t\tfatalErrorSAXFunc fatalError;\t\t\t/* fatalError */\n\n\t};\n\n\n\n\n\n\t/* Function Prototypes */\n\n\tbool sopSAXParseFile(sopSAXHandlerPtr sax, void *UserData, const char *filename);\n", "file_path": "mxflib/sopsax.h", "rank": 4, "score": 86356.08929983043 }, { "content": "namespace mxflib\n\n{\n\n#ifdef MXFLIB_DEBUG\n\n\tvoid debug(const char *Fmt, ...);\t\t\t\t\t\t//!< Display a general debug message\n\n#else\n\n\tinline void debug(const char *Fmt, ...) { return; };\t//!< Make debug messages optimise out\n\n#endif\n\n\n\n\tvoid warning(const char *Fmt, ...);\t\t\t\t\t\t//!< Display a warning message\n\n\tvoid error(const char *Fmt, ...);\t\t\t\t\t\t//!< Display an error message\n", "file_path": "mxflib/debug.h", "rank": 5, "score": 86356.08929983043 }, { "content": "namespace mxflib\n\n{\n\n\t//! Load dictionary from the specified legacy format XML definitions with a default symbol space\n\n\t/*! \\return 0 if all OK\n\n\t * \\return -1 on error\n\n\t */\n\n\tint LoadLegacyDictionary(const char *DictFile, SymbolSpacePtr DefaultSymbolSpace, bool FastFail = false);\n\n\n\n\t//! Load dictionary from the specified legacy format XML definitions with a default symbol space\n\n\t/*! \\return 0 if all OK\n\n\t * \\return -1 on error\n\n\t */\n\n\tinline int LoadLegacyDictionary(std::string DictFile, SymbolSpacePtr DefaultSymbolSpace, bool FastFail = false)\n\n\t{\n\n\t\treturn LoadLegacyDictionary(DictFile.c_str(), DefaultSymbolSpace, FastFail );\n", "file_path": "mxflib/legacytypes.h", "rank": 6, "score": 86356.08929983043 }, { "content": "namespace mxflib\n\n{\n\n\ttypedef UInt8 Uint8;\n\n\ttypedef UInt16 Uint16;\n\n\ttypedef UInt32 Uint32;\n\n\ttypedef UInt64 Uint64;\n\n\tinline std::string Uint64toString(Uint64 Val) { return UInt64toString(Val); }\n", "file_path": "mxflib/system.h", "rank": 7, "score": 86356.08929983043 }, { "content": "namespace mxflib {\n\n\n\n\t//! types of XML output format\n\n\tenum XML_Type_t {\n\n\t\tXML_Type_None,\n\n\t\tXML_Type_Default,\n\n\t\tXML_Type_AAFx,\n\n\t\tXML_Type_AAF_XML,\t// pre-std RegXML per AAFSDK 1.1.4\n\n\t\tXML_Type_MXFixer,\n\n\t\tXML_Type_RegXML,\t// SMPTE 2001 once it is approved\n\n\t\tXML_Type_SMPTE_434\n\n\t};\n\n\n\n\t//! XML output options struct\n\n\ttypedef struct _XML_options_t {\n\n\n\n\t\tXML_Type_t XMLType;\n\n\n\n\t} XML_options_t;\n\n\n\n\t//! Dump an MDObject\n\n\tvoid DumpObject( MDObjectPtr Object, std::string PrefixString, bool bare = false );\n\n\n", "file_path": "mxflib/dumpobject.h", "rank": 8, "score": 86356.08929983043 }, { "content": "namespace mxflib\n\n{\n\n\t/*\n\n\t** PutUxx() - Put unsigned xx-bit integer\n\n\t*/\n\n\tinline void PutU8(UInt8 x, unsigned char *dest) { *dest=(x); }\n\n\tinline void PutU16(UInt16 Data, unsigned char *Dest) { PutU8(Data >> 8, Dest); PutU8(Data & 0xff, &Dest[1]); }\n\n\tinline void PutU32(UInt32 Data, unsigned char *Dest) { PutU16(Data >> 16, Dest); PutU16(Data & 0xffff, &Dest[2]); }\n\n\tinline void PutU64(UInt64 Data, unsigned char *Dest) { PutU32((UInt32)(Data >> 32), Dest); \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t PutU32((UInt32)Data & 0xffffffff, &Dest[4]); }\n\n\n\n\t/*\n\n\t** PutIxx() - Signed versions of PutUxx()\n\n\t*/\n\n\tinline void PutI8(Int8 x, unsigned char *dest) { PutU8((UInt8)x,dest); }\n\n\tinline void PutI16(Int16 x, unsigned char *dest) { PutU16((UInt16)x,dest); }\n\n\tinline void PutI32(Int32 x, unsigned char *dest) { PutU32((UInt32)x,dest); }\n\n\tinline void PutI64(Int64 x, unsigned char *dest) { PutU64((UInt64)x,dest); }\n\n\n\n\t/*\n\n\t** GetUxx() - Get unsigned xx-bit integer\n\n\t*/\n\n\tinline UInt8 GetU8(const unsigned char *src) { return (UInt8) *src; }\n\n\tinline UInt16 GetU16(const unsigned char *src) { return (GetU8(src) << 8) | GetU8(&src[1]); }\n\n\tinline UInt32 GetU32(const unsigned char *src) { return (GetU16(src) << 16) | GetU16(&src[2]); }\n\n\tinline UInt64 GetU64(const unsigned char *src) { return (((UInt64)GetU32(src)) << 32) | (GetU32(&src[4])); }\n\n\n\n\t/*\n\n\t** GetIxx() - Signed versions of GetUxx()\n\n\t*/\n\n\tinline Int8 GetI8(const unsigned char *src) { return (Int8)GetU8(src); }\n\n\tinline Int16 GetI16(const unsigned char *src) { return (Int16)GetU16(src); }\n\n\tinline Int32 GetI32(const unsigned char *src) { return (Int32)GetU32(src); }\n\n\tinline Int64 GetI64(const unsigned char *src) { return (Int64)GetU64(src); }\n\n\n\n\t/*\n\n\t** PutUxx_LE() - Put LITTLE ENDIAN unsigned xx-bit integer\n\n\t*/\n\n\tinline void PutU8_LE(UInt8 x, unsigned char *dest) { *dest=(x); }\n\n\tinline void PutU16_LE(UInt16 Data, unsigned char *Dest) { PutU8_LE(Data & 0xff, Dest); PutU8_LE(Data >> 8, &Dest[1]); }\n\n\tinline void PutU32_LE(UInt32 Data, unsigned char *Dest) { PutU16_LE(Data & 0xffff, Dest); PutU16_LE(Data >> 16, &Dest[2]); }\n\n\tinline void PutU64_LE(UInt64 Data, unsigned char *Dest) { PutU32_LE((UInt32)(Data & 0xffffffff), Dest); \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t PutU32_LE((UInt32)(Data >> 32), &Dest[4]); }\n\n\n\n\t/*\n\n\t** PutIxx_LE() - Signed versions of PutUxx_LE()\n\n\t*/\n\n\tinline void PutI8_LE(Int8 x, unsigned char *dest) { PutU8_LE((UInt8)x,dest); }\n\n\tinline void PutI16_LE(Int16 x, unsigned char *dest) { PutU16_LE((UInt16)x,dest); }\n\n\tinline void PutI32_LE(Int32 x, unsigned char *dest) { PutU32_LE((UInt32)x,dest); }\n\n\tinline void PutI64_LE(Int64 x, unsigned char *dest) { PutU64_LE((UInt64)x,dest); }\n\n\n\n\t/*\n\n\t** GetUxx_LE() - Get LITTLE ENDIAN unsigned xx-bit integer\n\n\t*/\n\n\tinline UInt8 GetU8_LE(const unsigned char *src) { return (UInt8) *src; }\n\n\tinline UInt16 GetU16_LE(const unsigned char *src) { return GetU8_LE(src) | (GetU8_LE(&src[1]) << 8); }\n\n\tinline UInt32 GetU32_LE(const unsigned char *src) { return GetU16_LE(src) | (GetU16_LE(&src[2]) << 16); }\n\n\tinline UInt64 GetU64_LE(const unsigned char *src) { return GetU32_LE(src) | ((UInt64)(GetU32_LE(&src[4])) << 32); }\n\n\n\n\t/*\n\n\t** GetIxx_LE() - Signed versions of GetUxx_LE()\n\n\t*/\n\n\tinline Int8 GetI8_LE(const unsigned char *src) { return (Int8)GetU8_LE(src); }\n\n\tinline Int16 GetI16_LE(const unsigned char *src) { return (Int16)GetU16_LE(src); }\n\n\tinline Int32 GetI32_LE(const unsigned char *src) { return (Int32)GetU32_LE(src); }\n\n\tinline Int64 GetI64_LE(const unsigned char *src) { return (Int64)GetU64_LE(src); }\n\n\n", "file_path": "mxflib/endian.h", "rank": 9, "score": 86356.08929983043 }, { "content": "\tnamespace mxflib\n\n\t{\n\n\t\tconst UInt8 AS_12_ShimName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0c, 0x01, 0x01, 0x01 };\n\n\t\tconst UL AS_12_ShimName_UL(AS_12_ShimName_UL_Data);\n\n\n\n\t\tconst UInt8 AS_12_Slate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0c, 0x01, 0x01, 0x02 };\n\n\t\tconst UL AS_12_Slate_UL(AS_12_Slate_UL_Data);\n\n\n\n\t\tconst UInt8 DMS_AS_12_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0c, 0x01, 0x00, 0x00 };\n\n\t\tconst UL DMS_AS_12_UL(DMS_AS_12_UL_Data);\n\n\n\n\t\tconst UInt8 DMS_AS_12_AdID_Slate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL DMS_AS_12_AdID_Slate_UL(DMS_AS_12_AdID_Slate_UL_Data);\n\n\n\n\t\tconst UInt8 DMS_AS_12_Framework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0c, 0x01, 0x01, 0x00 };\n\n\t\tconst UL DMS_AS_12_Framework_UL(DMS_AS_12_Framework_UL_Data);\n\n\n\n\t\tconst UInt8 AS_12_DescriptiveObject_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0c, 0x01, 0x02, 0x00 };\n\n\t\tconst UL AS_12_DescriptiveObject_UL(AS_12_DescriptiveObject_UL_Data);\n\n\n\n\t\tconst UInt8 ad_title_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL ad_title_UL(ad_title_UL_Data);\n\n\n\n\t\tconst UInt8 adid_code_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL adid_code_UL(adid_code_UL_Data);\n\n\n\n\t\tconst UInt8 adid_prefix_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL adid_prefix_UL(adid_prefix_UL_Data);\n\n\n\n\t\tconst UInt8 advertiser_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL advertiser_UL(advertiser_UL_Data);\n\n\n\n\t\tconst UInt8 agency_office_location_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL agency_office_location_UL(agency_office_location_UL_Data);\n\n\n\n\t\tconst UInt8 brand_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL brand_UL(brand_UL_Data);\n\n\n\n\t\tconst UInt8 length_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL length_UL(length_UL_Data);\n\n\n\n\t\tconst UInt8 product_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x0d, 0x0d, 0x0d, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00 };\n\n\t\tconst UL product_UL(product_UL_Data);\n\n\n", "file_path": "mxflib/dict_DMS_AS_03.h", "rank": 10, "score": 84981.41102193357 }, { "content": "using namespace std;\n", "file_path": "mxflib/dumpobject.h", "rank": 11, "score": 81110.09081996424 }, { "content": "namespace mxflib\n\n{\n\n\t// Operational Pattern Labels\n\n\t// ==========================\n\n\t// DRAGONS: These are often just the degenerate labels - Qualifiers need to be filled in later!\n\n\n\n\t// OP-Atom - #### DRAGONS: Qualifiers need work later!\n\n\t// Note: pre mxflib 0.5.3, byte 8 version was erroneously = 01\n\n\tconst UInt8 OPAtom_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x02, 0x0d, 0x01, 0x02, 0x01, 0x10, 0x00, 0x00, 0x00 };\n\n\tconst UL OPAtomUL(OPAtom_Data);\n\n\n\n\tconst UInt8 OPAtom_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x02, 0x0d, 0x01, 0x02, 0x01, 0x10, 0x00, 0x00, 0x00 };\n\n\tconst UL OPAtom_UL(OPAtom_UL_Data);\n\n\n\n\t// OP1a - #### DRAGONS: Qualifiers may need work!\n\n\tconst UInt8 OP1a_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x00 };\n\n\tconst UL OP1aUL(OP1a_Data);\n\n\n\n\t// OP1b - #### DRAGONS: Qualifiers need work!\n\n\tconst UInt8 OP1b_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x01, 0x02, 0x05, 0x00 };\n\n\tconst UL OP1bUL(OP1b_Data);\n\n\n\n\t// OP2a - #### DRAGONS: Qualifiers need work!\n\n\tconst UInt8 OP2a_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x01, 0x01, 0x00 };\n\n\tconst UL OP2aUL(OP2a_Data);\n\n\n\n\t// OP2b - #### DRAGONS: Qualifiers need work!\n\n\tconst UInt8 OP2b_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x02, 0x05, 0x00 };\n\n\tconst UL OP2bUL(OP2b_Data);\n", "file_path": "libprocesswrap/opmap.h", "rank": 12, "score": 80455.43522530445 }, { "content": "\t//! Version for VBI usage of ANCVBISource\n\n\tclass VBISource : public ANCVBISource\n\n\t{\n\n\tpublic:\n\n\t\tVBISource(EssenceSource *Master = NULL) : ANCVBISource(Master) {};\n\n\n\n\t\t//! Get the GCEssenceType to use when wrapping this essence in a Generic Container\n\n\t\tvirtual UInt8 GetGCElementType(void) { return 0x01; }\n\n\n\n\tprotected:\n\n\t\t//! Get the wrapping UL to use\n\n\t\tvirtual ULPtr GetWrappingUL(void)\n\n\t\t{\n\n\t\t\tconst UInt8 WrappingUL[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x09, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0d, 0x00, 0x00 };\n\n\t\t\treturn new UL(WrappingUL);\n\n\t\t}\n\n\t};\n\n\n\n\n\n\t//! Smart pointer to ANCVBISource\n\n\ttypedef SmartPtr<ANCVBISource> ANCVBISourcePtr;\n\n\n\n\t//! Alias for ANC usage of ANCVBISourcePtr\n\n\ttypedef ANCVBISourcePtr ANCSourcePtr;\n\n\n\n\t//! Alias for VBI usage of ANCVBISourcePtr\n\n\ttypedef ANCVBISourcePtr VBISourcePtr;\n\n\n\n\n", "file_path": "mxflib/vbi.h", "rank": 13, "score": 80216.26160409968 }, { "content": "\t//! Version for ANC usage of ANCVBISource\n\n\tclass ANCSource : public ANCVBISource\n\n\t{\n\n\tpublic:\n\n\t\tANCSource(EssenceSource *Master = NULL) : ANCVBISource(Master) {};\n\n\n\n\t\t//! Get the GCEssenceType to use when wrapping this essence in a Generic Container\n\n\t\tvirtual UInt8 GetGCElementType(void) { return 0x02; }\n\n\n\n\tprotected:\n\n\t\t//! Get the wrapping UL to use\n\n\t\tvirtual ULPtr GetWrappingUL(void)\n\n\t\t{\n\n\t\t\tconst UInt8 WrappingUL[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x09, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x0e, 0x00, 0x00 };\n\n\t\t\treturn new UL(WrappingUL);\n\n\t\t}\n\n\t};\n\n\n", "file_path": "mxflib/vbi.h", "rank": 14, "score": 80216.26160409968 }, { "content": "\t//! Class for essence source that supplies system items\n\n\tclass SystemSource : public EssenceSource\n\n\t{\n\n\tprotected:\n\n\t\tEssenceSourceParent Master;\t\t\t\t\t\t\t\t//!< The master stream for this essence\n\n\t\tGCStreamID SMPackID;\t\t\t\t\t\t\t\t\t//!< Stream ID of the system metadata pack\n\n\t\tGCStreamID PMPackID;\t\t\t\t\t\t\t\t\t//!< Stream ID of the package metadata pack\n\n\t\tUInt16 ContinuityCount;\t\t\t\t\t\t\t\t\t//!< Continuity count as per SMPTE 385M\n\n\t\tint FPS;\t\t\t\t\t\t\t\t\t\t\t\t//!< Integer frame rate value (25 or 30)\n\n\t\tbool Rate1001;\t\t\t\t\t\t\t\t\t\t\t//!< True if FSP is a (n*1000) / 1001 rate\n\n\t\tUInt8 EssenceLabel[16];\t\t\t\t\t\t\t\t\t//!< The essence container label\n\n\t\tbool DropFrame;\t\t\t\t\t\t\t\t\t\t\t//!< True if timecode is using drop-frame counting\n\n\t\tUInt8 EssenceBitmap;\t\t\t\t\t\t\t\t\t//!< Bitmap flags for essence items, bit 1 = 1 if data, bit 2 = 1 if sound, bit 3 = 1 if picture\n\n\t\tBodyStream *Stream;\t\t\t\t\t\t\t\t\t\t//!< Our parent stream\n\n\t\tDataChunk CreationDate;\t\t\t\t\t\t\t\t\t//!< A pre-formatted 17-byte chunk holding the creation date/time, or an empty chunk if not set\n\n\t\tDataChunk TimecodeData;\t\t\t\t\t\t\t\t\t//!< A pre-formatted 17-byte chunk holding the timecode, or an empty chunk if not set\n\n\t\tDataChunk UMIDData;\t\t\t\t\t\t\t\t\t\t//!< A pre-formatted chunk holding the UMID data for the Package Item, or an empty chunk if not set\n\n\t\tDataChunk KLVData;\t\t\t\t\t\t\t\t\t\t//!< A pre-formatted chunk holding the KLV metadata for the Package Item, or an empty chunk if not set\n\n\n\n\tpublic:\n\n\t\tSystemSource(EssenceSource *MasterSource, const UL &WrappingUL) : EssenceSource()\n", "file_path": "mxflib/essence.h", "rank": 15, "score": 80216.1963906149 }, { "content": "\tclass SourceClip;\n", "file_path": "mxflib/metadata.h", "rank": 16, "score": 78617.61180730443 }, { "content": "\tclass EssenceSource;\n\n\n\n\t//! Return the MXF version as the year of the main MXF specification document\n\n\t/*! /ret 2004 if we are writing files as per SMPTE 377M-2004\n\n\t *! /ret 2009 if we are writing files as per SMPTE 377-1-2009\n\n\t */\n\n\tint MXFVersion(void);\n\n\n\n\t//! Set the MXF version as the year of the main MXF specification document\n\n\t/*! Use 2004 if we are writing files as per SMPTE 377M-2004\n\n\t *! Use 2009 if we are writing files as per SMPTE 377-1-2009\n\n\t */\n\n\tvoid SetMXFVersion(int Year);\n\n\n\n\t// Declare the global null-ul which is 16 zero bytes\n\n\textern const UL Null_UL;\n\n//_atoi64 is s wondows only - rewrite to linux version\n\n#ifndef _WIN32\n\n#define _atoi64 atoll\n\n#endif\n", "file_path": "mxflib/helper.h", "rank": 17, "score": 78617.61180730443 }, { "content": "\tMXFLIB_DICTIONARY_END\n\n\n\n\n\n\t// Define ULs for the global keys in this dictionary\n\n\tnamespace AS_11\n\n\t{\n\n\t\tconst UInt8 AS11CoreFramework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x00 };\n\n\t\tconst UL AS11CoreFramework_UL(AS11CoreFramework_UL_Data);\n\n\n\n\t\tconst UInt8 AS11CoreSchemeLabel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x00, 0x00 };\n\n\t\tconst UL AS11CoreSchemeLabel_UL(AS11CoreSchemeLabel_UL_Data);\n\n\n\n\t\tconst UInt8 AS11SegmentationFramework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x02, 0x01, 0x00 };\n\n\t\tconst UL AS11SegmentationFramework_UL(AS11SegmentationFramework_UL_Data);\n\n\n\n\t\tconst UInt8 AS11SegmentationSchemeLabel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x02, 0x00, 0x00 };\n\n\t\tconst UL AS11SegmentationSchemeLabel_UL(AS11SegmentationSchemeLabel_UL_Data);\n\n\n\n\t\tconst UInt8 AudioComments_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x14, 0x00 };\n\n\t\tconst UL AudioComments_UL(AudioComments_UL_Data);\n\n\n\n\t\tconst UInt8 AudioDescriptionPresent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x19, 0x00 };\n\n\t\tconst UL AudioDescriptionPresent_UL(AudioDescriptionPresent_UL_Data);\n\n\n\n\t\tconst UInt8 AudioDescriptionType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x1a, 0x00 };\n\n\t\tconst UL AudioDescriptionType_UL(AudioDescriptionType_UL_Data);\n\n\n\n\t\tconst UInt8 AudioLoudnessStandard_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x13, 0x00 };\n\n\t\tconst UL AudioLoudnessStandard_UL(AudioLoudnessStandard_UL_Data);\n\n\n\n\t\tconst UInt8 AudioTrackLayout_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x05 };\n\n\t\tconst UL AudioTrackLayout_UL(AudioTrackLayout_UL_Data);\n\n\n\n\t\tconst UInt8 AFD_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x05, 0x01, 0x0b, 0x01, 0x01, 0x05 };\n\n\t\tconst UL AFD_UL(AFD_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedCaptionsLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x09 };\n\n\t\tconst UL ClosedCaptionsLanguage_UL(ClosedCaptionsLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedCaptionsPresent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x07 };\n\n\t\tconst UL ClosedCaptionsPresent_UL(ClosedCaptionsPresent_UL_Data);\n\n\n\n\t\tconst UInt8 ClosedCaptionsType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x08 };\n\n\t\tconst UL ClosedCaptionsType_UL(ClosedCaptionsType_UL_Data);\n\n\n\n\t\tconst UInt8 CompletionDate_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00 };\n\n\t\tconst UL CompletionDate_UL(CompletionDate_UL_Data);\n\n\n\n\t\tconst UInt8 ContactEmail_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x24, 0x00 };\n\n\t\tconst UL ContactEmail_UL(ContactEmail_UL_Data);\n\n\n\n\t\tconst UInt8 ContactTelephoneNo_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x25, 0x00 };\n\n\t\tconst UL ContactTelephoneNo_UL(ContactTelephoneNo_UL_Data);\n\n\n\n\t\tconst UInt8 CopyrightYear_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x04, 0x00 };\n\n\t\tconst UL CopyrightYear_UL(CopyrightYear_UL_Data);\n\n\n\n\t\tconst UInt8 DMSegmentationFramework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x01, 0x01, 0x01, 0x00 };\n\n\t\tconst UL DMSegmentationFramework_UL(DMSegmentationFramework_UL_Data);\n\n\n\n\t\tconst UInt8 Distributor_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x08, 0x00 };\n\n\t\tconst UL Distributor_UL(Distributor_UL_Data);\n\n\n\n\t\tconst UInt8 EpisodeTitleNumber_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x03 };\n\n\t\tconst UL EpisodeTitleNumber_UL(EpisodeTitleNumber_UL_Data);\n\n\n\n\t\tconst UInt8 FPAManufacturer_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x0e, 0x00 };\n\n\t\tconst UL FPAManufacturer_UL(FPAManufacturer_UL_Data);\n\n\n\n\t\tconst UInt8 FPAPass_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x00 };\n\n\t\tconst UL FPAPass_UL(FPAPass_UL_Data);\n\n\n\n\t\tconst UInt8 FPAVersion_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x0f, 0x00 };\n\n\t\tconst UL FPAVersion_UL(FPAVersion_UL_Data);\n\n\n\n\t\tconst UInt8 Genre_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x07, 0x00 };\n\n\t\tconst UL Genre_UL(Genre_UL_Data);\n\n\n\n\t\tconst UInt8 IdentClockStart_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x16, 0x00 };\n\n\t\tconst UL IdentClockStart_UL(IdentClockStart_UL_Data);\n\n\n\n\t\tconst UInt8 LineUpStart_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x15, 0x00 };\n\n\t\tconst UL LineUpStart_UL(LineUpStart_UL_Data);\n\n\n\n\t\tconst UInt8 OpenCaptionsLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x00 };\n\n\t\tconst UL OpenCaptionsLanguage_UL(OpenCaptionsLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 OpenCaptionsPresent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x1b, 0x00 };\n\n\t\tconst UL OpenCaptionsPresent_UL(OpenCaptionsPresent_UL_Data);\n\n\n\n\t\tconst UInt8 OpenCaptionsType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x1c, 0x00 };\n\n\t\tconst UL OpenCaptionsType_UL(OpenCaptionsType_UL_Data);\n\n\n\n\t\tconst UInt8 Originator_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x03, 0x00 };\n\n\t\tconst UL Originator_UL(Originator_UL_Data);\n\n\n\n\t\tconst UInt8 OtherIdentifier_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x05, 0x00 };\n\n\t\tconst UL OtherIdentifier_UL(OtherIdentifier_UL_Data);\n\n\n\n\t\tconst UInt8 OtherIdentifierType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x06, 0x00 };\n\n\t\tconst UL OtherIdentifierType_UL(OtherIdentifierType_UL_Data);\n\n\n\n\t\tconst UInt8 PartNumber_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x02, 0x01, 0x01 };\n\n\t\tconst UL PartNumber_UL(PartNumber_UL_Data);\n\n\n\n\t\tconst UInt8 PartTotal_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x02, 0x01, 0x02 };\n\n\t\tconst UL PartTotal_UL(PartTotal_UL_Data);\n\n\n\n\t\tconst UInt8 PictureRatio_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x09, 0x00 };\n\n\t\tconst UL PictureRatio_UL(PictureRatio_UL_Data);\n\n\n\n\t\tconst UInt8 PrimaryAudioLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x06 };\n\n\t\tconst UL PrimaryAudioLanguage_UL(PrimaryAudioLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 ProductPlacement_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x0c, 0x00 };\n\n\t\tconst UL ProductPlacement_UL(ProductPlacement_UL_Data);\n\n\n\n\t\tconst UInt8 ProductionNumber_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00 };\n\n\t\tconst UL ProductionNumber_UL(ProductionNumber_UL_Data);\n\n\n\n\t\tconst UInt8 ProgrammeHasText_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x22, 0x00 };\n\n\t\tconst UL ProgrammeHasText_UL(ProgrammeHasText_UL_Data);\n\n\n\n\t\tconst UInt8 ProgrammeTextLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x23, 0x00 };\n\n\t\tconst UL ProgrammeTextLanguage_UL(ProgrammeTextLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 ProgrammeTitle_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x02 };\n\n\t\tconst UL ProgrammeTitle_UL(ProgrammeTitle_UL_Data);\n\n\n\n\t\tconst UInt8 SecondaryAudioLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x11, 0x00 };\n\n\t\tconst UL SecondaryAudioLanguage_UL(SecondaryAudioLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 SeriesTitle_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x01 };\n\n\t\tconst UL SeriesTitle_UL(SeriesTitle_UL_Data);\n\n\n\n\t\tconst UInt8 ShimName_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x01, 0x07, 0x01, 0x0b, 0x01, 0x01, 0x04 };\n\n\t\tconst UL ShimName_UL(ShimName_UL_Data);\n\n\n\n\t\tconst UInt8 SignLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x1f, 0x00 };\n\n\t\tconst UL SignLanguage_UL(SignLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 SigningPresent_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x1e, 0x00 };\n\n\t\tconst UL SigningPresent_UL(SigningPresent_UL_Data);\n\n\n\n\t\tconst UInt8 Synopsis_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00 };\n\n\t\tconst UL Synopsis_UL(Synopsis_UL_Data);\n\n\n\n\t\tconst UInt8 TertiaryAudioLanguage_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x12, 0x00 };\n\n\t\tconst UL TertiaryAudioLanguage_UL(TertiaryAudioLanguage_UL_Data);\n\n\n\n\t\tconst UInt8 TextlessElementsExist_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x21, 0x00 };\n\n\t\tconst UL TextlessElementsExist_UL(TextlessElementsExist_UL_Data);\n\n\n\n\t\tconst UInt8 ThreeD_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x0a, 0x00 };\n\n\t\tconst UL ThreeD_UL(ThreeD_UL_Data);\n\n\n\n\t\tconst UInt8 ThreeDType_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x0b, 0x00 };\n\n\t\tconst UL ThreeDType_UL(ThreeDType_UL_Data);\n\n\n\n\t\tconst UInt8 TotalNumberOfParts_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x17, 0x00 };\n\n\t\tconst UL TotalNumberOfParts_UL(TotalNumberOfParts_UL_Data);\n\n\n\n\t\tconst UInt8 TotalProgrammeDuration_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x18, 0x00 };\n\n\t\tconst UL TotalProgrammeDuration_UL(TotalProgrammeDuration_UL_Data);\n\n\n\n\t\tconst UInt8 UKDPPFramework_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00 };\n\n\t\tconst UL UKDPPFramework_UL(UKDPPFramework_UL_Data);\n\n\n\n\t\tconst UInt8 UKDPPSchemeLabel_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00 };\n\n\t\tconst UL UKDPPSchemeLabel_UL(UKDPPSchemeLabel_UL_Data);\n\n\n\n\t\tconst UInt8 VideoComments_UL_Data[16] = { 0x06, 0x0e, 0x2b, 0x34, 0x01, 0x01, 0x01, 0x01, 0x0d, 0x0c, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00 };\n\n\t\tconst UL VideoComments_UL(VideoComments_UL_Data);\n\n\n", "file_path": "mxflib/dict_as11.h", "rank": 18, "score": 77456.04504559484 }, { "content": "\t//! An essence source for sub-streams that slave from a master stream\n\n\tclass EssenceSubSource : public EssenceSource\n\n\t{\n\n\tprotected:\n\n\t\tEssenceSourceParent MasterSource;\t\t//!< The EssenceSource for the master source\n\n\t\tWrappingOptionPtr SelectedWrapping;\t\t//!< The selected wrapping options\n\n\n\n\tpublic:\n\n\t\t//! Base constructor\n\n\t\tEssenceSubSource(EssenceSource *Master = NULL) : MasterSource(Master) {};\n\n\n\n\t\t//! Virtual destructor to allow polymorphism\n\n\t\tvirtual ~EssenceSubSource() {};\n\n\n\n\t\t//! Set a new master after construction (useful if the master source is not known at construction time) \n\n\t\tvoid SetMaster(EssenceSource *Master)\n\n\t\t{\n\n\t\t\tMasterSource = Master;\n\n\t\t}\n\n\n\n\t\t//! Get a pointer to the current master source, this may be NULL if it is not yet defined\n", "file_path": "mxflib/essence.h", "rank": 19, "score": 76900.55598803768 }, { "content": "\t//! Essence source class to be used as the output of AudioDemux objects\n\n\tclass AudioDemuxSource : public EssenceSource\n\n\t{\n\n\tprotected:\n\n\t\tAudioDemuxParent Parent;\t\t\t//!< The parent demux object\n\n\t\tint Channel;\t\t\t\t\t\t//!< The number of our first channel (zero being the first in the outer source)\n\n\t\tint ChannelCount;\t\t\t\t\t//!< The number of channels to read at a time (e.g. ChannelCount = 2 give a stereo pair)\n\n\t\tbool Eoi;\t\t\t\t\t\t\t//!< True if the last GetEssenceData() call completed a wrapping item\n\n\n\n\t\tLength BytesPerEditUnit;\t\t\t//!< The size of an edit unit, if constant, else zero. Set to -1 when not known\n\n\t\tUInt32 BPEUKAGSize;\t\t\t\t\t//!< The KAGSize used to calculate BytesPerEditUnit\n\n\n\n\tprivate:\n\n\t\tAudioDemuxSource();\t\t\t\t\t//!< Prevent default construction\n\n\t\tAudioDemuxSource(AudioDemux&);\t\t//!< Prevent copy construction\n\n\n\n\tpublic:\n\n\t\t/*! \\param Channel The number of the first channel to read with the new source (zero being the first in the outer source)\n\n\t\t * \\param ChannelCount The number of channels to read at a time (e.g. ChannelCount = 2 give a stereo pair)\n\n\t\t */\n\n\t\tAudioDemuxSource(AudioDemux *Parent, unsigned int Channel, unsigned int ChannelCount = 1) \n", "file_path": "mxflib/audiomux.h", "rank": 20, "score": 76900.24200014865 }, { "content": "\t\t//! Essence Source that manages a sequence of essence sources from a list of file patterns\n\n\t\tclass SequentialEssenceSource : public EssenceSource\n\n\t\t{\n\n\t\tprotected:\n\n\t\t\tEssenceSourcePtr CurrentSource;\t\t\t\t//!< An EssenceSource for the current source file\n\n\t\t\tFileParserPtr Outer;\t\t\t\t\t\t//!< The outer file parser which is owned by us to prevent it being released until be are done\n\n\t\t\tLength PreviousLength;\t\t\t\t\t\t//!< The total size of all previously read essence sources for this set\n\n\t\t\tbool VBRIndexMode;\t\t\t\t\t\t\t//!< Are we needing to use VBRIndexMode for this essence?\n\n\t\t\t\n\n\t\t\t//! Option pair for OptionList\n\n\t\t\ttypedef std::pair<std::string, Int64> OptionPair;\n\n\t\t\t\n\n\t\t\t//! List of all options set for this source\n\n\t\t\tstd::list<OptionPair> OptionList;\n\n\n\n\t\t\t//! Prevent default construction\n\n\t\t\tSequentialEssenceSource();\n\n\n\n\t\tpublic:\n\n\t\t\t//! Construct a SequentialEssenceSource\n\n\t\t\tSequentialEssenceSource(FileParser *Outer) : Outer(Outer), PreviousLength(0), VBRIndexMode(false) {}\n", "file_path": "mxflib/essence.h", "rank": 21, "score": 76895.58375280364 }, { "content": "\t//! Holds data relating to a DMSourceClip\n\n\tclass DMSourceClip : public SourceClip\n\n\t{\n\n\tprotected:\n\n\t\t//! Protected constructor used to create from an existing MDObject\n\n\t\tDMSourceClip(MDObjectPtr BaseObject) : SourceClip(BaseObject) {}\n\n\n\n\tpublic:\n\n\t\tDMSourceClip(std::string BaseType) : SourceClip(BaseType) {};\n\n\t\tDMSourceClip(MDOTypePtr BaseType) : SourceClip(BaseType) {};\n\n\t\tDMSourceClip(const UL &BaseUL) : SourceClip(BaseUL) {};\n\n\t\tDMSourceClip(ULPtr &BaseUL) : SourceClip(BaseUL) {};\n\n\n\n\t\t//! Return the containing \"DMSourceClip\" object for this MDObject\n\n\t\t/*! \\return NULL if MDObject is not contained in a SourceClip object\n\n\t\t */\n\n\t\tstatic DMSourceClipPtr GetDMSourceClip(MDObjectPtr Object);\n\n\n\n\t\t//! Parse an existing MDObject into a DMSourceClip object\n\n\t\tstatic DMSourceClipPtr Parse(MDObjectPtr BaseObject);\n\n\t};\n\n}\n\n\n\n\n\nnamespace mxflib\n\n{\n", "file_path": "mxflib/metadata.h", "rank": 22, "score": 76894.75852668207 }, { "content": "\t//! Class that holds the ANC or VBI data for a frame and supplies it as an EssenceSource\n\n\tclass ANCVBISource : public EssenceSubSource\n\n\t{\n\n\tprotected:\n\n\t\tANCVBILineSourceList Sources;\t\t//!< List of line sources used to build lines\n\n\n\n\t\tANCVBILineMap Lines;\t\t\t\t//!< Map of lines built for this frame\n\n\n\n\t\tDataChunkList BufferedData;\t\t\t//!< List of data items prepared and ready to be supplied in response to GetEssenceData() - next to be supplied is the head\n\n\n\n\t\tsize_t BufferOffset;\t\t\t\t//!< An offset into the current data buffer if we are returning a partial chunk in GetEssenceData()\n\n\n\n\t\tPosition CurrentPosition;\t\t\t//!< Our current position. This is relative to the start of the stream, so the first edit unit is always 0\n\n\n\n\t\tint F2Offset;\t\t\t\t\t\t//!< The offset to add to field 2 line numbers (0 if no field 2, -1 if unknown)\n\n\n\n\t\tPosition EndAtPosition;\t\t\t\t//!< The position at which we end (0 for slave from master, -1 for not yet set)\n\n\n\n\tpublic:\n\n\t\t//! Base constructor\n\n\t\tANCVBISource(EssenceSource *Master = NULL) : EssenceSubSource(Master), BufferOffset(0), CurrentPosition(0), F2Offset(-1), EndAtPosition(-1) {};\n", "file_path": "mxflib/vbi.h", "rank": 23, "score": 76894.57129089406 }, { "content": "\t\tclass ESP_EssenceSource : public EssenceSource\n\n\t\t{\n\n\t\tprotected:\n\n\t\t\tEssenceSubParserPtr Caller;\n\n\t\t\tFileHandle File;\n\n\t\t\tUInt32 Stream;\n\n\t\t\tUInt64 RequestedCount;\n\n\t\t\tIndexTablePtr Index;\n\n\t\t\tDataChunkPtr RemainingData;\n\n\t\t\tbool AtEndOfData;\n\n\t\t\tbool Started;\n\n\n\n\t\tpublic:\n\n\t\t\t//! Construct and initialise for essence parsing/sourcing\n\n\t\t\tESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1)\n\n\t\t\t{\n\n\t\t\t\tCaller = TheCaller;\n\n\t\t\t\tFile = InFile;\n\n\t\t\t\tStream = UseStream;\n\n\t\t\t\tRequestedCount = Count;\n", "file_path": "mxflib/essence.h", "rank": 24, "score": 76888.94732715066 }, { "content": "\tclass RangedEssenceSource : public EssenceSource\n\n\t{\n\n\tprotected:\n\n\t\tEssenceSourcePtr Base;\t\t\t\t\t\t\t\t//!< The source being filtered\n\n\t\tPosition CurrentPosition;\t\t\t\t\t\t\t//!< The current position, stream relative not range relative\n\n\t\tPosition RequestedStart;\t\t\t\t\t\t\t//!< The requested first edit unit\n\n\t\tPosition RequestedEnd;\t\t\t\t\t\t\t\t//!< The requested last edit unit, or -1 if using RequestedDuration\n\n\t\tLength RequestedDuration;\t\t\t\t\t\t\t//!< The requested duration, or -1 if using RequestedEnd\n\n\n\n\t\tbool Started;\t\t\t\t\t\t\t\t\t\t//!< Set true once we have skipped the edit units before any pre-charge\n\n\t\tbool Ending;\t\t\t\t\t\t\t\t\t\t//!< Set true once beyond the end of the range, but not necessarily done with the overrun\n\n\t\tbool Ended;\t\t\t\t\t\t\t\t\t\t\t//!< Set true once the overrun is done\n\n\n\n\t\tPosition PreChargeStart;\t\t\t\t\t\t\t//!< The first edit unit in any pre-charge\n\n\t\tDataChunkList PreCharge;\t\t\t\t\t\t\t//!< Buffers of pre-charge essence\n\n\n\n\t\tDataChunkPtr FirstData;\t\t\t\t\t\t\t\t//!< The first edit unit following any pre-charge (as we will need to read it to check the pre-charge size)\n\n\n\n\tprivate:\n\n\t\t//! Prevent a default constructor\n", "file_path": "mxflib/essence.h", "rank": 25, "score": 76888.94732715066 }, { "content": "\t//! Class for holding a description of an essence stream \n\n\tclass EssenceStreamDescriptor;\n\n\n\n\t//! A smart pointer to a EssenceStreamDescriptor object\n\n\ttypedef SmartPtr<EssenceStreamDescriptor> EssenceStreamDescriptorPtr;\n\n\n\n\t//! A list of smart pointers to EssenceStreamDescriptor objects\n\n\ttypedef std::list<EssenceStreamDescriptorPtr> EssenceStreamDescriptorList;\n\n\n\n\t/*! \\page SubStreamNotes Notes on Sub-Streams\n\n\t * \\section SubStreams1 Sub-Streams Introduction\n\n\t * Certain essence streams may have intimate data related to the essence that is linked as a substream.\n\n\t * \\section SubParserSubStreams Sub-Streams in EssenceSubParsers\n\n\t * An EssenceSubParser may produce a main EssenceSource with sub-streams which are EssenceSources whose \n\n\t * data is extracted during the parsing that produces the main source's data. These SubStreams are indicated\n\n\t * by members of the EssenceStreamDescriptor::SubStreams properties of members of the EssenceStreamDescriptorList\n\n\t * returned by a call to EssenceSubParserBase::IdentifyEssence(). This in turn gets propogated to the \n\n\t * EssenceParser::WrapingConfig::SubStreams properties of members of the EssenceParser::WrapingConfigList\n\n\t * returned by a call to EssenceParser::ListWrappingOptions().\n\n\t *\n\n\t * The value of EssenceStreamDescriptor::ID, and hence EssenceParser::WrapingConfig::Stream, will differ\n", "file_path": "mxflib/essence.h", "rank": 26, "score": 73923.4727817756 }, { "content": "\t// Forward declare the demux output source class\n\n\tclass AudioDemuxSource;\n\n\n\n\t// A Smart pointer to an AudioDemuxSource object\n\n\ttypedef SmartPtr<AudioDemuxSource> AudioDemuxSourcePtr;\n\n\n\n\t// A parent pointer to an AudioDemuxSource object\n\n\ttypedef ParentPtr<AudioDemuxSource> AudioDemuxSourceParent;\n\n\n\n\n", "file_path": "mxflib/audiomux.h", "rank": 27, "score": 73901.68874945595 }, { "content": "\tclass DMSourceClip;\n", "file_path": "mxflib/metadata.h", "rank": 28, "score": 73895.87754992454 }, { "content": "\t//! Simple AFD line source\n\n\tclass SimpleAFDSource : public ANCVBILineSource\n\n\t{\n\n\tprotected:\n\n\t\tUInt8 CurrentAFD;\t\t\t\t\t\t\t\t//!< Current value of the AFD, will insert this value each frame\n\n\t\tint FieldNum;\t\t\t\t\t\t\t\t\t//!< Field number in which to insert this AFD\n\n\t\tint LineNum;\t\t\t\t\t\t\t\t\t//!< Line number in field to insert this AFD\n\n\n\n\tpublic:\n\n\t\t//! Construct from binary value\n\n\t\tSimpleAFDSource(UInt8 AFDValue, int Field, int Line) : CurrentAFD(AFDValue), FieldNum(Field), LineNum(Line) {};\n\n\n\n\t\t//! Construct from text value\n\n\t\tSimpleAFDSource(std::string AFDText, int Field, int Line) : FieldNum(Field), LineNum(Line) \n\n\t\t{\n\n\t\t\tCurrentAFD = TextToAFD(AFDText);\n\n\t\t};\n\n\n\n\t\t//! Allow polymorphic destructors\n\n\t\tvirtual ~SimpleAFDSource() {};\n\n\n", "file_path": "mxflib/vbi.h", "rank": 29, "score": 73844.95933130838 }, { "content": "\tclass EssenceSource : public RefCount<EssenceSource>\n\n\t{\n\n\tprotected:\n\n\t\t//! Holds the stream ID for this essence stream when added to a GCWriter\n\n\t\t/*! This value is persisted here between calls to a GCWriter via BodyWriter or similar.\n\n\t\t * Set to -1 if no stream ID yet set.\n\n\t\t */\n\n\t\tGCStreamID StreamID;\n\n\t\t\n\n\t\t//! Index manager to use if we can index the essence\n\n\t\tIndexManagerPtr IndexMan;\n\n\n\n\t\t//! Sub-stream ID to use for our index data if we can index the essence\n\n\t\tint IndexStreamID;\n\n\n\n\t\t//! If the default essence key has been overridden for this source it is stored here\n\n\t\tDataChunkPtr SpecifiedKey;\n\n\n\n\t\t//! True if the default essence key has been overridden with a key that does not use GC track number mechanism\n\n\t\tbool NonGC;\n", "file_path": "mxflib/essence.h", "rank": 30, "score": 73839.01622453978 }, { "content": "\t//! A smart pointer to a SourceClip object (with operator[] overload)\n\n\tclass SourceClipPtr : public SmartPtr<SourceClip>\n\n\t{\n\n\tpublic:\n\n\t\t//! Build a NULL pointer\n\n\t\tSourceClipPtr() : SmartPtr<SourceClip>() {}\n\n\n\n\t\t//! Build a pointer to an existing object\n\n\t\t/*! \\note The IRefCount has to be to a Component because that is what SourceClip is derived from */\n\n\t\tSourceClipPtr(IRefCount<Component> * ptr) : SmartPtr<SourceClip>((IRefCount<SourceClip> *)ptr) {}\n\n\n\n\t\t//! Child access operators that overcome dereferencing problems with SmartPtrs\n\n\t\tMDObjectPtr operator[](const char *ChildName);\n\n\t\tMDObjectPtr operator[](MDOTypePtr ChildType);\n\n\t\tMDObjectPtr operator[](const UL &ChildType);\n\n\t\tMDObjectPtr operator[](ULPtr &ChildType);\n\n\t};\n\n\n\n\n", "file_path": "mxflib/metadata.h", "rank": 31, "score": 71033.52882985433 }, { "content": "\tclass RangedEssenceSubSource : public EssenceSubSource\n\n\t{\n\n\tprotected:\n\n\t\tEssenceSourcePtr Base;\t\t\t\t\t\t\t\t//!< The source being filtered\n\n\t\tPosition RequestedStart;\t\t\t\t\t\t\t//!< The requested first edit unit\n\n\t\tPosition RequestedEnd;\t\t\t\t\t\t\t\t//!< The requested last edit unit, or -1 if using RequestedDuration\n\n\t\tLength RequestedDuration;\t\t\t\t\t\t\t//!< The requested duration, or -1 if using RequestedEnd\n\n\n\n\t\tbool Started;\t\t\t\t\t\t\t\t\t\t//!< Set true once we are ready to start reading\n\n\t\tbool Ended;\t\t\t\t\t\t\t\t\t\t\t//!< Set true once the range is done\n\n\n\n\tprivate:\n\n\t\t//! Prevent a default constructor\n\n\t\tRangedEssenceSubSource();\n\n\n\n\t\t//! Prevent copy construction\n\n\t\tRangedEssenceSubSource(const RangedEssenceSource &);\n\n\n\n\tpublic:\n\n\t\t// Base constructor\n", "file_path": "mxflib/essence.h", "rank": 32, "score": 71027.78141228095 }, { "content": "using namespace mxflib;\n", "file_path": "libprocesswrap/opmap.h", "rank": 33, "score": 69731.78750782346 }, { "content": "using namespace mxflib;\n", "file_path": "libprocesswrap/process.h", "rank": 34, "score": 69731.78750782346 }, { "content": "\t//! Holds data relating to a SourceClip\n\n\tclass SourceClip : public Component\n\n\t{\n\n\tprotected:\n\n\n\n\t\t//! Common construction code\n\n\t\tvoid Init(void)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\t//! Protected constructor used to create from an existing MDObject\n\n\t\tSourceClip(MDObjectPtr BaseObject) : Component(BaseObject) { Init(); }\n\n\n\n\tpublic:\n\n\t\tSourceClip(std::string BaseType) : Component(BaseType) { Init(); };\n\n\t\tSourceClip(MDOTypePtr BaseType) : Component(BaseType) { Init(); };\n\n\t\tSourceClip(const UL &BaseUL) : Component(BaseUL) { Init(); };\n\n\t\tSourceClip(ULPtr &BaseUL) : Component(BaseUL) { Init(); };\n\n\n\n\n\n\t\t//! Make a link to a specified track\n", "file_path": "mxflib/metadata.h", "rank": 35, "score": 69715.05568676494 }, { "content": "\tclass EssenceStreamDescriptor : public RefCount<EssenceStreamDescriptor>\n\n\t{\n\n\tpublic:\n\n\t\t//! Construct with any optional items cleared\n\n\t\tEssenceStreamDescriptor() : StartTimecode(0) {}\n\n\n\n\tpublic:\n\n\t\tUInt32 ID;\t\t\t\t\t\t\t\t//!< ID for this essence stream\n\n\t\tstd::string Description;\t\t\t\t//!< Description of this essence stream\n\n\t\tUUID SourceFormat;\t\t\t\t\t\t//!< A UUID (or byte-swapped UL) identifying the source format\n\n\t\tMDObjectPtr Descriptor;\t\t\t\t\t//!< Pointer to an actual essence descriptor for this stream\n\n\t\tEssenceStreamDescriptorList SubStreams;\t//!< A list of sub-streams that can be derived from this stream. See \\ref SubStreamNotes\n\n\t\tPosition StartTimecode;\t\t\t\t\t//!< The starting timecode of this essence, if known, or zero\n\n\t};\n\n\n\n\n", "file_path": "mxflib/essence.h", "rank": 36, "score": 68457.42446379681 }, { "content": "\t//! Superclass for objects that supply data to be wrapped by an ANCVBISource\n\n\tclass ANCVBILineSource : public RefCount<ANCVBILineSource>\n\n\t{\n\n\tprotected:\n\n\t\tEssenceSourceParent Parent;\t\t\t\t\t\t//!< The ANCVBISource that owns this line source\n\n\n\n\tpublic:\n\n\t\t//! Get the field number for the supplied ANC/VBI line\n\n\t\tvirtual int GetField(void) = 0;\n\n\n\n\t\t//! Get the line number within the field for the supplied ANC/VBI line\n\n\t\tvirtual int GetLineNumber(void) = 0;\n\n\n\n\t\t//! Get the SMPTE 436M wrapping type for this line\n\n\t\tvirtual ANCWrappingType GetWrappingType(void) = 0;\n\n\n\n\t\t//! Get the SMPTE 436M sample coding for this line\n\n\t\tvirtual ANCSampleCoding GetSampleCoding(void) = 0;\n\n\n\n\t\t//! Get the next line of data to wrap\n\n\t\tvirtual DataChunkPtr GetLineData(void) = 0;\n", "file_path": "mxflib/vbi.h", "rank": 37, "score": 68433.37769034416 }, { "content": "\t//! A smart pointer to a DMSourceClip object (with operator[] overload)\n\n\tclass DMSourceClipPtr : public SmartPtr<DMSourceClip>\n\n\t{\n\n\tpublic:\n\n\t\t//! Build a NULL pointer\n\n\t\tDMSourceClipPtr() : SmartPtr<DMSourceClip>() {}\n\n\n\n\t\t//! Build a pointer to an existing object\n\n\t\t/*! \\note The IRefCount has to be to a Component because that is what DMSourceClip is derived from */\n\n\t\tDMSourceClipPtr(IRefCount<Component> * ptr) : SmartPtr<DMSourceClip>((IRefCount<DMSourceClip> *)ptr) {}\n\n\n\n\t\t//! Child access operators that overcome dereferencing problems with SmartPtrs\n\n\t\tMDObjectPtr operator[](const char *ChildName);\n\n\t\tMDObjectPtr operator[](MDOTypePtr ChildType);\n\n\t\tMDObjectPtr operator[](const UL &ChildType);\n\n\t\tMDObjectPtr operator[](ULPtr &ChildType);\n\n\t};\n\n\n", "file_path": "mxflib/metadata.h", "rank": 38, "score": 66020.82385365084 }, { "content": "\tbool UseIndex\t;\t\t\t\t\t\t//!< Write complete index tables\n", "file_path": "libprocesswrap/process.h", "rank": 39, "score": 65999.51548227791 }, { "content": "\tbool IncludeSubstreams;\t\t\t\t\t//!< Should sub-streams also be wrapped\n", "file_path": "libprocesswrap/process.h", "rank": 40, "score": 65999.51548227791 }, { "content": "using namespace mxflib;\n", "file_path": "libprocesswrap/process_utils.h", "rank": 41, "score": 65992.84893587037 }, { "content": "using namespace mxflib;\n", "file_path": "libprocesswrap/process_metadata.h", "rank": 42, "score": 65992.84893587037 }, { "content": "\t//! List of pairs of essence parser pointers with associated file descriptors\n\n\tclass ParserDescriptorList : public RefCount<ParserDescriptorList>, public std::list<ParserDescriptorPair> {};\n\n\ttypedef SmartPtr<ParserDescriptorList> ParserDescriptorListPtr;\n\n\n\n\n", "file_path": "mxflib/essence.h", "rank": 43, "score": 64596.353533565074 }, { "content": "\t// Forware declare MDObjectPtr and EssenceSource\n\n\tclass MDObjectPtr;\n", "file_path": "mxflib/helper.h", "rank": 44, "score": 63912.761412228494 }, { "content": "\tclass MDObjectPtr;\n\n}\n\n\n\n\n\nnamespace mxflib\n\n{\n\n\t//! Soft limit for strings returned by MDTraits\n\n\t/*! \\note This is a soft limit in that it is not enforced strictly.\n\n\t * It is possible for string values to be returned that are longer than this value, but where\n\n\t *\t\t the string is built by several passes around a loop that loop should exit once this value\n\n\t *\t\t has been reached\n\n\t *\n\n * TODO: Apply this limit to everywhere it is required!!\n\n\t */\n\n\textern UInt32 MDTraits_StringLimit;\n\n\n\n\t//! Set the string size soft limit\n\n\tinline void SetStringLimit(UInt32 StringLimit) { MDTraits_StringLimit = StringLimit; }\n\n\n\n\t//! Get the current string size soft limit\n", "file_path": "mxflib/mdtraits.h", "rank": 45, "score": 63907.01399465511 }, { "content": "\tclass MDObjectPtr;\n", "file_path": "mxflib/typeif.h", "rank": 46, "score": 63907.01399465511 }, { "content": "\t\t//! Class for EssenceSource objects for parsing/sourcing <Type> essence\n\n\t\tclass ESP_EssenceSource : public EssenceSubParserBase::ESP_EssenceSource\n\n\t\t{\n\n\t\tprotected:\n\n\t\t\tsize_t BytesRemaining;\t\t\t\t\t\t\t//!< The number of bytes remaining in a multi-part GetEssenceData, or zero if not part read\n\n\n\n\t\tpublic:\n\n\t\t\t//! Construct and initialise for essence parsing/sourcing\n\n\t\t\tESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1/*, IndexTablePtr UseIndex = NULL*/)\n\n\t\t\t\t: EssenceSubParserBase::ESP_EssenceSource(TheCaller, InFile, UseStream, Count/*, UseIndex*/) \n\n\t\t\t{\n\n\t\t\t\tBytesRemaining = 0;\n\n\t\t\t};\n\n\n\n\t\t\t//! Get the size of the essence data in bytes\n\n\t\t\t/*! \\note There is intentionally no support for an \"unknown\" response \n\n\t\t\t */\n\n\t\t\tvirtual size_t GetEssenceDataSize(void) \n\n\t\t\t{\n\n\t\t\t\tTEMPLATE_EssenceSubParser *pCaller = SmartPtr_Cast(Caller, TEMPLATE_EssenceSubParser);\n\n\t\t\t\treturn pCaller->ReadInternal(File, Stream, RequestedCount);\n", "file_path": "mxflib/esp_template.h", "rank": 47, "score": 61682.55573922708 }, { "content": "\t\t//! Class for EssenceSource objects for parsing/sourcing <Type> essence\n\n\t\tclass ESP_EssenceSource : public EssenceSubParserBase::ESP_EssenceSource\n\n\t\t{\n\n\t\tpublic:\n\n\t\t\t//! Construct and initialise for essence parsing/sourcing\n\n\t\t\tESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1/*, IndexTablePtr UseIndex = NULL*/)\n\n\t\t\t\t: EssenceSubParserBase::ESP_EssenceSource(TheCaller, InFile, UseStream, Count/*, UseIndex*/) \n\n\t\t\t{\n\n\t\t\t};\n\n\n\n\t\t\t//! Get the size of the essence data in bytes\n\n\t\t\t/*! \\note There is intentionally no support for an \"unknown\" response \n\n\t\t\t */\n\n\t\t\tvirtual size_t GetEssenceDataSize(void) \n\n\t\t\t{\n\n\t\t\t\tJP2K_EssenceSubParser *pCaller = SmartPtr_Cast(Caller, JP2K_EssenceSubParser);\n\n\t\t\t\treturn pCaller->ReadInternal(File, Stream, RequestedCount);\n\n\t\t\t};\n\n\n\n\t\t\t//! Get the next \"installment\" of essence data\n\n\t\t\t/*! \\return Pointer to a data chunk holding the next data or a NULL pointer when no more remains\n", "file_path": "mxflib/esp_jp2k.h", "rank": 48, "score": 61682.55573922708 }, { "content": "\t\t//! Class for EssenceSource objects for parsing/sourcing MPEG-VES essence\n\n\t\tclass ESP_EssenceSource : public EssenceSubParserBase::ESP_EssenceSource\n\n\t\t{\n\n\t\tprotected:\n\n\t\t\tsize_t BytesRemaining;\t\t\t\t\t\t\t//!< The number of bytes remaining in a multi-part GetEssenceData, or zero if not part read\n\n\n\n\t\tpublic:\n\n\t\t\t//! Construct and initialise for essence parsing/sourcing\n\n\t\t\tESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1)\n\n\t\t\t\t: EssenceSubParserBase::ESP_EssenceSource(TheCaller, InFile, UseStream, Count) \n\n\t\t\t{\n\n\t\t\t\tBytesRemaining = 0;\n\n\t\t\t};\n\n\n\n\t\t\t//! Get the size of the essence data in bytes\n\n\t\t\t/*! \\note There is intentionally no support for an \"unknown\" response \n\n\t\t\t */\n\n\t\t\tvirtual size_t GetEssenceDataSize(void) \n\n\t\t\t{\n\n\t\t\t\tMPEG2_VES_EssenceSubParser *pCaller = SmartPtr_Cast(Caller, MPEG2_VES_EssenceSubParser);\n\n\t\t\t\t\n", "file_path": "mxflib/esp_mpeg2ves.h", "rank": 49, "score": 61682.51341797262 }, { "content": "\t\t//! Class for EssenceSource objects for parsing/sourcing DV-DIF essence\n\n\t\tclass ESP_EssenceSource : public EssenceSubParserBase::ESP_EssenceSource\n\n\t\t{\n\n\t\tpublic:\n\n\t\t\t//! Construct and initialise for essence parsing/sourcing\n\n\t\t\tESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1/*, IndexTablePtr UseIndex = NULL*/)\n\n\t\t\t\t: EssenceSubParserBase::ESP_EssenceSource(TheCaller, InFile, UseStream, Count/*, UseIndex*/) \n\n\t\t\t{\n\n\t\t\t\tDV_DIF_EssenceSubParser *pCaller = SmartPtr_Cast(Caller, DV_DIF_EssenceSubParser);\n\n\n\n\t\t\t\tif(pCaller->SelectedWrapping->ThisWrapType == WrappingOption::Clip) RequestedCount = 0;\n\n\t\t\t};\n\n\n\n\t\t\t//! Get the size of the essence data in bytes\n\n\t\t\t/*! \\note There is intentionally no support for an \"unknown\" response \n\n\t\t\t */\n\n\t\t\tvirtual size_t GetEssenceDataSize(void) \n\n\t\t\t{\n\n\t\t\t\tDV_DIF_EssenceSubParser *pCaller = SmartPtr_Cast(Caller, DV_DIF_EssenceSubParser);\n\n\t\t\t\treturn pCaller->ReadInternal(File, Stream, RequestedCount/*, Index*/);\n\n\t\t\t};\n", "file_path": "mxflib/esp_dvdif.h", "rank": 50, "score": 61682.51341797262 }, { "content": "\t\t//! Class for EssenceSource objects for parsing/sourcing MPEG-VES essence\n\n\t\tclass ESP_EssenceSource : public EssenceSubParserBase::ESP_EssenceSource\n\n\t\t{\n\n\t\tprotected:\n\n\t\t\tsize_t BytesRemaining;\t\t\t\t\t\t\t//!< The number of bytes remaining in a multi-part GetEssenceData, or zero if not part read\n\n\n\n\t\t\tbool PaddingEnabled;\t\t\t\t\t\t\t//!< Is padding after the end of the essence stream enabled? Used when audio input is less than video\n\n\t\t\tDataChunkPtr PaddingChunk;\t\t\t\t\t\t//!< A chunk containing padding bytes (if required) for use in GetPadding()\n\n\t\t\tInt64 ExtraSamples;\t\t\t\t\t\t\t //!< Number of extra samples to output after end of frame\n\n\n\n\n\n\t\tpublic:\n\n\t\t\t//! Construct and initialise for essence parsing/sourcing\n\n\t\t\tESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1/*, IndexTablePtr UseIndex = NULL*/)\n\n\t\t\t\t: EssenceSubParserBase::ESP_EssenceSource(TheCaller, InFile, UseStream, Count/*, UseIndex*/) \n\n\t\t\t{\n\n\t\t\t\tBytesRemaining = 0;\n\n\t\t\t\tPaddingEnabled = false;\n\n\t\t\t};\n\n\n\n\t\t\t//! Get the size of the essence data in bytes\n", "file_path": "mxflib/esp_wavepcm.h", "rank": 51, "score": 61682.51341797262 }, { "content": "\t// Extended implementations\n\n\tclass MDTraits_BasicInt : public MDTraits\n\n\t{\n\n\tpublic:\n\n\t\t//! A unique name for this trait\n\n\t\tvirtual std::string Name() const { return \"mxflib::MDTraits_BasicInt\"; };\n\n\n\n\tprotected:\n\n\t\tvirtual void SetInt64(MDObject *Object, Int64 Val);\n\n\t\tvirtual void SetUInt(MDObject *Object, UInt32 Val);\n\n\t\tvirtual void SetUInt64(MDObject *Object, UInt64 Val);\n\n\t\tvirtual void SetString(MDObject *Object, std::string Val);\n\n\t\tvirtual Int64 GetInt64(const MDObject *Object) const;\n\n\t\tvirtual UInt64 GetUInt64(const MDObject *Object) const;\n\n\t\tvirtual std::string GetString(const MDObject *Object) const;\n\n\n\n //Overridden to avoid partial overriden virtual function issues with ICC\n\n virtual std::string GetString(const MDObject *Object, OutputFormatEnum Format) const { return GetString(Object); }\n\n\n\n\t\tvirtual size_t ReadValue(MDObject *Object, const UInt8 *Buffer, size_t Size, int Count=0);\n\n\t};\n\n\n\n\t//! Special unsigned integer ReadValue\n\n\tsize_t ReadValueUInt(MDObject *Object, const UInt8 *Buffer, size_t Size, int Count=0);\n\n\n", "file_path": "mxflib/mdtraits.h", "rank": 52, "score": 59604.26416957685 }, { "content": "\tclass MDTraits_Int16 : public MDTraits_BasicInt\n\n\t{\n\n\tpublic:\n\n\t\t//! A unique name for this trait\n\n\t\tvirtual std::string Name() const { return \"mxflib::MDTraits_Int16\"; };\n\n\n\n\tprotected:\n\n\t\tvirtual void SetInt(MDObject *Object, Int32 Val);\n\n\t\tvirtual Int32 GetInt(const MDObject *Object) const;\n\n\t\tvirtual UInt32 GetUInt(const MDObject *Object) const;\n\n\t};\n\n\n", "file_path": "mxflib/mdtraits.h", "rank": 53, "score": 56851.20020699433 }, { "content": "\tclass MDTraits_Int32 : public MDTraits_BasicInt\n\n\t{\n\n\tpublic:\n\n\t\t//! A unique name for this trait\n\n\t\tvirtual std::string Name() const { return \"mxflib::MDTraits_Int32\"; };\n\n\n\n\tprotected:\n\n\t\tvirtual void SetInt(MDObject *Object, Int32 Val);\n\n\t\tvirtual Int32 GetInt(const MDObject *Object) const;\n\n\t\tvirtual UInt32 GetUInt(const MDObject *Object) const;\n\n\t};\n\n\n", "file_path": "mxflib/mdtraits.h", "rank": 54, "score": 56851.20020699433 }, { "content": "\tclass MDTraits_Int8 : public MDTraits_BasicInt\n\n\t{\n\n\tpublic:\n\n\t\t//! A unique name for this trait\n\n\t\tvirtual std::string Name() const { return \"mxflib::MDTraits_Int8\"; };\n\n\n\n\tprotected:\n\n\t\tvirtual void SetInt(MDObject *Object, Int32 Val);\n\n\t\tvirtual Int32 GetInt(const MDObject *Object) const;\n\n\t\tvirtual UInt32 GetUInt(const MDObject *Object) const;\n\n\t};\n\n\n", "file_path": "mxflib/mdtraits.h", "rank": 55, "score": 56851.20020699433 }, { "content": "struct tm mxflib::StringToTm(std::string String)\n\n{\n\n\tstruct tm Time;\n\n\tTime.tm_isdst = 0;\n\n\n\n\tif(String.length() < 18)\n\n\t{\n\n\t\tTime.tm_year = 0;\n\n\t\tTime.tm_mon = 0;\n\n\t\tTime.tm_mday = 0;\n\n\t\tTime.tm_hour = 0;\n\n\t\tTime.tm_min = 0;\n\n\t\tTime.tm_sec = 0;\n\n\t\treturn Time;\n\n\t}\n\n\n\n\tTime.tm_year = atoi(&String.c_str()[0]) - 1970;\n\n\tTime.tm_mon = atoi(&String.c_str()[5]) - 1;\n\n\tTime.tm_mday = atoi(&String.c_str()[8]);\n\n\tTime.tm_hour = atoi(&String.c_str()[11]);\n", "file_path": "mxflib/helper.cpp", "rank": 56, "score": 52681.55245362313 }, { "content": "\tclass BodyStream : public RefCount<BodyStream>, public EssenceSourceList\n\n\t{\n\n\tpublic:\n\n\t\t//! Define the action required next for this stream\n\n\t\tenum StateType\n\n\t\t{\n\n\t\t\tBodyStreamStart = 0,\t\t\t\t\t\t\t\t\t//!< This stream has not yet done anything - state unknown\n\n\t\t\tBodyStreamHeadIndex,\t\t\t\t\t\t\t\t\t//!< Next action: Write a \"header\" index table - if required in an isolated partition following the header\n\n\t\t\tBodyStreamPreBodyIndex,\t\t\t\t\t\t\t\t\t//!< Next action: Write an isolated index table before the next body partition\n\n\t\t\tBodyStreamBodyWithIndex,\t\t\t\t\t\t\t\t//!< Next action: Write a body partition with an index table\n\n\t\t\tBodyStreamBodyNoIndex,\t\t\t\t\t\t\t\t\t//!< Next action: Write a body partition without index table\n\n\t\t\tBodyStreamPostBodyIndex,\t\t\t\t\t\t\t\t//!< Next action: Write an isolated index table after a body partition\n\n\t\t\tBodyStreamFootIndex,\t\t\t\t\t\t\t\t\t//!< Next action: Write a \"footer\" index table - if required in an isolated partition before the footer\n\n\t\t\tBodyStreamDone\t\t\t\t\t\t\t\t\t\t\t//!< All done - no more actions required\n\n\t\t};\n\n\n\n\t\t//! The index table type or types of this stream\n\n\t\tenum IndexType\n\n\t\t{\n\n\t\t\tStreamIndexNone = 0,\t\t\t\t\t\t\t\t\t//!< No index table will be written\n", "file_path": "mxflib/essence.h", "rank": 57, "score": 49913.59438482755 }, { "content": "\tMXFLIB_TYPE_END\n\n\n\n\t// Types definitions converted from file ./dict.xml\n", "file_path": "mxflib/dict.h", "rank": 58, "score": 45684.801582741486 }, { "content": "\t\tMXFLIB_DICTIONARY_CLASSES(DictData_Classes_10)\n", "file_path": "mxflib/dict.h", "rank": 59, "score": 45684.801582741486 }, { "content": "\t\tMXFLIB_CLASS_SET_END\n\n\tMXFLIB_CLASS_END\n\n\n", "file_path": "mxflib/dict.h", "rank": 60, "score": 45684.801582741486 }, { "content": "\t\tMXFLIB_DICTIONARY_TYPES(DictData_Types_8)\n", "file_path": "mxflib/dict.h", "rank": 61, "score": 45684.801582741486 }, { "content": "\t\tMXFLIB_DICTIONARY_CLASSES(DictData_Classes_8)\n", "file_path": "mxflib/dict.h", "rank": 62, "score": 45684.801582741486 }, { "content": "\tMXFLIB_TYPE_END\n\n\n\n\t// Class definitions converted from file ./dict.xml\n", "file_path": "mxflib/dict.h", "rank": 63, "score": 45684.801582741486 }, { "content": "\t//! A smart pointer to an MDObject object (with operator[] overloads)\n\n\tclass MDObjectPtr : public SmartPtr<MDObject>\n\n\t{\n\n\tpublic:\n\n\t\tMDObjectPtr() : SmartPtr<MDObject>() {};\n\n\t\tMDObjectPtr(IRefCount<MDObject> * ptr) : SmartPtr<MDObject>(ptr) {};\n\n\t\tMDObjectPtr(MDObjectParent ptr);\n\n\n\n\t\t//! Child access operators that overcome dereferencing problems with SmartPtrs\n\n\t\tMDObjectPtr operator[](const char *ChildName) const;\n\n\t\tMDObjectPtr operator[](const MDOTypePtr &ChildType) const;\n\n\t\tMDObjectPtr operator[](const MDTypePtr &ChildType) const;\n\n\t\tMDObjectPtr operator[](int Index) const;\n\n\t\tMDObjectPtr operator[](const UL &ChildType) const;\n\n\t\tMDObjectPtr operator[](const ULPtr &ChildType) const;\n\n\t};\n\n\n", "file_path": "mxflib/forward.h", "rank": 64, "score": 45138.35083437733 }, { "content": "\tMXFLIB_TYPE_END\n\n\n\n\t// Types definitions converted from file C:\\dev\\mxflib\\dict_as11.xml\n", "file_path": "mxflib/dict_as11.h", "rank": 65, "score": 44451.244470523605 }, { "content": "\t\tMXFLIB_CLASS_SET_END\n\n\tMXFLIB_CLASS_END\n\n\n", "file_path": "mxflib/dict_as11.h", "rank": 66, "score": 44451.244470523605 }, { "content": "\tMXFLIB_DICTIONARY_START(AS11)\n", "file_path": "mxflib/dict_as11.h", "rank": 67, "score": 44451.244470523605 }, { "content": "\t\tMXFLIB_TYPE_ENUM_END\n\n\tMXFLIB_TYPE_END\n\n\n", "file_path": "mxflib/dict_as11.h", "rank": 68, "score": 44451.244470523605 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\nusing namespace mxflib;\n\n\n\n// Define the features bitmap - turn on those features set by compile time switch\n\nUInt64 mxflib::Features = MXFLIB_FEATURE_DEFAULT & MXFLIB_FEATURE_MASK;\n\n\n\n\n\nnamespace\n\n{\n\n\t//! The version year of the MXF specification being used to write files. Returned by MXFVersion() and set by SetMXFVersion()\n\n\tint MXFVersionYear = 2004;\n\n\n", "file_path": "mxflib/helper.cpp", "rank": 69, "score": 36.449243272925585 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"testmxfsplit.h\"\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"libmxfsplit.h\"\n\n#include \"containerinfo.h\"\n\n\n\n//! very basic usage assumes all Descriptors wanted\n\nbool Wanted( DescriptorPtr d ){ return true; }\n\n\n\n//! Simple test of Processor-based splitting\n\nint Simple( const char *file, const unsigned firstFrame, const unsigned nFrames, const char ProcSink /*='\\0'*/ )\n", "file_path": "libmxfsplit/testmxfsplit.cpp", "rank": 70, "score": 33.82557317315029 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n#include \"dumpobject.h\"\n\n\n\n#include \"utility/utility.h\"\n\nusing namespace utility;\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include <stdio.h>\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nnamespace mxflib {\n\n\n", "file_path": "mxflib/dumpobject.cpp", "rank": 71, "score": 31.958112786446378 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"libmxfsplit.h\"\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"containerinfo.h\"\n\n\n\n//! Initialize SplitProcessor\n\nint SplitProcessor::Initialize()\n\n{\n\n\tint Ret = 0;\n\n\n\n\t_ContainerInfo = ContainerInfo::CreateAndBuild(_File);\n", "file_path": "libmxfsplit/libmxfsplit.cpp", "rank": 72, "score": 31.605117030177887 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n#ifndef _LIBMXFSPLIT_H_\n\n#define _LIBMXFSPLIT_H_\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"containerinfo.h\"\n\n#include \"basesink.h\"\n\n\n\n#include <vector>\n\n\n\ntypedef MDObjectPtr DescriptorPtr;\n\n\n\nnamespace mxflib\n\n{\n\n\t//! SplitProcessor - singleton class to do all processing of MXF file splitting\n", "file_path": "libmxfsplit/libmxfsplit.h", "rank": 73, "score": 31.420824721353483 }, { "content": "#include \"DotFile.h\"\n\n#include <mxflib/mxflib.h>\n\n\n\n#include <vector>\n\n#include <cassert>\n\n#include <stdarg.h>\n\n\n\n\n\n#ifdef COMPILED_DICT\n\n#include <mxflib/dict.h>\n\n#endif\n\n\n\nusing namespace std;\n\nusing namespace dot;\n\nusing namespace mxflib;\n\n\n\n\n\n// Debug flag for KLVLib\n\nint Verbose = 0;\n\n\n", "file_path": "mxf2dot/mxf2dot.cpp", "rank": 74, "score": 31.256964811172637 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n\n\n\n\n#include <string.h>\t\t/* strcpy */\n\n\n\n\n\n#include \"mxflib/mxflib.h\"\n\n#include \"sopsax.h\"\n\n\n\nusing namespace mxflib;\n\n\n\n\n\n/* Local Prototypes */\n\nstatic int sopSkipToClose(FILE *xmlFile);\n", "file_path": "mxflib/sopsax.cpp", "rank": 75, "score": 31.189863623602072 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <stdio.h>\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\n\n\n\n\nnamespace\n\n{\n", "file_path": "mxflib/metadict.cpp", "rank": 76, "score": 31.1639638406016 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include <stdio.h>\n\n#include <iostream>\n\n#include <string>\n\nusing namespace std;\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n\n\n#include \"process.h\"\n\n#include \"process_utils.h\"\n\n\n\n\n", "file_path": "libprocesswrap/process.cpp", "rank": 77, "score": 30.474614319973153 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"process_utils.h\"\n\n\n\n#include <stdio.h>\n\n#include <iostream>\n\n#include <string>\n\n\n\nusing namespace std;\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"libprocesswrap/process.h\"\n\n\n", "file_path": "libprocesswrap/process_utils.cpp", "rank": 78, "score": 30.341821430295212 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"process_metadata.h\"\n\n\n\n#include <stdio.h>\n\n#include <iostream>\n\n#include <string>\n\nusing namespace std;\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n// Include the timecode class\n\n#include \"utility/timecode.h\"\n\n\n", "file_path": "libprocesswrap/process_metadata.cpp", "rank": 79, "score": 30.21552679282955 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"parseoptions.h\"\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\nusing namespace std;\n\n\n\n#include \"mxflib/system.h\" // for stricmp/strcasecmp\n\n\n\n#include \"libprocesswrap/process.h\"\n\n\n\n#define KXS\t\t\t\t\t\"kxs\"\n\n#define KXS_Used\t\t\t\"kxu\"\n\n#define KXS_Loaded\t\t\t\"kxl\"\n", "file_path": "mxfwrap/parseoptions.cpp", "rank": 80, "score": 29.805578894637097 }, { "content": " * 1. The origin of this software must not be misrepresented; you must\n\n * not claim that you wrote the original software. If you use this\n\n * software in a product, you must include an acknowledgment of the\n\n * authorship in the product documentation.\n\n * \n\n * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n \n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <stdarg.h>\n\n\n\nusing namespace mxflib;\n\n\n\n\n\n//! Static flag to say if dark metadata sets that appear to be valid KLV 2x2 sets should be parsed\n", "file_path": "mxflib/mdobject.cpp", "rank": 81, "score": 29.769496698259506 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n \n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <stdarg.h>\n\n\n\n\n\nusing namespace mxflib;\n\n\n\n// Allow us simple access to deftypes specials\n\nusing namespace mxflib_deftypes;\n\n\n\n\n\n/* XML parsing functions - with file scope */\n\nnamespace\n", "file_path": "mxflib/legacytypes.cpp", "rank": 82, "score": 29.50570239884339 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <math.h>\t// For \"floor\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <mxflib/esp_template.h>\n\n\n\n\n\n//! Local definitions\n\nnamespace\n\n{\n\n\t//! Modified UUID for <Source Type>\n", "file_path": "mxflib/esp_template.cpp", "rank": 83, "score": 29.38867445930807 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <math.h>\t// For \"floor\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <mxflib/esp_wavepcm.h>\n\n\n\n\n\n\n\n//! Local definitions\n\nnamespace\n\n{\n", "file_path": "mxflib/esp_wavepcm.cpp", "rank": 84, "score": 29.349967532773842 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n#ifndef _BASESINK_H_\n\n#define _BASESINK_H_\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"IPartial.h\"\n\n#include \"streamfile.h\"\n\n\n\nnamespace mxflib\n\n{\n", "file_path": "libmxfsplit/basesink.h", "rank": 85, "score": 29.051372793288046 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <math.h>\t// For \"floor\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <mxflib/esp_dvdif.h>\n\n\n\n\n\n//! Local definitions\n\nnamespace\n\n{\n\n\t//! Modified UUID for raw DV\n", "file_path": "mxflib/esp_dvdif.cpp", "rank": 86, "score": 28.759439663559426 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include <mxflib/mxflib.h>\n\n\n\n#include <math.h>\t// For \"floor\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <mxflib/esp_mpeg2ves.h>\n\n\n\n\n\n//! Local definitions\n\nnamespace\n\n{\n\n\t//! Modified UUID for MPEG2-VES\n", "file_path": "mxflib/esp_mpeg2ves.cpp", "rank": 87, "score": 28.759439663559426 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n\n\n#include \"timecode.h\"\n\n\n\n#ifndef EXCLUDE_MXFLIB_H\n\nusing namespace mxflib;\n\n#endif\n\n\n\n\t// construct from string\n\n\t// note that defaults to 1000 fps - intentionally\n\n\t// MUST call SetFPS() before persisting\n\n\tTimecode_t::Timecode_t( const char* arg, unsigned fps /* = defaultfps */, bool drop /*= false*/ ) : _start(0),_valid(false),_fps(fps),_drop(drop),_text(NULL)\n\n\t{\n\n\t\tif((!arg) || !strlen(arg)) return;\n", "file_path": "utility/timecode.cpp", "rank": 88, "score": 28.702441135122225 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <ios>\n\n#include <sstream>\n\n\n\n// Use mxflib by default in library source\n\nusing namespace mxflib;\n\n\n\n// Standard library includes\n\n//#include <stdexcept>\n\n\n\n//! Soft limit for strings returned by MDTraits - Defaults to 10k\n\n/*! \\note This is a soft limit in that it is not enforced strictly.\n", "file_path": "mxflib/mdtraits.cpp", "rank": 89, "score": 28.48310028624482 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <math.h>\t// For \"floor\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <mxflib/esp_jp2k.h>\n\n\n\n\n\n//! Local definitions\n\nnamespace\n\n{\n\n\tconst char *PictureEssenceCoding_Base = \"060e2b34.04010107.04010202.03010100\";\n", "file_path": "mxflib/esp_jp2k.cpp", "rank": 90, "score": 28.47392565521818 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"libprocesswrap/process.h\"\n\n\n\n\n\n\n\n#include \"parseoptions.h\"\n\n\n\n\n\n\n\n#include <stdio.h>\n\n#include <iostream>\n", "file_path": "mxfwrap/mxfwrap.cpp", "rank": 91, "score": 28.4438328446601 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\n\n\nusing namespace mxflib;\n\n\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n\n\n\n\n// Include the AS-DCP crypto header\n\n#include \"crypto_asdcp.h\"\n\n\n\n#include \"mxflib/dict.h\"\n\n\n", "file_path": "mxfcrypt/mxfcrypt.cpp", "rank": 92, "score": 28.23023422159863 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n \n\n#include \"mxflib/mxflib.h\"\n\n\n\n#include <stdarg.h>\n\n\n\n/* Allow us to use std::numeric_limits<>::max(), which includes removing any \"max\" macro! */\n\n#ifdef max\n\n#undef max\n\n#endif\n\n#include <limits>\n\n/******************************************************************************************/\n\n\n\nusing namespace mxflib;\n\n\n", "file_path": "mxflib/rxiparser.cpp", "rank": 93, "score": 28.025461462236272 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"utility/osprintf.h\"\n\n\n\n// include the autogenerated dictionary\n\n#include \"mxflib/dict.h\"\n\n\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <iostream>\n\n#include <map>\n\n#include <stdarg.h>\n", "file_path": "mxfsplit/mxfsplit.cpp", "rank": 94, "score": 27.8810799356323 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n\n\n#include \"mxflib/mxflib.h\"\n\n#include <cstddef>\n\n\n\n\n\n\n\nusing namespace mxflib;\n\n\n\n//! Template for all GC essence item keys\n\n/*! DRAGONS: Version number is hard coded as 0 - must be overwritten */\n\n\n\nnamespace\n\n{\n", "file_path": "mxflib/essence.cpp", "rank": 95, "score": 27.599134880439173 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n\n\n#include <mxflib/mxflib.h>\n\n\n\nusing namespace mxflib;\n\n\n\n\n\n/* List of all essence sub-parser header files */\n\n/***********************************************/\n\n\n\n#include <mxflib/esp_mpeg2ves.h>\n\n#include <mxflib/esp_wavepcm.h>\n\n#include <mxflib/esp_dvdif.h>\n\n#include <mxflib/esp_jp2k.h>\n", "file_path": "mxflib/esp.cpp", "rank": 96, "score": 27.564960593189276 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n#ifndef _CONTAINERINFO_H_\n\n#define _CONTAINERINFO_H_\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\nnamespace mxflib\n\n{\n\n\t//! Map of Descriptors indexed by Track Number\n\n\ttypedef std::map<UInt32, MDObjectPtr> TrackDescriptorMap;\n\n\n\n\t//! Map of EssenceSinks indexed by Track Number\n\n\ttypedef std::map<UInt32, EssenceSinkPtr> EssenceSinkMap;\n\n\n\n\t//! Structure holding information about the essence in each Container\n", "file_path": "libmxfsplit/containerinfo.h", "rank": 97, "score": 27.564820187638173 }, { "content": " * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n\n\n#include <mxflib/mxflib.h>\n\n\n\nusing namespace mxflib;\n\n\n\n\n\n#ifdef COMPILED_DICT\n\nbool UseCompiledDict = true;\n\n// include the autogenerated dictionary\n\n#include \"mxflib/dict.h\"\n\n#else // COMPILED_DICT\n\nbool UseCompiledDict = false;\n\nMXFLIB_DICTIONARY_START(DictData)\n\nMXFLIB_DICTIONARY_END\n\n#endif // COMPILED_DICT\n\n\n\n// Include the bootstrap dictionary\n", "file_path": "mxfdump/mxfdump.cpp", "rank": 98, "score": 27.55070170195469 }, { "content": " * 2. Altered source versions must be plainly marked as such, and must\n\n * not be misrepresented as being the original software.\n\n * \n\n * 3. This notice may not be removed or altered from any source\n\n * distribution.\n\n */\n\n#ifndef _AUDIOSINK_H_\n\n#define _AUDIOSINK_H_\n\n\n\n#include \"mxflib/mxflib.h\"\n\nusing namespace mxflib;\n\n\n\n#include \"streamfile.h\"\n\n\n\nnamespace mxflib\n\n{\n\n\t//! EssenceSink that writes a wave file to the currently open file\n", "file_path": "libmxfsplit/audiosink.h", "rank": 99, "score": 27.536829092147634 } ]
C++
include/ftk/mesh/lattice_partitioner.hh
hguo/FTT
f1d5387d6353cf2bd165c51fc717eb5d6b2675ef
#ifndef _FTK_LATTICE_PARTITIONER_HH #define _FTK_LATTICE_PARTITIONER_HH #include <ftk/mesh/lattice.hh> namespace ftk { struct lattice_partitioner { lattice_partitioner(const lattice& l_) : l(l_) {} friend std::ostream& operator<<(std::ostream& os, const lattice_partitioner&); size_t nd() const {return l.nd();} size_t np() const {return cores.size();} public: void partition(size_t np); void partition(size_t np, const std::vector<size_t> &given); void partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost); void partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost_low, const std::vector<size_t> &ghost_high); const lattice& get_core(size_t i) const {return cores[i];} const lattice& get_ext(size_t i) const {return extents[i];} size_t partition_id(const std::vector<size_t> &p) const; lattice add_ghost(const lattice& b, const std::vector<size_t>&, const std::vector<size_t>&) const; private: void partition(std::vector<std::vector<size_t>> prime_factors_dims); template<typename uint = size_t> static std::vector<uint> prime_factorization(uint n); protected: const lattice &l; std::vector<lattice> cores, extents; }; template<typename uint> inline std::vector<uint> lattice_partitioner::prime_factorization(uint n) { std::vector<uint> factors; while (n % 2 == 0) { factors.push_back(2); n = n/2; } for (int i = 3; i <= sqrt(n); i += 2) { while (n % i == 0) { factors.push_back(i); n = n / i; } } if(n > 1) { factors.push_back(n); } std::reverse(factors.begin(), factors.end()); return factors; } inline bool is_vector_zero(const std::vector<size_t> vec) { if(vec.size() == 0 || (vec.size() == 1 && vec[0] == 0)) { return true; } return false; } inline void lattice_partitioner::partition(size_t np) { std::vector<size_t> vector_zero(0, nd()); partition(np, vector_zero, vector_zero, vector_zero); } inline void lattice_partitioner::partition(size_t np, const std::vector<size_t> &given) { std::vector<size_t> vector_zero(0, nd()); partition(np, given, vector_zero, vector_zero); } inline void lattice_partitioner::partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost) { partition(np, given, ghost, ghost); } inline void lattice_partitioner::partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost_low, const std::vector<size_t> &ghost_high) { if(np <= 0) { return ; } int ndim = l.nd_cuttable(); std::vector<std::vector<size_t>> prime_factors_dims(ndim, std::vector<size_t>()); if(!is_vector_zero(given)) { bool has_zero = false; for(size_t nslice: given) { if(nslice != 0) { if(np % nslice != 0) { return ; } np /= nslice; } else { has_zero = true; } } if(!has_zero && np > 1) { return ; } for(auto i = 0; i < given.size(); ++i) { size_t nslice = given[i]; if(nslice > 1) { std::vector<size_t> prime_factors_dim = prime_factorization(nslice); prime_factors_dims[i] = prime_factors_dim; } } } if(np > 1) { std::vector<size_t> prime_factors_all = prime_factorization(np); int curr = 0; for(size_t& prime : prime_factors_all) { while(!is_vector_zero(given) && given[curr] != 0) { curr = (curr + 1) % ndim; } prime_factors_dims[curr].push_back(prime); curr = (curr + 1) % ndim; } } partition(prime_factors_dims); if (cores.size() == 0) return; for(const auto& core : cores) { #if 0 auto starts = core.starts(), sizes = core.sizes(); for(int d = 0; d < ndim; ++d) { { size_t offset = starts[d] - l.start(d); if(ghost_low[d] < offset) { offset = ghost_low[d]; } starts[d] -= offset; sizes[d] += offset; } { size_t offset = (l.start(d) + l.size(d)) - (starts[d] + sizes[d]); if(ghost_high[d] < offset) { offset = ghost_high[d]; } sizes[d] += offset; } } #endif lattice ext = add_ghost(core, ghost_low, ghost_high); extents.push_back(ext); } } inline void lattice_partitioner::partition(std::vector<std::vector<size_t>> prime_factors_dims) { int ndim = l.nd_cuttable(); std::queue<lattice> lattice_queue; lattice_queue.push(l); for(int curr = 0; curr < ndim; ++curr) { for(size_t& nslice : prime_factors_dims[curr]) { int n = lattice_queue.size(); for (int j = 0; j < n; ++j) { auto p = lattice_queue.front(); if(p.size(curr) < nslice) { return ; } size_t ns = p.size(curr) / nslice; std::vector<size_t> starts(p.starts()); std::vector<size_t> sizes(p.sizes()); sizes[curr] = ns; for(int k = 0; k < nslice - 1; ++k) { lattice_queue.push(lattice(starts, sizes)); starts[curr] += ns; } sizes[curr] = p.size(curr) - ns * (nslice - 1); lattice_queue.push(lattice(starts, sizes)); lattice_queue.pop(); } } } while (!lattice_queue.empty()) { lattice core = lattice_queue.front(); lattice ghost(core.starts(), core.sizes()); cores.push_back(core); lattice_queue.pop(); } } inline std::ostream& operator<<(std::ostream& os, const lattice_partitioner& partitioner) { os << "lattice.nd=" << partitioner.nd() << ", np=" << partitioner.np() << std::endl; for (auto i = 0; i < partitioner.np(); i ++) { os << "--" << "id=" << i <<", " << "core: " << partitioner.cores[i] << "; " << "ext: " << partitioner.extents[i]; if (i < partitioner.np() - 1) os << std::endl; } return os; } inline lattice lattice_partitioner::add_ghost(const lattice& b, const std::vector<size_t>& ghost_low, const std::vector<size_t>& ghost_high) const { if (ghost_low.empty() || ghost_high.empty()) return b; auto starts = b.starts(), sizes = b.sizes(); for(int d = 0; d < l.nd_cuttable(); ++d) { { size_t offset = starts[d] - l.start(d); if(ghost_low[d] < offset) { offset = ghost_low[d]; } starts[d] -= offset; sizes[d] += offset; } { size_t offset = (l.start(d) + l.size(d)) - (starts[d] + sizes[d]); if(ghost_high[d] < offset) { offset = ghost_high[d]; } sizes[d] += offset; } } return lattice(starts, sizes); } }; #endif
#ifndef _FTK_LATTICE_PARTITIONER_HH #define _FTK_LATTICE_PARTITIONER_HH #include <ftk/mesh/lattice.hh> namespace ftk { struct lattice_partitioner { lattice_partitioner(const lattice& l_) : l(l_) {} friend std::ostream& operator<<(std::ostream& os, const lattice_partitioner&); size_t nd() const {return l.nd();} size_t np() const {return cores.size();} public: void partition(size_t np); void partition(size_t np, const std::vector<size_t> &given); void partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost); void partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost_low, const std::vector<size_t> &ghost_high); const lattice& get_core(size_t i) const {return cores[i];} const lattice& get_ext(size_t i) const {return extents[i];} size_t partition_id(const std::vector<size_t> &p) const; lattice add_ghost(const lattice& b, const std::vector<size_t>&, const std::vector<size_t>&) const; private: void partition(std::vector<std::vector<size_t>> prime_factors_dims); template<typename uint = size_t> static std::vector<uint> prime_factorization(uint n); protected: const lattice &l; std::vector<lattice> cores, extents; }; template<typename uint> inline std::vector<uint> lattice_partitioner::prime_factorization(uint n) { std::vector<uint> factors; while (n % 2 == 0) { factors.push_back(2); n = n/2; } for (int i = 3; i <= sqrt(n); i += 2) { while (n % i == 0) { factors.push_back(i); n = n / i; } } if(n > 1) { factors.push_back(n); } std::reverse(factors.begin(), factors.end());
(curr + 1) % ndim; } } partition(prime_factors_dims); if (cores.size() == 0) return; for(const auto& core : cores) { #if 0 auto starts = core.starts(), sizes = core.sizes(); for(int d = 0; d < ndim; ++d) { { size_t offset = starts[d] - l.start(d); if(ghost_low[d] < offset) { offset = ghost_low[d]; } starts[d] -= offset; sizes[d] += offset; } { size_t offset = (l.start(d) + l.size(d)) - (starts[d] + sizes[d]); if(ghost_high[d] < offset) { offset = ghost_high[d]; } sizes[d] += offset; } } #endif lattice ext = add_ghost(core, ghost_low, ghost_high); extents.push_back(ext); } } inline void lattice_partitioner::partition(std::vector<std::vector<size_t>> prime_factors_dims) { int ndim = l.nd_cuttable(); std::queue<lattice> lattice_queue; lattice_queue.push(l); for(int curr = 0; curr < ndim; ++curr) { for(size_t& nslice : prime_factors_dims[curr]) { int n = lattice_queue.size(); for (int j = 0; j < n; ++j) { auto p = lattice_queue.front(); if(p.size(curr) < nslice) { return ; } size_t ns = p.size(curr) / nslice; std::vector<size_t> starts(p.starts()); std::vector<size_t> sizes(p.sizes()); sizes[curr] = ns; for(int k = 0; k < nslice - 1; ++k) { lattice_queue.push(lattice(starts, sizes)); starts[curr] += ns; } sizes[curr] = p.size(curr) - ns * (nslice - 1); lattice_queue.push(lattice(starts, sizes)); lattice_queue.pop(); } } } while (!lattice_queue.empty()) { lattice core = lattice_queue.front(); lattice ghost(core.starts(), core.sizes()); cores.push_back(core); lattice_queue.pop(); } } inline std::ostream& operator<<(std::ostream& os, const lattice_partitioner& partitioner) { os << "lattice.nd=" << partitioner.nd() << ", np=" << partitioner.np() << std::endl; for (auto i = 0; i < partitioner.np(); i ++) { os << "--" << "id=" << i <<", " << "core: " << partitioner.cores[i] << "; " << "ext: " << partitioner.extents[i]; if (i < partitioner.np() - 1) os << std::endl; } return os; } inline lattice lattice_partitioner::add_ghost(const lattice& b, const std::vector<size_t>& ghost_low, const std::vector<size_t>& ghost_high) const { if (ghost_low.empty() || ghost_high.empty()) return b; auto starts = b.starts(), sizes = b.sizes(); for(int d = 0; d < l.nd_cuttable(); ++d) { { size_t offset = starts[d] - l.start(d); if(ghost_low[d] < offset) { offset = ghost_low[d]; } starts[d] -= offset; sizes[d] += offset; } { size_t offset = (l.start(d) + l.size(d)) - (starts[d] + sizes[d]); if(ghost_high[d] < offset) { offset = ghost_high[d]; } sizes[d] += offset; } } return lattice(starts, sizes); } }; #endif
return factors; } inline bool is_vector_zero(const std::vector<size_t> vec) { if(vec.size() == 0 || (vec.size() == 1 && vec[0] == 0)) { return true; } return false; } inline void lattice_partitioner::partition(size_t np) { std::vector<size_t> vector_zero(0, nd()); partition(np, vector_zero, vector_zero, vector_zero); } inline void lattice_partitioner::partition(size_t np, const std::vector<size_t> &given) { std::vector<size_t> vector_zero(0, nd()); partition(np, given, vector_zero, vector_zero); } inline void lattice_partitioner::partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost) { partition(np, given, ghost, ghost); } inline void lattice_partitioner::partition(size_t np, const std::vector<size_t> &given, const std::vector<size_t> &ghost_low, const std::vector<size_t> &ghost_high) { if(np <= 0) { return ; } int ndim = l.nd_cuttable(); std::vector<std::vector<size_t>> prime_factors_dims(ndim, std::vector<size_t>()); if(!is_vector_zero(given)) { bool has_zero = false; for(size_t nslice: given) { if(nslice != 0) { if(np % nslice != 0) { return ; } np /= nslice; } else { has_zero = true; } } if(!has_zero && np > 1) { return ; } for(auto i = 0; i < given.size(); ++i) { size_t nslice = given[i]; if(nslice > 1) { std::vector<size_t> prime_factors_dim = prime_factorization(nslice); prime_factors_dims[i] = prime_factors_dim; } } } if(np > 1) { std::vector<size_t> prime_factors_all = prime_factorization(np); int curr = 0; for(size_t& prime : prime_factors_all) { while(!is_vector_zero(given) && given[curr] != 0) { curr = (curr + 1) % ndim; } prime_factors_dims[curr].push_back(prime); curr =
random
[ { "content": "struct formatter<void*, Char> : formatter<const void*, Char> {\n\n template <typename FormatContext>\n\n auto format(void* val, FormatContext& ctx) -> decltype(ctx.out()) {\n\n return formatter<const void*, Char>::format(val, ctx);\n\n }\n\n};\n\n\n\ntemplate <typename Char, size_t N>\n", "file_path": "include/ftk/external/diy/fmt/format.h", "rank": 0, "score": 275478.4127111879 }, { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n\n\n#include <limits> // numeric_limits\n\n#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type\n\n#include <utility> // declval\n\n\n\n// #include <nlohmann/detail/boolean_operators.hpp>\n\n\n\n// #include <nlohmann/detail/iterators/iterator_traits.hpp>\n", "file_path": "include/ftk/external/json.hh", "rank": 1, "score": 270002.3350678477 }, { "content": "struct function_traits<const T&&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 2, "score": 244117.9108136032 }, { "content": "struct function_traits<const T&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 3, "score": 244117.9108136032 }, { "content": "struct FMT_DEPRECATED convert_to_int\n\n : bool_constant<!std::is_arithmetic<T>::value &&\n\n std::is_convertible<T, int>::value> {};\n\n\n\nnamespace internal {\n\n\n\n// Specifies if T has an enabled formatter specialization. A type can be\n\n// formattable even if it doesn't have a formatter e.g. via a conversion.\n\ntemplate <typename T, typename Context>\n\nusing has_formatter =\n\n std::is_constructible<typename Context::template formatter_type<T>>;\n\n\n\n/** A contiguous memory buffer with an optional growing ability. */\n\ntemplate <typename T> class buffer {\n\n private:\n\n buffer(const buffer&) = delete;\n\n void operator=(const buffer&) = delete;\n\n\n\n T* ptr_;\n\n std::size_t size_;\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 4, "score": 243862.8403661732 }, { "content": "struct feature_curve_set_t : public std::multimap<int, feature_curve_t>\n\n{\n\n int add(const feature_curve_t&);\n\n void add(const feature_curve_t&, int label);\n\n std::vector<int> add(const std::vector<feature_curve_t>&);\n\n\n\n std::list<feature_curve_t> to_list() const;\n\n void from_list(const std::list<feature_curve_t>&);\n\n\n\n // std::vector<int> split(int);\n\n void split_all();\n\n \n\n void foreach(std::function<void(const feature_curve_t&)> f) const {for (const auto& kv : *this) f(kv.second);}\n\n void foreach(std::function<void(feature_curve_t&)> f) {for (auto& kv : *this) f(kv.second);}\n\n void foreach(std::function<void(int, const feature_curve_t&)> f) const {for (const auto& kv : *this) f(kv.first, kv.second);}\n\n void foreach(std::function<void(int, feature_curve_t&)> f) {for (auto& kv : *this) f(kv.first, kv.second);}\n\n\n\n void filter(std::function<bool(const feature_curve_t&)> f);\n\n\n\n std::vector<feature_point_t> slice(int t) const;\n", "file_path": "include/ftk/features/feature_curve_set.hh", "rank": 5, "score": 239483.4874555793 }, { "content": "struct lattice {\n\n friend class lattice_partitioner;\n\n template <typename T> friend class ndarray;\n\n\n\n lattice() {}\n\n lattice(int n);\n\n lattice(int n, const int *dims);\n\n lattice(const std::vector<size_t> &starts, const std::vector<size_t> &sizes) {reshape(starts, sizes);}\n\n lattice(const std::vector<size_t> &sizes) {reshape(sizes);}\n\n\n\n lattice(const diy::DiscreteBounds& b);\n\n diy::DiscreteBounds to_diy_bounds() const;\n\n\n\n friend std::ostream& operator<<(std::ostream& os, const lattice&);\n\n\n\n size_t nd() const {return sizes_.size();}\n\n size_t nd_cuttable() const {return unlimited_time() ? nd() - 1 : nd();}\n\n size_t start(size_t i) const {return starts_[i];}\n\n size_t size(size_t i) const {return sizes_[i];}\n\n size_t upper_bound(size_t i) const {return starts_[i] + sizes_[i] - 1;}\n", "file_path": "include/ftk/mesh/lattice.hh", "rank": 6, "score": 239412.66999667895 }, { "content": "struct function_traits<const volatile T&&> : public function_traits<T> {};\n\n\n\n\n\n#define FORWARD_RES_8QR485JMSBT \\\n\n typename std::conditional< \\\n\n std::is_lvalue_reference<R>::value, \\\n\n T&, \\\n\n typename std::remove_reference<T>::type&& \\\n\n >::type\n\n\n\n/**\n\n.. function:: auto utils::forward_like<Like, T>(T&& t) noexcept\n\n\n\n Forward the reference *t* like the type of *Like*. That means, if *Like* is\n\n an lvalue (reference), this function will return an lvalue reference of *t*.\n\n Otherwise, if *Like* is an rvalue, this function will return an rvalue\n\n reference of *t*.\n\n\n\n This is mainly used to propagate the expression category (lvalue/rvalue) of\n\n a member of *Like*, generalizing ``std::forward``.\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 7, "score": 234463.7372208183 }, { "content": "struct function_traits<const volatile T&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 8, "score": 234463.7372208183 }, { "content": "struct filter : public object {\n\n filter(diy::mpi::communicator comm) : object(comm) {\n\n nthreads = default_nthreads();\n\n }\n\n\n\n virtual void update() = 0;\n\n virtual void reset() {};\n\n\n\n void use_thread_backend(const std::string& backend);\n\n void use_thread_backend(int i) { thread_backend = i; }\n\n\n\n void use_accelerator(const std::string& acc);\n\n void use_accelerator(int i) {\n\n xl = i;\n\n#if 0\n\n if (xl == FTK_THREAD_OPENMP || xl == FTK_XL_SYCL || xl == FTK_XL_KOKKOS_CUDA) {\n\n warn(\"Accelerator not available. Using FTK_XL_NONE.\");\n\n xl = FTK_XL_NONE;\n\n }\n\n#endif\n", "file_path": "include/ftk/filters/filter.hh", "rank": 9, "score": 231624.74558363826 }, { "content": "struct tracker : public filter\n\n{\n\n tracker(diy::mpi::communicator comm) : filter(comm) {} // , master(comm) {}\n\n virtual ~tracker() {}\n\n \n\n // virtual int cpdims() const = 0; // featutre dimension\n\n \n\n void set_start_timestep(int t) { start_timestep = t;}\n\n void set_end_timestep(int t) { end_timestep = t; }\n\n \n\n virtual void set_current_timestep(int t) {current_timestep = t;}\n\n int get_current_timestep() const {return current_timestep;}\n\n \n\n void set_input_array_partial(bool b) {is_input_array_partial = b;}\n\n void set_use_default_domain_partition(bool b) {use_default_domain_partition = true;}\n\n\n\n static int str2tracker(const std::string&);\n\n\n\npublic:\n\n virtual void initialize() = 0;\n", "file_path": "include/ftk/filters/tracker.hh", "rank": 10, "score": 231624.74558363826 }, { "content": "struct ndarray : public ndarray_base {\n\n friend class diy::Serialization<ndarray<T>>;\n\n\n\n int type() const;\n\n\n\n unsigned int hash() const;\n\n\n\n ndarray() {}\n\n ndarray(const std::vector<size_t> &dims) {reshape(dims);}\n\n ndarray(const std::vector<size_t> &dims, T val) {reshape(dims, val);}\n\n ndarray(const lattice& l) {reshape(l.sizes());}\n\n ndarray(const T *a, const std::vector<size_t> &shape);\n\n \n\n template <typename T1> ndarray(const ndarray<T1>& array1) { from_array<T1>(array1); }\n\n ndarray(const ndarray<T>& a) { dims = a.dims; s = a.s; ncd = a.ncd; tv = a.tv; p = a.p; }\n\n \n\n template <typename T1> ndarray<T>& operator=(const ndarray<T1>& array1) { from_array<T1>(array1); return *this; }\n\n ndarray<T>& operator=(const ndarray<T>& a) { dims = a.dims; s = a.s; ncd = a.ncd; tv = a.tv; p = a.p; return *this; }\n\n\n\n std::ostream& print(std::ostream& os) const;\n", "file_path": "include/ftk/ndarray.hh", "rank": 11, "score": 231624.74558363826 }, { "content": "struct function_traits<ReturnType(ClassType::*)(Args...) const>\n\n : public function_traits<ReturnType(Args...)>\n\n{\n\n typedef const ClassType& owner_type;\n\n};\n\n\n\ntemplate <typename ClassType, typename ReturnType, typename... Args>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 12, "score": 228839.68936066466 }, { "content": "struct ndarray_writer : public object {\n\n void configure(const json& j_);\n\n // JSON specificications:\n\n // required fields: \n\n // - nd, number. dimensionality of the data\n\n // - filename, string, e.g. \"tornado-%04d.nc\". Should be able to expand to file names with sprintf(3)\n\n // - format (nc|vti|float32|float64)\n\n // format-specific fields: \n\n // - nc (NetCDF), serial\n\n // - variable (required), string or array of strings. Possible to use the same\n\n // specification in the input stream config. Will be converted to array of \n\n // strings internally. Will write one or multiple variables.\n\n // - dimensions (optional), array of strings; by default use [\"x\", \"y\"] and \n\n // [\"x\", \"y\", \"z\"] for 2D and 3D data, respectively\n\n // - unlimited_time (optional, by default true), bool. If true, include time \n\n // in dimensions, e.g. (time,z,y,x), in netcdf. \n\n // - vti (vtkImageData w/ vtkXMLImageDataWriter)\n\n // - variable (required), string or array of strings. Possible to use the same\n\n // specification in the input stream config. \n\n // - string: write one single variable, assuming the data is single-component\n", "file_path": "include/ftk/ndarray/writer.hh", "rank": 14, "score": 226227.42489461444 }, { "content": "struct ndarray_stream : public object {\n\n ndarray_stream(diy::mpi::communicator comm = MPI_COMM_WORLD);\n\n ndarray_stream(const std::string adios2_config_filename, // = \"adios2.xml\",\n\n const std::string adios2_io_name, // = \"SimulationOutput\",\n\n diy::mpi::communicator comm); // = MPI_COMM_WORLD);\n\n ~ndarray_stream();\n\n\n\n void configure(const json& j) {set_input_source_json(j);}\n\n // JSON specifications:\n\n // required fields: \n\n // - type, string. Must be one of \"synthetic\" and \"file\". This field may be ommited\n\n // if `format' is given.\n\n // - name (required if type is synthetic), string. Must be one of the follows: \"woven\", \n\n // \"double_gyre\", \"merger_2d\".\n\n // optional fields:\n\n // - filenames (required if type is file), string. The list of filenames will be \n\n // determined by glob(3)\n\n // - mesh_filename (required for unstructured mesh, must be in vtu format in the \n\n // current version), string.\n\n // - format (required if type is file and format is float32/float64), string. If not \n", "file_path": "include/ftk/ndarray/stream.hh", "rank": 15, "score": 226227.42489461444 }, { "content": "struct xgc_tracker : public tracker {\n\n xgc_tracker(diy::mpi::communicator comm,\n\n std::shared_ptr<simplicial_xgc_3d_mesh<>> mx);\n\n\n\n void reset() { field_data_snapshots.clear(); }\n\n\n\n void set_use_roi(bool b) { use_roi = b; }\n\n\n\npublic:\n\n std::shared_ptr<simplicial_unstructured_2d_mesh<>> get_m2() { return m2; }\n\n void initialize_ff_mesh(const std::string& filename) { mf3.reset(new simplicial_xgc_3dff_mesh<>(m2, m3->get_nphi(), m3->get_iphi(), m3->get_vphi()) ); mf3->initialize_ff_mesh(filename); }\n\n\n\npublic:\n\n virtual void push_field_data_snapshot(std::shared_ptr<ndarray_group>);\n\n virtual void push_field_data_snapshot(const ndarray<double> &scalar);\n\n virtual void push_field_data_snapshot(\n\n const ndarray<double> &scalar, \n\n const ndarray<double> &vector,\n\n const ndarray<double> &jacobian);\n\n \n", "file_path": "include/ftk/filters/xgc_tracker.hh", "rank": 16, "score": 221148.19272714184 }, { "content": "struct xgc_stream : public object {\n\n static std::shared_ptr<xgc_stream> new_xgc_stream(const std::string& path, diy::mpi::communicator comm = MPI_COMM_WORLD);\n\n xgc_stream(const std::string& path_, diy::mpi::communicator comm = MPI_COMM_WORLD) : path(path_), object(comm) {}\n\n \n\n void set_start_timestep(int s) { start_timestep = s; }\n\n void set_ntimesteps(int n) { ntimesteps = n; }\n\n void set_vphi(int v) { vphi = v; }\n\n\n\n void set_enable_initialize_smoothing_kernel(bool b) { enable_initialize_smoothing_kernel = b; }\n\n void set_enable_initialize_interpolants(bool b) { enable_initialize_interpolants = b; }\n\n\n\n void initialize();\n\n void probe_nphi_iphi();\n\n\n\n void set_smoothing_kernel_size(double s) { smoothing_kernel_size = s; }\n\n void set_smoothing_kernel_filename(const std::string f) { smoothing_kernel_filename = f; }\n\n void set_interpolant_filename(const std::string f) { interpolant_filename = f; }\n\n\n\n void set_callback(std::function<void(int, std::shared_ptr<ndarray_group>)> f) { callback = f; }\n\n\n", "file_path": "include/ftk/io/xgc_stream.hh", "rank": 17, "score": 221148.19272714184 }, { "content": "struct json_interface : public object {\n\n // json options (WIP):\n\n // - feature, string, required: possible values include\n\n // critical_point|cp: 2D/3D critical points\n\n // critical_line|cl: 3D critical line (intersections of two isosurfaces)\n\n // isosurface|iso: 3D isosurface\n\n // tdgl_vortex|tdgl: magnetic flux vortices in 3D time-dependent Ginzburg-Landau (TDGL) simulations\n\n // sujudi_haimes|sh: Sujudi-Haimes vortices in 3D vector fields\n\n // levy_degani_seginer|lds: Levy-Degani-Seginer vortices in 3D vector fields\n\n // connected_component|cc: 2D/3D connected components\n\n // xgc_blob_filament_2d: 2D XGC blob filaments defined by local extrema\n\n // xgc_blob_filament: 3D XGX blob filaments defined by local extrema\n\n // xgc_blob_threshold: 3D XGC blob filaments defined by levelsets\n\n // - input, json, see ndarray/stream.hh for details\n\n // // - writeback, json, optional: write input data back to files; see ndarray/writer.hh for details\n\n // - archive, json, optional:\n\n // - discrete, string, optional: file name to load/store discrete feature points w/o tracking\n\n // - traced, string, optional: file name to load/store traced features\n\n // - output, json, required:\n\n // - type, string, by default \"traced\": intersections, traced, sliced, or intercepted\n", "file_path": "include/ftk/filters/json_interface.hh", "rank": 18, "score": 221148.19272714184 }, { "content": "struct mpas_stream : public object {\n\n mpas_stream(const std::string& path, diy::mpi::communicator comm=MPI_COMM_WORLD);\n\n\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "include/ftk/io/mpas_stream.hh", "rank": 19, "score": 221148.19272714184 }, { "content": "struct function_traits<ReturnType(ClassType::*)(Args...) const volatile>\n\n : public function_traits<ReturnType(Args...)>\n\n{\n\n typedef const volatile ClassType& owner_type;\n\n};\n\n\n\ntemplate <typename FunctionType>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 20, "score": 220156.28346334162 }, { "content": "struct monostate {};\n\n\n\n// An enable_if helper to be used in template parameters which results in much\n\n// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed\n\n// to workaround a bug in MSVC 2019 (see #1140 and #1186).\n\n#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0\n\n\n\nnamespace internal {\n\n\n\n// A workaround for gcc 4.8 to make void_t work in a SFINAE context.\n\ntemplate <typename... Ts> struct void_t_impl { using type = void; };\n\n\n\n#if defined(FMT_USE_STRING_VIEW)\n\ntemplate <typename Char> using std_string_view = std::basic_string_view<Char>;\n\n#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)\n\ntemplate <typename Char>\n\nusing std_string_view = std::experimental::basic_string_view<Char>;\n\n#else\n\ntemplate <typename T> struct std_string_view {};\n\n#endif\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 21, "score": 219870.7871491524 }, { "content": "struct formatter {\n\n // A deleted default constructor indicates a disabled formatter.\n\n formatter() = delete;\n\n};\n\n\n\ntemplate <typename T, typename Char, typename Enable = void>\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 22, "score": 219870.78714915237 }, { "content": "struct view {};\n\ntemplate <bool...> struct bool_pack;\n\ntemplate <bool... Args>\n\nusing all_true =\n\n std::is_same<bool_pack<Args..., true>, bool_pack<true, Args...>>;\n\n\n\ntemplate <typename... Args, typename S, typename Char = char_t<S>>\n\ninline format_arg_store<buffer_context<Char>, remove_reference_t<Args>...>\n\nmake_args_checked(const S& format_str,\n\n const remove_reference_t<Args>&... args) {\n\n static_assert(all_true<(!std::is_base_of<view, remove_reference_t<Args>>() ||\n\n !std::is_reference<Args>())...>::value,\n\n \"passing views as lvalues is disallowed\");\n\n check_format_string<remove_const_t<remove_reference_t<Args>>...>(format_str);\n\n return {args...};\n\n}\n\n\n\ntemplate <typename Char>\n\nstd::basic_string<Char> vformat(basic_string_view<Char> format_str,\n\n basic_format_args<buffer_context<Char>> args);\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 23, "score": 219870.78714915237 }, { "content": "struct is_sax_static_asserts\n\n{\n\n private:\n\n static_assert(is_basic_json<BasicJsonType>::value,\n\n \"BasicJsonType must be of type basic_json<...>\");\n\n\n\n using number_integer_t = typename BasicJsonType::number_integer_t;\n\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n\n using number_float_t = typename BasicJsonType::number_float_t;\n\n using string_t = typename BasicJsonType::string_t;\n\n using exception_t = typename BasicJsonType::exception;\n\n\n\n public:\n\n static_assert(is_detected_exact<bool, null_function_t, SAX>::value,\n\n \"Missing/invalid function: bool null()\");\n\n static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,\n\n \"Missing/invalid function: bool boolean(bool)\");\n\n static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,\n\n \"Missing/invalid function: bool boolean(bool)\");\n\n static_assert(\n", "file_path": "include/ftk/external/json.hh", "rank": 24, "score": 214181.48873858034 }, { "content": "struct fixed_integer {\n\n fixed_integer() {for (int i = 0; i < N; i ++) num[i] = 0;}\n\n fixed_integer(const std::string& str);\n\n fixed_integer(const fixed_integer& x) {\n\n for (int i = 0; i < N; i ++) \n\n num[i] = x.num[i];\n\n }\n\n fixed_integer(int x) {I[0] = x;}\n\n\n\n fixed_integer& operator=(const fixed_integer& x) {\n\n for (int i = 0; i < N; i ++)\n\n num[i] = x.num[i];\n\n return *this;\n\n }\n\n fixed_integer& operator=(int x) {\n\n for (int i = 1; i < N; i ++)\n\n num[i] = 0;\n\n num[0] = x;\n\n return *this;\n\n }\n", "file_path": "include/ftk/numeric/fixed_int.hh", "rank": 25, "score": 214178.0641676684 }, { "content": "// A base class for compile-time strings. It is defined in the fmt namespace to\n\n// make formatting functions visible via ADL, e.g. format(fmt(\"{}\"), 42).\n\nstruct compile_string {};\n\n\n\ntemplate <typename S>\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 26, "score": 214131.92893787267 }, { "content": "struct fallback_formatter {\n\n fallback_formatter() = delete;\n\n};\n\n\n\n// Specifies if T has an enabled fallback_formatter specialization.\n\ntemplate <typename T, typename Context>\n\nusing has_fallback_formatter =\n\n std::is_constructible<fallback_formatter<T, typename Context::char_type>>;\n\n\n\ntemplate <typename Char> struct named_arg_base;\n\ntemplate <typename T, typename Char> struct named_arg;\n\n\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 27, "score": 214120.77106610767 }, { "content": "struct error_handler {\n\n FMT_CONSTEXPR error_handler() {}\n\n FMT_CONSTEXPR error_handler(const error_handler&) {}\n\n\n\n // This function is intentionally not constexpr to give a compile-time error.\n\n FMT_NORETURN FMT_API void on_error(const char* message);\n\n};\n\n} // namespace internal\n\n\n\n/** String's character type. */\n\ntemplate <typename S> using char_t = typename internal::char_t_impl<S>::type;\n\n\n\n// Parsing context consisting of a format string range being parsed and an\n\n// argument counter for automatic indexing.\n\ntemplate <typename Char, typename ErrorHandler = internal::error_handler>\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 28, "score": 214120.77106610767 }, { "content": "struct connected_component_tracker : public tracker\n\n{\n\n connected_component_tracker(diy::mpi::communicator comm) : tracker(comm) {}\n\n virtual ~connected_component_tracker() {};\n\n\n\n virtual bool advance_timestep();\n\n virtual void update_timestep();\n\n void update() {};\n\n void finalize();\n\n\n\n virtual void push_labeled_data_snapshot(const std::vector<LabelIdType>& labels);\n\n const std::vector<LabelIdType>& get_last_labeled_data_snapshot() const {return labeled_data_snapshots.back();}\n\n \n\n template <typename ContainerType>\n\n void push_unlabeled_data_snapshot(const std::vector<LabelIdType>& labels, std::function<ContainerType(LabelIdType)> neighbors);\n\n\n\n bool pop_snapshot();\n\n\n\n const ftk::tracking_graph<>& get_tracking_graph() const {return tg;}\n\n\n", "file_path": "include/ftk/filters/connected_component_tracker.hh", "rank": 29, "score": 211837.7755177343 }, { "content": "struct simplicial_unstructured_mesh : public object { \n\n simplicial_unstructured_mesh() {}\n\n\n\n // dimensionality of the mesh\n\n virtual int nd() const = 0;\n\n\n\n // numer of d-dimensional elements\n\n virtual size_t n(int d) const = 0;\n\n\n\npublic: // io\n\n void from_legacy_vtk_file(const std::string& filename);\n\n void from_vtk_unstructured_grid_file(const std::string &filename);\n\n void to_vtk_unstructured_grid_file(const std::string &filename) const;\n\n\n\n void scalar_to_vtk_unstructured_grid_data_file(const std::string& filename, const std::string& varname, const ndarray<F>&) const;\n\n void vector_to_vtk_unstructured_grid_data_file(const std::string& filename, const std::string& varname, const ndarray<F>&) const;\n\n#if FTK_HAVE_VTK\n\n vtkSmartPointer<vtkUnstructuredGrid> scalar_to_vtk_unstructured_grid_data(const std::string& varname, const ndarray<F>&) const;\n\n vtkSmartPointer<vtkUnstructuredGrid> vector_to_vtk_unstructured_grid_data(const std::string& varname, const ndarray<F>&) const;\n\n // vtkSmartPointer<vtkUnstructuredGrid> scalars_to_vtk_unstructured_grid_data(\n", "file_path": "include/ftk/mesh/simplicial_unstructured_mesh.hh", "rank": 30, "score": 211837.7755177343 }, { "content": "#if 0\n\nstruct data_stream_synthetic : public data_stream {\n\n void set_input_source(const std::string&) {} // nothing todo\n\n\n\n void advance_timestep() {\n\n data_group *g = data_group::create();\n\n const ndarray<double>& array = synthesize_timestep(current_timestep);\n\n g->set(default_variable_name(), array);\n\n push_timestep(g);\n\n }\n\n\n\n void set_input_parameters(const std::map<std::string, std::string>& param) {\n\n data_stream::set_input_parameters(param);\n\n if (param.find(str_dw) != param.end()) DW = std::stoi(param.at(str_dw));\n\n if (param.find(str_dh) != param.end()) DH = std::stoi(param.at(str_dh));\n\n if (param.find(str_dd) != param.end()) DD = std::stoi(param.at(str_dd));\n\n if (param.find(str_dt) != param.end()) n_timesteps = std::stoi(param.at(str_dt));\n\n if (param.find(str_time_scale) != param.end()) time_scale = stod(param.at(str_time_scale));\n\n }\n\n\n\n virtual std::string default_variable_name() const {return std::string();};\n\n\n\n virtual ndarray<double> synthesize_timestep(int t) = 0;\n\n\n\nprotected:\n\n size_t DW = 32, DH = 32, DD = 32;\n\n double time_scale = 1.0;\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 31, "score": 211837.7755177343 }, { "content": "struct data_stream_files : public data_stream {\n\n void set_input_source(const std::string& pattern) {\n\n filenames = ndarray<float>::glob(pattern);\n\n if (n_timesteps == 0) n_timesteps = filenames.size();\n\n else filenames.resize(n_timesteps);\n\n }\n\n\n\n void set_input_filenames(const std::vector<std::string>& f) {filenames = f;}\n\n\n\n void load_timestep(int k);\n\n\n\n void advance_timestep();\n\n\n\nprotected:\n\n std::vector<std::string> filenames;\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 32, "score": 211837.7755177343 }, { "content": "struct simplicial_regular_mesh : public object {\n\n friend class simplicial_regular_mesh_element;\n\n typedef simplicial_regular_mesh_element iterator;\n\n\n\n simplicial_regular_mesh(int n) : nd_(n), lattice_(n) {\n\n for (int i = 0; i < n; i ++) {\n\n lb_.push_back(0);\n\n ub_.push_back(0);\n\n }\n\n\n\n initialize_subdivision();\n\n\n\n lattice_.reshape(lb_, sizes()); \n\n }\n\n\n\n simplicial_regular_mesh(const lattice l) : simplicial_regular_mesh(l.nd()) {\n\n set_lb_ub(l);\n\n }\n\n\n\n#if 0\n", "file_path": "include/ftk/mesh/simplicial_regular_mesh.hh", "rank": 33, "score": 211837.7755177343 }, { "content": "// this is an abstract class, not for users\n\nstruct contour_tracker_regular : public contour_tracker, public regular_tracker {\n\n contour_tracker_regular(diy::mpi::communicator comm, int nd/*2 or 3*/) : contour_tracker(comm), regular_tracker(comm, nd), tracker(comm) {}\n\n virtual ~contour_tracker_regular() {}\n\n\n\n void reset();\n\n\n\nprotected:\n\n typedef simplicial_regular_mesh_element element_t;\n\n \n\n std::map<element_t, feature_point_t> intersections;\n\n std::set<element_t> related_cells;\n\n\n\nprotected:\n\n void build_isovolumes();\n\n\n\npublic: // cp io\n\n const std::map<element_t, feature_point_t>& get_discrete_intersections() const {return intersections;}\n\n std::vector<feature_point_t> get_intersections() const;\n\n};\n\n\n", "file_path": "include/ftk/filters/contour_tracker_regular.hh", "rank": 34, "score": 211598.8056706593 }, { "content": "struct unstructured_2d_tracker : public virtual tracker {\n\n unstructured_2d_tracker(diy::mpi::communicator comm, const simplicial_unstructured_extruded_2d_mesh<> &m) : \n\n m(simplicial_unstructured_extruded_2d_mesh<>(m)), tracker(comm) {}\n\n virtual ~unstructured_2d_tracker() {}\n\n\n\npublic:\n\n void initialize() {}\n\n\n\nprotected:\n\n const simplicial_unstructured_extruded_2d_mesh<> m;\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "include/ftk/filters/unstructured_2d_tracker.hh", "rank": 35, "score": 210161.59371114278 }, { "content": "//! Enables communication within a group during a reduction.\n\n//! DIY creates the ReduceProxy for you in diy::reduce()\n\n//! and provides a reference to ReduceProxy each time the user's reduction function is called\n\nstruct ReduceProxy: public Master::Proxy\n\n{\n\n typedef std::vector<int> GIDVector;\n\n\n\n ReduceProxy(const Master::Proxy& proxy, //!< parent proxy\n\n void* block, //!< diy block\n\n unsigned round, //!< current round\n\n const Assigner& assigner, //!< assigner\n\n const GIDVector& incoming_gids, //!< incoming gids in this group\n\n const GIDVector& outgoing_gids): //!< outgoing gids in this group\n\n Master::Proxy(proxy),\n\n block_(block),\n\n round_(round),\n\n assigner_(assigner)\n\n {\n\n // setup in_link\n\n for (unsigned i = 0; i < incoming_gids.size(); ++i)\n\n {\n\n BlockID nbr;\n\n nbr.gid = incoming_gids[i];\n", "file_path": "include/ftk/external/diy/reduce.hpp", "rank": 36, "score": 210161.59371114278 }, { "content": "struct unstructured_3d_tracker : public virtual tracker {\n\n unstructured_3d_tracker(diy::mpi::communicator comm, const simplicial_unstructured_extruded_3d_mesh<> &m) : \n\n m(simplicial_unstructured_extruded_3d_mesh<>(m)), tracker(comm) {}\n\n virtual ~unstructured_3d_tracker() {}\n\n\n\npublic:\n\n void initialize() {}\n\n\n\nprotected:\n\n const simplicial_unstructured_extruded_3d_mesh<> m;\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "include/ftk/filters/unstructured_3d_tracker.hh", "rank": 37, "score": 210161.59371114278 }, { "content": "struct contour_tracker : public virtual tracker {\n\n contour_tracker(diy::mpi::communicator comm) : tracker(comm) {}\n\n\n\n virtual void update() {}; \n\n void reset() {\n\n field_data_snapshots.clear();\n\n // traced_contours.clear();\n\n }\n\n \n\n void set_scalar_components(const std::vector<std::string>& c);\n\n int get_num_scalar_components() const {return scalar_components.size();}\n\n\n\n double get_threshold() const { return threshold; }\n\n void set_threshold(double t) {threshold = t;}\n\n\n\npublic:\n\n virtual bool advance_timestep();\n\n\n\npublic: // inputs\n\n bool pop_field_data_snapshot();\n", "file_path": "include/ftk/filters/contour_tracker.hh", "rank": 38, "score": 210161.59371114278 }, { "content": "struct regular_tracker : public virtual tracker {\n\n regular_tracker(diy::mpi::communicator comm, int nd/*2 or 3*/) : tracker(comm), m(nd+1) {}\n\n virtual ~regular_tracker() {}\n\n \n\npublic:\n\n void set_domain(const lattice& l) {domain = l;} // spatial domain\n\n void set_array_domain(const lattice& l) {array_domain = l;}\n\n\n\n void set_local_domain(const lattice&); // rank-specific \"core\" region of the block\n\n void set_local_array_domain(const lattice&); // rank-specific \"ext\" region of the block\n\n\n\n void initialize();\n\n\n\n lattice get_local_array_domain() const { return local_array_domain; }\n\n \n\npublic: // physics coordinates\n\n // void set_coordinates(const ndarray<double>& coords_) {coords = coords_; use_explicit_coords = true;}\n\n std::array<double, 3> get_coords(const std::vector<int>&) const;\n\n\n\n void set_coords_bounds(const std::vector<double>& bounds) { bounds_coords = bounds; mode_phys_coords = REGULAR_COORDS_BOUNDS; }\n", "file_path": "include/ftk/filters/regular_tracker.hh", "rank": 39, "score": 210161.59371114275 }, { "content": "struct data_stream_vti : public data_stream_files {\n\n void initialize() {\n\n\n\n }\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 40, "score": 207560.67061998916 }, { "content": "struct xgc_stream_h5 : public xgc_stream\n\n{\n\n xgc_stream_h5(const std::string& path, diy::mpi::communicator comm = MPI_COMM_WORLD) : xgc_stream(path, comm) {}\n\n \n\n std::string postfix() const { return \".h5\"; }\n\n \n\n std::shared_ptr<ndarray_group> request_step(int step) { return NULL; } // TODO\n\n\n\n bool read_oneddiag();\n\n bool advance_timestep();\n\n};\n\n\n\ninline bool xgc_stream_h5::read_oneddiag()\n\n{\n\n const auto f = oneddiag_filename();\n\n ndarray<double> etemp_par, etemp_per;\n\n \n\n steps.read_h5(f, \"steps\");\n\n time.read_h5(f, \"time\");\n\n etemp_par.read_h5(f, \"e_parallel_mean_en_avg\");\n", "file_path": "include/ftk/io/xgc_stream_h5.hpp", "rank": 41, "score": 207560.67061998916 }, { "content": "struct data_stream_pnc : public data_stream_files {\n\n\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 42, "score": 207560.67061998916 }, { "content": "struct data_stream_raw : public data_stream_files {\n\n void initialize() {}\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 43, "score": 207560.67061998916 }, { "content": "struct xgc_stream_adios2 : public xgc_stream\n\n{\n\n xgc_stream_adios2(const std::string& path, diy::mpi::communicator comm = MPI_COMM_WORLD) : xgc_stream(path, comm) {}\n\n \n\n std::string postfix() const { return \".bp\"; }\n\n\n\n std::shared_ptr<ndarray_group> request_step(int step);\n\n\n\n bool read_units();\n\n\n\n bool read_oneddiag();\n\n bool advance_timestep();\n\n};\n\n\n\ninline bool xgc_stream_adios2::read_units()\n\n{\n\n xgc_units_t u;\n\n bool succ = true;\n\n\n\n if (!u.read(units_filename())) \n", "file_path": "include/ftk/io/xgc_stream_adios2.hpp", "rank": 44, "score": 207560.67061998916 }, { "content": "struct RegularSwapPartners: public RegularPartners\n\n{\n\n typedef RegularPartners Parent;\n\n\n\n // contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion;\n\n // contiguous is useful when data needs to be united;\n\n // round-robin is useful for vector-\"halving\"\n\n template<class Decomposer>\n\n RegularSwapPartners(const Decomposer& decomposer, //!< domain decomposition\n\n int k, //!< target k value\n\n bool contiguous = true //!< distance halving (true) or doubling (false)\n\n ):\n\n Parent(decomposer, k, contiguous) {}\n\n RegularSwapPartners(const DivisionVector& divs, //!< explicit division vector\n\n const KVSVector& kvs, //!< explicit k vector\n\n bool contiguous = true //!< distance halving (true) or doubling (false)\n\n ):\n\n Parent(divs, kvs, contiguous) {}\n\n\n\n bool active(int, int, const Master&) const { return true; } // in swap-reduce every block is always active\n\n\n\n void incoming(int round, int gid, std::vector<int>& partners, const Master&) const { Parent::fill(round - 1, gid, partners); }\n\n void outgoing(int round, int gid, std::vector<int>& partners, const Master&) const { Parent::fill(round, gid, partners); }\n\n};\n\n\n\n} // diy\n\n\n\n#endif\n", "file_path": "include/ftk/external/diy/partners/swap.hpp", "rank": 45, "score": 207560.67061998916 }, { "content": "struct data_stream_nc : public data_stream_files {\n\n\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 46, "score": 207560.67061998916 }, { "content": "struct RegularMergePartners: public RegularPartners\n\n{\n\n typedef RegularPartners Parent;\n\n\n\n // contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion;\n\n // contiguous is useful when data needs to be united;\n\n // round-robin is useful for vector-\"halving\"\n\n template<class Decomposer>\n\n RegularMergePartners(const Decomposer& decomposer, //!< domain decomposition\n\n int k, //!< target k value\n\n bool contiguous = true //!< distance doubling (true) or halving (false)\n\n ):\n\n Parent(decomposer, k, contiguous) {}\n\n RegularMergePartners(const DivisionVector& divs, //!< explicit division vector\n\n const KVSVector& kvs, //!< explicit k vector\n\n bool contiguous = true //!< distance doubling (true) or halving (false)\n\n ):\n\n Parent(divs, kvs, contiguous) {}\n\n\n\n inline bool active(int round, int gid, const Master&) const;\n", "file_path": "include/ftk/external/diy/partners/merge.hpp", "rank": 47, "score": 207560.67061998916 }, { "content": "struct Block : public ftk::distributed_union_find_exchange<std::string> {\n\n Block(): nchanges(0), distributed_union_find_exchange() { \n\n \n\n }\n\n\n\n // add an element\n\n void add(std::string ele) {\n\n distributed_union_find_exchange::add(ele); \n\n this->ele2gid[ele] = -1;\n\n }\n\n\n\n void add_related_element(std::string ele, std::string related_ele) {\n\n this->related_elements[ele].push_back(related_ele); \n\n this->ele2gid[related_ele] = -1; \n\n }\n\n\n\npublic: \n\n // map element id to ids of its related elements\n\n // Can be optimized by ordered the related elements, put related elements on process first and ordered decreingly by ids\n\n std::map<std::string, std::vector<std::string>> related_elements; \n\n std::map<std::string, int> ele2gid; \n\n\n\n int nchanges; // # of processed unions per round = valid unions (united unions) + passing unions\n\n};\n\n\n\n// ==========================================================\n\n\n", "file_path": "include/ftk/basic/legacy/distributed_union_find_deprecated.hh", "rank": 48, "score": 206448.90304668123 }, { "content": "// DIY Block for distributed union-find\n\nstruct Block_Union_Find : public ftk::distributed_union_find<std::string> {\n\n Block_Union_Find(): nchanges(0), related_elements(), all_related_elements(), temporary_root_2_gids(), nonlocal_temporary_roots_2_grandparents(), ele2gid(), distributed_union_find() { \n\n \n\n }\n\n\n\n // add an element\n\n void add(std::string ele) {\n\n this->nchanges += 1;\n\n\n\n if(this->has(ele)) {\n\n std::cout<<\"This ele has been added. \"<<ele<<std::endl; \n\n } else {\n\n distributed_union_find::add(ele); \n\n this->related_elements.insert(std::make_pair(ele, std::set<std::string>())); \n\n this->has_sent_gparent_query[ele] = false;\n\n }\n\n }\n\n\n\n void erase_element(std::string ele) {\n\n this->nchanges += 1;\n", "file_path": "include/ftk/basic/legacy/distributed_union_find.hh", "rank": 49, "score": 206448.90304668123 }, { "content": "struct RegularBroadcastPartners: public RegularMergePartners\n\n{\n\n typedef RegularMergePartners Parent; //!< base class merge reduction\n\n\n\n //! contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion;\n\n //! contiguous is useful when data needs to be united;\n\n //! round-robin is useful for vector-\"halving\"\n\n template<class Decomposer>\n\n RegularBroadcastPartners(const Decomposer& decomposer, //!< domain decomposition\n\n int k, //!< target k value\n\n bool contiguous = true //!< distance doubling (true) or halving (false)\n\n ):\n\n Parent(decomposer, k, contiguous) {}\n\n RegularBroadcastPartners(const DivisionVector& divs,//!< explicit division vector\n\n const KVSVector& kvs, //!< explicit k vector\n\n bool contiguous = true //!< distance doubling (true) or halving (false)\n\n ):\n\n Parent(divs, kvs, contiguous) {}\n\n\n\n //! returns total number of rounds\n", "file_path": "include/ftk/external/diy/partners/broadcast.hpp", "rank": 50, "score": 203509.0564796531 }, { "content": "struct contour_tracker_3d_regular : public contour_tracker_regular {\n\n contour_tracker_3d_regular(diy::mpi::communicator comm) : contour_tracker_regular(comm, 3), tracker(comm) {}\n\n virtual ~contour_tracker_3d_regular() {}\n\n\n\n // int cpdims() const { return 3; }\n\n\n\n void finalize();\n\n void reset();\n\n\n\n void update_timestep();\n\n\n\npublic:\n\n const feature_volume_t& get_isovolume() { return isovolume; }\n\n\n\nprotected:\n\n void build_isovolume();\n\n\n\nprotected:\n\n void write_isovolume_vtu(const std::string& filename) const;\n\n#if FTK_HAVE_VTK\n", "file_path": "include/ftk/filters/contour_tracker_3d_regular.hh", "rank": 51, "score": 203509.0564796531 }, { "content": "struct feature_flow_tracer_regular_distributed : public filter {\n\n\n\nprivate:\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "include/ftk/filters/feature_flow_tracer.hh", "rank": 52, "score": 203509.0564796531 }, { "content": "struct data_stream_synthetic_woven : public data_stream_synthetic {\n\n ndarray<double> synthesize_timestep(int t) {\n\n return synthetic_woven_2D(DW, DH, t*time_scale);\n\n };\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 53, "score": 203509.0564796531 }, { "content": "struct contour_tracker_2d_regular : public contour_tracker_regular {\n\n contour_tracker_2d_regular(diy::mpi::communicator comm) : \n\n contour_tracker_regular(comm, 2),\n\n tracker(comm)\n\n {}\n\n virtual ~contour_tracker_2d_regular() {}\n\n\n\n // int cpdims() const { return 2; }\n\n\n\n void finalize();\n\n void reset();\n\n\n\n void update_timestep();\n\n\n\n const feature_surface_t& get_surfaces() const { return surfaces; }\n\n\n\npublic:\n\n void write_isovolume_vtu(const std::string& filename) const;\n\n#if FTK_HAVE_VTK\n\n vtkSmartPointer<vtkPolyData> get_isovolume_vtp() const;\n", "file_path": "include/ftk/filters/contour_tracker_2d_regular.hh", "rank": 54, "score": 203509.0564796531 }, { "content": "struct RegularAllReducePartners: public RegularMergePartners\n\n{\n\n typedef RegularMergePartners Parent; //!< base class merge reduction\n\n\n\n //! contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion;\n\n //! contiguous is useful when data needs to be united;\n\n //! round-robin is useful for vector-\"halving\"\n\n template<class Decomposer>\n\n RegularAllReducePartners(const Decomposer& decomposer, //!< domain decomposition\n\n int k, //!< target k value\n\n bool contiguous = true //!< distance doubling (true) or halving (false)\n\n ):\n\n Parent(decomposer, k, contiguous) {}\n\n RegularAllReducePartners(const DivisionVector& divs,//!< explicit division vector\n\n const KVSVector& kvs, //!< explicit k vector\n\n bool contiguous = true //!< distance doubling (true) or halving (false)\n\n ):\n\n Parent(divs, kvs, contiguous) {}\n\n\n\n //! returns total number of rounds\n", "file_path": "include/ftk/external/diy/partners/all-reduce.hpp", "rank": 55, "score": 203509.0564796531 }, { "content": "// this is an abstract class, not for users\n\nstruct critical_point_tracker_regular : public critical_point_tracker, public regular_tracker {\n\n critical_point_tracker_regular(diy::mpi::communicator comm, int nd) : critical_point_tracker(comm), regular_tracker(comm, nd), tracker(comm) {}\n\n virtual ~critical_point_tracker_regular() {}\n\n\n\nprotected:\n\n typedef simplicial_regular_mesh_element element_t;\n\n \n\n std::map<element_t, feature_point_t> discrete_critical_points;\n\n std::vector<std::set<element_t>> connected_components;\n\n\n\npublic: // cp io\n\n const std::map<element_t, feature_point_t>& get_discrete_critical_points() const {return discrete_critical_points;}\n\n\n\n std::vector<feature_point_t> get_critical_points() const;\n\n // void put_critical_points(const std::vector<feature_point_t>&);\n\n};\n\n\n\n/////\n\n////\n\ninline std::vector<feature_point_t> critical_point_tracker_regular::get_critical_points() const\n", "file_path": "include/ftk/filters/critical_point_tracker_regular.hh", "rank": 56, "score": 201711.61360899865 }, { "content": "struct critical_point_tracker_2d_unstructured : public critical_point_tracker, public unstructured_2d_tracker\n\n{\n\n // critical_point_tracker_2d_unstructured(const simplicial_unstructured_extruded_2d_mesh<>& m) : m(m) {}\n\n // critical_point_tracker_2d_unstructured() {}\n\n critical_point_tracker_2d_unstructured(diy::mpi::communicator comm, const simplicial_unstructured_2d_mesh<>& m) : \n\n critical_point_tracker(comm), unstructured_2d_tracker(comm, m), tracker(comm) {}\n\n virtual ~critical_point_tracker_2d_unstructured() {};\n\n \n\n int cpdims() const { return 3; }\n\n // int cpdims() const { return m.ncoords() - 1; }\n\n\n\n void initialize() {}\n\n void finalize();\n\n void reset() {}\n\n\n\n void update_timestep();\n\n\n\npublic:\n\n std::vector<feature_point_t> get_critical_points() const;\n\n void put_critical_points(const std::vector<feature_point_t>&);\n", "file_path": "include/ftk/filters/critical_point_tracker_2d_unstructured.hh", "rank": 57, "score": 201711.61360899865 }, { "content": "// we define critical lines as intersections of two isosurfaces in 3D\n\nstruct critical_line_tracker : public virtual tracker {\n\n critical_line_tracker(diy::mpi::communicator comm) : tracker(comm) {}\n\n\n\n // int cpdims() const { return 3; }\n\n \n\n virtual void update() {}; \n\n void reset() {\n\n field_data_snapshots.clear();\n\n }\n\n \n\npublic:\n\n bool advance_timestep();\n\n\n\npublic:\n\n bool pop_field_data_snapshot();\n\n virtual void push_field_data_snapshot(const ndarray<float> &uv);\n\n \n\nprotected:\n\n struct field_data_snapshot_t {\n\n ndarray<float> uv; // shape is (2, width, height, depth)\n", "file_path": "include/ftk/filters/critical_line_tracker.hh", "rank": 58, "score": 201368.69426347443 }, { "content": "struct critical_point_tracker : public virtual tracker {\n\n critical_point_tracker(diy::mpi::communicator comm) : tracker(comm) {}\n\n\n\n virtual void update() {}; \n\n void reset() {\n\n field_data_snapshots.clear();\n\n traced_critical_points.clear();\n\n }\n\n\n\n void set_enable_robust_detection(bool b) { enable_robust_detection = b; }\n\n void set_enable_computing_degrees(bool b) { enable_computing_degrees = b; }\n\n void set_enable_streaming_trajectories(bool b) { enable_streaming_trajectories = b; }\n\n void set_enable_discarding_interval_points(bool b) { enable_discarding_interval_points = b; }\n\n void set_enable_discarding_degenerate_points(bool b) { enable_discarding_degenerate_points = b; }\n\n void set_enable_ignoring_degenerate_points(bool b) { enable_ignoring_degenerate_points = b; }\n\n\n\n void set_type_filter(unsigned int);\n\n\n\n void set_scalar_field_source(int s) {scalar_field_source = s;}\n\n void set_vector_field_source(int s) {vector_field_source = s;}\n", "file_path": "include/ftk/filters/critical_point_tracker.hh", "rank": 59, "score": 201362.5299534425 }, { "content": "struct tdgl_vortex_tracker : public virtual tracker {\n\n tdgl_vortex_tracker(diy::mpi::communicator comm) : tracker(comm) {}\n\n\n\n int cpdims() const { return 3; }\n\n \n\n virtual void update() {}; \n\n void reset() {\n\n field_data_snapshots.clear();\n\n }\n\n \n\npublic:\n\n bool advance_timestep();\n\n\n\npublic:\n\n bool pop_field_data_snapshot();\n\n void push_field_data_snapshot(\n\n const tdgl_metadata_t &meta,\n\n const ndarray<float> &rho, \n\n const ndarray<float> &phi, \n\n const ndarray<float> &re, \n", "file_path": "include/ftk/filters/tdgl_vortex_tracker.hh", "rank": 60, "score": 201362.5299534425 }, { "content": "struct Grid: public GridRef<C,D>\n\n{\n\n public:\n\n typedef GridRef<C,D> Parent;\n\n typedef typename Parent::Value Value;\n\n typedef typename Parent::Index Index;\n\n typedef typename Parent::Vertex Vertex;\n\n typedef Parent Reference;\n\n\n\n template<class U>\n\n struct rebind { typedef Grid<U,D> type; };\n\n\n\n public:\n\n Grid():\n\n Parent(new C[0], Vertex::zero()) {}\n\n template<class Int>\n\n Grid(const Point<Int, D>& shape, bool c_order = true):\n\n Parent(new C[size(shape)], shape, c_order)\n\n {}\n\n\n", "file_path": "include/ftk/external/diy/grid.hpp", "rank": 61, "score": 200720.84557116285 }, { "content": "// DIY Block for distributed union-find\n\nstruct Block_Union_Find : public ftk::distributed_union_find<std::string> {\n\n Block_Union_Find(): nchanges(0), related_elements(), all_related_elements(), ele2gid(), distributed_union_find() { \n\n \n\n }\n\n\n\n // add an element\n\n void add(std::string ele) {\n\n this->nchanges += 1;\n\n\n\n if(this->has(ele)) {\n\n std::cout<<\"This ele has been added. \"<<ele<<std::endl; \n\n } else {\n\n distributed_union_find::add(ele); \n\n this->related_elements.insert(std::make_pair(ele, std::set<std::string>())); \n\n }\n\n }\n\n\n\n void erase_element(std::string ele) {\n\n this->nchanges += 1;\n\n\n", "file_path": "include/ftk/basic/legacy/distributed_union_find_test_backup.hh", "rank": 62, "score": 200280.30290210337 }, { "content": "// DIY Block for distributed union-find\n\nstruct Block_Union_Find : public ftk::distributed_union_find<std::string> {\n\n Block_Union_Find(): nchanges(0), related_elements(), all_related_elements(), ele2gid(), distributed_union_find() { \n\n \n\n }\n\n\n\n // add an element\n\n void add(std::string ele) {\n\n this->nchanges += 1;\n\n\n\n if(this->has(ele)) {\n\n std::cout<<\"This ele has been added. \"<<ele<<std::endl; \n\n } else {\n\n distributed_union_find::add(ele); \n\n this->related_elements.insert(std::make_pair(ele, std::set<std::string>())); \n\n }\n\n }\n\n\n\n void erase_element(std::string ele) {\n\n this->nchanges += 1;\n\n\n", "file_path": "include/ftk/basic/legacy/distributed_union_find_storing_children.hh", "rank": 63, "score": 200280.30290210337 }, { "content": "struct data_stream_synthetic_double_gyre : public data_stream_synthetic {\n\n ndarray<double> synthesize_timestep(int t) {\n\n return synthetic_double_gyre(DW, DH, t * time_scale);\n\n };\n\n};\n\n\n", "file_path": "include/ftk/io/data_stream.hh", "rank": 64, "score": 199665.55912774935 }, { "content": "struct xgc_blob_filament_tracker : public xgc_tracker {\n\n xgc_blob_filament_tracker(diy::mpi::communicator comm,\n\n std::shared_ptr<simplicial_xgc_3d_mesh<>> mx);\n\n virtual ~xgc_blob_filament_tracker();\n\n\n\n // xgc_blob_filament_tracker(diy::mpi::communicator comm, \n\n // std::shared_ptr<simplicial_unstructured_2d_mesh<>> m2, \n\n // int nphi_, int iphi_);\n\n\n\n // int cpdims() const { return 3; }\n\n \n\n void initialize();\n\n void reset() {\n\n field_data_snapshots.clear();\n\n }\n\n void update() {}\n\n void finalize();\n\n\n\npublic:\n\n void update_timestep();\n", "file_path": "include/ftk/filters/xgc_blob_filament_tracker.hh", "rank": 65, "score": 199665.5591277494 }, { "content": "struct xgc_blob_threshold_tracker : public xgc_tracker {\n\n xgc_blob_threshold_tracker(diy::mpi::communicator comm, \n\n std::shared_ptr<simplicial_xgc_3d_mesh<>> m3) : xgc_tracker(comm, m3) {}\n\n virtual ~xgc_blob_threshold_tracker() {}\n\n \n\n void set_threshold(double t) { threshold = t; }\n\n\n\n // int cpdims() const { return 0; }\n\n \n\n void initialize() {}\n\n void update() {}\n\n void finalize();\n\n\n\n void update_timestep();\n\n\n\n void push_field_data_snapshot(const ndarray<double> &scalar);\n\n\n\npublic:\n\n ndarray<int> get_sliced(int t) const;\n\n void write_sliced(int t, const std::string& pattern) const;\n", "file_path": "include/ftk/filters/xgc_blob_threshold_tracker.hh", "rank": 66, "score": 199665.5591277494 }, { "content": "struct feature_curve_t : public std::vector<feature_point_t>\n\n{\n\n feature_curve_t() {}\n\n feature_curve_t(const feature_curve_t&);\n\n feature_curve_t& operator=(const feature_curve_t&);\n\n\n\n void relabel(int i); // assign id for traj and each point in the traj\n\n void update_statistics();\n\n void derive_velocity(); // (const std::vector<double> &dog_kernel); // assuming the traj contains only ordinal points (dt=1)\n\n\n\n std::vector<feature_curve_t> split() const; // split to consistent subtrajs\n\n std::vector<int/*idx in original traj*/> to_ordinals() const;\n\n std::vector<int/*idx in original traj*/> select(std::function<bool(const feature_point_t&)> f);\n\n\n\n void rotate(); //! if the traj is a loop and the type is inconsistent, rotate the traj before splitting\n\n void reorder(); //! reorder by timestep\n\n void adjust_time(); //! assuming traj has only one single branch and is organized in ascending order, ensure that the time increases monotonously\n\n\n\n void smooth_ordinal_types(const int half_window_size=2); // make types of ordinal points robust to noises\n\n void smooth_interval_types(); //! make types in intervals consistent\n", "file_path": "include/ftk/features/feature_curve.hh", "rank": 67, "score": 196443.7406734177 }, { "content": " class StaticAssigner: public Assigner\n\n {\n\n public:\n\n /**\n\n * \\ingroup Assignment\n\n * \\brief Intermediate type to express assignment that cannot change; adds `local_gids` query method\n\n */\n\n using Assigner::Assigner;\n\n\n\n //! gets the local gids for a given process rank\n\n virtual void local_gids(int rank, std::vector<int>& gids) const =0;\n\n };\n\n\n", "file_path": "include/ftk/external/diy/assigner.hpp", "rank": 68, "score": 194579.13244805645 }, { "content": "struct critical_point_tracker_2d_regular : public critical_point_tracker_regular {\n\n critical_point_tracker_2d_regular(diy::mpi::communicator comm) : \n\n critical_point_tracker_regular(comm, 2),\n\n tracker(comm)\n\n {}\n\n virtual ~critical_point_tracker_2d_regular() {}\n\n\n\n int cpdims() const { return 2; }\n\n\n\n void finalize();\n\n void reset();\n\n\n\n void update_timestep();\n\n\n\n void push_scalar_field_snapshot(const ndarray<double>&);\n\n void push_vector_field_snapshot(const ndarray<double>&);\n\n\n\nprotected:\n\n typedef simplicial_regular_mesh_element element_t;\n\n \n", "file_path": "include/ftk/filters/critical_point_tracker_2d_regular.hh", "rank": 69, "score": 192541.90727723652 }, { "content": "struct sujudi_haimes_tracker_3d_regular : public critical_line_tracker_3d_regular \n\n{\n\n sujudi_haimes_tracker_3d_regular(diy::mpi::communicator comm) : \n\n critical_line_tracker_3d_regular(comm), \n\n critical_line_tracker(comm),\n\n regular_tracker(comm, 3), \n\n tracker(comm) {}\n\n virtual ~sujudi_haimes_tracker_3d_regular() {};\n\n\n\nprotected:\n\n bool check_simplex(const element_t& s, feature_point_t& cp) const;\n\n\n\n void simplex_residue_J(\n\n const std::vector<std::vector<int>>& vertices,\n\n float residues[3], float Js[3][3][3]) const;\n\n\n\n void push_field_data_snapshot(const ndarray<float>& data);\n\n\n\n std::vector<std::string> varnames() const { return {\"residue\", \"discJ\"}; }\n\n};\n", "file_path": "include/ftk/filters/sujudi_haimes_tracker_3d_regular.hh", "rank": 70, "score": 192541.90727723652 }, { "content": "struct critical_point_tracker_3d_regular : public critical_point_tracker_regular {\n\n critical_point_tracker_3d_regular(diy::mpi::communicator comm) : critical_point_tracker_regular(comm, 3), tracker(comm) {}\n\n virtual ~critical_point_tracker_3d_regular() {}\n\n \n\n // int cpdims() const { return 3; }\n\n\n\n void finalize();\n\n\n\n void update_timestep();\n\n \n\n void push_scalar_field_snapshot(const ndarray<double>&);\n\n void push_vector_field_snapshot(const ndarray<double>&);\n\n \n\nprotected:\n\n typedef simplicial_regular_mesh_element element_t;\n\n\n\nprotected:\n\n bool check_simplex(const element_t& s, feature_point_t& cp);\n\n void trace_intersections();\n\n void trace_connected_components();\n", "file_path": "include/ftk/filters/critical_point_tracker_3d_regular.hh", "rank": 71, "score": 192541.90727723652 }, { "content": "struct ridge_valley_tracker_3d_regular : public sujudi_haimes_tracker_3d_regular \n\n{\n\n ridge_valley_tracker_3d_regular(diy::mpi::communicator comm) : \n\n sujudi_haimes_tracker_3d_regular(comm),\n\n critical_line_tracker(comm),\n\n regular_tracker(comm, 3), \n\n tracker(comm) {}\n\n virtual ~ridge_valley_tracker_3d_regular() {};\n\n\n\nprotected:\n\n bool check_simplex(const element_t& s, feature_point_t& cp) const;\n\n void push_field_data_snapshot(const ndarray<float>& data);\n\n \n\n void simplex_scalars(\n\n const std::vector<std::vector<int>>& vertices,\n\n float scalars[3]) const;\n\n\n\n std::vector<std::string> varnames() const { return {\"residue\", \"discJ\", \"scalar\"}; }\n\n};\n\n\n", "file_path": "include/ftk/filters/ridge_valley_tracker_3d_regular.hh", "rank": 72, "score": 192541.90727723652 }, { "content": "struct function_traits<T&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 73, "score": 192392.12653308164 }, { "content": "struct function_traits<T&&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 74, "score": 192392.12653308164 }, { "content": "struct point_locator_2d_quad : public point_locator_2d<I, F> {\n\n point_locator_2d_quad(const simplicial_unstructured_2d_mesh<I, F> &m) \n\n : point_locator_2d<I, F>(m) { initialize(); }\n\n virtual ~point_locator_2d_quad();\n\n\n\n void initialize();\n\n // I locate(const F x[], F mu[]) const { return locate_point_recursive(x, root, mu); }\n\n I locate(const F x[], F mu[]) const { return locate_point_nonrecursive(x, mu); }\n\n\n\n std::vector<bvh2d_node_t<I, F>> to_bvh() const;\n\n\n\nprotected:\n\n struct quad_node {\n\n quad_node *parent = NULL;\n\n quad_node *children[4] = {NULL};\n\n AABB<F> aabb;\n\n std::vector<AABB<F>> elements; // valid only for leaf nodes\n\n\n\n ~quad_node();\n\n bool is_leaf() const { return elements.size() > 0; }\n", "file_path": "include/ftk/mesh/point_locator_2d_quad.hh", "rank": 75, "score": 192392.12653308164 }, { "content": " class ContiguousAssigner: public StaticAssigner\n\n {\n\n public:\n\n /**\n\n * \\ingroup Assignment\n\n * \\brief Assigns blocks to processes in contiguous gid (block global id) order\n\n */\n\n using StaticAssigner::StaticAssigner;\n\n\n\n using StaticAssigner::size;\n\n using StaticAssigner::nblocks;\n\n\n\n int rank(int gid) const override\n\n {\n\n int div = nblocks() / size();\n\n int mod = nblocks() % size();\n\n int r = gid / (div + 1);\n\n if (r < mod)\n\n {\n\n return r;\n\n } else\n\n {\n\n return mod + (gid - (div + 1)*mod)/div;\n\n }\n\n }\n\n inline\n\n void local_gids(int rank, std::vector<int>& gids) const override;\n\n };\n\n\n", "file_path": "include/ftk/external/diy/assigner.hpp", "rank": 76, "score": 189783.6907323662 }, { "content": "struct simplicial_unstructured_extruded_2d_mesh : public object { // extruded from \n\n simplicial_unstructured_extruded_2d_mesh(const simplicial_unstructured_2d_mesh<I, F>& m_) : m(m_) {extrude();}\n\n\n\n size_t n(int d) const;\n\n size_t n_ordinal(int d) const { return m.n(d); }\n\n size_t n_interval(int d) const;\n\n\n\n bool is_ordinal(int d, I i) const {\n\n I k = mod(i, n(d));\n\n return k < n_ordinal(d);\n\n }\n\n\n\n I flat_vertex_id(I i) const { return mod(i, m.n(0)); }\n\n I flat_vertex_time(I i) const { return i / m.n(0); }\n\n I extruded_vertex_id(I i, bool t=true) { return t ? i + m.n(0) : i; }\n\n\n\n int face_type(I i) const; // legacy\n\n int simplex_type(int d, I i) const;\n\n\n\n int get_triangle_chi(I i) const;\n", "file_path": "include/ftk/mesh/simplicial_unstructured_extruded_2d_mesh.hh", "rank": 77, "score": 188548.6291811779 }, { "content": "struct simplicial_unstructured_extruded_3d_mesh : public object { // extruded from \n\n simplicial_unstructured_extruded_3d_mesh(const simplicial_unstructured_3d_mesh<I, F>& m_) : m(m_) {extrude();}\n\n\n\n size_t n(int d) const;\n\n size_t n_ordinal(int d) const { if (d == 4) return m.n(3)*4; else return m.n(d); }\n\n size_t n_interval(int d) const;\n\n\n\n bool is_ordinal(int d, I i) const {\n\n I k = mod(i, n(d));\n\n return k < n_ordinal(d);\n\n }\n\n\n\n I flat_vertex_id(I i) const { return mod(i, m.n(0)); }\n\n I flat_vertex_time(I i) const { return std::floor((double)i / n(0)); } // return i / m.n(0); }\n\n I extruded_vertex_id(I i, bool t=true) { return t ? i + m.n(0) : i; }\n\n\n\n int tet_type(I i) const { return simplex_type(3, i); }\n\n int simplex_type(int d, I i) const;\n\n\n\npublic: // element iteration\n", "file_path": "include/ftk/mesh/simplicial_unstructured_extruded_3d_mesh.hh", "rank": 78, "score": 188548.62918117794 }, { "content": "struct simplicial_xgc_3d_mesh : public simplicial_unstructured_3d_mesh<I, F> {\n\n simplicial_xgc_3d_mesh(std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> m2_); // nphi and iphi must be specified before using\n\n simplicial_xgc_3d_mesh(std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> m2_, int nphi, int iphi=1, int vphi=1);\n\n // simplicial_xgc_3d_mesh(const std::string& mesh_filename);\n\n\n\n std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> get_m2() const {return m2;}\n\n\n\n virtual size_t n(int d) const;\n\n size_t np() const {return nphi * iphi * vphi;} // number of poloidal planes, incl. virtual planes defined by vphi\n\n\n\n bool probe_nphi_iphi(const std::string& filename);\n\n void set_nphi_iphi(int n, int i) {nphi = n; iphi = i;}\n\n void set_vphi(int v) { vphi = v; }\n\n\n\n int get_nphi() const {return nphi;}\n\n int get_iphi() const {return iphi;}\n\n int get_vphi() const {return vphi;}\n\n\n\n bool is_poloidal(int p) const { return p % vphi == 0; }\n\n bool is_poloidal(int d, I i) const { return m3->is_ordinal(d, i); }\n", "file_path": "include/ftk/mesh/simplicial_xgc_3d_mesh.hh", "rank": 79, "score": 188548.62918117794 }, { "content": "struct feature_point_set_t : public std::list<feature_point_t>\n\n{\n\n#if FTK_HAVE_VTK\n\n vtkSmartPointer<vtkPolyData> to_vtp(\n\n const std::vector<std::string>& scalar_components) const;\n\n#endif\n\n};\n\n\n\n#if FTK_HAVE_VTK\n\nvtkSmartPointer<vtkPolyData> feature_point_set_t::to_vtp(\n\n const std::vector<std::string>& scalar_components) const\n\n{\n\n vtkSmartPointer<vtkPolyData> poly = vtkPolyData::New();\n\n vtkSmartPointer<vtkPoints> points = vtkPoints::New();\n\n vtkSmartPointer<vtkCellArray> vertices = vtkCellArray::New();\n\n \n\n vtkIdType pid[1];\n\n for (const auto &cp : *this) {\n\n double p[3] = {cp.x[0], cp.x[1], cp.x[2]}; \n\n pid[0] = points->InsertNextPoint(p);\n", "file_path": "include/ftk/features/feature_point_set.hh", "rank": 80, "score": 188548.6291811779 }, { "content": "struct simplicial_unstructured_3d_mesh : public simplicial_unstructured_mesh<I, F> {\n\n friend class diy::Serialization<simplicial_unstructured_3d_mesh<I, F>>;\n\n \n\n simplicial_unstructured_3d_mesh() {}\n\n\n\n simplicial_unstructured_3d_mesh(\n\n const std::vector<F>& coords, \n\n const std::vector<I>& tetrahedra);\n\n\n\n int nd() const {return 3;}\n\n virtual size_t n(int d) const;\n\n \n\n void build_smoothing_kernel(F sigma);\n\n void smooth_scalar_gradient_jacobian(\n\n const ndarray<F>& f, \n\n const F sigma,\n\n ndarray<F>& fs, // smoothed scalar field\n\n ndarray<F>& g, // smoothed gradient field\n\n ndarray<F>& j // smoothed jacobian field\n\n ) const; \n", "file_path": "include/ftk/mesh/simplicial_unstructured_3d_mesh.hh", "rank": 81, "score": 188548.6291811779 }, { "content": "struct simplicial_xgc_2d_mesh : public simplicial_unstructured_2d_mesh<I, F> {\n\n simplicial_xgc_2d_mesh(\n\n const ndarray<F>& coords, \n\n const ndarray<I>& triangles,\n\n const ndarray<F>& psi,\n\n const ndarray<I>& nextnodes);\n\n \n\n simplicial_xgc_2d_mesh(\n\n const ndarray<F>& coords, \n\n const ndarray<I>& triangles) : simplicial_unstructured_2d_mesh<I, F>(coords, triangles) {}\n\n\n\n void initialize_point_locator();\n\n void initialize_roi(double psin_min = 0.9, double psin_max = 1.05, \n\n double theta_min_deg = -60.0, double theta_max_deg = 60.0);\n\n\n\n static std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> from_xgc_mesh_file(const std::string& filename, diy::mpi::communicator comm = MPI_COMM_WORLD);\n\n static std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> from_xgc_mesh_h5(const std::string& filename);\n\n static std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> from_xgc_mesh_bp(const std::string& filename, diy::mpi::communicator comm = MPI_COMM_WORLD);\n\n\n\n void read_oneddiag(const std::string& filename, diy::mpi::communicator comm = MPI_COMM_WORLD);\n", "file_path": "include/ftk/mesh/simplicial_xgc_2d_mesh.hh", "rank": 82, "score": 188548.6291811779 }, { "content": "struct simplicial_mpas_2d_mesh : public simplicial_unstructured_2d_mesh<I, F> {\n\n simplicial_mpas_2d_mesh(\n\n const ndarray<F>& coords, \n\n const ndarray<I>& triangles) : simplicial_unstructured_2d_mesh<I, F>(coords, triangles) {}\n\n\n\n // int ncoords() const { return 3; }\n\n\n\n static std::shared_ptr<simplicial_mpas_2d_mesh<I, F>> from_file(const std::string& filename, diy::mpi::communicator comm = MPI_COMM_WORLD);\n\n};\n\n\n\n// inline simplicial_mpas_2d_mesh::simplicial_mpas_2d_mesh(const mpas_mesh& mm) :\n\n\n\ntemplate <typename I, typename F>\n\nstd::shared_ptr<simplicial_mpas_2d_mesh<I, F>> simplicial_mpas_2d_mesh<I, F>::from_file(\n\n const std::string& filename, \n\n diy::mpi::communicator comm)\n\n{\n\n#if FTK_HAVE_NETCDF\n\n int ncid;\n\n NC_SAFE_CALL( nc_open(filename.c_str(), NC_NOWRITE, &ncid) );\n", "file_path": "include/ftk/mesh/simplicial_mpas_2d_mesh.hh", "rank": 83, "score": 188548.6291811779 }, { "content": "struct critical_line_tracker_3d_regular : public virtual critical_line_tracker, public virtual regular_tracker\n\n{\n\n critical_line_tracker_3d_regular(diy::mpi::communicator comm) : critical_line_tracker(comm), regular_tracker(comm, 3), tracker(comm) {}\n\n virtual ~critical_line_tracker_3d_regular() {}\n\n\n\n void finalize();\n\n void reset();\n\n\n\n void update_timestep();\n\n\n\npublic:\n\n void build_vortex_surfaces();\n\n\n\n void read_surfaces(const std::string& filename, std::string format=\"auto\");\n\n\n\n void write_intersections(const std::string& filename) const;\n\n void write_sliced(const std::string& pattern) const;\n\n void write_surfaces(const std::string& filename, std::string format=\"auto\") const;\n\n#if FTK_HAVE_VTK\n\n vtkSmartPointer<vtkPolyData> get_intersections_vtp() const;\n", "file_path": "include/ftk/filters/critical_line_tracker_3d_regular.hh", "rank": 84, "score": 187586.58315122855 }, { "content": "struct tdgl_vortex_tracker_3d_regular : public virtual tdgl_vortex_tracker, public virtual regular_tracker\n\n{\n\n tdgl_vortex_tracker_3d_regular(diy::mpi::communicator comm) : tdgl_vortex_tracker(comm), regular_tracker(comm, 3), tracker(comm) {}\n\n virtual ~tdgl_vortex_tracker_3d_regular() {}\n\n\n\n void finalize();\n\n void reset();\n\n\n\n void update_timestep();\n\n\n\npublic:\n\n void build_vortex_surfaces();\n\n\n\n void read_surfaces(const std::string& filename, std::string format=\"auto\");\n\n\n\n void write_intersections(const std::string& filename) const;\n\n void write_sliced(const std::string& pattern) const;\n\n void write_surfaces(const std::string& filename, std::string format=\"auto\") const;\n\n#if FTK_HAVE_VTK\n\n vtkSmartPointer<vtkPolyData> get_intersections_vtp() const;\n", "file_path": "include/ftk/filters/tdgl_vortex_tracker_3d_regular.hh", "rank": 85, "score": 187586.58315122855 }, { "content": "struct diyfp // f * 2^e\n\n{\n\n static constexpr int kPrecision = 64; // = q\n\n\n\n std::uint64_t f = 0;\n\n int e = 0;\n\n\n\n constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}\n\n\n\n /*!\n\n @brief returns x - y\n\n @pre x.e == y.e and x.f >= y.f\n\n */\n\n static diyfp sub(const diyfp& x, const diyfp& y) noexcept\n\n {\n\n assert(x.e == y.e);\n\n assert(x.f >= y.f);\n\n\n\n return {x.f - y.f, x.e};\n\n }\n", "file_path": "include/ftk/external/json.hh", "rank": 86, "score": 186165.48364938895 }, { "content": "struct levy_degani_seginer_tracker_3d_regular : public critical_line_tracker_3d_regular \n\n{\n\n levy_degani_seginer_tracker_3d_regular(diy::mpi::communicator comm) : \n\n critical_line_tracker_3d_regular(comm), \n\n critical_line_tracker(comm),\n\n regular_tracker(comm, 3), \n\n tracker(comm) {}\n\n virtual ~levy_degani_seginer_tracker_3d_regular() {};\n\n\n\nprotected:\n\n bool check_simplex(const element_t& s, feature_point_t& cp) const;\n\n\n\n void simplex_residue_vorts(\n\n const std::vector<std::vector<int>>& vertices,\n\n float residues[3], float vorts[3][3]) const;\n\n\n\n void push_field_data_snapshot(const ndarray<float>& data);\n\n\n\n std::vector<std::string> varnames() const { return {\"residue\", \"vortmag\"}; }\n\n};\n", "file_path": "include/ftk/filters/levy_degani_seginer_tracker_3d_regular.hh", "rank": 87, "score": 186081.9089972477 }, { "content": " class RoundRobinAssigner: public StaticAssigner\n\n {\n\n public:\n\n /**\n\n * \\ingroup Assignment\n\n * \\brief Assigns blocks to processes in cyclic or round-robin gid (block global id) order\n\n */\n\n using StaticAssigner::StaticAssigner;\n\n\n\n using StaticAssigner::size;\n\n using StaticAssigner::nblocks;\n\n\n\n int rank(int gid) const override { return gid % size(); }\n\n inline\n\n void local_gids(int rank, std::vector<int>& gids) const override;\n\n };\n\n\n", "file_path": "include/ftk/external/diy/assigner.hpp", "rank": 88, "score": 185255.1371622713 }, { "content": "struct function_traits<ReturnType(*)(Args...)>\n\n : public function_traits<ReturnType(Args...)>\n\n{};\n\n\n\ntemplate <typename ClassType, typename ReturnType, typename... Args>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 89, "score": 184948.612786814 }, { "content": "struct function_traits<ReturnType(Args...)>\n\n{\n\n /**\n\n .. type:: type result_type\n\n\n\n The type returned by calling an instance of the function object type *F*.\n\n */\n\n typedef ReturnType result_type;\n\n\n\n /**\n\n .. type:: type function_type\n\n\n\n The function type (``R(T...)``).\n\n */\n\n typedef ReturnType function_type(Args...);\n\n\n\n /**\n\n .. type:: type member_function_type<OwnerType>\n\n\n\n The member function type for an *OwnerType* (``R(OwnerType::*)(T...)``).\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 90, "score": 184948.612786814 }, { "content": "struct function_traits<volatile T&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 91, "score": 184550.14245891082 }, { "content": "struct function_traits<volatile T&&> : public function_traits<T> {};\n\ntemplate <typename T>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 92, "score": 184550.14245891082 }, { "content": "struct simplicial_xgc_3dff_mesh : public simplicial_xgc_3d_mesh<I, F> {\n\n simplicial_xgc_3dff_mesh(std::shared_ptr<simplicial_xgc_2d_mesh<I, F>> m2_, int nphi, int iphi=1, int vphi=1) \n\n : simplicial_xgc_3d_mesh<I, F>(m2_, nphi, iphi, vphi) {}\n\n\n\n void initialize_ff_mesh() {}; // TODO\n\n void initialize_ff_mesh(const std::string& filename);\n\n void read_ff_mesh(const std::string& filename) { um = simplicial_unstructured_3d_mesh<I, F>::from_file(filename); }\n\n void write_ff_mesh(const std::string& filename) const { um->to_file(filename); }\n\n\n\npublic: // reimpl\n\n size_t n(int d) const;\n\n\n\n void get_simplex(int d, I i, I verts[]) const;\n\n bool find_simplex(int d, const I v[], I &i) const { return false; } // TODO\n\n\n\nprotected:\n\n std::shared_ptr<simplicial_unstructured_3d_mesh<I, F>> um; // the \"unit\" 3D mesh between poloidal planes\n\n};\n\n\n\n///////////////////\n", "file_path": "include/ftk/mesh/simplicial_xgc_3dff_mesh.hh", "rank": 93, "score": 181424.97733066507 }, { "content": "struct function_traits<MEM_FN_SYMBOL_XX0SL7G4Z0J<R(C::*)(A...) const>>\n\n : public function_traits<R(const C*, A...)>\n\n{};\n\ntemplate <typename R, typename C, typename... A>\n", "file_path": "include/ftk/external/diy/detail/traits.hpp", "rank": 94, "score": 181368.92219256973 }, { "content": "// It is a separate type rather than an alias to make symbols readable.\n\nstruct format_args : basic_format_args<format_context> {\n\n template <typename... Args>\n\n format_args(Args&&... args)\n\n : basic_format_args<format_context>(std::forward<Args>(args)...) {}\n\n};\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 95, "score": 180615.5125566115 }, { "content": "struct wformat_args : basic_format_args<wformat_context> {\n\n template <typename... Args>\n\n wformat_args(Args&&... args)\n\n : basic_format_args<wformat_context>(std::forward<Args>(args)...) {}\n\n};\n\n\n\ntemplate <typename Container> struct is_contiguous : std::false_type {};\n\n\n\ntemplate <typename Char>\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 96, "score": 180615.5125566115 }, { "content": "struct is_contiguous_back_insert_iterator : std::false_type {};\n\ntemplate <typename Container>\n", "file_path": "include/ftk/external/diy/fmt/core.h", "rank": 97, "score": 180615.5125566115 }, { "content": "struct object {\n\n object() {}\n\n object(diy::mpi::communicator c) {comm = c;}\n\n\n\n void set_communicator(const diy::mpi::communicator comm_) {comm = comm_;}\n\n void set_root_proc(int p) {root_proc = p;}\n\n int get_root_proc() const {return root_proc;}\n\n bool is_root_proc() const {return root_proc == comm.rank();}\n\n\n\n static void set_affinity(int cpu) {\n\n#if !defined(_MSC_VER) && !defined(__APPLE__)\n\n cpu_set_t cpu_set;\n\n CPU_ZERO(&cpu_set);\n\n CPU_SET(cpu, &cpu_set);\n\n\n\n pthread_t thread = pthread_self();\n\n pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpu_set);\n\n // fprintf(stderr, \"cpu=%d\\n\", cpu);\n\n#endif\n\n }\n", "file_path": "include/ftk/object.hh", "rank": 98, "score": 179096.8093001128 }, { "content": "struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleObjectType,\n\n typename = void>\n", "file_path": "include/ftk/external/json.hh", "rank": 99, "score": 178875.67468895108 } ]
C++
src/menu.cpp
WMXZ-EU/basicSoundRecorder
3ff2fd5aad50dcd8c29580a05a9247f079a28cc3
#include "config.h" #include "filing.h" #include "utils.h" #include "mTime.h" #include "menu.h" #define CONFIG_FILE "/Config.txt" #define LOCK_FILE "/cVAS.lock" extern SDClass sdx[]; uint16_t store[16]; extern int t_acq; void storeConfig(uint16_t *store, int ns) { File configFile; char text[32]; configFile=sdx[0].open(CONFIG_FILE,FILE_WRITE_BEGIN); for(int ii=0; ii<ns; ii++) { sprintf(text,"%10d\r\n",(int) store[ii]); configFile.write((uint8_t*)text,strlen(text)); } configFile.close(); } void loadConfig(uint16_t *store, int ns) { File configFile; char text[32]; if(!(configFile=sdx[0].open(CONFIG_FILE,FILE_READ))) { store[0]=0; return; } for(int ii=0; ii<ns; ii++) { if(configFile.readBytesUntil('\n',text,32)<=0) { store[0]=0; return;} int x; sscanf(text, "%d",&x); store[ii]=(int16_t) x; } configFile.close(); } void saveParameters(void) { store[0]= 1; store[2]= t_acq; storeConfig(store, 16); } void loadParameters(void) { loadConfig(store,16); if(store[0]==1) { t_acq=store[2]; } } void printMenu(void) { Serial.println("\n Menu"); Serial.println(" ':h' : print help"); Serial.println(" ':s' : start acquisition"); Serial.println(" ':e' : stop acquisition"); Serial.println(" ':w' : write parameters to microSD card"); Serial.println(" ':l' : list disks"); Serial.println(" ':r' : reset MTP"); Serial.println(" ':b' : reboot CPU"); Serial.println(); Serial.println(" '?p' : show all parameters"); Serial.println(" '?d' : get date"); Serial.println(" '?t' : get time"); Serial.println(" '?a' : get file duration (s)"); Serial.println(); Serial.println(" '!d yyyy/mm/dd<cr>' : set date"); Serial.println(" '!t hh:mm:ss<cr>' : set time"); Serial.println(" '!a val<cr>' : set file duration (s)"); Serial.println(); } void printMenuEntries(void) { tmElements_t tm; breakTime(rtc_get(), tm); Serial.println("CVAS_V3 Version: " __DATE__ " " __TIME__ ); Serial.printf("Teensy: %d: %06x\n",teensy,SerNum); Serial.printf("Date d = %04d/%02d/%02d\n",tmYearToCalendar(tm.Year), tm.Month, tm.Day); Serial.printf("Time t = %02d:%02d:%02d\n",tm.Hour, tm.Minute, tm.Second); Serial.printf("T_acq a = %d\n",t_acq); } int menuGetInt(int *val) { char buffer[40]; while(!Serial.available()); int count = Serial.readBytesUntil('\r',buffer,40); buffer[count]=0; return sscanf(buffer,"%d",val); } int menuGet3Int(int *val1, int *val2, int *val3) { char buffer[40]; while(!Serial.available()); int count = Serial.readBytesUntil('\r',buffer,40); buffer[count]=0; char c1,c2; return sscanf(buffer,"%d%c%d%c%d",val1,&c1,val2,&c2,val3); } void listDisks(void); void resetMTP(void) ; void dumpMTP(void) ; #if defined (KINETISK) #define CPU_RESTART #endif int16_t menu(void) { if(!Serial.available()) return 0; char ch=Serial.read(); if(ch==':') { while(!Serial.available()) ; ch=Serial.read(); if(ch=='s') { Serial.print("\n"); Serial.print("start"); return +1;} else if(ch=='e') { Serial.print("\n"); Serial.print("stop"); return -1;} else if(ch=='h') { printMenu(); return 0;} else if(ch=='w') { saveParameters(); return 0;} else if(ch=='l') { listDisks(); return 0;} else if(ch=='b') { Serial.print("\n"); Serial.print("rebooting CPU"); Serial.flush(); delay(100); CPU_RESTART; return 0;} } else if(ch=='?') { while(!Serial.available()) ; ch=Serial.read(); tmElements_t tm; breakTime(rtc_get(), tm); if(ch=='p') { printMenuEntries(); return 0;} else if(ch=='d') { Serial.printf("%04d/%02d/%02d\n",tmYearToCalendar(tm.Year), tm.Month, tm.Day); return 0;} else if(ch=='t') { Serial.printf("%02d:%02d:%02d\n",tm.Hour, tm.Minute, tm.Second); return 0;} else if(ch=='a') { Serial.printf("%d\n",t_acq); return 0;} } else if(ch=='!') { while(!Serial.available()) ; ch=Serial.read(); if(ch=='d') { int year,month,day; menuGet3Int(&year,&month,&day); tmElements_t tm; breakTime(rtc_get(), tm); setRTCTime(tm.Hour, tm.Minute, tm.Second, day, month, year); return 0; } else if(ch=='t') { int hour,minutes,seconds; menuGet3Int(&hour,&minutes,&seconds); tmElements_t tm; breakTime(rtc_get(), tm); setRTCTime(hour, minutes, seconds, tm.Day, tm.Month, tmYearToCalendar(tm.Year)); return 0; } else if(ch=='a') { menuGetInt(&t_acq); return 0;} } return 0; }
#include "config.h" #include "filing.h" #include "utils.h" #include "mTime.h" #include "menu.h" #define CONFIG_FILE "/Config.txt" #define LOCK_FILE "/cVAS.lock" extern SDClass sdx[]; uint16_t store[16]; extern int t_acq; void storeConfig(uint16_t *store, int ns) { File configFile; char text[32]; configFile=sdx[0].open(CONFIG_FILE,FILE_WRITE_BEGIN); for(int ii=0; ii<ns; ii++) { sprintf(text,"%10d\r\n",(int) store[ii]); configFile.write((uint8_t*)text,strlen(text)); } configFile.close(); } void loadConfig(uint16_t *store, int ns) { File configFile; char text[32]; if(!(configFile=sdx[0].open(CONFIG_FILE,FILE_READ))) { store[0]=0; return; } for(int ii=0; ii<ns; ii++) { if(configFile.readBytesUntil('\n',text,32)<=0) { store[0]=0; return;} int x; sscanf(text, "%d",&x); store[ii]=(int16_t) x; } configFile.close(); } void saveParameters(void) { store[0]= 1; store[2]= t_acq; storeConfig(store, 16); } void loadParameters(void) { loadConfig(store,16); if(store[0]==1) { t_acq=store[2]; } } void printMenu(void) { Serial.println("\n Menu"); Serial.println(" ':h' : print help"); Serial.println(" ':s' : start acquisition"); Serial.println(" ':e' : stop acquisition"); Serial.println(" ':w' : write parameters to microSD card"); Serial.println(" ':l' : list disks"); Serial.println(" ':r' : reset MTP"); Serial.println(" ':b' : reboot CPU"); Serial.println(); Serial.println(" '?p' : show all parameters"); Serial.println(" '?d' : get date"); Serial.println(" '?t' : get time"); Serial.println(" '?a' : get file duration (s)"); Serial.println(); Serial.println(" '!d yyyy/mm/dd<cr>' : set date"); Serial.println(" '!t hh:mm:ss<cr>' : set time"); Serial.println(" '!a val<cr>' : set file duration (s)"); Serial.println(); } void printMenuEntries(void) { tmElements_t tm; breakTime(rtc_get(), tm); Serial.println("CVAS_V3 Version: " __DATE__ " " __TIME__ ); Serial.printf("Teensy: %d: %06x\n",teensy,SerNum); Serial.printf("Date d = %04d/%02d/%02d\n",tmYearToCalendar(tm.Year), tm.Month, tm.Day); Serial.printf("Time t = %02d:%02d:%02d\n",tm.Hour, tm.Minute, tm.Second); Serial.printf("T_acq a = %d\n",t_acq); } int menuGetInt(int *val) { char buffer[40]; while(!Serial.available()); int count = Serial.readBytesUntil('\r',buffer,40); buffer[count]=0; return sscanf(buffer,"%d",val); } int menuGet3Int(int *val1, int *val2, int *val3) { char buffer[40]; while(!Serial.available()); int count = Serial.readBytesUntil('\r',buffer,40); buffer[count]=0; char c1,c2; return sscanf(buffer,"%d%c%d%c%d",val1,&c1,val2,&c2,val3); } void listDisks(void); void resetMTP(void) ; void dumpMTP(void) ; #if defined (KINETISK) #define CPU_RESTART #endif int16_t menu(void) { if(!Serial.available()) return 0; char ch=Serial.read(); if(ch==':') { while(!Serial.availabl
e()) ; ch=Serial.read(); if(ch=='s') { Serial.print("\n"); Serial.print("start"); return +1;} else if(ch=='e') { Serial.print("\n"); Serial.print("stop"); return -1;} else if(ch=='h') { printMenu(); return 0;} else if(ch=='w') { saveParameters(); return 0;} else if(ch=='l') { listDisks(); return 0;} else if(ch=='b') { Serial.print("\n"); Serial.print("rebooting CPU"); Serial.flush(); delay(100); CPU_RESTART; return 0;} } else if(ch=='?') { while(!Serial.available()) ; ch=Serial.read(); tmElements_t tm; breakTime(rtc_get(), tm); if(ch=='p') { printMenuEntries(); return 0;} else if(ch=='d') { Serial.printf("%04d/%02d/%02d\n",tmYearToCalendar(tm.Year), tm.Month, tm.Day); return 0;} else if(ch=='t') { Serial.printf("%02d:%02d:%02d\n",tm.Hour, tm.Minute, tm.Second); return 0;} else if(ch=='a') { Serial.printf("%d\n",t_acq); return 0;} } else if(ch=='!') { while(!Serial.available()) ; ch=Serial.read(); if(ch=='d') { int year,month,day; menuGet3Int(&year,&month,&day); tmElements_t tm; breakTime(rtc_get(), tm); setRTCTime(tm.Hour, tm.Minute, tm.Second, day, month, year); return 0; } else if(ch=='t') { int hour,minutes,seconds; menuGet3Int(&hour,&minutes,&seconds); tmElements_t tm; breakTime(rtc_get(), tm); setRTCTime(hour, minutes, seconds, tm.Day, tm.Month, tmYearToCalendar(tm.Year)); return 0; } else if(ch=='a') { menuGetInt(&t_acq); return 0;} } return 0; }
function_block-function_prefixed
[ { "content": "void resetMTP(void) ;\n", "file_path": "src/menu.h", "rank": 0, "score": 67831.51723899825 }, { "content": "void listDisks(void);\n", "file_path": "src/menu.h", "rank": 1, "score": 67804.58596994064 }, { "content": " void listDisks(void);\n", "file_path": "src/filing.h", "rank": 2, "score": 67446.00704694324 }, { "content": " uint16_t getCount ();\n", "file_path": "src/filing.h", "rank": 3, "score": 67420.73567706192 }, { "content": "void setRTCTime(int hr,int min,int sec,int dy, int mnth, int yr);\n", "file_path": "src/mTime.h", "rank": 4, "score": 52022.566451270315 }, { "content": "int16_t menu(void);\n", "file_path": "src/menu.h", "rank": 5, "score": 51802.5010771718 }, { "content": "void storeConfig(uint16_t *store, int ns);\n", "file_path": "src/menu.h", "rank": 6, "score": 45077.89954362695 }, { "content": "void loadParameters(void);\n", "file_path": "src/menu.h", "rank": 7, "score": 45050.96827456933 }, { "content": "void dumpMTP(void) ;\n", "file_path": "src/menu.h", "rank": 8, "score": 45050.96827456933 }, { "content": "void saveParameters(void);\n", "file_path": "src/menu.h", "rank": 9, "score": 45050.96827456933 }, { "content": "uint32_t get_Lock(void);\n", "file_path": "src/menu.h", "rank": 10, "score": 45025.69690468803 }, { "content": "void setAGain(int8_t again);\n", "file_path": "src/menu.h", "rank": 11, "score": 45000.89082576827 }, { "content": "void set_Lock(uint32_t t_start);\n", "file_path": "src/menu.h", "rank": 12, "score": 45000.89082576827 }, { "content": " int16_t checkReboot(void);\n", "file_path": "src/filing.h", "rank": 13, "score": 44719.32062062954 }, { "content": " extern int t_acq;\n", "file_path": "src/filing.h", "rank": 14, "score": 42725.68492101255 }, { "content": "void breakTime(uint32_t timeInput, tmElements_t &tm);\n", "file_path": "src/mTime.h", "rank": 15, "score": 31003.089492490075 }, { "content": "uint32_t makeTime(const tmElements_t &tm);\n", "file_path": "src/mTime.h", "rank": 16, "score": 31003.089492490075 }, { "content": " } else {\n\n seconds += SECS_PER_DAY * monthDays[i-1]; //monthDay array starts from 0\n\n }\n\n }\n\n seconds+= (tm.Day-1) * SECS_PER_DAY;\n\n seconds+= tm.Hour * SECS_PER_HOUR;\n\n seconds+= tm.Minute * SECS_PER_MIN;\n\n seconds+= tm.Second;\n\n return seconds; \n\n}\n\n\n\nextern \"C\" void rtc_set(uint32_t tt);\n\n\n\nvoid setRTCTime(int hr,int min,int sec,int dy, int mnth, int yr){\n\n // year can be given as full four digit year or two digts (2010 or 10 for 2010); \n\n // it is converted to years since 1970\n\n if( yr > 99)\n\n yr = yr - 1970;\n\n else\n\n yr += 30; \n", "file_path": "src/mTime.cpp", "rank": 26, "score": 30738.586075565065 }, { "content": "\n\n/*============================================================================*/\t\n\n/* functions to convert to and from system time */\n\n/* These are for interfacing with time services and are not normally needed in a sketch */\n\n\n\nstatic const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0\n\n \n\nvoid breakTime(uint32_t timeInput, tmElements_t &tm){\n\n// break the given time_t into time components\n\n// this is a more compact version of the C library localtime function\n\n// note that year is offset from 1970 !!!\n\n\n\n uint8_t year;\n\n uint8_t month, monthLength;\n\n uint32_t time;\n\n unsigned long days;\n\n\n\n time = (uint32_t)timeInput;\n\n tm.Second = time % 60;\n\n time /= 60; // now it is minutes\n", "file_path": "src/mTime.cpp", "rank": 27, "score": 30735.676758087233 }, { "content": "uint32_t makeTime(const tmElements_t &tm){ \n\n// assemble time elements into time_t \n\n// note year argument is offset from 1970 (see macros in time.h to convert to other formats)\n\n// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9\n\n \n\n int i;\n\n uint32_t seconds;\n\n\n\n // seconds from 1970 till 1 jan 00:00:00 of the given year\n\n seconds= tm.Year*(SECS_PER_DAY * 365);\n\n for (i = 0; i < tm.Year; i++) {\n\n if (LEAP_YEAR(i)) {\n\n seconds += SECS_PER_DAY; // add extra days for leap years\n\n }\n\n }\n\n \n\n // add days for this year, months start from 1\n\n for (i = 1; i < tm.Month; i++) {\n\n if ( (i == 2) && LEAP_YEAR(tm.Year)) { \n\n seconds += SECS_PER_DAY * 29;\n", "file_path": "src/mTime.cpp", "rank": 28, "score": 30734.382978445825 }, { "content": "#include \"config.h\"\n\n#include \"mTime.h\"\n\n\n\nint32_t day_ = 0;\n\nint16_t newDay(void)\n\n{ uint32_t tx=rtc_get();\n\n int32_t d_ = (int32_t)tx/SECS_PER_DAY; // use days since 1970 as measure\n\n if(day_== d_) return 0;\n\n day_ = d_;\n\n return 1;\n\n}\n\n\n\nint32_t hour_ = 0;\n\nint16_t newHour(void)\n\n{ uint32_t tx=rtc_get();\n\n int32_t h_ = (int32_t) tx/SECS_PER_HOUR; // use hours since 1970 as measures\n\n if(hour_== h_) return 0;\n\n hour_ = h_;\n\n return 1;\n\n}\n", "file_path": "src/mTime.cpp", "rank": 29, "score": 30732.874500418722 }, { "content": " tm.Minute = time % 60;\n\n time /= 60; // now it is hours\n\n tm.Hour = time % 24;\n\n time /= 24; // now it is days\n\n tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1 \n\n \n\n year = 0; \n\n days = 0;\n\n while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {\n\n year++;\n\n }\n\n tm.Year = year; // year is offset from 1970 \n\n \n\n days -= LEAP_YEAR(year) ? 366 : 365;\n\n time -= days; // now it is days in this year, starting at 0\n\n \n\n days=0;\n\n month=0;\n\n monthLength=0;\n\n for (month=0; month<12; month++) {\n", "file_path": "src/mTime.cpp", "rank": 30, "score": 30732.21658385193 }, { "content": " \n\n tmElements_t tm;\n\n tm.Year = yr;\n\n tm.Month = mnth;\n\n tm.Day = dy;\n\n tm.Hour = hr;\n\n tm.Minute = min;\n\n tm.Second = sec;\n\n\n\n uint32_t tt = makeTime(tm);\n\n rtc_set(tt); // for RTC\n\n}\n", "file_path": "src/mTime.cpp", "rank": 31, "score": 30731.86088502321 }, { "content": " if (month==1) { // february\n\n if (LEAP_YEAR(year)) {\n\n monthLength=29;\n\n } else {\n\n monthLength=28;\n\n }\n\n } else {\n\n monthLength = monthDays[month];\n\n }\n\n \n\n if (time >= monthLength) {\n\n time -= monthLength;\n\n } else {\n\n break;\n\n }\n\n }\n\n tm.Month = month + 1; // jan is month 1 \n\n tm.Day = time + 1; // day of month\n\n}\n\n\n", "file_path": "src/mTime.cpp", "rank": 32, "score": 30729.52885853795 }, { "content": " }\n\n}\n\n\n\nvoid listDisks(void)\n\n{\n\n for(int ii=0;ii<nsd;ii++)\n\n {\n\n Serial.print(\"\\n\"); \n\n Serial.printf(\"Storage %d %d %s \",ii,cs[ii],sd_str[ii]);\n\n Serial.printf(\"%d %d\",sdx[ii].sdfs.freeClusterCount(),diskSize[ii]);\n\n }\n\n Serial.print(\"\\n\"); \n\n}\n\n\n\nint16_t checkReboot(void)\n\n{\n\n int ii=0;\n\n while((ii<nsd) && (diskSpace[ii]<MIN_SPACE)) ii++;\n\n if(ii<nsd) CPU_RESTART;\n\n return -1;\n", "file_path": "src/filing.cpp", "rank": 33, "score": 30289.859694696504 }, { "content": "void dateTime(uint16_t* date, uint16_t* time, uint8_t* ms10) \n\n{ \n\n tmElements_t tm;\n\n breakTime(rtc_get(), tm);\n\n\n\n *date = FS_DATE(tmYearToCalendar(tm.Year),tm.Month, tm.Day);\n\n *time = FS_TIME(tm.Hour, tm.Minute, tm.Second);\n\n *ms10 = tm.Second & 1 ? 100 : 0;\n\n}\n\n\n\nvoid storage_configure()\n\n{\n\n #if defined SD_SCK\n\n SPI.setMOSI(SD_MOSI);\n\n SPI.setMISO(SD_MISO);\n\n SPI.setSCK(SD_SCK);\n\n #endif\n\n\n\n // Set Time callback\n\n FsDateTime::callback = dateTime;\n", "file_path": "src/filing.cpp", "rank": 34, "score": 30283.11853913592 }, { "content": "\n\n //\n\n Serial.print(\"\\n\"); Serial.print(dirName);\n\n #if PRINT_LOGFILE>0\n\n log_start();\n\n if(logFile) {logFile.print(\"\\n\");logFile.print(dirName);}\n\n #endif\n\n return 1;\n\n }\n\n return 0;\n\n\n\n}\n\nstatic int16_t newFileName(char *fileName)\n\n{\n\n tmElements_t tm;\n\n breakTime(rtc_get(), tm);\n\n\tsprintf(fileName, \"%s_%02d%02d%02d.bin\", FilePrefix, tm.Hour, tm.Minute, tm.Second);\n\n //\n\n Serial.print(\"\\n\"); Serial.print(isd); Serial.print(\": \");Serial.print(fileName);\n\n #if PRINT_LOGFILE>0\n", "file_path": "src/filing.cpp", "rank": 35, "score": 30282.991337792006 }, { "content": "}\n\n\n\nstatic int isd=(nsd>1)?1:0; // fist SPI disk is #1 if there are more than one\n\nextern int32_t hour_; // to force newHour on new disk\n\n\n\nstatic SDClass *checkDiskSpace(void)\n\n{ static int isd_ = nsd;\n\n\n\n doTransactions(true);\n\n while((isd<nsd) && ((diskSize[isd]==0) \n\n || ((diskSpace[isd]=sdx[isd].sdfs.freeClusterCount()) < MIN_SPACE) )) isd++;\n\n doTransactions(false);\n\n if(isd<nsd) \n\n { sdx[isd].sdfs.chvol();\n\n Serial.println(); Serial.print(isd);\n\n Serial.print(\": \"); Serial.print(sdx[isd].sdfs.freeClusterCount());\n\n }\n\n //\n\n if(isd != isd_) hour_=0; // set hour_ to zero to trigger creation of directories in new disk\n\n isd_=isd;\n", "file_path": "src/filing.cpp", "rank": 36, "score": 30282.305240752034 }, { "content": " if(logFile) \n\n { logFile.print(\"\\n\"); logFile.print(isd); logFile.print(\": \"); logFile.print(fileName);}\n\n #endif\n\n return 1;\n\n}\n\n\n\n/* main data filing routine */\n\nint16_t saveData(int16_t status)\n\n{ static char dirName[80];\n\n static char fileName[80];\n\n static char header[512];\n\n static int dirFlag=0;\n\n\n\n if(status<CLOSED) return status; // we are stopped: don't do anything\n\n\n\n //fetch data from circular buffer\n\n if(pullData(diskBuffer,NDBL))\n\n { disk_count++;\n\n if(status==CLOSED) // file closed: should open\n\n { //doTransactions(true);\n", "file_path": "src/filing.cpp", "rank": 37, "score": 30282.00337455444 }, { "content": " uint64_t usedSize = sdx[ii].usedSize();\n\n\n\n Serial.printf(\"Storage %d %d %s \",ii,cs[ii],sd_str[ii]); \n\n Serial.print(totalSize); Serial.print(\" \"); Serial.println(usedSize);\n\n\n\n Serial.print(sdx[ii].sdfs.clusterCount()); Serial.print(\" \"); \n\n Serial.print(sdx[ii].sdfs.freeClusterCount()); Serial.print(\" \");\n\n\n\n clusterSize[ii] = sdx[ii].sdfs.bytesPerCluster()/512; // count sectors\n\n Serial.println(clusterSize[ii]) ;Serial.print(\" \");\n\n\n\n diskSpace[ii]=diskSize[ii]=sdx[ii].sdfs.freeClusterCount();\n\n Serial.println(diskSize[ii]) ;Serial.print(\" \");\n\n }\n\n else\n\n {\n\n diskSize[ii]=0;\n\n diskSpace[ii]=0;\n\n clusterSize[ii]=1;\n\n }\n", "file_path": "src/filing.cpp", "rank": 38, "score": 30281.89184879836 }, { "content": "\n\n uint16_t getCount () { return rawData.getCount(); }\n\n uint16_t pushData(uint32_t * src){ return rawData.push(src);}\n\n uint16_t pullData(uint32_t * dst, uint32_t ndbl) {return rawData.pull(dst,ndbl);}\n\n\n\n/****************************** Filing Utility *******************************************/\n\n\n\nextern int t_acq;\n\n\n\nFile file=NULL; // is used by saveData and saveNAD\n\nuint32_t disk_count=0;\n\nuint32_t diskBuffer[MAX_DISK_BUFFER];\n\n\n\nSDClass *msd; // storage of next free disk\n\n\n\nstatic int16_t makeHeader(char *header)\n\n{\n\n /**\n\n * @brief Make file header\n\n * @param header is pointer to header\n", "file_path": "src/filing.cpp", "rank": 39, "score": 30280.444336694716 }, { "content": " else\n\n {\n\n return MUST_REBOOT; // if file open fails: don't do anything\n\n }\n\n }\n\n //\n\n if(status==OPENED) // file is open: write first record (header)\n\n { makeHeader(header);\n\n if(file.write((const void*)header,512) < 512) return MUST_REBOOT; else status=2;\n\n }\n\n //\n\n if(status>=RUNNING) // file is open, header written: store data records\n\n { \n\n if(file.write((const void *)diskBuffer,4*MAX_DISK_BUFFER) < 4*MAX_DISK_BUFFER) return MUST_REBOOT;\n\n }\n\n }\n\n // following is done independent of data availability\n\n if(status==DOCLOSE) // should close file\n\n {\n\n // writes are done, so enable again transaction activations\n", "file_path": "src/filing.cpp", "rank": 40, "score": 30278.378326009337 }, { "content": " * \n\n */\n\n #define MAGIC \"WMXZ\"\n\n tmElements_t tm;\n\n breakTime(rtc_get(), tm);\n\n\n\n int nd=sprintf(header,\"%s%04d%02d%02d_%02d%02d%02d\",\n\n MAGIC,tmYearToCalendar(tm.Year),tm.Month,tm.Day,tm.Hour,tm.Minute,tm.Second);\n\n char *ptr = header+(nd+1);\n\n\n\n int32_t *iptr = (int32_t *) ptr;\n\n iptr[0] = 4; // SW version\n\n iptr[1] = (int32_t)SerNum; // serial number\n\n iptr[2] = fsamp;\n\n iptr[3] = NCHAN_ACQ;\n\n iptr[4] = t_acq;\n\n iptr[5] = 0;\n\n\n\n uint32_t *uptr = (uint32_t*) header;\n\n uptr[127] = 0x55555555;\n\n //\n\n return 1;\n\n}\n\n\n\nstatic uint32_t dummy_buffer[MAX_DISK_BUFFER];\n\n/******************************** SPI Interface *****************************************/\n", "file_path": "src/filing.cpp", "rank": 41, "score": 30278.295660088163 }, { "content": " if(isd==nsd) return (SDClass *) 0; else return &sdx[isd];\n\n}\n\n\n\nstatic int16_t newDirectory(char *dirName, int dirFlag)\n\n{ if(newHour())\n\n { \n\n tmElements_t tm;\n\n breakTime(rtc_get(), tm);\n\n if(!dirFlag)\n\n {\n\n sprintf(dirName, \"/%s%06x_%04d%02d%02d/%02d/\", \n\n DirPrefix,(unsigned int)SerNum,\n\n tmYearToCalendar(tm.Year),tm.Month, tm.Day, tm.Hour);\n\n }\n\n else\n\n {\n\n sprintf(dirName, \"/%s%06x_%04d%02d%02d/%02d_%02d/\", \n\n DirPrefix,(unsigned int)SerNum,\n\n tmYearToCalendar(tm.Year),tm.Month, tm.Day, tm.Hour,dirFlag);\n\n }\n", "file_path": "src/filing.cpp", "rank": 42, "score": 30278.054401788853 }, { "content": "\n\n// adjust to HW configuration\n\n// only build-in SD card T3.5/6 and T4.0/1\n\n const char *sd_str[]={\"sdio\"};\n\n const int cs[] = {BUILTIN_SDCARD};\n\n// only audio board\n\n// const char *sd_str[]={\"sd1\"};\n\n// const int cs[] = {10 };\n\n// general example\n\n// const char *sd_str[]={\"sdio\", \"sd1\",\"sd2\",\"sd3\",\"sd4\",\"sd5\",\"sd6\"};\n\n// const int cs[] = {BUILTIN_SDCARD, 34, 33, 35, 36, 37, 38 };\n\n\n\n const int nsd = sizeof(cs)/sizeof(int);\n\n\n\n SDClass sdx[nsd];\n\n uint32_t diskSize[nsd];\n\n uint32_t diskSpace[nsd];\n\n uint32_t clusterSize[nsd];\n\n\n\n// Call back for file timestamps. Only called for file create and sync(). needed by SDFat-beta\n", "file_path": "src/filing.cpp", "rank": 43, "score": 30276.296596098557 }, { "content": "\n\n for(int ii=0; ii<nsd; ii++)\n\n { Serial.println(ii);\n\n\n\n uint16_t status=0;\n\n if(cs[ii] == BUILTIN_SDCARD)\n\n {\n\n uint16_t tries=0;\n\n while(!sdx[ii].sdfs.begin(SdioConfig(FIFO_SDIO)) && tries<10)\n\n { Serial.print(tries); Serial.print(\" \"); tries++; delay(1000); } \n\n\n\n if(tries<10) \n\n {\n\n status=1;\n\n }\n\n else\n\n {\n\n Serial.println(\"No sdio storage\"); \n\n }\n\n }\n", "file_path": "src/filing.cpp", "rank": 44, "score": 30275.911674685984 }, { "content": "\n\n // Receive multiple bytes. \n\n // Replace this function if your board has multiple byte receive.\n\n uint8_t receive(uint8_t* buf, size_t count) \n\n { memset(buf, 0XFF, count); SPI.transfer(buf, count); return 0; }\n\n\n\n // Send multiple bytes.\n\n // Replace this function if your board has multiple byte send.\n\n void send(const uint8_t* buf, size_t count) \n\n { SPI.transfer((void *)buf, (void *) dummy_buffer, count); }\n\n\n\n // Save SPISettings for new max SCK frequency\n\n void setSckSpeed(uint32_t maxSck) { m_spiSettings = SPISettings(maxSck, MSBFIRST, SPI_MODE0); }\n\n\n\n private:\n\n SPISettings m_spiSettings;\n\n\n\n public:\n\n bool doTransactions=true;\n\n\n", "file_path": "src/filing.cpp", "rank": 45, "score": 30274.482924654567 }, { "content": " else if(cs[ii]<BUILTIN_SDCARD)\n\n { \n\n sdCsInit(cs[ii]);\n\n delay(100);\n\n uint16_t tries=0;\n\n while(!sdx[ii].sdfs.begin(SdSpiConfig(cs[ii], SHARED_SPI, SPI_SPEED, &mySpi)) && tries<10)\n\n { Serial.print(tries); Serial.print(\" \"); tries++; delay(1000); } \n\n\n\n if(tries<10) \n\n {\n\n status=1;\n\n }\n\n else\n\n {\n\n Serial.println(\"No spi storage\");\n\n }\n\n }\n\n if (status)\n\n {\n\n uint64_t totalSize = sdx[ii].totalSize();\n", "file_path": "src/filing.cpp", "rank": 46, "score": 30274.104009144176 }, { "content": "/**\n\n * @file filing.cpp\n\n * @author Walter Zimmer \n\n * @version 1.0\n\n *\n\n * @section LICENSE\n\n *\n\n * MIT\n\n * \n\n * @section DESCRIPTION\n\n *\n\n * contains filing interface\n\n */\n\n #include \"config.h\"\n\n #include \"mTime.h\"\n\n #include \"filing.h\"\n\n #include \"utils.h\"\n\n #include \"adc.h\"\n\n\n\n /**\n", "file_path": "src/filing.cpp", "rank": 47, "score": 30274.01379732683 }, { "content": "};\n\nMySpiClass mySpi;\n\n\n\nvoid doTransactions(bool val) {mySpi.doTransactions=val;}\n\n\n\nvoid sdCsInit(SdCsPin_t pin) { pinMode(pin, OUTPUT); digitalWriteFast(pin, HIGH);}\n\nvoid sdCsWrite(SdCsPin_t pin, bool level) { digitalWriteFast(pin, level); }\n\n\n\n#define SPI_SPEED SD_SCK_MHZ(33) // adjust to sd card \n\n#if USE_SDIO==2\n\n #define SD_CONFIG SdioConfig(FIFO_SDIO)\n\n #define SD_MOSI 11\n\n #define SD_MISO 12\n\n #define SD_SCK 13\n\n#endif\n\n#if defined(ARDUINO_TEENSY36)\n\n #define SD_MOSI 7\n\n #define SD_MISO 12\n\n #define SD_SCK 14\n\n#endif\n", "file_path": "src/filing.cpp", "rank": 48, "score": 30273.828464008424 }, { "content": " if(!(msd=checkDiskSpace())) return MUST_REBOOT;\n\n //\n\n if(newDirectory(dirName,dirFlag)) \n\n { if(!msd->sdfs.exists(dirName) && !msd->sdfs.mkdir(dirName)) dirFlag++; \n\n if(!msd->sdfs.chdir(dirName)) dirFlag++; else dirFlag=0;\n\n }\n\n //\n\n if(dirFlag>5) return MUST_REBOOT; // too many directory errors\n\n if(dirFlag>0) return CLOSED; // create new directory with different name\n\n\n\n if(newFileName(fileName))\n\n { \n\n file = msd->open(fileName, FILE_WRITE_BEGIN); \n\n if(file) \n\n status = OPENED; \n\n else \n\n { Serial.println(\"Failing open file\");\n\n return MUST_REBOOT; \n\n }\n\n } \n", "file_path": "src/filing.cpp", "rank": 49, "score": 30273.36025631045 }, { "content": " if(++r >= (MAXBUF/ndbl)) r=0;\n\n rear_ = r*ndbl;\n\n return 1;\n\n }\n\n uint16_t getCount () \n\n { \n\n /**\n\n * @brief get number of data blocks in storage\n\n * \n\n */\n\n if(front_ >= rear_) return front_ - rear_; return front_+ MAXBUF -rear_; \n\n }\n\n\n\n private: \n\n uint16_t front_, rear_;\n\n uint32_t *data_buffer;\n\n\n\n };\n\n\n\n Data rawData(data_buffer);\n", "file_path": "src/filing.cpp", "rank": 50, "score": 30270.340844255494 }, { "content": " file.flush();\n\n file.close();\n\n status = CLOSED;\n\n }\n\n if(status==MUSTSTOP) // should close file and stop\n\n { \n\n file.flush();\n\n file.close();\n\n status = STOPPED;\n\n }\n\n return status;\n\n}\n", "file_path": "src/filing.cpp", "rank": 51, "score": 30268.415901208456 }, { "content": " #else\n\n uint32_t data_buffer[MAXBUF*NBUF_ACQ];\n\n #endif\n\n\n\n #define MAX_DISK_BUFFER (NDBL*NBUF_ACQ)\n\n\n\n /**\n\n * @brief Data storage class\n\n * \n\n */\n", "file_path": "src/filing.cpp", "rank": 52, "score": 30267.747958978965 }, { "content": " if(f == rear_) return 0;\n\n\n\n uint32_t *ptr= data_buffer+f*NBUF_ACQ;\n\n memcpy(ptr,src,NBUF_ACQ*4);\n\n front_ = f;\n\n return 1;\n\n }\n\n\n\n uint16_t pull(uint32_t * dst, uint32_t ndbl)\n\n { \n\n /** \n\n * @brief pull data from storage\n\n * @param dst is pointer to data blocks\n\n * @param ndbl is number of data blocks\n\n */\n\n uint16_t r = (rear_/ndbl) ;\n\n if(r == (front_/ndbl)) return 0;\n\n\n\n uint32_t *ptr= data_buffer + r*ndbl*NBUF_ACQ;\n\n memcpy(dst,ptr,ndbl*NBUF_ACQ*4);\n", "file_path": "src/filing.cpp", "rank": 53, "score": 30264.931983553855 }, { "content": " * @brief Definitions\n\n * \n\n */\n\n\n\n #if defined(ARDUINO_TEENSY36)\n\n #define MAXBUF (160)\n\n #elif defined(ARDUINO_TEENSY40)\n\n #define MAXBUF (200)\n\n #elif defined(ARDUINO_TEENSY41)\n\n #define MAXBUF (200)\n\n #endif\n\n \n\n\n\n\n\n /**\n\n * @brief Circular Data Buffer\n\n * \n\n */ \n\n #if defined(ARDUINO_TEENSY41) && defined(USE_EXT_MEM)\n\n EXTMEM uint32_t data_buffer[MAXBUF*NBUF_ACQ];\n", "file_path": "src/filing.cpp", "rank": 54, "score": 30264.931983553855 }, { "content": " class Data\n\n {\n\n public:\n\n Data(uint32_t * buffer) \n\n { /**\n\n * @brief Constructor\n\n * @param buffer is pointer to data store\n\n * \n\n */\n\n data_buffer=buffer; front_=rear_=0;\n\n }\n\n\n\n uint16_t push(uint32_t * src)\n\n { \n\n /** \n\n * @brief push data to storage\n\n * @param src is pointer to data block\n\n */\n\n uint16_t f =front_ + 1;\n\n if(f >= MAXBUF) f=0;\n", "file_path": "src/filing.cpp", "rank": 55, "score": 28708.449767256796 }, { "content": "extern int32_t hour_ ;\n", "file_path": "src/mTime.h", "rank": 56, "score": 23181.85555233917 }, { "content": "extern int32_t day_ ;\n", "file_path": "src/mTime.h", "rank": 57, "score": 23181.85555233917 }, { "content": " uint8_t Hour; \n", "file_path": "src/mTime.h", "rank": 58, "score": 23181.85555233917 }, { "content": " uint8_t Wday; // day of week, sunday is day 1\n", "file_path": "src/mTime.h", "rank": 59, "score": 23181.85555233917 }, { "content": " uint8_t Year; // offset from 1970; \n", "file_path": "src/mTime.h", "rank": 60, "score": 23181.85555233917 }, { "content": " uint8_t Second; \n", "file_path": "src/mTime.h", "rank": 61, "score": 23181.85555233917 }, { "content": " uint8_t Month; \n", "file_path": "src/mTime.h", "rank": 62, "score": 23181.85555233917 }, { "content": " uint8_t Minute; \n", "file_path": "src/mTime.h", "rank": 63, "score": 23181.85555233917 }, { "content": " uint8_t Day;\n", "file_path": "src/mTime.h", "rank": 64, "score": 23181.85555233917 }, { "content": " void acq_start(void);\n", "file_path": "src/acq.h", "rank": 65, "score": 22753.61769537131 }, { "content": " void acq_stop(void);\n", "file_path": "src/acq.h", "rank": 66, "score": 22753.61769537131 }, { "content": " extern volatile uint32_t acq_count;\n", "file_path": "src/acq.h", "rank": 67, "score": 22753.61769537131 }, { "content": " void setAGain(int8_t again);\n", "file_path": "src/adc.h", "rank": 68, "score": 22703.540246570254 }, { "content": "void loadConfig(uint16_t *store, int ns);\n", "file_path": "src/menu.h", "rank": 69, "score": 22297.35057919802 }, { "content": "int16_t newDay(void);\n", "file_path": "src/mTime.h", "rank": 70, "score": 22270.778259889157 }, { "content": "int16_t newHour(void);\n", "file_path": "src/mTime.h", "rank": 71, "score": 22270.778259889157 }, { "content": " int16_t saveData(int16_t status);\n", "file_path": "src/filing.h", "rank": 72, "score": 21942.171597315817 }, { "content": "// following is from SdFat examples to allow transactions to be avoided between open and close\n\n//\n\n// This is a simple driver based on the the standard SPI.h library.\n\n// You can write a driver entirely independent of SPI.h.\n\n// It can be optimized for your board or a different SPI port can be used.\n\n// The driver must be derived from SdSpiBaseClass.\n\n// See: SdFat/src/SpiDriver/SdSpiBaseClass.h\n\nclass MySpiClass : public SdSpiBaseClass {\n\n /**\n\n * @brief SPI interface class\n\n * \n\n */\n\n\n\n public:\n\n // Initialize the SPI bus.\n\n void begin(SdSpiConfig config) { (void) config; SPI.begin(); }\n\n\n\n // Activate SPI hardware with correct speed and mode.\n\n void activate() { if(doTransactions) SPI.beginTransaction(m_spiSettings); }\n\n // Deactivate SPI hardware.\n\n void deactivate() { if(doTransactions) SPI.endTransaction(); }\n\n\n\n // Receive a byte.\n\n uint8_t receive() { return SPI.transfer(0XFF); }\n\n\n\n // Send a byte.\n\n void send(uint8_t data) { SPI.transfer(data); }\n", "file_path": "src/filing.cpp", "rank": 73, "score": 21940.692335417683 }, { "content": " #define FilePrefix \"F\"\n\n\n", "file_path": "src/config.h", "rank": 74, "score": 21938.771656200614 }, { "content": " void storage_configure();\n", "file_path": "src/filing.h", "rank": 75, "score": 21938.771656200614 }, { "content": " uint16_t pushData(uint32_t * src);\n", "file_path": "src/filing.h", "rank": 76, "score": 21938.771656200614 }, { "content": " uint16_t pullData(uint32_t * dst, uint32_t ndbl);\n", "file_path": "src/filing.h", "rank": 77, "score": 21938.771656200614 }, { "content": " void acq_stopClocks(void);\n", "file_path": "src/acq.h", "rank": 78, "score": 21893.186774117778 }, { "content": " void acq_startClocks(void);\n", "file_path": "src/acq.h", "rank": 79, "score": 21893.186774117778 }, { "content": "uint32_t getTeensySerial(void);\n", "file_path": "src/utils.h", "rank": 80, "score": 21868.871044274005 }, { "content": " w 98 0E 03 # Set U1 Ch4 mapped to slot 3 of SDOUT\n\n */\n\n\n\n void adc_init(void)\n\n {\n\n // reset ADC's \n\n pinMode(22,OUTPUT);\n\n digitalWriteFast(22,LOW); //SHDNZ\n\n delay(100);\n\n digitalWriteFast(22,HIGH); //SHDNZ\n\n\n\n /* ADDRESS L,L: 0x4C ; H,L: 0x4D; L,H: 0x4E; H,H: 0x4F */\n\n i2c_class i2c(&Wire1,100'000);\n\n\n\n // check existance of device\n\n for(int ii=0; ii<2; ii++)\n\n {\n\n if(i2c.exist(i2c_addr[ii]))\n\n Serial.printf(\"found %x\\n\",i2c_addr[ii]);\n\n else\n", "file_path": "src/adc.cpp", "rank": 81, "score": 21.96310494824983 }, { "content": " if(status==MUST_REBOOT) status=checkReboot(); // hapens only if microSD card write fails: reboot if space on disk\n\n\n\n // normal operation\n\n int16_t ch=menu(); // check if we have serial line command (0: no input; 1: start; -1: stop)\n\n\n\n if(ch>0 && status==STOPPED) // was stopped, should run now \n\n { \n\n status=CLOSED; acq_start(); adcStatus();\n\n } \n\n \n\n if(ch<0 && status>=CLOSED) // was running, should stop now\n\n { \n\n status=MUSTSTOP; acq_stop(); \n\n } \n\n\n\n if(status > CLOSED) // RUNNING\n\n {\n\n status = checkToCloseFile(status, (uint32_t) t_acq); // check if we reached file size or aquisition time\n\n }\n\n\n", "file_path": "src/main.cpp", "rank": 82, "score": 18.922587669806628 }, { "content": "/**\n\n * basicSoundRecorder\n\n*/\n\n#define START_MODE -1 // -1 wait for menu; 0 start with closed files\n\n\n\n#include \"config.h\"\n\n#include \"menu.h\"\n\n#include \"adc.h\"\n\n#include \"acq.h\"\n\n#include \"filing.h\"\n\n#include \"mTime.h\"\n\n\n\n#include \"utils.h\"\n\n\n\n/********************************* *********************************/\n\n// Function prototypes and variables\n\n\n\nuint32_t max_write=0;\n\nuint32_t max_count=0;\n\n\n", "file_path": "src/main.cpp", "rank": 83, "score": 16.795341238721264 }, { "content": " i2c_class i2c(&Wire1,100'000);\n\n for(int ii=0; ii<2; ii++)\n\n for(int jj=0; jj<4; jj++)\n\n {\n\n i2c.write(i2c_addr[ii],regs[jj]+1, again); // CH1_CFG1 (0dB gain)\n\n }\n\n }\n\n void adcStatus(void)\n\n {\n\n i2c_class i2c(&Wire1,100'000);\n\n for(int ii=0; ii<2; ii++)\n\n { Serial.print(\"\\n ADC 0x15: \"); Serial.print(i2c.read(i2c_addr[ii],0x15),HEX);\n\n }\n\n Serial.println();\n\n }\n\n bool adcEnable(void) { }\n\n#endif\n", "file_path": "src/adc.cpp", "rank": 84, "score": 15.845899112664636 }, { "content": "\n\n i2c.write(i2c_addr[ii],0x3B,0x00); // 0: 2.75V; 1: 2.5V; 2: 1.375V\n\n\n\n for(int jj=0; jj<4; jj++)\n\n { \n\n #if ATEST==1\n\n again=AG[ii][jj];\n\n #endif\n\n\n\n i2c.write(i2c_addr[ii],regs[jj]+0, 0x88); // CH1_CFG0 (Line in, 20 kOhm))\n\n i2c.write(i2c_addr[ii],regs[jj]+1, again); // CH1_CFG1 (0dB gain)\n\n i2c.write(i2c_addr[ii],regs[jj]+2, 201+dgain); // CH1_CFG2\n\n i2c.write(i2c_addr[ii],regs[jj]+3, 0x80); // CH1_CFG3 (0dB decimal gain correction: +/- 0.8 dB) \n\n i2c.write(i2c_addr[ii],regs[jj]+4, 0x00); // CH1_CFG4 (0bit)\n\n }\n\n }\n\n }\n\n\n\n void setAGain(int8_t again)\n\n {\n", "file_path": "src/adc.cpp", "rank": 85, "score": 14.058593679299685 }, { "content": " if(status >= CLOSED) // NOT STOPPED\n\n {\n\n uint32_t mc = getCount();\n\n if(mc>max_count) max_count=mc;\n\n //\n\n uint32_t to=millis();\n\n status = saveData(status); \n\n uint32_t dt=millis()-to;\n\n if(max_write<dt) max_write=dt;\n\n }\n\n\n\n static uint32_t t0;\n\n static uint32_t loop_count=0;\n\n if(millis()-t0>1000)\n\n {\n\n if(status>=CLOSED)\n\n {\n\n Serial.print(\"\\nLoop: \");\n\n Serial.print(status); Serial.print(\" \"); \n\n Serial.print(loop_count); Serial.print(\" : \"); \n", "file_path": "src/main.cpp", "rank": 86, "score": 13.449550312279348 }, { "content": " Serial.println(\"basic Sound Recorder Version: \" __DATE__ \" \" __TIME__ );\n\n SerNum = getTeensySerial();\n\n Serial.println((int32_t)SerNum,HEX);\n\n\n\n storage_configure();\n\n\n\n adc_init();\n\n acq_init(fsamp);\n\n adc_enable();\n\n\n\n #if START_MODE==CLOSED\n\n acq_start(); \n\n #endif\n\n\n\n Serial.println(\"End of Setup\");\n\n}\n\n\n\nvoid loop()\n\n{ static int16_t status=START_MODE; \n\n\n", "file_path": "src/main.cpp", "rank": 87, "score": 13.217402813383687 }, { "content": "#include \"core_pins.h\"\n\n#include \"config.h\"\n\n#include \"utils.h\"\n\n\n\nuint32_t SerNum;\n\n\n\n/* following from https://github.com/sstaub/TeensyID/blob/master/TeensyID.cpp */\n\n#if defined ARDUINO_TEENSY40 || defined ARDUINO_TEENSY41\n\n uint32_t getTeensySerial(void) \n\n {\n\n uint32_t num;\n\n num = HW_OCOTP_MAC0 & 0xFFFFFF;\n\n return num;\n\n }\n\n\n\n // from https://forum.pjrc.com/threads/33443-How-to-display-free-ram?p=275013&viewfull=1#post275013\n\n extern unsigned long _heap_start; \n\n extern unsigned long _heap_end;\n\n extern char *__brkval;\n\n\n", "file_path": "src/utils.cpp", "rank": 88, "score": 12.518123630448578 }, { "content": "uint32_t t_start;\n\n\n\n/* check if we should close file */\n\nint t_acq = 60; // close file on the minute\n\n\n\nint16_t checkToCloseFile(int16_t status, uint32_t t_acq)\n\n{ if((status == OPENED) || (status == RUNNING))\n\n { //\n\n static uint32_t to =0;\n\n uint32_t tx=rtc_get();\n\n tx %= t_acq;\n\n if(tx<to) status = DOCLOSE; // time wrapped, file must be closed\n\n to=tx;\n\n } \n\n return status;\n\n}\n\n\n\nvoid setup()\n\n{\n\n while(!Serial) continue;\n", "file_path": "src/main.cpp", "rank": 89, "score": 11.743796789683165 }, { "content": "// Wire.setSDA(18);\n\n// Wire.setSCL(19);\n\n Wire.setClock(100'000);\n\n\n\n for(int ii=0;ii<127;ii++)\n\n {\n\n Wire.beginTransmission(ii);\n\n uint8_t error = Wire.endTransmission();\n\n if(error) \n\n Serial.printf(\"I2C not found %x\\n\",ii); \n\n else \n\n Serial.printf(\"I2C found %x\\n\",ii); \n\n }\n\n while(1); \n\n}\n\n\n\nvoid test_wire1(void)\n\n{\n\n Wire1.begin();\n\n delay(100);\n", "file_path": "src/i2c.cpp", "rank": 90, "score": 11.642630494058054 }, { "content": " FTFL_FSTAT = FTFL_FSTAT_RDCOLERR | FTFL_FSTAT_ACCERR | FTFL_FSTAT_FPVIOL;\n\n *(uint32_t *)&FTFL_FCCOB3 = 0x41070000;\n\n FTFL_FSTAT = FTFL_FSTAT_CCIF;\n\n while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait\n\n num = *(uint32_t *)&FTFL_FCCOBB;\n\n kinetis_hsrun_enable();\n\n #endif\n\n __enable_irq();\n\n return num & 0xFFFFFF;\n\n }\n\n#endif\n\n\n\n#include \"usb_serial.h\"\n\nPrint *stdPrint = &Serial;\n\n\n\nextern \"C\"\n\n{\n\n int _write(int file, const void *buf, size_t len) {\n\n // https://forum.pjrc.com/threads/28473-Quick-Guide-Using-printf()-on-Teensy-ARM\n\n Print *out;\n", "file_path": "src/utils.cpp", "rank": 91, "score": 11.584033516078605 }, { "content": " if (Wire1.endTransmission(false) != 0) return 0;\n\n if (Wire1.requestFrom((int)addr, 1) < 1) return 0;\n\n val = Wire1.read();\n\n return val;\n\n}\n\n\n\nbool i2c1_write(uint8_t addr, uint8_t reg, uint8_t val)\n\n{\n\n Wire1.beginTransmission(addr);\n\n Wire1.write(reg);\n\n Wire1.write(val);\n\n return (Wire1.endTransmission() == 0);\n\n}\n\n*/\n\n\n\n#if 0\n\nvoid test_wire0(void)\n\n{\n\n Wire.begin();\n\n delay(100);\n", "file_path": "src/i2c.cpp", "rank": 92, "score": 11.500013115271589 }, { "content": " CS536X_GCTL_MODE(speed));\n\n val[1] = i2c.read(addr, CS536X_GCTL);\n\n\n\n val[2] = i2c.read(addr, CS536X_PDN);\n\n val[3] = i2c.read(addr, CS536X_nSDOUT);\n\n \n\n Serial.printf(\"CS536x: %x %x %x %x %x\\r\\n\",addr, val[0],val[1],val[2],val[3]);\n\n\n\n // i2c.write(addr, CS536X_nHPF, 0b01111111);\n\n // i2c.write(addr, CS536X_PDN, 0b00001000);\n\n // i2c.write(addr, CS536X_nSDOUT, 0b00001000);\n\n\n\n // i2c.write(addr, CS536X_MUTE, 0b11111110);\n\n }\n\n\n\n void setAGain(int8_t again) { }\n\n void adcStatus(void) { }\n\n bool adcEnable(void) { }\n\n\n\n#elif (ADC_MODEL == TLDV320ADC6140) || (ADC_MODEL == TLDV320ADC6140_2)\n", "file_path": "src/adc.cpp", "rank": 93, "score": 11.113602842244518 }, { "content": " int freeram() { return (char *)&_heap_end - __brkval; }\n\n\n\n #define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C\n\n #define CPU_RESTART_VAL 0x5FA0004\n\n #define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL)\n\n\n\n#else\n\n uint32_t getTeensySerial(void) \n\n {\n\n uint32_t num = 0;\n\n __disable_irq();\n\n #if defined(HAS_KINETIS_FLASH_FTFA) || defined(HAS_KINETIS_FLASH_FTFL)\n\n FTFL_FSTAT = FTFL_FSTAT_RDCOLERR | FTFL_FSTAT_ACCERR | FTFL_FSTAT_FPVIOL;\n\n FTFL_FCCOB0 = 0x41;\n\n FTFL_FCCOB1 = 15;\n\n FTFL_FSTAT = FTFL_FSTAT_CCIF;\n\n while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF)) ; // wait\n\n num = *(uint32_t *)&FTFL_FCCOB7;\n\n #elif defined(HAS_KINETIS_FLASH_FTFE)\n\n kinetis_hsrun_disable();\n", "file_path": "src/utils.cpp", "rank": 94, "score": 11.035085812111161 }, { "content": " void acq_startClocks(void)\n\n {\n\n SIM_SCGC6 |= SIM_SCGC6_I2S;\n\n SIM_SCGC7 |= SIM_SCGC7_DMA;\n\n SIM_SCGC6 |= SIM_SCGC6_DMAMUX;\n\n }\n\n\n\n void acq_start(void)\n\n {\n\n acq_startClocks();\n\n I2S0_RCSR |= I2S_RCSR_RE;\n\n }\n\n\n\n void acq_stop(void)\n\n {\n\n I2S0_RCSR &= ~I2S_RCSR_RE;\n\n acq_stopClocks();\n\n }\n\n\n\n void acq_init(int fsamp)\n", "file_path": "src/acq.cpp", "rank": 95, "score": 10.931760945540297 }, { "content": " Serial.print(acq_count); Serial.print(\" \");\n\n Serial.print(acq_miss); Serial.print(\" \");\n\n Serial.print(max_count); Serial.print(\" \");\n\n Serial.print(max_write);\n\n }\n\n loop_count=0;\n\n acq_count=0;\n\n acq_miss=0;\n\n max_count=0;\n\n max_write=0;\n\n t0=millis();\n\n }\n\n loop_count++;\n\n}", "file_path": "src/main.cpp", "rank": 96, "score": 10.857575792003276 }, { "content": " wire->setClock(speed);\n\n wire->setSCL(scl);\n\n wire->setSDA(sda);\n\n }\n\n\n\n uint8_t exist(uint8_t addr)\n\n {\n\n wire->beginTransmission(addr);\n\n return (wire->endTransmission()==0);\n\n }\n\n\n\n uint8_t read(uint8_t addr, uint8_t reg) \n\n { \n\n unsigned int val;\n\n wire->beginTransmission(addr);\n\n wire->write(reg);\n\n if (wire->endTransmission(false) != 0) return 0;\n\n if (wire->requestFrom((int)addr, 1) < 1) return 0;\n\n val = wire->read();\n\n return val;\n", "file_path": "src/i2c.h", "rank": 97, "score": 10.62070057380434 }, { "content": "#include \"i2c.h\"\n\n\n\n\n\n/*\n\nuint8_t i2c_exist(uint8_t addr)\n\n{\n\n Wire.beginTransmission(addr);\n\n return (Wire.endTransmission()==0);\n\n}\n\n\n\nuint8_t i2c_read(uint8_t addr, uint8_t reg)\n\n{\n\n unsigned int val;\n\n Wire.beginTransmission(addr);\n\n Wire.write(reg);\n\n if (Wire.endTransmission(false) != 0) return 0;\n\n if (Wire.requestFrom((int)addr, 1) < 1) return 0;\n\n val = Wire.read();\n\n return val;\n\n}\n", "file_path": "src/i2c.cpp", "rank": 98, "score": 10.05789944845505 }, { "content": " { Serial.printf(\"ADC I2C %x not found\\n\",i2c_addr[ii]); while(1) ;}\n\n\n\n i2c.write(i2c_addr[ii],0x02,0x81); // 1.8V AREG, not sleep\n\n\n\n i2c.write(i2c_addr[ii],0x02,0x81); // 1.8V AREG, not sleep\n\n i2c.write(i2c_addr[ii],0x07,(3<<4)); // TDM; 32 bit; default clock xmit on rising edge); zero fill\n\n// i2c.write(i2c_addr[ii],0x07,(3<<4) | (1<<1)); // 32 bit and TX-edge\n\n i2c.write(i2c_addr[ii],0x08,0x00); // TX_offset 0\n\n\n\n//// i2c.write(i2c_addr[ii],0x13,0<<6); // AUTO_CLK_TX\n\n// i2c.write(i2c_addr[ii],0x16,0x16, (0<<6 | 0<<3));\n\n\n\n for(int jj=0;jj<4;jj++)\n\n {\n\n i2c.write(i2c_addr[ii],0x0B+jj,chmap[ii][jj]); \n\n }\n\n\n\n i2c.write(i2c_addr[ii],0x73,chanMask[ii]); \n\n i2c.write(i2c_addr[ii],0x74,chanMask[ii]);\n\n i2c.write(i2c_addr[ii],0x75,0x60);\n", "file_path": "src/adc.cpp", "rank": 99, "score": 9.695365157669894 } ]
C++
alljoyn_c/samples/about/about_service.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
#include <alljoyn_c/AboutData.h> #include <alljoyn_c/AboutListener.h> #include <alljoyn_c/AboutObj.h> #include <alljoyn_c/AboutObjectDescription.h> #include <alljoyn_c/AboutProxy.h> #include <alljoyn_c/BusAttachment.h> #include <alljoyn_c/Init.h> #include <alljoyn/BusAttachment.h> #include <alljoyn/BusListener.h> #include <alljoyn/BusObject.h> #include <alljoyn/AboutObj.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #define ArraySize(a) (sizeof(a) / sizeof(a[0])) using namespace ajn; static volatile sig_atomic_t s_interrupt = QCC_FALSE; static void CDECL_CALL sig_int_handler(int sig) { QCC_UNUSED(sig); s_interrupt = QCC_TRUE; } static alljoyn_sessionport ASSIGNED_SESSION_PORT = 900; static const char INTERFACE_NAME[] = "com.example.about.feature.interface.sample"; static void AJ_CALL sessionportlistener_sessionjoined_cb(const void* context, alljoyn_sessionport sessionPort, alljoyn_sessionid id, const char* joiner) { QCC_UNUSED(context); QCC_UNUSED(sessionPort); QCC_UNUSED(joiner); printf("Session Joined SessionId = %u\n", id); } static QCC_BOOL AJ_CALL sessionportlistener_acceptsessionjoiner_cb(const void* context, alljoyn_sessionport sessionPort, const char* joiner, const alljoyn_sessionopts opts) { QCC_UNUSED(context); QCC_UNUSED(joiner); QCC_UNUSED(opts); if (sessionPort != ASSIGNED_SESSION_PORT) { printf("Rejecting join attempt on unexpected session port %d\n", sessionPort); return QCC_FALSE; } return QCC_TRUE; } static alljoyn_sessionportlistener create_my_alljoyn_sessionportlistener() { alljoyn_sessionportlistener_callbacks* callbacks = (alljoyn_sessionportlistener_callbacks*) malloc(sizeof(alljoyn_sessionportlistener_callbacks)); callbacks->accept_session_joiner = sessionportlistener_acceptsessionjoiner_cb; callbacks->session_joined = sessionportlistener_sessionjoined_cb; return alljoyn_sessionportlistener_create(callbacks, NULL); } static void AJ_CALL echo_cb(alljoyn_busobject object, const alljoyn_interfacedescription_member* member, alljoyn_message msg) { alljoyn_msgarg arg = alljoyn_message_getarg(msg, 0); QCC_UNUSED(member); printf("Echo method called %s\n", ((ajn::MsgArg*)arg)->v_string.str); QStatus status = alljoyn_busobject_methodreply_args(object, msg, arg, 1); if (status != ER_OK) { printf("Failed to created MethodReply.\n"); } } static alljoyn_busobject create_my_alljoyn_busobject(alljoyn_busattachment bus, const char* path) { QStatus status = ER_FAIL; alljoyn_busobject result = NULL; result = alljoyn_busobject_create(path, QCC_FALSE, NULL, NULL); alljoyn_interfacedescription iface = alljoyn_busattachment_getinterface(bus, INTERFACE_NAME); QCC_ASSERT(iface != NULL); status = alljoyn_busobject_addinterface(result, iface); alljoyn_busobject_setannounceflag(result, iface, ANNOUNCED); if (status != ER_OK) { printf("Failed to add %s interface to the BusObject\n", INTERFACE_NAME); } alljoyn_interfacedescription_member echomember; alljoyn_interfacedescription_getmember(iface, "Echo", &echomember); const alljoyn_busobject_methodentry methodEntries[] = { { &echomember, echo_cb } }; status = alljoyn_busobject_addmethodhandlers(result, methodEntries, sizeof(methodEntries) / sizeof(methodEntries[0])); return result; } int CDECL_CALL main(void) { signal(SIGINT, sig_int_handler); QStatus status = alljoyn_init(); if (ER_OK != status) { printf("alljoyn_init failed (%s)\n", QCC_StatusText(status)); return 1; } #ifdef ROUTER status = alljoyn_routerinit(); if (ER_OK != status) { printf("alljoyn_routerinit failed (%s)\n", QCC_StatusText(status)); alljoyn_shutdown(); return 1; } #endif alljoyn_busattachment bus = alljoyn_busattachment_create("About Service Example", QCC_TRUE); status = alljoyn_busattachment_start(bus); if (ER_OK == status) { printf("BusAttachment started.\n"); } else { printf("FAILED to start BusAttachment (%s)\n", QCC_StatusText(status)); return 1; } status = alljoyn_busattachment_connect(bus, NULL); if (ER_OK == status) { printf("BusAttachment connect succeeded. BusName %s\n", alljoyn_busattachment_getuniquename(bus)); } else { printf("FAILED to connect to router node (%s)\n", QCC_StatusText(status)); return 1; } alljoyn_sessionopts opts = alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, QCC_FALSE, ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY); alljoyn_sessionport sessionPort = ASSIGNED_SESSION_PORT; alljoyn_sessionportlistener listener = create_my_alljoyn_sessionportlistener(); status = alljoyn_busattachment_bindsessionport(bus, &sessionPort, opts, listener); if (ER_OK != status) { printf("Failed to BindSessionPort (%s)", QCC_StatusText(status)); return 1; } alljoyn_aboutdata aboutData = alljoyn_aboutdata_create("en"); uint8_t appId[] = { 0x01, 0xB3, 0xBA, 0x14, 0x1E, 0x82, 0x11, 0xE4, 0x86, 0x51, 0xD1, 0x56, 0x1D, 0x5D, 0x46, 0xB0 }; status = alljoyn_aboutdata_setappid(aboutData, appId, 16); status = alljoyn_aboutdata_setdevicename(aboutData, "My Device Name", "en"); status = alljoyn_aboutdata_setdeviceid(aboutData, "93c06771-c725-48c2-b1ff-6a2a59d445b8"); status = alljoyn_aboutdata_setappname(aboutData, "Application", "en"); status = alljoyn_aboutdata_setmanufacturer(aboutData, "Manufacturer", "en"); status = alljoyn_aboutdata_setmodelnumber(aboutData, "123456"); status = alljoyn_aboutdata_setdescription(aboutData, "A poetic description of this application", "en"); status = alljoyn_aboutdata_setdateofmanufacture(aboutData, "2014-03-24"); status = alljoyn_aboutdata_setsoftwareversion(aboutData, "0.1.2"); status = alljoyn_aboutdata_sethardwareversion(aboutData, "0.0.1"); status = alljoyn_aboutdata_setsupporturl(aboutData, "http://www.example.org"); status = alljoyn_aboutdata_setdevicename(aboutData, "Mi dispositivo Nombre", "es"); status = alljoyn_aboutdata_setappname(aboutData, "aplicación", "es"); status = alljoyn_aboutdata_setmanufacturer(aboutData, "fabricante", "es"); status = alljoyn_aboutdata_setdescription(aboutData, "Una descripción poética de esta aplicación", "es"); if (!alljoyn_aboutdata_isvalid(aboutData, "en")) { printf("failed to setup about data.\n"); } char interface[256] = { 0 }; #if defined(QCC_OS_GROUP_WINDOWS) _snprintf( #else snprintf( #endif interface, ArraySize(interface), "<node>" \ "<interface name='%s'>" \ " <method name='Echo'>" \ " <arg name='out_arg' type='s' direction='in' />" \ " <arg name='return_arg' type='s' direction='out' />" \ " </method>" \ "</interface>" \ "</node>", INTERFACE_NAME); interface[ArraySize(interface) - 1] = '\0'; printf("Interface = %s\n", interface); status = alljoyn_busattachment_createinterfacesfromxml(bus, interface); if (ER_OK != status) { printf("Failed to parse the xml interface definition (%s)", QCC_StatusText(status)); return 1; } alljoyn_busobject busObject = create_my_alljoyn_busobject(bus, "/example/path"); status = alljoyn_busattachment_registerbusobject(bus, busObject); if (ER_OK != status) { printf("Failed to register BusObject (%s)", QCC_StatusText(status)); return 1; } alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(bus, UNANNOUNCED); status = alljoyn_aboutobj_announce(aboutObj, sessionPort, aboutData); if (ER_OK == status) { printf("AboutObj Announce Succeeded.\n"); } else { printf("AboutObj Announce failed (%s)\n", QCC_StatusText(status)); return 1; } if (ER_OK == status) { while (s_interrupt == QCC_FALSE) { #ifdef _WIN32 Sleep(100); #else usleep(100 * 1000); #endif } } alljoyn_aboutobj_unannounce(aboutObj); alljoyn_sessionportlistener_destroy(listener); alljoyn_busattachment_stop(bus); alljoyn_busattachment_join(bus); alljoyn_sessionopts_destroy(opts); alljoyn_aboutdata_destroy(aboutData); alljoyn_busobject_destroy(busObject); alljoyn_aboutobj_destroy(aboutObj); alljoyn_busattachment_destroy(bus); #ifdef ROUTER alljoyn_routershutdown(); #endif alljoyn_shutdown(); return 0; }
#include <alljoyn_c/AboutData.h> #include <alljoyn_c/AboutListener.h> #include <alljoyn_c/AboutObj.h> #include <alljoyn_c/AboutObjectDescription.h> #include <alljoyn_c/AboutProxy.h> #include <alljoyn_c/BusAttachment.h> #include <alljoyn_c/Init.h> #include <alljoyn/BusAttachment.h> #include <alljoyn/BusListener.h> #include <alljoyn/BusObject.h> #include <alljoyn/AboutObj.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #define ArraySize(a) (sizeof(a) / sizeof(a[0])) using namespace ajn; static volatile sig_atomic_t s_interrupt = QCC_FALSE; static void CDECL_CALL sig_int_handler(int sig) { QCC_UNUSED(sig); s_interrupt = QCC_TRUE; } static alljoyn_sessionport ASSIGNED_SESSION_PORT = 900; static const char INTERFACE_NAME[] = "com.example.about.feature.interface.sample"; static void AJ_CALL sessionportlistener_sessionjoined_cb(const void* context, alljoyn_sessionport sessionPort, alljoyn_sessionid id, const char* joiner) { QCC_UNUSED(context); QCC_UNUSED(sessionPort); QCC_UNUSED(joiner); printf("Session Joined SessionId = %u\n", id); } static QCC_BOOL AJ_CALL sessionportlistener_acceptsessionjoiner_cb(const void* context, alljoyn_sessionport sessionPort, const char* joiner, const alljoyn_sessionopts opts) { QCC_UNUSED(context); QCC_UNUSED(joiner); QCC_UNUSED(opts); if (sessionPort != ASSIGNED_SESSION_PORT) { printf("Rejecting join attempt on unexpected session port %d\n", sessionPort); return QCC_FALSE; } return QCC_TRUE; } static alljoyn_sessionportlistener create_my_alljoyn_sessionportlistener() { alljoyn_sessionportlistener_callbacks* callbacks = (alljoyn_sessionportlistener_callbacks*) malloc(sizeof(alljoyn_sessionportlistener_callbacks)); callbacks->accept_session_joiner = sessionportlistener_acceptsessionjoiner_cb; callbacks->session_joined = sessionportlistener_sessionjoined_cb; return alljoyn_sessionportlistener_create(callbacks, NULL); } static void AJ_CALL echo_cb(alljoyn_busobject object, const alljoyn_interfacedescription_member* member, alljoyn_message msg) { alljoyn_msgarg arg = alljoyn_message_getarg(msg, 0); QCC_UNUSED(member); printf("Echo method called %s\n", ((ajn::MsgArg*)arg)->v_string.str); QStatus status = alljoyn_busobject_methodreply_args(object, msg, arg, 1); if (status != ER_OK) { printf("Failed to created MethodReply.\n"); } } static alljoyn_busobject create_my_alljoyn_busobject(alljoyn_busattachment bus, const char* path) { QStatus status = ER_FAIL; alljoyn_busobject result = NULL; result = alljoyn_busobject_create(path, QCC_FALSE, NULL, NULL); alljoyn_interfacedescription iface = alljoyn_busattachment_getinterface(bus, INTERFACE_NAME); QCC_ASSERT(iface != NULL); status = alljoyn_busobject_addinterface(result, iface); alljoyn_busobject_setannounceflag(result, iface, ANNOUNCED); if (status != ER_OK) { printf("Failed to add %s interface to the BusObject\n", INTERFACE_NAME); } alljoyn_interfacedescription_member echomember; alljoyn_interfacedescription_getmember(iface, "Echo", &echomember); const alljoyn_busobject_methodentry methodEntries[] = { { &echomember, echo_cb } }; status = alljoyn_busobject_addmethodhandlers(result, methodEntries, sizeof(methodEntries) / sizeof(methodEntries[0])); return result; } int CDECL_CALL main(void) { signal(SIGINT, sig_int_handler); QStatus status = alljoyn_init(); if (ER_OK != status) { printf("alljoyn_init failed (%s)\n", QCC_StatusText(status)); return 1; } #ifdef ROUTER status = alljoyn_routerinit(); if (ER_OK != status) { printf("alljoyn_routerinit failed (%s)\n", QCC_StatusText(status)); alljoyn_shutdown(); return 1; } #endif alljoyn_busattachment bus = alljoyn_busattachment_create("About Service Example", QCC_TRUE); status = alljoyn_busattachment_start(bus); if (ER_OK == status) { printf("BusAttachment started.\n"); } else { printf("FAILED to start BusAttachment (%s)\n", QCC_StatusText(status)); return 1; } status = alljoyn_busattachment_connect(bus, NULL); if (ER_OK == status) { printf("BusAttachment connect succeeded. BusName %s\n", alljoyn_busattachment_getuniquename(bus)); } else { printf("FAILED to connect to router node (%s)\n", QCC_StatusText(status)); return 1; } alljoyn_sessionopts opts = alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, QCC_FALSE, ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY); alljoyn_sessionport sessionPort = ASSIGNED_SESSION_PORT; alljoyn_sessionportlistener listener = create_my_alljoyn_sessionportlistener(); status = alljoyn_busattachment_bindsessionport(bus, &sessionPort, opts, listener); if (ER_OK != status) { printf("Failed to BindSessionPort (%s)", QCC_StatusText(status)); return 1; } alljoyn_aboutdata aboutData = alljoyn_aboutdata_create("en"); uint8_t appId[] = { 0x01, 0xB3, 0xBA, 0x14, 0x1E, 0x82, 0x11, 0xE4, 0x86, 0x51, 0xD1, 0x56, 0x1D, 0x5D, 0x46, 0xB0 }; status = alljoyn_aboutdata_setappid(aboutData, appId, 16); status = alljoyn_aboutdata_setdevicename(aboutData, "My Device Name", "en"); status = alljoyn_aboutdata_setdeviceid(aboutData, "93c06771-c725-48c2-b1ff-6a2a59d445b8"); status = alljoyn_aboutdata_setappname(aboutData, "Application", "en"); status = alljoyn_aboutdata_setmanufacturer(aboutData, "Manufacturer", "en"); status = alljoyn_aboutdata_setmodelnumber(aboutData, "123456"); status = alljoyn_aboutdata_setdescription(aboutData, "A poetic description of this application", "en"); status = alljoyn_aboutdata_setdateofmanufacture(aboutData, "2014-03-24"); status = alljoyn_aboutdata_setsoftwareversion(aboutData, "0.1.2"); status = alljoyn_aboutdata_sethardwareversion(aboutData, "0.0.1"); status = alljoyn_aboutdata_setsupporturl(aboutData, "http://www.example.org"); status = alljoyn_aboutdata_setdevicename(aboutData, "Mi dispositivo Nombre", "es"); status = alljoyn_aboutdata_setappname(aboutData, "aplicación", "es"); status = alljoyn_aboutdata_setmanufacturer(aboutData, "fabricante", "es"); status = alljoyn_aboutdata_setdescription(aboutData, "Una descripción poética de esta aplicación", "es"); if (!alljoyn_aboutdata_isvalid(aboutData, "en")) { printf("failed to setup about data.\n"); } char interface[
256] = { 0 }; #if defined(QCC_OS_GROUP_WINDOWS) _snprintf( #else snprintf( #endif interface, ArraySize(interface), "<node>" \ "<interface name='%s'>" \ " <method name='Echo'>" \ " <arg name='out_arg' type='s' direction='in' />" \ " <arg name='return_arg' type='s' direction='out' />" \ " </method>" \ "</interface>" \ "</node>", INTERFACE_NAME); interface[ArraySize(interface) - 1] = '\0'; printf("Interface = %s\n", interface); status = alljoyn_busattachment_createinterfacesfromxml(bus, interface); if (ER_OK != status) { printf("Failed to parse the xml interface definition (%s)", QCC_StatusText(status)); return 1; } alljoyn_busobject busObject = create_my_alljoyn_busobject(bus, "/example/path"); status = alljoyn_busattachment_registerbusobject(bus, busObject); if (ER_OK != status) { printf("Failed to register BusObject (%s)", QCC_StatusText(status)); return 1; } alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(bus, UNANNOUNCED); status = alljoyn_aboutobj_announce(aboutObj, sessionPort, aboutData); if (ER_OK == status) { printf("AboutObj Announce Succeeded.\n"); } else { printf("AboutObj Announce failed (%s)\n", QCC_StatusText(status)); return 1; } if (ER_OK == status) { while (s_interrupt == QCC_FALSE) { #ifdef _WIN32 Sleep(100); #else usleep(100 * 1000); #endif } } alljoyn_aboutobj_unannounce(aboutObj); alljoyn_sessionportlistener_destroy(listener); alljoyn_busattachment_stop(bus); alljoyn_busattachment_join(bus); alljoyn_sessionopts_destroy(opts); alljoyn_aboutdata_destroy(aboutData); alljoyn_busobject_destroy(busObject); alljoyn_aboutobj_destroy(aboutObj); alljoyn_busattachment_destroy(bus); #ifdef ROUTER alljoyn_routershutdown(); #endif alljoyn_shutdown(); return 0; }
function_block-function_prefixed
[ { "content": "class BasicService: NSObject, AJNBusListener, AJNSessionPortListener, AJNSessionListener {\n\n\n\n weak var delegate: BasicServiceDelegate?\n\n\n\n private var bus: AJNBusAttachment?\n\n private var basicObject: BasicObject?\n\n\n\n func startServiceAsync() {\n\n DispatchQueue.global(qos: .default).async {\n\n self.startService()\n\n }\n\n }\n\n\n\n func stopServiceAsync() {\n\n DispatchQueue.global(qos: .default).async {\n\n self.stopService(bus: self.bus)\n\n }\n\n }\n\n\n\n func printVersionInformation() {\n", "file_path": "alljoyn_objc/samples/iOS/Swift/BasicService/BasicService/BasicService.swift", "rank": 0, "score": 381462.0778109959 }, { "content": "class AJNSessionPortListenerImpl : public ajn::SessionPortListener {\n\n protected:\n\n static const char* AJN_SESSION_PORT_LISTENER_DISPATCH_QUEUE_NAME;\n\n __weak AJNBusAttachment* busAttachment;\n\n\n\n /**\n\n * Objective C delegate called when one of the below virtual functions\n\n * is called.\n\n */\n\n __weak id<AJNSessionPortListener> m_delegate;\n\n\n\n public:\n\n\n\n\n\n /**\n\n * Constructor for the AJN session port listener implementation.\n\n *\n\n * @param aBusAttachment Objective C bus attachment wrapper object.\n\n * @param aDelegate Objective C delegate called when one of the below virtual functions is called.\n\n */\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionPortListenerImpl.h", "rank": 1, "score": 379336.7882531101 }, { "content": "class CommonBusListener : public ajn::BusListener, public ajn::SessionPortListener, public ajn::SessionListener {\n\n\n\n public:\n\n\n\n /**\n\n * Constructor of CommonBusListener\n\n * @param bus - used to set a session Listener\n\n * @param daemonDisconnectCB - used to set a callback for when the daemon is disconnected\n\n */\n\n CommonBusListener(ajn::BusAttachment* bus = NULL, void(*daemonDisconnectCB)() = NULL);\n\n\n\n /**\n\n * Destructor of CommonBusListener\n\n */\n\n ~CommonBusListener();\n\n\n\n /**\n\n * AcceptSessionJoiner - Receive request to join session and decide whether to accept it or not\n\n * @param sessionPort - the port of the request\n\n * @param joiner - the name of the joiner\n", "file_path": "services/config/cpp/samples/ConfigServiceSample/CommonBusListener.h", "rank": 2, "score": 363938.44836993434 }, { "content": "class BusListenerImpl : public ajn::BusListener, public ajn::SessionPortListener {\n\n\n\n public:\n\n\n\n /**\n\n * Constructor of CommonBusListener\n\n */\n\n BusListenerImpl();\n\n\n\n /**\n\n * Constructor of CommonBusListener\n\n * @param sessionPort - port of listener\n\n */\n\n BusListenerImpl(ajn::SessionPort sessionPort);\n\n\n\n /**\n\n * Destructor of CommonBusListener\n\n */\n\n ~BusListenerImpl();\n\n\n", "file_path": "services/about/cpp/samples/AboutServiceSample/BusListenerImpl.h", "rank": 3, "score": 352220.17762932804 }, { "content": "class SessionlessObj : public BusObject, public NameListener, public SessionListener, public SessionPortListener,\n\n public BusAttachment::JoinSessionAsyncCB, public qcc::AlarmListener, public IpNameServiceListener {\n\n\n\n public:\n\n /**\n\n * Constructor\n\n *\n\n * @param bus Bus to associate with org.freedesktop.DBus message handler.\n\n * @param router The DaemonRouter associated with the bus.\n\n * @param busController Controller that created this object.\n\n */\n\n SessionlessObj(Bus& bus, BusController* busController, DaemonRouter& router);\n\n\n\n /**\n\n * Destructor\n\n */\n\n ~SessionlessObj();\n\n\n\n /**\n\n * Initialize and register this DBusObj instance.\n", "file_path": "alljoyn_core/router/SessionlessObj.h", "rank": 4, "score": 348980.1591546877 }, { "content": "- (void)sessionWasLost:(AJNSessionId)sessionId;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionListener.h", "rank": 5, "score": 344762.494908794 }, { "content": "class AboutInterfaceTestSessionPortListener : public SessionPortListener {\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts)\n\n {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n return true;\n\n }\n\n};\n\n\n\n/*\n\n * A PropertyStoreImplementation with all of the AboutData fields filled out.\n\n * The AppId and DeviceId are generated at random using the qcc::GUID function\n\n */\n", "file_path": "services/about/cpp/unit_test/AboutInterfaceTest.cc", "rank": 6, "score": 340874.3751309329 }, { "content": " String mServiceName;\n", "file_path": "services/about/java/samples/java/AboutClientSample/src/org/alljoyn/about/sample/DeviceAnnouncementHandler.java", "rank": 7, "score": 335733.37415119883 }, { "content": "class JoinAnnounceHandler : public ajn::services::AnnounceHandler {\n\n public:\n\n virtual void Announce(unsigned short version, unsigned short port, const char* busName,\n\n const ObjectDescriptions& objectDescs, const AboutData& aboutData)\n\n {\n\n QCC_UNUSED(objectDescs);\n\n EXPECT_EQ(1, version);\n\n EXPECT_EQ(25, port);\n\n char* deviceName;\n\n aboutData.find(\"DeviceName\")->second.Get(\"s\", &deviceName);\n\n EXPECT_STREQ(\"AnnounceHandler Unit Test framework\", deviceName);\n\n char* defaultLanguage;\n\n aboutData.find(\"DefaultLanguage\")->second.Get(\"s\", &defaultLanguage);\n\n EXPECT_STREQ(\"en\", defaultLanguage);\n\n char* appName;\n\n aboutData.find(\"AppName\")->second.Get(\"s\", &appName);\n\n EXPECT_STREQ(\"AnnounceHander Unit Test\", appName);\n\n announcePort = port;\n\n announceBusName = busName;\n\n announceHandlerFlag = true;\n", "file_path": "services/about/cpp/unit_test/AboutInterfaceTest.cc", "rank": 8, "score": 335511.1062483499 }, { "content": "- (QStatus)addMember:(AJNMessageType)type name:(NSString*)name inputSig:(NSString*)inputSig outSig:(NSString*)outSig argNames:(NSString*)argNames annotation:(uint8_t)annotation accessPerms:(NSString*)accessPerms;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNInterfaceDescription.h", "rank": 9, "score": 332874.66350902256 }, { "content": "class AnnounceHandlerTestSessionPortListener : public SessionPortListener {\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts)\n\n {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n return true;\n\n }\n\n};\n\n\n", "file_path": "services/about/cpp/unit_test/AnnounceHandler2Test.cc", "rank": 10, "score": 332515.2214987622 }, { "content": "class AnnounceHandlerTestSessionPortListener : public SessionPortListener {\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n return true;\n\n }\n\n};\n\n\n\n/*\n\n * A PropertyStoreImplementation with all of the AboutData fields filled out.\n\n * The AppId and DeviceId are generated at random using the qcc::GUID function\n\n */\n", "file_path": "services/about/cpp/unit_test/AnnounceHandlerTest.cc", "rank": 11, "score": 332515.2214987622 }, { "content": "//ASACORE-651\n\nclass RemoveObjectDescriptionAnnounceHandler : public ajn::services::AnnounceHandler {\n\n\n\n public:\n\n RemoveObjectDescriptionAnnounceHandler(const char* objToBeRemoved) : announceHandlerCount(0), toRemove(objToBeRemoved) { }\n\n void Announce(unsigned short version, unsigned short port, const char* busName, const ObjectDescriptions& objectDescs,\n\n const AboutData& aboutData) {\n\n QCC_UNUSED(version);\n\n QCC_UNUSED(port);\n\n QCC_UNUSED(busName);\n\n QCC_UNUSED(aboutData);\n\n\n\n if (announceHandlerCount == 0) {\n\n EXPECT_NE(objectDescs.end(), objectDescs.find(\"/org/alljoyn/test/a\"));\n\n EXPECT_NE(objectDescs.end(), objectDescs.find(\"/org/alljoyn/test/b\"));\n\n } else {\n\n if (toRemove == \"/org/alljoyn/test/b\") {\n\n EXPECT_NE(objectDescs.end(), objectDescs.find(\"/org/alljoyn/test/a\"));\n\n EXPECT_EQ(objectDescs.end(), objectDescs.find(\"/org/alljoyn/test/b\"));\n\n } else {\n\n EXPECT_EQ(objectDescs.end(), objectDescs.find(\"/org/alljoyn/test/a\"));\n", "file_path": "services/about/cpp/unit_test/AnnounceHandlerTest.cc", "rank": 12, "score": 329887.5074416655 }, { "content": "class AboutClientSessionJoiner : public ajn::BusAttachment::JoinSessionAsyncCB {\n\n\n\n public:\n\n\n\n AboutClientSessionJoiner(ajn::BusAttachment& bus, const qcc::String& busName, SessionJoinedCallback callback = 0);\n\n\n\n virtual ~AboutClientSessionJoiner();\n\n\n\n void JoinSessionCB(QStatus status, ajn::SessionId id, const ajn::SessionOpts& opts, void* context);\n\n\n\n private:\n\n /* Private assigment operator - does nothing */\n\n AboutClientSessionJoiner operator=(const AboutClientSessionJoiner&);\n\n\n\n ajn::BusAttachment& bus;\n\n\n\n qcc::String m_BusName;\n\n\n\n SessionJoinedCallback m_Callback;\n\n};\n\n\n\n#endif /* ABOUTCLIENTSESSIONJOINER_H_ */\n", "file_path": "services/about/cpp/samples/AboutClientSample/AboutClientSessionJoiner.h", "rank": 13, "score": 326037.7320273883 }, { "content": " short mPort;\n", "file_path": "services/about/java/samples/java/AboutClientSample/src/org/alljoyn/about/sample/DeviceAnnouncementHandler.java", "rank": 14, "score": 322424.14541038126 }, { "content": " public void attemptToJoinSession(String serviceName, short port, Map<String, Variant> announceData)\n\n {\n\n SessionOpts sessionOpts = new SessionOpts();\n\n sessionOpts.traffic = SessionOpts.TRAFFIC_MESSAGES;\n\n sessionOpts.isMultipoint = false;\n\n sessionOpts.proximity = SessionOpts.PROXIMITY_ANY;\n\n sessionOpts.transports = SessionOpts.TRANSPORT_ANY;\n\n\n\n Mutable.IntegerValue sessionId = new Mutable.IntegerValue();\n\n\n\n Status status = mBusAttachment.joinSession(serviceName, port, sessionId, sessionOpts, new SessionListener());\n\n if (Status.OK == status) {\n\n System.out.println(\"Succesfully joined session with: \\\"\" + serviceName + \"\\\" SessionId: \\\"\" + sessionId.value +\"\\\"\");\n\n ProxyBusObject aboutObj = mBusAttachment.getProxyBusObject(serviceName, AboutTransport.OBJ_PATH,\n\n sessionId.value, new Class<?>[] { AboutTransport.class});\n\n AboutTransport aboutIntf = aboutObj.getInterface(AboutTransport.class);\n\n try {\n\n /*\n\n * Get property org.alljoyn.About.Version\n\n */\n\n System.out.println(\"--------------Getting org.alljoyn.About.Version property-------------\");\n\n int version = aboutIntf.getVersion();\n\n System.out.println(\"version: \" + version);\n\n } catch(BusException e1){\n\n System.out.println(e1.getMessage());\n\n }\n\n\n\n try{\n\n /*\n\n * Call org.alljoyn.About.GetObjectDescription method for default language\n\n */\n\n System.out.println(\"--------Calling org.alljoyn.About.GetObjectDescription method--------\");\n\n BusObjectDescription[] objDescription = aboutIntf.GetObjectDescription();\n\n System.out.println(\"ObjectDescriptions:\");\n\n for(BusObjectDescription busObjectDescription : objDescription) {\n\n System.out.println(\"\\tObjectPath = \" + busObjectDescription.path);\n\n for(String allJoynInterface : busObjectDescription.interfaces) {\n\n System.out.println(\"\\t\\tInterface = \" + allJoynInterface);\n\n }\n\n }\n\n } catch(BusException e2) {\n\n System.out.println(e2.getMessage());\n\n }\n\n\n\n try {\n\n /*\n\n * Call org.alljoyn.About.GetAboutData method for default language\n\n */\n\n String defaultLanguage = announceData.get(AboutKeys.ABOUT_DEFAULT_LANGUAGE).getObject(String.class);\n\n System.out.println(\"---------Calling org.alljoyn.About.GetAboutData method for \" + defaultLanguage + \"--------\");\n\n Map<String, Variant> defaultAboutData = aboutIntf.GetAboutData(defaultLanguage);\n\n System.out.println(\"AboutData: for \" + defaultLanguage + \" language\");\n\n printAboutData(defaultAboutData);\n\n\n\n Variant variant = defaultAboutData.get(AboutKeys.ABOUT_SUPPORTED_LANGUAGES);\n\n String[] supportedLangs = variant.getObject(String[].class);\n\n /*\n\n * Call org.alljoyn.About.GetAboutData method for supported languages\n\n */\n\n for (String lang: supportedLangs) {\n\n if (!lang.equals(defaultLanguage)) {\n\n System.out.println(\"---------Calling org.alljoyn.About.GetAboutData method for \" + lang + \"--------\");\n\n Map<String, Variant> aboutData = aboutIntf.GetAboutData(lang);\n\n System.out.println(\"AboutData: for \" + lang + \" language\");\n\n printAboutData(aboutData);\n\n }\n\n }\n\n\n\n } catch(BusException e3) {\n\n System.out.println(e3.getMessage());\n\n }\n\n status = mBusAttachment.leaveSession(sessionId.value);\n\n if (Status.OK == status) {\n\n System.out.println(\"left session with: \\\"\" + serviceName + \"\\\" SessionId: \\\"\" + sessionId.value +\"\\\"\");\n\n }\n\n }\n", "file_path": "services/about/java/samples/java/AboutClientSample/src/org/alljoyn/about/sample/DeviceAnnouncementHandler.java", "rank": 15, "score": 321821.6788206335 }, { "content": "class AsyncSessionJoiner : public ajn::BusAttachment::JoinSessionAsyncCB {\n\n\n\n public:\n\n /**\n\n * Constructor\n\n * @param name\n\n * @param callback\n\n */\n\n AsyncSessionJoiner(const char* name, SessionJoinedCallback callback = 0);\n\n\n\n /**\n\n * destructor\n\n */\n\n virtual ~AsyncSessionJoiner();\n\n\n\n /**\n\n * JoinSessionCB\n\n * @param status\n\n * @param id\n\n * @param opts\n", "file_path": "services/config/cpp/samples/ConfigClientSample/AsyncSessionJoiner.h", "rank": 16, "score": 317848.070833551 }, { "content": " @Deprecated\n", "file_path": "services/about/java/src/org/alljoyn/services/common/BusObjectDescription.java", "rank": 17, "score": 312621.30235521914 }, { "content": "class AJNSessionListenerImpl : public ajn::SessionListener {\n\n protected:\n\n __weak AJNBusAttachment* busAttachment;\n\n\n\n /**\n\n * Objective C delegate called when one of the below virtual functions\n\n * is called.\n\n */\n\n __weak id<AJNSessionListener> m_delegate;\n\n\n\n public:\n\n /**\n\n * Constructor for the AJN session listener implementation.\n\n *\n\n * @param aBusAttachment Objective C bus attachment wrapper object.\n\n * @param aDelegate Objective C delegate called when one of the below virtual functions is called.\n\n */\n\n AJNSessionListenerImpl(AJNBusAttachment* aBusAttachment, id<AJNSessionListener> aDelegate);\n\n\n\n /**\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionListenerImpl.h", "rank": 18, "score": 311818.82364210486 }, { "content": " @Deprecated\n", "file_path": "services/config/java/src/org/alljoyn/services/common/BusObjectDescription.java", "rank": 19, "score": 309335.62614550075 }, { "content": "class MyBusListener : public BusListener, public SessionPortListener {\n\n\n\n public:\n\n MyBusListener() : BusListener() { }\n\n\n\n bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts);\n\n\n\n};\n\n\n\n/* Auth Listener */\n", "file_path": "alljoyn_core/unit_test/ServiceSetup.h", "rank": 20, "score": 303384.6273910875 }, { "content": "class AJNApplicationStateListenerImpl : public ajn::ApplicationStateListener {\n\n protected:\n\n /**\n\n * Objective C delegate called when one of the below virtual functions\n\n * is called.\n\n */\n\n __weak id<AJNApplicationStateListener> m_delegate;\n\n\n\n public:\n\n /**\n\n * Constructor for the AJNApplicationStateListener implementation.\n\n *\n\n * @param aDelegate Objective C delegate called when one of the below virtual functions is called.\n\n */\n\n AJNApplicationStateListenerImpl(id<AJNApplicationStateListener> aDelegate);\n\n\n\n /**\n\n * Virtual destructor for derivable class.\n\n */\n\n virtual ~AJNApplicationStateListenerImpl();\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNApplicationStateListenerImpl.h", "rank": 21, "score": 303279.0651083387 }, { "content": " int sessionId;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/AboutListenerTest.java", "rank": 22, "score": 300522.25056413794 }, { "content": "class SessionPortListener : public ajn::SessionPortListener {\n\n public:\n\n\n", "file_path": "alljoyn_js/jni/BusAttachmentHost.cc", "rank": 23, "score": 299968.6799825398 }, { "content": "class AboutClientSessionListener : public ajn::SessionListener {\n\n public:\n\n AboutClientSessionListener(qcc::String inServiceName);\n\n\n\n virtual ~AboutClientSessionListener();\n\n\n\n void SessionLost(ajn::SessionId sessionId, ajn::SessionListener::SessionLostReason reason);\n\n\n\n private:\n\n\n\n qcc::String serviceName;\n\n\n\n};\n\n\n\n#endif /* ABOUTCLIENTSESSIONLISTENER_H_ */\n\n\n", "file_path": "services/about/cpp/samples/AboutClientSample/AboutClientSessionListener.h", "rank": 24, "score": 298531.8152308282 }, { "content": " @Override\n\n public void addBusObjectAnnouncements(List<BusObjectDescription> descriptions)\n\n {\n\n m_ObjectDescriptions.addAll(descriptions);\n", "file_path": "services/about/java/src/org/alljoyn/about/AboutServiceImpl.java", "rank": 25, "score": 298213.77727848035 }, { "content": "class SessionPortListenerCallbackC : public SessionPortListener {\n\n public:\n\n SessionPortListenerCallbackC(const alljoyn_sessionportlistener_callbacks* in_callbacks, const void* in_context)\n\n {\n\n QCC_DbgTrace((\"%s\", __FUNCTION__));\n\n memcpy(&callbacks, in_callbacks, sizeof(alljoyn_sessionportlistener_callbacks));\n\n context = in_context;\n\n }\n\n\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts)\n\n {\n\n QCC_DbgTrace((\"%s\", __FUNCTION__));\n\n QCC_BOOL ret = SessionPortListener::AcceptSessionJoiner(sessionPort, joiner, opts) ? QCC_TRUE : QCC_FALSE;\n\n if (callbacks.accept_session_joiner != NULL) {\n\n if (!DeferredCallback::sMainThreadCallbacksOnly) {\n\n ret = callbacks.accept_session_joiner(context, sessionPort, joiner, (alljoyn_sessionopts)(&opts));\n\n } else {\n\n DeferredCallback_4<QCC_BOOL, const void*, SessionPort, const char*, alljoyn_sessionopts>* dcb =\n\n new DeferredCallback_4<QCC_BOOL, const void*, SessionPort, const char*, alljoyn_sessionopts>(callbacks.accept_session_joiner, context, sessionPort, joiner, (alljoyn_sessionopts)(&opts));\n\n ret = DEFERRED_CALLBACK_EXECUTE(dcb);\n", "file_path": "alljoyn_c/src/SessionPortListener.cc", "rank": 26, "score": 298011.3917419807 }, { "content": "\n\n /**\n\n * Called by the bus when a session has been successfully joined. The session is now fully up.\n\n *\n\n * This callback is only used by session creators. Therefore it is only called on listeners\n\n * passed to BusAttachment::BindSessionPort.\n\n *\n\n * @param sessionPort Session port that was joined.\n\n * @param sessionId Id of session.\n\n * @param joiner Unique name of the joiner.\n\n */\n\n virtual void SessionJoined(ajn::SessionPort sessionPort, ajn::SessionId sessionId, const char* joiner);\n\n\n\n\n\n /**\n\n * Accessor for Objective-C delegate.\n\n *\n\n * return delegate The Objective-C delegate called to handle the above event methods.\n\n */\n\n id<AJNSessionPortListener> getDelegate();\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionPortListenerImpl.h", "rank": 27, "score": 296101.1162275686 }, { "content": " AJNSessionPortListenerImpl(AJNBusAttachment* aBusAttachment, id<AJNSessionPortListener> aDelegate);\n\n\n\n /**\n\n * Virtual destructor for derivable class.\n\n */\n\n virtual ~AJNSessionPortListenerImpl();\n\n\n\n /**\n\n * Accept or reject an incoming JoinSession request. The session does not exist until this\n\n * after this function returns.\n\n *\n\n * This callback is only used by session creators. Therefore it is only called on listeners\n\n * passed to BusAttachment::BindSessionPort.\n\n *\n\n * @param sessionPort Session port that was joined.\n\n * @param joiner Unique name of potential joiner.\n\n * @param opts Session options requested by the joiner.\n\n * @return Return true if JoinSession request is accepted. false if rejected.\n\n */\n\n virtual bool AcceptSessionJoiner(ajn::SessionPort sessionPort, const char* joiner, const ajn::SessionOpts& opts);\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionPortListenerImpl.h", "rank": 28, "score": 296094.9925792182 }, { "content": "\n\n /**\n\n * Mutator for Objective-C delegate.\n\n *\n\n * @param delegate The Objective-C delegate called to handle the above event methods.\n\n */\n\n void setDelegate(id<AJNSessionPortListener> delegate);\n\n};\n\n\n\ninline id<AJNSessionPortListener> AJNSessionPortListenerImpl::getDelegate()\n\n{\n\n return m_delegate;\n\n}\n\n\n\ninline void AJNSessionPortListenerImpl::setDelegate(id<AJNSessionPortListener> delegate)\n\n{\n\n m_delegate = delegate;\n\n}\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionPortListenerImpl.h", "rank": 29, "score": 296070.1372516573 }, { "content": "// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n\n// WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE\n\n// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n\n// DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n\n// PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n\n// PERFORMANCE OF THIS SOFTWARE.\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\n#import <Foundation/Foundation.h>\n\n#import <alljoyn/SessionPortListener.h>\n\n#import <alljoyn/TransportMask.h>\n\n#import \"AJNBusListener.h\"\n\n#import \"AJNBusAttachment.h\"\n\n\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionPortListenerImpl.h", "rank": 30, "score": 296050.88355035346 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n// Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source\n\n// Project (AJOSP) Contributors and others.\n\n//\n\n// SPDX-License-Identifier: Apache-2.0\n\n//\n\n// All rights reserved. This program and the accompanying materials are\n\n// made available under the terms of the Apache License, Version 2.0\n\n// which accompanies this distribution, and is available at\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Copyright (c) Open Connectivity Foundation and Contributors to AllSeen\n\n// Alliance. All rights reserved.\n\n//\n\n// Permission to use, copy, modify, and/or distribute this software for\n\n// any purpose with or without fee is hereby granted, provided that the\n\n// above copyright notice and this permission notice appear in all\n\n// copies.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNSessionPortListenerImpl.h", "rank": 31, "score": 296015.15322204144 }, { "content": "- (id)initWithVersion:(uint16_t)version port:(uint16_t)port busName:(NSString *)busName objectDescriptions:(NSMutableDictionary *)objectDescs aboutData:(NSMutableDictionary **)aboutData __deprecated;\n", "file_path": "services/about/ios/inc/alljoyn/about/AJNAnnouncement.h", "rank": 32, "score": 294964.94741872593 }, { "content": "class BasicClient: NSObject, AJNBusListener, AJNSessionListener, AJNJoinSessionDelegate {\n\n\n\n weak var delegate: BasicClientDelegate?\n\n\n\n private let joinedSessionCondition = NSCondition()\n\n private var bus: AJNBusAttachment?\n\n private var sessionId: AJNSessionId?\n\n private var foundServiceName: String?\n\n private var wasNameAlreadyFound = false\n\n private var clientQueue = DispatchQueue(label: \"org.alljoyn.swift.BasicClient.ClientQueue\")\n\n private var lockQueue = DispatchQueue(label: \"org.alljoyn.swift.BasicClient.LockQueue\")\n\n\n\n func sendHelloMessage() {\n\n clientQueue.async {\n\n self.wasNameAlreadyFound = false\n\n self.run()\n\n }\n\n }\n\n\n\n func run() {\n", "file_path": "alljoyn_objc/samples/iOS/Swift/BasicClient/BasicClient/BasicClient.swift", "rank": 33, "score": 293754.370759628 }, { "content": "class SessionListenerImpl : public ajn::SessionListener {\n\n public:\n\n /**\n\n * SessionListenerImpl\n\n * @param inServiceNAme\n\n */\n\n SessionListenerImpl(qcc::String const& inServiceNAme);\n\n\n\n /**\n\n * destructor\n\n */\n\n virtual ~SessionListenerImpl();\n\n\n\n /**\n\n * SessionLost\n\n * @param sessionId\n\n * @param reason\n\n */\n\n void SessionLost(ajn::SessionId sessionId, ajn::SessionListener::SessionLostReason reason);\n\n\n\n private:\n\n\n\n qcc::String serviceName;\n\n\n\n};\n\n\n\n#endif /* SESSIONLISTENERIMPL_H_ */\n\n\n", "file_path": "services/config/cpp/samples/ConfigClientSample/SessionListenerImpl.h", "rank": 34, "score": 291620.36618557794 }, { "content": "static const AJNInterfacePropertyAnnotationFlags kAJNInterfacePropertyEmitChangedSignalConst = 4;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNInterfaceMember.h", "rank": 35, "score": 286145.39092651405 }, { "content": "@class AJNInterfaceDescription;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNBusObject.h", "rank": 36, "score": 286102.3935360234 }, { "content": " public int sessionId;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/AboutProxyTest.java", "rank": 37, "score": 286087.9731392142 }, { "content": "class _SessionOptsInterface : public ScriptableObject {\n\n public:\n\n static std::map<qcc::String, int32_t>& Constants();\n\n _SessionOptsInterface(Plugin& plugin);\n\n virtual ~_SessionOptsInterface();\n\n\n\n private:\n\n static std::map<qcc::String, int32_t> constants;\n\n};\n\n\n\ntypedef qcc::ManagedObj<_SessionOptsInterface> SessionOptsInterface;\n\n\n\n#endif // _SESSIONOPTSINTERFACE_H\n", "file_path": "alljoyn_js/jni/SessionOptsInterface.h", "rank": 38, "score": 285280.46885034046 }, { "content": "class MySessionPortListener : public SessionPortListener {\n\n bool AcceptSessionJoiner(ajn::SessionPort sessionPort, const char* joiner, const ajn::SessionOpts& opts)\n\n {\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n\n\n if (sessionPort != ASSIGNED_SESSION_PORT) {\n\n printf(\"Rejecting join attempt on unexpected session port %d\\n\", sessionPort);\n\n return false;\n\n }\n\n return true;\n\n }\n\n void SessionJoined(SessionPort sessionPort, SessionId id, const char* joiner)\n\n {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n\n\n printf(\"Session Joined SessionId = %u\\n\", id);\n\n }\n\n};\n\n\n", "file_path": "alljoyn_core/samples/about/AboutService.cc", "rank": 39, "score": 284600.1792538432 }, { "content": "class SessionJoinedSessionPortListener : public SessionPortListener {\n\n\n\n private:\n\n /* Private assigment operator - does nothing */\n\n SessionJoinedSessionPortListener& operator=(const SessionJoinedSessionPortListener&);\n\n\n\n BusAttachment& bus;\n\n SessionListener*sl;\n\n\n\n\n\n\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n\n\n sessionJoinerAcceptedFlag = true;\n\n return true;\n\n }\n\n virtual void SessionJoined(SessionPort sessionPort, SessionId id, const char* joiner) {\n", "file_path": "alljoyn_core/unit_test/SessionTest.cc", "rank": 40, "score": 283183.9581309152 }, { "content": "class JoinSession_SessionPortListener : public SessionPortListener, SessionListener {\n\n public:\n\n JoinSession_SessionPortListener(BusAttachment* bus) : bus(bus) { };\n\n\n\n bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n\n\n if (sessionPort == 42) {\n\n sessionAccepted = true;\n\n bus->EnableConcurrentCallbacks();\n\n return true;\n\n } else {\n\n sessionAccepted = false;\n\n return false;\n\n }\n\n }\n\n\n\n void SessionLost(SessionId id, SessionListener::SessionLostReason reason) {\n\n QCC_UNUSED(id);\n", "file_path": "alljoyn_core/unit_test/BusAttachmentTest.cc", "rank": 41, "score": 282111.13776820473 }, { "content": "@class AJNInterfaceMember;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNProxyBusObject.h", "rank": 42, "score": 281576.19931048964 }, { "content": "@class AJNInterfaceDescription;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNProxyBusObject.h", "rank": 43, "score": 281426.27762807725 }, { "content": " public int sessionId;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/AboutIconProxyTest.java", "rank": 44, "score": 279953.4449723898 }, { "content": "class AnnounceListenerTestSessionPortListener : public SessionPortListener {\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n return true;\n\n }\n\n};\n\n\n\n\n", "file_path": "alljoyn_core/unit_test/AboutListenerTest.cc", "rank": 45, "score": 279804.3673016026 }, { "content": " class JoinSessionThread extends Thread {\n\n JoinSessionThread(String serviceName, short port, Map<String, Variant> announceData) {\n\n mServiceName = serviceName;\n\n mPort = port;\n\n mAnnounceData = announceData;\n\n }\n\n public void run() {\n\n attemptToJoinSession(mServiceName, mPort, mAnnounceData);\n\n }\n\n String mServiceName;\n\n short mPort;\n\n Map<String, Variant> mAnnounceData;\n", "file_path": "services/about/java/samples/java/AboutClientSample/src/org/alljoyn/about/sample/DeviceAnnouncementHandler.java", "rank": 46, "score": 279616.95965199417 }, { "content": "@interface AJNAboutObjectDescription : AJNObject\n\n\n\n/**\n\n * Get a list of the paths that are added to this AboutObjectDescription.\n\n * @return paths found in the AboutObjectDescription\n\n */\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNAboutObjectDescription.h", "rank": 47, "score": 279433.52547042625 }, { "content": " Map<String, Variant> mAnnounceData;\n", "file_path": "services/about/java/samples/java/AboutClientSample/src/org/alljoyn/about/sample/DeviceAnnouncementHandler.java", "rank": 48, "score": 278552.19510551286 }, { "content": "class BindMemberSessionPortListener : public SessionPortListener {\n\n public:\n\n BindMemberSessionPortListener(BusAttachment* bus, BindMemberSessionListenerA* bindMemberSessionListener) :\n\n bus(bus),\n\n sessionListener(bindMemberSessionListener) { }\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n\n\n sessionJoinerAcceptedFlag = true;\n\n return true;\n\n }\n\n virtual void SessionJoined(SessionPort sessionPort, SessionId id, const char* joiner) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n\n\n bindMemberSessionId = id;\n\n sessionJoinedFlag = true;\n\n QStatus status = bus->SetSessionListener(id, sessionListener);\n\n EXPECT_EQ(ER_OK, status);\n\n }\n\n BusAttachment* bus;\n\n BindMemberSessionListenerA* sessionListener;\n\n};\n\n\n", "file_path": "alljoyn_core/unit_test/SessionTest.cc", "rank": 49, "score": 278324.91121574095 }, { "content": "@protocol AJNBusObject<AJNHandle>\n\n\n\n/**\n\n * Return the path for the object\n\n *\n\n * @return Object path\n\n */\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNBusObject.h", "rank": 50, "score": 277311.61240903585 }, { "content": "class SessionJoinedListenerNative : public NativeObject {\n\n public:\n\n SessionJoinedListenerNative(Plugin& plugin, NPObject* objectValue);\n\n virtual ~SessionJoinedListenerNative();\n\n\n\n void onJoined(ajn::SessionPort port, ajn::SessionId id, const qcc::String& joiner);\n\n};\n\n\n\n#endif // _SESSIONJOINEDLISTENERNATIVE_H\n", "file_path": "alljoyn_js/jni/SessionJoinedListenerNative.h", "rank": 51, "score": 277248.5851079859 }, { "content": "@interface AJNInterfaceProperty : AJNObject\n\n\n\n/** Name of the property */\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNInterfaceProperty.h", "rank": 52, "score": 277046.586994512 }, { "content": "@protocol AJNServiceDelegate <AJNBusControllerDelegate>\n\n\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNServiceController.h", "rank": 53, "score": 276545.84907169134 }, { "content": " public void run() {\n\n attemptToJoinSession(mServiceName, mPort, mAnnounceData);\n", "file_path": "services/about/java/samples/java/AboutClientSample/src/org/alljoyn/about/sample/DeviceAnnouncementHandler.java", "rank": 54, "score": 276063.19587232673 }, { "content": " public void sessionMemberAdded(int sessionId, String uniqueName) {\n\n sessionMemberAddedFlagA = true;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/BusAttachmentTest.java", "rank": 55, "score": 275540.72779271664 }, { "content": " public void sessionMemberRemoved(int sessionId, String uniqueName) {\n\n sessionMemberRemovedFlagA = true;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/BusAttachmentTest.java", "rank": 56, "score": 275540.72779271664 }, { "content": " private int mSessionId = 0;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocMethodsClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 57, "score": 274792.52147756726 }, { "content": "- (QStatus)setLinkTimeoutAsync:(uint32_t)timeout forSession:(AJNSessionId)sessionId completionBlock:(AJNLinkTimeoutBlock) block context:(void *)context;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNBusAttachment.h", "rank": 58, "score": 273248.05160177976 }, { "content": "- (void)didJoinInSession:(AJNSessionId)sessionId withService:(NSString *)serviceName;\n", "file_path": "alljoyn_objc/AllJoynFramework/AllJoynFramework/include/AJNClientController.h", "rank": 59, "score": 273248.05160177976 }, { "content": "struct SessionJoinerContext {\n\n qcc::String busName;\n\n AboutClientSessionListener* aboutClientSessionListener;\n\n\n\n SessionJoinerContext(qcc::String name, AboutClientSessionListener* absl) :\n\n busName(name), aboutClientSessionListener(absl) { }\n\n};\n\n\n", "file_path": "services/about/cpp/samples/AboutClientSample/AboutClientSessionJoiner.h", "rank": 60, "score": 273226.5567859194 }, { "content": "class IpNameServiceListener {\n\n public:\n\n virtual ~IpNameServiceListener() { }\n\n virtual bool QueryHandler(TransportMask transport, MDNSPacket query, const qcc::IPEndpoint& src, const qcc::IPEndpoint& dst) {\n\n QCC_UNUSED(transport);\n\n QCC_UNUSED(query);\n\n QCC_UNUSED(src);\n\n QCC_UNUSED(dst);\n\n return false;\n\n }\n\n virtual bool ResponseHandler(TransportMask transport, MDNSPacket response, uint16_t recvPort) {\n\n QCC_UNUSED(transport);\n\n QCC_UNUSED(response);\n\n QCC_UNUSED(recvPort);\n\n return false;\n\n }\n\n};\n\n\n\n/**\n\n * @brief API to provide an implementation dependent IP (Layer 3) Name Service\n", "file_path": "alljoyn_core/router/ns/IpNameService.h", "rank": 61, "score": 271860.85526184225 }, { "content": " public int getSessionId() {\n\n return mSessionId;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocMethodsClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 62, "score": 271847.63053241855 }, { "content": " private int mSessionId = 0;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocIntrospectWithDescriptionClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 63, "score": 271754.08032604575 }, { "content": " public void sessionJoined(short sessionPort, int id, String joiner) {}\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/SecurityApplicationProxyTest.java", "rank": 64, "score": 270378.46623088676 }, { "content": "class AcceptSessionJoinerListenerNative : public NativeObject {\n\n public:\n\n AcceptSessionJoinerListenerNative(Plugin& plugin, NPObject* objectValue);\n\n virtual ~AcceptSessionJoinerListenerNative();\n\n\n\n bool onAccept(ajn::SessionPort port, const qcc::String& joiner, SessionOptsHost& opts);\n\n};\n\n\n\n#endif // _ACCEPTSESSIONJOINERLISTENERNATIVE_H\n", "file_path": "alljoyn_js/jni/AcceptSessionJoinerListenerNative.h", "rank": 65, "score": 269848.0955506684 }, { "content": "class SessionMemberAddedListenerNative : public NativeObject {\n\n public:\n\n SessionMemberAddedListenerNative(Plugin& plugin, NPObject* objectValue);\n\n virtual ~SessionMemberAddedListenerNative();\n\n\n\n void onMemberAdded(ajn::SessionId id, const qcc::String& uniqueName);\n\n};\n\n\n\n#endif // _SESSIONMEMBERADDEDLISTENERNATIVE_H\n", "file_path": "alljoyn_js/jni/SessionMemberAddedListenerNative.h", "rank": 66, "score": 269836.77639379096 }, { "content": "class SessionMemberRemovedListenerNative : public NativeObject {\n\n public:\n\n SessionMemberRemovedListenerNative(Plugin& plugin, NPObject* objectValue);\n\n virtual ~SessionMemberRemovedListenerNative();\n\n\n\n void onMemberRemoved(ajn::SessionId id, const qcc::String& uniqueName);\n\n};\n\n\n\n#endif // _SESSIONMEMBERREMOVEDLISTENERNATIVE_H\n", "file_path": "alljoyn_js/jni/SessionMemberRemovedListenerNative.h", "rank": 67, "score": 269836.77639379096 }, { "content": "class BindSessionPortCallbackContext : public CallbackContext {\n\n public:\n\n ajn::SessionPort port;\n\n BindSessionPortCallbackContext(CallbackNative* callbackNative, QStatus status, ajn::SessionPort port) :\n\n CallbackContext(callbackNative, status),\n\n port(port) { }\n\n};\n\n\n\nvoid CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, ajn::SessionPort port)\n\n{\n\n PluginData::Callback callback(plugin, _BindSessionPortCallbackCB);\n\n callback->context = new BindSessionPortCallbackContext(callbackNative, status, port);\n\n PluginData::DispatchCallback(callback);\n\n}\n\n\n\nvoid CallbackNative::_BindSessionPortCallbackCB(PluginData::CallbackContext* ctx)\n\n{\n\n BindSessionPortCallbackContext* context = static_cast<BindSessionPortCallbackContext*>(ctx);\n\n context->callbackNative->onCallback(context->status, context->port);\n\n}\n\n\n", "file_path": "alljoyn_js/jni/CallbackNative.cc", "rank": 68, "score": 269337.0019873697 }, { "content": " public int getSessionId() {\n\n return mSessionId;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocIntrospectWithDescriptionClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 69, "score": 268876.0356088272 }, { "content": " public void sessionJoined(short sessionPort, int id, String joiner) {}\n", "file_path": "alljoyn_java/src/org/alljoyn/bus/SessionPortListener.java", "rank": 70, "score": 268343.876779462 }, { "content": "class BindMemberJoinSessionAsyncCB : public ajn::BusAttachment::JoinSessionAsyncCB {\n\n public:\n\n virtual void JoinSessionCB(QStatus status, SessionId sessionId, const SessionOpts& opts, void* context) {\n\n QCC_UNUSED(sessionId);\n\n QCC_UNUSED(opts);\n\n QCC_UNUSED(context);\n\n\n\n EXPECT_EQ(ER_OK, status);\n\n sessionJoinedCBFlag = true;\n\n }\n\n};\n\nTEST_F(SessionTest, BindMemberAddedRemoved) {\n\n QStatus status = ER_FAIL;\n\n /* make sure global flags are initialized */\n\n sessionMemberAddedFlagA = false;\n\n sessionMemberRemovedFlagA = false;\n\n sessionMemberAddedFlagB = false;\n\n sessionMemberRemovedFlagB = false;\n\n sessionMemberAddedFlagC = false;\n\n sessionMemberRemovedFlagC = false;\n", "file_path": "alljoyn_core/unit_test/SessionTest.cc", "rank": 71, "score": 268221.9742260587 }, { "content": " public boolean isConnected() {\n\n return mIsConnected;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocMethodsClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 72, "score": 268041.65550288593 }, { "content": " private boolean mIsConnected = false;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocMethodsClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 73, "score": 268041.65550288593 }, { "content": " public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts opts) {\n\n return true;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/SecurityApplicationProxyTest.java", "rank": 74, "score": 266805.9759365538 }, { "content": " static int sessionId;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocMethodsService/src/org/alljoyn/bus/samples/Service.java", "rank": 75, "score": 265242.0371739067 }, { "content": " public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts opts) {return false;}\n", "file_path": "alljoyn_java/src/org/alljoyn/bus/SessionPortListener.java", "rank": 76, "score": 265193.61697020347 }, { "content": " public boolean isConnected() {\n\n return mIsConnected;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocIntrospectWithDescriptionClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 77, "score": 264872.6062592003 }, { "content": " private boolean mIsConnected = false;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocIntrospectWithDescriptionClient/src/org/alljoyn/bus/samples/SampleOnJoinSessionListener.java", "rank": 78, "score": 264872.6062592003 }, { "content": "class RemoveSessionMemberBusAListener : public SessionPortListener, public SessionListener {\n\n public:\n\n RemoveSessionMemberBusAListener(BusAttachment* bus) : bus(bus) {\n\n }\n\n\n\n virtual bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n sessionJoinerAcceptedFlag = true;\n\n return true;\n\n }\n\n virtual void SessionJoined(SessionPort sessionPort, SessionId id, const char* joiner) {\n\n QCC_UNUSED(sessionPort);\n\n\n\n bindMemberSessionId = id;\n\n sessionJoinedTestJoiner = joiner;\n\n sessionJoinedFlag = true;\n\n ++sessionJoinedCounter;\n\n EXPECT_EQ(ER_OK, bus->SetHostedSessionListener(id, this));\n", "file_path": "alljoyn_core/unit_test/SessionTest.cc", "rank": 79, "score": 264765.3941336497 }, { "content": "class MyBusListener : public BusListener, public SessionPortListener, public SessionListener {\n\n public:\n\n\n\n MyBusListener(JavaVM* vm, jobject& jobj) : vm(vm), jobj(jobj), _id(0) { }\n\n\n\n void NameOwnerChanged(const char* busName, const char* previousOwner, const char* newOwner)\n\n {\n\n }\n\n\n\n /* Accept an incoming JoinSession request */\n\n bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts)\n\n {\n\n if (sessionPort != SESSION_PORT) {\n\n LOGE(\"Rejecting join attempt on non-chat session port %d\\n\", sessionPort);\n\n return false;\n\n }\n\n\n\n LOGD(\"Accepting join session request from %s (opts.proximity=%x, opts.traffic=%x, opts.transports=%x)\\n\",\n\n joiner, opts.proximity, opts.traffic, opts.transports);\n\n\n", "file_path": "alljoyn_core/samples/simple/android/service/jni/Service_jni.cpp", "rank": 80, "score": 263529.8905985035 }, { "content": " public void sessionJoined(short sessionPort, int id, String joiner) {}\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/SecurityProxyBusObjectTest.java", "rank": 81, "score": 263136.87386225443 }, { "content": " private native void create();\n", "file_path": "alljoyn_java/src/org/alljoyn/bus/SessionPortListener.java", "rank": 82, "score": 263023.1127368889 }, { "content": " private native void create();\n", "file_path": "alljoyn_java/src/org/alljoyn/bus/OnJoinSessionListener.java", "rank": 83, "score": 263014.03204567917 }, { "content": " static int sessionId;\n", "file_path": "alljoyn_java/samples/java/JavaSDKDoc/JavaSDKDocIntrospectWithDescriptionService/src/org/alljoyn/bus/samples/Service.java", "rank": 84, "score": 262409.73421092366 }, { "content": " int sessionId;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/AboutDataCheckTest.java", "rank": 85, "score": 262347.08496037254 }, { "content": " @Override\n\n public void sessionJoined(short sessionPort, int id, String joiner) {\n\n sessionJoinedFlag = true;\n\n bus.setSessionListener(id, new SessionListener() {\n\n public void sessionLost(final int sessionId, int reason) {\n\n sessionLostFlagA = true;\n\n }\n\n public void sessionMemberAdded(int sessionId, String uniqueName) {\n\n sessionMemberAddedFlagA = true;\n\n }\n\n public void sessionMemberRemoved(int sessionId, String uniqueName) {\n\n sessionMemberRemovedFlagA = true;\n\n }\n\n });\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/BusAttachmentTest.java", "rank": 86, "score": 262067.03521314063 }, { "content": " public void sessionLost(final int sessionId, int reason) {\n\n sessionLostFlagA = true;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/BusAttachmentTest.java", "rank": 87, "score": 260962.736233726 }, { "content": " public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts opts) {\n\n return true;\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/SecurityProxyBusObjectTest.java", "rank": 88, "score": 259756.11883304664 }, { "content": " short port;\n", "file_path": "services/config/java/samples/java/ConfigClientSample/src/org/alljoyn/config/samples/configclient/ConfigApplication.java", "rank": 89, "score": 259108.82335958473 }, { "content": " @Deprecated\n", "file_path": "services/about/java/src/org/alljoyn/services/common/BusObjectDescription.java", "rank": 90, "score": 258626.5467604007 }, { "content": " @Override\n\n public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts sessionOpts) {\n\n if (sessionPort == 42) {\n\n sessionAccepted = true;\n\n return true;\n\n } else {\n\n sessionAccepted = false;\n\n return false;\n\n }\n", "file_path": "alljoyn_java/test/org/alljoyn/bus/BusAttachmentTest.java", "rank": 91, "score": 258546.07024760763 }, { "content": " UUID appId;\n", "file_path": "services/config/java/samples/java/ConfigClientSample/src/org/alljoyn/config/samples/configclient/ConfigApplication.java", "rank": 92, "score": 256226.7933274436 }, { "content": "class Service : public App, private SessionPortListener, private SessionListener {\n\n public:\n\n Service(BusAttachment& bus);\n\n ~Service();\n\n\n\n private:\n\n BusAttachment& bus;\n\n multimap<SessionId, BusObject*> objects;\n\n SessionPort port;\n\n\n\n void Add(SessionId id, bool autoUpdate);\n\n\n\n // SessionPortListener methods\n\n bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n\n return true;\n\n }\n\n void SessionJoined(SessionPort sessionPort, SessionId id, const char* joiner);\n", "file_path": "alljoyn_core/test/proptester.cc", "rank": 93, "score": 256130.49228565392 }, { "content": "class Service : public App, private SessionPortListener, private SessionListener {\n\n public:\n\n Service(BusAttachment& bus, int nbrOfObjects);\n\n ~Service();\n\n\n\n void Execute(uint64_t timeToRun);\n\n\n\n private:\n\n BusAttachment& bus;\n\n int nbrOfObjects;\n\n multimap<SessionId, PropTesterObject*> objects;\n\n SessionPort port;\n\n\n\n void Add(SessionId id, uint32_t number);\n\n\n\n // SessionPortListener methods\n\n bool AcceptSessionJoiner(SessionPort sessionPort, const char* joiner, const SessionOpts& opts) {\n\n QCC_UNUSED(sessionPort);\n\n QCC_UNUSED(joiner);\n\n QCC_UNUSED(opts);\n", "file_path": "alljoyn_core/test/propstresstest.cc", "rank": 94, "score": 256130.49228565392 }, { "content": " @Deprecated\n\n public String getPath()\n\n {\n\n return path;\n", "file_path": "services/about/java/src/org/alljoyn/services/common/BusObjectDescription.java", "rank": 95, "score": 255638.41753945046 }, { "content": " */\n\n void shutdown();\n\n\n\n /* From About */\n\n void Announce(unsigned short version, unsigned short port, const char* busName,\n\n const ajn::services::AboutClient::ObjectDescriptions& objectDescs,\n\n const ajn::services::AboutClient::AboutData& aboutData);\n\n\n\n void EventHandler(const ajn::InterfaceDescription::Member* member, const char* srcPath, ajn::Message& msg);\n\n\n\n /* For MethodCallAsync */\n\n void AsyncCallReplyHandler(ajn::Message& msg, void* context);\n\n\n\n /* From SessionListener */\n\n virtual void SessionLost(ajn::SessionId sessionId, ajn::SessionListener::SessionLostReason reason);\n\n\n\n /** JoinSessionAsync callback */\n\n virtual void JoinSessionCB(QStatus status, ajn::SessionId sessionId, const ajn::SessionOpts& opts, void* context);\n\n\n\n private:\n", "file_path": "alljoyn_core/samples/eventaction/Android_test_tools/Events/jni/MyAllJoynCode.h", "rank": 96, "score": 129.8947158802489 }, { "content": "using namespace std;\n\nusing namespace qcc;\n\nusing namespace ajn;\n\n\n\n/** Static top level message bus object */\n\nstatic BusAttachment* s_msgBus = nullptr;\n\n\n\nstatic const char* INTERFACE_NAME = \"org.alljoyn.Bus.signal_sample\";\n\nstatic const char* SERVICE_NAME = \"org.alljoyn.Bus.signal_sample\";\n\nstatic const char* SERVICE_PATH = \"/\";\n\nstatic const SessionPort SERVICE_PORT = 25;\n\n\n\nstatic volatile sig_atomic_t s_interrupt = false;\n\n\n\nstatic void CDECL_CALL SigIntHandler(int sig)\n\n{\n\n QCC_UNUSED(sig);\n\n s_interrupt = true;\n\n}\n\n\n\nstatic const char* tags[] = { \"en\", \"de\", \"hi\" };\n\nstatic const char* objId = \"obj\";\n\nstatic const char* objDescription[] = { \"This is the object\", \"Es ist das Objekt\", \"Ye Object hai\" };\n\n\n", "file_path": "alljoyn_core/samples/basic/signal_service.cc", "rank": 97, "score": 126.85039777068097 }, { "content": "\n\n bool enableEvent(EventInfo* event);\n\n\n\n /**\n\n * Free up and release the objects used\n\n */\n\n void shutdown();\n\n\n\n /* From About */\n\n void Announced(const char* busName, uint16_t version, ajn::SessionPort port,\n\n const ajn::MsgArg& objectDescriptionArg, const ajn::MsgArg& aboutDataArg);\n\n\n\n void EventHandler(const ajn::InterfaceDescription::Member* member, const char* srcPath, ajn::Message& msg);\n\n\n\n /* For MethodCallAsync */\n\n void AsyncCallReplyHandler(ajn::Message& msg, void* context);\n\n\n\n /* From SessionListener */\n\n virtual void SessionLost(ajn::SessionId sessionId, ajn::SessionListener::SessionLostReason reason);\n\n\n", "file_path": "alljoyn_core/samples/eventaction/Android/jni/event/MyEventCode.h", "rank": 98, "score": 119.06379387901552 }, { "content": " /**\n\n * Setup AllJoyn, creating the objects needed and registering listeners.\n\n *\n\n * @param packageName\tThis value is provided to the BusAttachment constructor to name the application\n\n *\n\n */\n\n void initialize(const char* packageName);\n\n\n\n /**\n\n * Free up and release the objects used\n\n */\n\n void shutdown();\n\n\n\n private:\n\n\n\n /* From About */\n\n void Announced(const char* busName, uint16_t version, ajn::SessionPort port, const ajn::MsgArg& objectDescriptionArg, const ajn::MsgArg& aboutDataArg);\n\n\n\n /* From SessionPortListener */\n\n virtual bool AcceptSessionJoiner(ajn::SessionPort sessionPort, const char* joiner, const ajn::SessionOpts& opts);\n", "file_path": "alljoyn_core/samples/eventaction/SimpleRulesEngine/posix/MyAllJoynCode.h", "rank": 99, "score": 113.43479064180853 } ]
C++
src/Sound/AttenuationShapes.cpp
SparkyStudios/AmplitudeSDK
bcfb9d9c2fcea8ecd3a540576508f062fb3d5e21
#include <Sound/AttenuationShapes.h> #include <SparkyStudios/Audio/Amplitude/Core/Engine.h> #include <SparkyStudios/Audio/Amplitude/Core/Log.h> #include <Core/EngineInternalState.h> namespace SparkyStudios::Audio::Amplitude { AttenuationShape::AttenuationShape() : m_maxAttenuationFactor(1.0f) {} float AttenuationShape::GetAttenuationFactor(const Attenuation*, const hmm_vec3&, const ListenerInternalState*) { return m_maxAttenuationFactor; } float AttenuationShape::GetAttenuationFactor(const Attenuation*, const EntityInternalState*, const ListenerInternalState*) { return m_maxAttenuationFactor; } AttenuationShape* AttenuationShape::Create(const AttenuationShapeDefinition* definition) { if (definition == nullptr) return nullptr; AttenuationShape* shape = nullptr; switch (definition->model()) { default: case AttenuationShapeModel_Default: shape = new AttenuationShape(); break; case AttenuationShapeModel_Cone: shape = new ConeAttenuationShape(definition->settings_as_Cone()); break; case AttenuationShapeModel_Sphere: shape = new SphereAttenuationShape(definition->settings_as_Sphere()); break; case AttenuationShapeModel_Box: shape = new BoxAttenuationShape(definition->settings_as_Box()); break; case AttenuationShapeModel_Capsule: shape = new CapsuleAttenuationShape(definition->settings_as_Capsule()); break; } shape->m_maxAttenuationFactor = definition->max_attenuation_factor(); return shape; } float ConeAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { if (const hmm_vec3& soundToListener = listener->GetLocation() - soundLocation; AM_Length(soundToListener) >= attenuation->GetMaxDistance()) return 0.0f; return 1.0f; } float ConeAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - entity->GetLocation(); const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); const float coneDist = AM_Dot(soundToListener, entity->GetDirection()); if (coneDist < 0.0f || coneDist > _outerHeight) return gain * m_maxAttenuationFactor; if (coneDist > _innerHeight) return gain * AM_Lerp(1.0f, (coneDist - _innerHeight) / (_outerHeight - _innerHeight), m_maxAttenuationFactor); const float innerConeRadius = coneDist / _innerHeight * _innerRadius; const float outerConeRadius = coneDist / _outerHeight * _outerRadius; const float d = AM_Length(soundToListener - coneDist * entity->GetDirection()); if (d <= innerConeRadius) return gain * 1.0f; if (d >= outerConeRadius) return gain * m_maxAttenuationFactor; const float delta = (distance - innerConeRadius) / (outerConeRadius - innerConeRadius); return gain * AM_Lerp(1.0f, AM_CLAMP(delta, 0.0f, 1.0f), m_maxAttenuationFactor); } float ConeAttenuationShape::GetOuterRadius() const { return _outerRadius; } float ConeAttenuationShape::GetInnerRadius() const { return _innerRadius; } float ConeAttenuationShape::GetInnerHeight() const { return _innerHeight; } float ConeAttenuationShape::GetOuterHeight() const { return _outerHeight; } float SphereAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - soundLocation; const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); const float delta = (distance - _innerRadius) / (_outerRadius - _innerRadius); return gain * AM_Lerp(1.0f, AM_CLAMP(delta, 0.0f, 1.0f), m_maxAttenuationFactor); } float SphereAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { return GetAttenuationFactor(attenuation, entity->GetLocation(), listener); } float BoxAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - soundLocation; const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); return gain * _getFactor(soundLocation, listener, AM_Mat4d(1.0f)); } float BoxAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - entity->GetLocation(); const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); return gain * _getFactor(entity->GetLocation(), listener, AM_LookAt(AM_Vec3(0, 0, 0), entity->GetDirection(), entity->GetUp())); } float BoxAttenuationShape::_getFactor(const hmm_vec3& soundLocation, const ListenerInternalState* listener, hmm_mat4 lookAt) { lookAt = AM_Multiply(AM_Translate(soundLocation), lookAt); const hmm_vec3& x = listener->GetLocation(); hmm_vec3 iP1, iP2, iP3, iP4, oP1, oP2, oP3, oP4; switch (amEngine->GetState()->up_axis) { default: case GameEngineUpAxis_Y: iP1 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfHeight, -_innerHalfDepth, 1.0f)).XYZ; iP2 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfHeight, _innerHalfDepth, 1.0f)).XYZ; iP3 = AM_Multiply(lookAt, AM_Vec4(_innerHalfWidth, -_innerHalfHeight, -_innerHalfDepth, 1.0f)).XYZ; iP4 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, _innerHalfHeight, -_innerHalfDepth, 1.0f)).XYZ; oP1 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfHeight, -_outerHalfDepth, 1.0f)).XYZ; oP2 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfHeight, _outerHalfDepth, 1.0f)).XYZ; oP3 = AM_Multiply(lookAt, AM_Vec4(_outerHalfWidth, -_outerHalfHeight, -_outerHalfDepth, 1.0f)).XYZ; oP4 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, _outerHalfHeight, -_outerHalfDepth, 1.0f)).XYZ; break; case GameEngineUpAxis_Z: iP1 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfDepth, -_innerHalfHeight, 1.0f)).XYZ; iP2 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, _innerHalfDepth, -_innerHalfHeight, 1.0f)).XYZ; iP3 = AM_Multiply(lookAt, AM_Vec4(_innerHalfWidth, -_innerHalfDepth, -_innerHalfHeight, 1.0f)).XYZ; iP4 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfDepth, _innerHalfHeight, 1.0f)).XYZ; oP1 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfDepth, -_outerHalfHeight, 1.0f)).XYZ; oP2 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, _outerHalfDepth, -_outerHalfHeight, 1.0f)).XYZ; oP3 = AM_Multiply(lookAt, AM_Vec4(_outerHalfWidth, -_outerHalfDepth, -_outerHalfHeight, 1.0f)).XYZ; oP4 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfDepth, _outerHalfHeight, 1.0f)).XYZ; break; } hmm_vec3 iU = AM_Normalize(iP2 - iP1); hmm_vec3 iV = AM_Normalize(iP3 - iP1); hmm_vec3 iW = AM_Normalize(iP4 - iP1); hmm_vec3 oU = AM_Normalize(oP2 - oP1); hmm_vec3 oV = AM_Normalize(oP3 - oP1); hmm_vec3 oW = AM_Normalize(oP4 - oP1); const float iUX = AM_Dot(iU, x); const float iVX = AM_Dot(iV, x); const float iWX = AM_Dot(iW, x); const float oUX = AM_Dot(oU, x); const float oVX = AM_Dot(oV, x); const float oWX = AM_Dot(oW, x); const float iUP1 = AM_Dot(iU, iP1); const float iVP1 = AM_Dot(iV, iP1); const float iWP1 = AM_Dot(iW, iP1); const float iUP2 = AM_Dot(iU, iP2); const float iVP3 = AM_Dot(iV, iP3); const float iWP4 = AM_Dot(iW, iP4); const float oUP1 = AM_Dot(oU, oP1); const float oVP1 = AM_Dot(oV, oP1); const float oWP1 = AM_Dot(oW, oP1); const float oUP2 = AM_Dot(oU, oP2); const float oVP3 = AM_Dot(oV, oP3); const float oWP4 = AM_Dot(oW, oP4); if (AM_BETWEEN(iUX, iUP1, iUP2) && AM_BETWEEN(iVX, iVP1, iVP3) && AM_BETWEEN(iWX, iWP1, iWP4)) return 1.0f; if (!(AM_BETWEEN(oUX, oUP1, oUP2) && AM_BETWEEN(oVX, oVP1, oVP3) && AM_BETWEEN(oWX, oWP1, oWP4))) return m_maxAttenuationFactor; const float dP1 = HMM_ABS(AM_Dot(x - oP1, AM_Normalize(oP2 - oP1))) / (_outerHalfDepth - _innerHalfDepth); const float dP2 = HMM_ABS(AM_Dot(x - oP2, AM_Normalize(oP1 - oP2))) / (_outerHalfDepth - _innerHalfDepth); const float dP3 = HMM_ABS(AM_Dot(x - oP3, AM_Normalize(oP1 - oP3))) / (_outerHalfWidth - _innerHalfWidth); const float dP4 = HMM_ABS(AM_Dot(x - oP4, AM_Normalize(oP1 - oP4))) / (_outerHalfHeight - _innerHalfHeight); const float dP5 = HMM_ABS(AM_Dot(x - oP1, AM_Normalize(oP3 - oP1))) / (_outerHalfWidth - _innerHalfWidth); const float dP6 = HMM_ABS(AM_Dot(x - oP1, AM_Normalize(oP4 - oP1))) / (_outerHalfHeight - _innerHalfHeight); const float shortestRoad = AM_MIN(dP1, AM_MIN(dP2, AM_MIN(dP3, AM_MIN(dP4, AM_MIN(dP5, dP6))))); return AM_Lerp(m_maxAttenuationFactor, AM_CLAMP(shortestRoad, 0.0f, 1.0f), 1.0f); } float CapsuleAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { return _getFactor(attenuation, soundLocation, listener, AM_Mat4d(1.0f)); } float CapsuleAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { return _getFactor( attenuation, entity->GetLocation(), listener, AM_LookAt(AM_Vec3(0, 0, 0), entity->GetDirection(), entity->GetUp())); } float CapsuleAttenuationShape::_getFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener, hmm_mat4 lookAt) { lookAt = AM_Multiply(AM_Translate(soundLocation), lookAt); const hmm_vec3& x = listener->GetLocation(); const float distanceToOrigin = AM_Length(x - soundLocation); const float innerHalfHeight = _innerHalfHeight - _innerRadius; const float outerHalfHeight = _outerHalfHeight - _outerRadius; hmm_vec3 iA, iB, oA, oB; switch (amEngine->GetState()->up_axis) { default: case GameEngineUpAxis_Y: iA = AM_Multiply(lookAt, AM_Vec4(0.0f, innerHalfHeight, 0.0f, 1.0f)).XYZ; iB = AM_Multiply(lookAt, AM_Vec4(0.0f, -innerHalfHeight, 0.0f, 1.0f)).XYZ; oA = AM_Multiply(lookAt, AM_Vec4(0.0f, outerHalfHeight, 0.0f, 1.0f)).XYZ; oB = AM_Multiply(lookAt, AM_Vec4(0.0f, -outerHalfHeight, 0.0f, 1.0f)).XYZ; break; case GameEngineUpAxis_Z: iA = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, innerHalfHeight, 1.0f)).XYZ; iB = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, -innerHalfHeight, 1.0f)).XYZ; oA = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, outerHalfHeight, 1.0f)).XYZ; oB = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, -outerHalfHeight, 1.0f)).XYZ; break; } hmm_vec3 iE = iB - iA; hmm_vec3 iM = AM_Cross(iA, iB); hmm_vec3 oE = oB - oA; hmm_vec3 oM = AM_Cross(oA, oB); const float iDistanceToAxis = AM_Length(iM + AM_Cross(iE, x)) / AM_Length(iE); const float oDistanceToAxis = AM_Length(oM + AM_Cross(oE, x)) / AM_Length(oE); if (oDistanceToAxis >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(iDistanceToAxis); const float iDistanceToA = AM_Length(x - iA); const float iDistanceToB = AM_Length(x - iB); const float oDistanceToA = AM_Length(x - oA); const float oDistanceToB = AM_Length(x - oB); if (iDistanceToAxis <= _innerRadius && distanceToOrigin <= innerHalfHeight) return gain * 1.0f; if (oDistanceToAxis >= _outerRadius && distanceToOrigin >= outerHalfHeight) return gain * m_maxAttenuationFactor; const float rDelta = 1.0f - (oDistanceToAxis - _innerRadius) / (_outerRadius - _innerRadius); const float hDelta = 1.0f - (distanceToOrigin - _innerHalfHeight) / (_outerHalfHeight - _innerHalfHeight); const float delta = AM_MIN(rDelta, hDelta); return gain * AM_Lerp(m_maxAttenuationFactor, AM_CLAMP(delta, 0.0f, 1.0f), 1.0f); } }
#include <Sound/AttenuationShapes.h> #include <SparkyStudios/Audio/Amplitude/Core/Engine.h> #include <SparkyStudios/Audio/Amplitude/Core/Log.h> #include <Core/EngineInternalState.h> namespace SparkyStudios::Audio::Amplitude { AttenuationShape::AttenuationShape() : m_maxAttenuationFactor(1.0f) {} float AttenuationShape::GetAttenuationFactor(const Attenuation*, const hmm_vec3&, const ListenerInternalState*) { return m_maxAttenuationFactor; } float AttenuationShape::GetAttenuationFactor(const Attenuation*, const EntityInternalState*, const ListenerInternalState*) { return m_maxAttenuationFactor; } AttenuationShape* AttenuationShape::Create(const AttenuationShapeDefinition* definition) { if (definition == nullptr) return nullptr; AttenuationShape* shape = nullptr; switch (definition->model()) { default: case AttenuationShapeModel_Default: shape = new AttenuationShape(); break; case AttenuationShapeModel_Cone: shape = new ConeAttenuationShape(definition->settings_as_Cone()); break; case AttenuationShapeModel_Sphere: shape = new SphereAttenuationShape(definition->settings_as_Sphere()); break; case AttenuationShapeModel_Box: shape = new BoxAttenuationShape(definition->settings_as_Box()); break; case AttenuationShapeModel_Capsule: shape = new CapsuleAttenuationShape(definition->settings_as_Capsule()); break; } shape->m_maxAttenuationFactor = definition->max_attenuation_factor(); return shape; } float ConeAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { if (const hmm_vec3& soundToListener = listener->GetLocation() - soundLocation; AM_Length(soundToListener) >= attenuation->GetMaxDistance()) return 0.0f; return 1.0f; } float ConeAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - entity->GetLocation(); const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); const float coneDist = AM_Dot(soundToListener, entity->GetDirection()); if (coneDist < 0.0f || coneDist > _outerHeight) return gain * m_maxAttenuationFactor; if (coneDist > _innerHeight) return gain * AM_Lerp(1.0f, (coneDist - _innerHeight) / (_outerHeight - _innerHeight), m_maxAttenuationFactor); const float innerConeRadius = coneDist / _innerHeight * _innerRadius; const float outerConeRadius = coneDist / _outerHeight * _outerRadius; const float d = AM_Length(soundToListener - coneDist * entity->GetDirection()); if (d <= innerConeRadius) return gain * 1.0f; if (d >= outerConeRadius) return gain * m_maxAttenuationFactor; const float delta = (distance - innerConeRadius) / (outerConeRadius - innerConeRadius); return gain * AM_Lerp(1.0f, AM_CLAMP(delta, 0.0f, 1.0f), m_maxAttenuationFactor); } float ConeAttenuationShape::GetOuterRadius() const { return _outerRadius; } float ConeAttenuationShape::GetInnerRadius() const { return _innerRadius; } float ConeAttenuationShape::GetInnerHeight() const { return _innerHeight; } float ConeAttenuationShape::GetOuterHeight() const { return _outerHeight; } float SphereAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - soundLocation; const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); const float delta = (distance - _innerRadius) / (_outerRadius - _innerRadius); return gain * AM_Lerp(1.0f, AM_CLAMP(delta, 0.0f, 1.0f), m_maxAttenuationFactor); } float SphereAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { return GetAttenuationFactor(attenuation, entity->GetLocation(), listener); } float BoxAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - soundLocation; const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); return gain * _getFactor(soundLocation, listener, AM_Mat4d(1.0f)); } float BoxAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { const hmm_vec3& soundToListener = listener->GetLocation() - entity->GetLocation(); const float distance = AM_Length(soundToListener); if (distance >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(distance); return gain * _getFactor(entity->GetLocation(), listener, AM_LookAt(AM_Vec3(0, 0, 0), entity->GetDirection(), entity->GetUp())); } float BoxAttenuationShape::_getFactor(const hmm_vec3& soundLocation, const ListenerInternalState* listener, hmm_mat4 lookAt) { lookAt = AM_Multiply(AM_Translate(soundLocation), lookAt); const hmm_vec3& x = listener->GetLocation(); hmm_vec3 iP1, iP2, iP3, iP4, oP1, oP2, oP3, oP4; switch (amEngine->GetState()->up_axis) { default: case GameEngineUpAxis_Y: iP1 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfHeight, -_innerHalfDepth, 1.0f)).XYZ; iP2 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfHeight, _innerHalfDepth, 1.0f)).XYZ; iP3 = AM_Multiply(lookAt, AM_Vec4(_innerHalfWidth, -_innerHalfHeight, -_innerHalfDepth, 1.0f)).XYZ; iP4 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, _innerHalfHeight, -_innerHalfDepth, 1.0f)).XYZ; oP1 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfHeight, -_outerHalfDepth, 1.0f)).XYZ; oP2 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfHeight, _outerHalfDepth, 1.0f)).XYZ; oP3 = AM_Multiply(lookAt, AM_Vec4(_outerHalfWidth, -_outerHalfHeight, -_outerHalfDepth, 1.0f)).XYZ; oP4 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, _outerHalfHeight, -_outerHalfDepth, 1.0f)).XYZ; break; case GameEngineUpAxis_Z: iP1 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfDepth, -_innerHalfHeight, 1.0f)).XYZ; iP2 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, _innerHalfDepth, -_innerHalfHeight, 1.0f)).XYZ; iP3 = AM_Multiply(lookAt, AM_Vec4(_innerHalfWidth, -_innerHalfDepth, -_innerHalfHeight, 1.0f)).XYZ; iP4 = AM_Multiply(lookAt, AM_Vec4(-_innerHalfWidth, -_innerHalfDepth, _innerHalfHeight, 1.0f)).XYZ; oP1 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfDepth, -_outerHalfHeight, 1.0f)).XYZ; oP2 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, _outerHalfDepth, -_outerHalfHeight, 1.0f)).XYZ; oP3 = AM_Multiply(lookAt, AM_Vec4(_outerHalfWidth, -_outerHalfDepth, -_outerHalfHeight, 1.0f)).XYZ; oP4 = AM_Multiply(lookAt, AM_Vec4(-_outerHalfWidth, -_outerHalfDepth, _outerHalfHeight, 1.0f)).XYZ; break; } hmm_vec3 iU = AM_Normalize(iP2 - iP1); hmm_vec3 iV = AM_Normalize(iP3 - iP1); hmm_vec3 iW = AM_Normalize(iP4 - iP1); hmm_vec3 oU = AM_Normalize(oP2 - oP1); hmm_vec3 oV = AM_Normalize(oP3 - oP1); hmm_vec3 oW = AM_Normalize(oP4 - oP1); const float iUX = AM_Dot(iU, x); const float iVX = AM_Dot(iV, x); const float iWX = AM_Dot(iW, x); const float oUX = AM_Dot(oU, x); const float oVX = AM_Dot(oV, x); const float oWX = AM_Dot(oW, x); const float iUP1 = AM_Dot(iU, iP1); const float iVP1 = AM_Dot(iV, iP1); const float iWP1 = AM_Dot(iW, iP1); const float iUP2 = AM_Dot(iU, iP2); const float iVP3 = AM_Dot(iV, iP3); const float iWP4 = AM_Dot(iW, iP4); const float oUP1 = AM_Dot(oU, oP1); const float oVP1 = AM_Dot(oV, oP1); const float oWP1 = AM_Dot(oW, oP1); const float oUP2 = AM_Dot(oU, oP2); const float oVP3 = AM_Dot(oV, oP3); const float oWP4 = AM_Dot(oW, oP4); if (AM_BETWEEN(iUX, iUP1, iUP2) && AM_BETWEEN(iVX, iVP1, iVP3) && AM_BETWEEN(iWX, iWP1, iWP4)) return 1.0f; if (!(AM_BETWEEN(oUX, oUP1, oUP2) && AM_BETWEEN(oVX, oVP1, oVP3) && AM_BETWEEN(oWX, oWP1, oWP4))) return m_maxAttenuationFactor; const float dP1 = HMM_ABS(AM_Dot(x - oP1, AM_Normalize(oP2 - oP1))) / (_outerHalfDepth - _innerHalfDepth); const float dP2 = HMM_ABS(AM_Dot(x - oP2, AM_Normalize(oP1 - oP2))) / (_outerHalfDepth - _innerHalfDepth); const float dP3 = HMM_ABS(AM_Dot(x - oP3, AM_Normalize(oP1 - oP3))) / (_outerHalfWidth - _innerHalfWidth); const float dP4 = HMM_ABS(AM_Dot(x - oP4, AM_Normalize(oP1 - oP4))) / (_outerHalfHeight - _innerHalfHeight); const float dP5 = HMM_ABS(AM_Dot(x - oP1, AM_Normalize(oP3 - oP1))) / (_outerHalfWidth - _innerHalfWidth); const float dP6 = HMM_ABS(AM_Dot(x - oP1, AM_Normalize(oP4 - oP1))) / (_outerHalfHeight - _innerHalfHeight); const float shortestRoad = AM_MIN(dP1, AM_MIN(dP2, AM_MIN(dP3, AM_MIN(dP4, AM_MIN(dP5, dP6))))); return AM_Lerp(m_maxAttenuationFactor, AM_CLAMP(shortestRoad, 0.0f, 1.0f), 1.0f); } float CapsuleAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener) { return _getFactor(attenuation, soundLocation, listener, AM_Mat4d(1.0f)); } float CapsuleAttenuationShape::GetAttenuationFactor( const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener) { return _getFactor( attenuation, entity->GetLocation(), listener, AM_LookAt(AM_Vec3(0, 0, 0), entity->GetDirection(), entity->GetUp())); } float CapsuleAttenuationShape::_getFactor( const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener, hmm_mat4 lookAt) { lookAt = AM_Multiply(AM_Translate(soundLocation),
const float outerHalfHeight = _outerHalfHeight - _outerRadius; hmm_vec3 iA, iB, oA, oB; switch (amEngine->GetState()->up_axis) { default: case GameEngineUpAxis_Y: iA = AM_Multiply(lookAt, AM_Vec4(0.0f, innerHalfHeight, 0.0f, 1.0f)).XYZ; iB = AM_Multiply(lookAt, AM_Vec4(0.0f, -innerHalfHeight, 0.0f, 1.0f)).XYZ; oA = AM_Multiply(lookAt, AM_Vec4(0.0f, outerHalfHeight, 0.0f, 1.0f)).XYZ; oB = AM_Multiply(lookAt, AM_Vec4(0.0f, -outerHalfHeight, 0.0f, 1.0f)).XYZ; break; case GameEngineUpAxis_Z: iA = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, innerHalfHeight, 1.0f)).XYZ; iB = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, -innerHalfHeight, 1.0f)).XYZ; oA = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, outerHalfHeight, 1.0f)).XYZ; oB = AM_Multiply(lookAt, AM_Vec4(0.0f, 0.0f, -outerHalfHeight, 1.0f)).XYZ; break; } hmm_vec3 iE = iB - iA; hmm_vec3 iM = AM_Cross(iA, iB); hmm_vec3 oE = oB - oA; hmm_vec3 oM = AM_Cross(oA, oB); const float iDistanceToAxis = AM_Length(iM + AM_Cross(iE, x)) / AM_Length(iE); const float oDistanceToAxis = AM_Length(oM + AM_Cross(oE, x)) / AM_Length(oE); if (oDistanceToAxis >= attenuation->GetMaxDistance()) return 0.0f; const float gain = attenuation->GetGainCurve().Get(iDistanceToAxis); const float iDistanceToA = AM_Length(x - iA); const float iDistanceToB = AM_Length(x - iB); const float oDistanceToA = AM_Length(x - oA); const float oDistanceToB = AM_Length(x - oB); if (iDistanceToAxis <= _innerRadius && distanceToOrigin <= innerHalfHeight) return gain * 1.0f; if (oDistanceToAxis >= _outerRadius && distanceToOrigin >= outerHalfHeight) return gain * m_maxAttenuationFactor; const float rDelta = 1.0f - (oDistanceToAxis - _innerRadius) / (_outerRadius - _innerRadius); const float hDelta = 1.0f - (distanceToOrigin - _innerHalfHeight) / (_outerHalfHeight - _innerHalfHeight); const float delta = AM_MIN(rDelta, hDelta); return gain * AM_Lerp(m_maxAttenuationFactor, AM_CLAMP(delta, 0.0f, 1.0f), 1.0f); } }
lookAt); const hmm_vec3& x = listener->GetLocation(); const float distanceToOrigin = AM_Length(x - soundLocation); const float innerHalfHeight = _innerHalfHeight - _innerRadius;
random
[ { "content": " class AttenuationShape\n\n {\n\n public:\n\n /**\n\n * @brief Returns the attenuation factor.\n\n *\n\n * This method is used only for position based sound sources.\n\n *\n\n * @param attenuation The Attenuator object to use for distance attenuation.\n\n * @param soundLocation The location of the sound source.\n\n * @param listener The listener for which compute the attenuation.\n\n *\n\n * @return The attenuation factor.\n\n */\n\n virtual float GetAttenuationFactor(\n\n const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener);\n\n\n\n /**\n\n * @brief Returns the attenuation factor.\n\n *\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 0, "score": 142188.14681399876 }, { "content": " class Switch\n\n {\n\n public:\n\n /**\n\n * @brief Construct an uninitialized Switch.\n\n *\n\n * An uninitialized Switch cannot set no provide the actual switch state.\n\n */\n\n Switch();\n\n\n\n bool LoadSwitchDefinition(const std::string& switchDefinition);\n\n bool LoadSwitchDefinitionFromFile(AmOsString filename);\n\n\n\n /**\n\n * @brief Get the switch definition which generated this Switch.\n\n *\n\n * @return The switch definition.\n\n */\n\n [[nodiscard]] const SwitchDefinition* GetSwitchDefinition() const;\n\n\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 1, "score": 130959.46592709041 }, { "content": " class ConeAttenuationShape : public AttenuationShape\n\n {\n\n public:\n\n explicit ConeAttenuationShape(const ConeAttenuationSettings* settings)\n\n : AttenuationShape()\n\n {\n\n _innerRadius = settings->inner_radius();\n\n _outerRadius = settings->outer_radius();\n\n _innerHeight = settings->inner_height();\n\n _outerHeight = settings->outer_height();\n\n }\n\n\n\n float GetAttenuationFactor(const Attenuation*, const hmm_vec3& soundLocation, const ListenerInternalState* listener) override;\n\n float GetAttenuationFactor(const Attenuation*, const EntityInternalState* entity, const ListenerInternalState* listener) override;\n\n [[nodiscard]] float GetInnerRadius() const;\n\n [[nodiscard]] float GetOuterRadius() const;\n\n [[nodiscard]] float GetInnerHeight() const;\n\n [[nodiscard]] float GetOuterHeight() const;\n\n\n\n private:\n\n float _innerRadius;\n\n float _outerRadius;\n\n float _innerHeight;\n\n float _outerHeight;\n\n };\n\n\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 2, "score": 125584.57552466364 }, { "content": " class SphereAttenuationShape : public AttenuationShape\n\n {\n\n public:\n\n explicit SphereAttenuationShape(const SphereAttenuationSettings* settings)\n\n : AttenuationShape()\n\n {\n\n _innerRadius = settings->inner_radius();\n\n _outerRadius = settings->outer_radius();\n\n }\n\n\n\n float GetAttenuationFactor(const Attenuation*, const hmm_vec3& soundLocation, const ListenerInternalState* listener) override;\n\n float GetAttenuationFactor(const Attenuation*, const EntityInternalState* entity, const ListenerInternalState* listener) override;\n\n\n\n [[nodiscard]] float GetInnerRadius() const\n\n {\n\n return _innerRadius;\n\n }\n\n\n\n [[nodiscard]] float GetOuterRadius() const\n\n {\n\n return _outerRadius;\n\n }\n\n\n\n private:\n\n float _innerRadius;\n\n float _outerRadius;\n\n };\n\n\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 3, "score": 125584.57552466364 }, { "content": " class BoxAttenuationShape : public AttenuationShape\n\n {\n\n public:\n\n explicit BoxAttenuationShape(const BoxAttenuationSettings* settings)\n\n : AttenuationShape()\n\n {\n\n _innerHalfHeight = settings->inner_half_height();\n\n _outerHalfHeight = settings->outer_half_height();\n\n _innerHalfWidth = settings->inner_half_width();\n\n _outerHalfWidth = settings->outer_half_width();\n\n _innerHalfDepth = settings->inner_half_depth();\n\n _outerHalfDepth = settings->outer_half_depth();\n\n }\n\n\n\n float GetAttenuationFactor(const Attenuation*, const hmm_vec3& soundLocation, const ListenerInternalState* listener) override;\n\n float GetAttenuationFactor(const Attenuation*, const EntityInternalState* entity, const ListenerInternalState* listener) override;\n\n\n\n [[nodiscard]] float GetInnerHalfHeight() const\n\n {\n\n return _innerHalfHeight;\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 4, "score": 125584.57552466364 }, { "content": " class CapsuleAttenuationShape : public AttenuationShape\n\n {\n\n public:\n\n explicit CapsuleAttenuationShape(const CapsuleAttenuationSettings* settings)\n\n : AttenuationShape()\n\n {\n\n _innerRadius = settings->inner_radius();\n\n _outerRadius = settings->outer_radius();\n\n _innerHalfHeight = settings->inner_half_height();\n\n _outerHalfHeight = settings->outer_half_height();\n\n }\n\n\n\n float GetAttenuationFactor(const Attenuation*, const hmm_vec3& soundLocation, const ListenerInternalState* listener) override;\n\n float GetAttenuationFactor(const Attenuation*, const EntityInternalState* entity, const ListenerInternalState* listener) override;\n\n\n\n [[nodiscard]] float GetInnerRadius() const\n\n {\n\n return _innerRadius;\n\n }\n\n\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 5, "score": 125584.57552466364 }, { "content": " float X, Y, Z;\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Math/HandmadeMath.h", "rank": 6, "score": 112187.17517551189 }, { "content": "\n\n#include <SparkyStudios/Audio/Amplitude/Core/Listener.h>\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Attenuation.h>\n\n\n\n#include <Core/EntityInternalState.h>\n\n#include <Core/ListenerInternalState.h>\n\n#include <SparkyStudios/Audio/Amplitude/Math/Curve.h>\n\n\n\n#include \"attenuation_definition_generated.h\"\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 7, "score": 103357.3084903441 }, { "content": " [[nodiscard]] float GetOuterRadius() const\n\n {\n\n return _outerRadius;\n\n }\n\n\n\n [[nodiscard]] float GetInnerHalfHeight() const\n\n {\n\n return _innerHalfHeight;\n\n }\n\n\n\n [[nodiscard]] float GetOuterHalfHeight() const\n\n {\n\n return _outerHalfHeight;\n\n }\n\n\n\n private:\n\n float _getFactor(const Attenuation* attenuation, const hmm_vec3& soundLocation, const ListenerInternalState* listener, hmm_mat4 lookAt);\n\n\n\n float _innerRadius;\n\n float _outerRadius;\n\n float _innerHalfHeight;\n\n float _outerHalfHeight;\n\n };\n\n} // namespace SparkyStudios::Audio::Amplitude\n\n\n\n#endif // SS_AMPLITUDE_AUDIO_ATTENUATION_INTERNAL_STATE_H\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 8, "score": 103349.68920415836 }, { "content": " }\n\n\n\n [[nodiscard]] float GetOuterHalfDepth() const\n\n {\n\n return _outerHalfDepth;\n\n }\n\n\n\n private:\n\n float _getFactor(const hmm_vec3& soundLocation, const ListenerInternalState* listener, hmm_mat4 lookAt);\n\n\n\n float _innerHalfHeight;\n\n float _outerHalfHeight;\n\n float _innerHalfWidth;\n\n float _outerHalfWidth;\n\n float _innerHalfDepth;\n\n float _outerHalfDepth;\n\n };\n\n\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 9, "score": 103344.72622815396 }, { "content": " }\n\n\n\n [[nodiscard]] float GetOuterHalfHeight() const\n\n {\n\n return _outerHalfHeight;\n\n }\n\n\n\n [[nodiscard]] float GetInnerHalfWidth() const\n\n {\n\n return _innerHalfWidth;\n\n }\n\n\n\n [[nodiscard]] float GetOuterHalfWidth() const\n\n {\n\n return _outerHalfWidth;\n\n }\n\n\n\n [[nodiscard]] float GetInnerHalfDepth() const\n\n {\n\n return _innerHalfDepth;\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 10, "score": 103340.0843248977 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#pragma once\n\n\n\n#ifndef SS_AMPLITUDE_AUDIO_ATTENUATION_INTERNAL_STATE_H\n\n#define SS_AMPLITUDE_AUDIO_ATTENUATION_INTERNAL_STATE_H\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n", "file_path": "src/Sound/AttenuationShapes.h", "rank": 11, "score": 103339.2070581073 }, { "content": " class Entity\n\n {\n\n public:\n\n /**\n\n * @brief Creates an uninitialized Entity.\n\n *\n\n * An uninitialized Entity cannot provide location and orientation\n\n * information, and therefore cannot play sounds.\n\n */\n\n Entity();\n\n\n\n explicit Entity(EntityInternalState* state);\n\n\n\n /**\n\n * @brief Uninitializes this Entity.\n\n *\n\n * Note that this does not destroy the internal state it references,\n\n * it just removes this reference to it.\n\n */\n\n void Clear();\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 12, "score": 102221.67793893711 }, { "content": " class Listener\n\n {\n\n public:\n\n /**\n\n * @brief Construct an uninitialized Listener.\n\n *\n\n * An uninitialized Listener cannot have its location set or queried.\n\n * To initialize the Listener, use <code>Engine::AddListener();</code>.\n\n */\n\n Listener();\n\n\n\n explicit Listener(ListenerInternalState* state);\n\n\n\n /**\n\n * @brief Uninitialize this Listener.\n\n *\n\n * Note that this does not destroy the internal state it references,\n\n * it just removes this reference to it. To destroy the Listener,\n\n * use <code>Engine::RemoveListener();</code>.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Listener.h", "rank": 13, "score": 102220.23484192528 }, { "content": " class Attenuation;\n\n\n\n /**\n\n * @brief The propagation shape for positional sounds.\n\n *\n\n * This allows to increase the attenuation according to the shape of\n\n * the sound propagation.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 14, "score": 102195.66138483437 }, { "content": " class Attenuation\n\n {\n\n public:\n\n /**\n\n * @brief Creates an uninitialized Attenuation.\n\n *\n\n * An uninitialized Attenuation instance cannot compute gain nor provide\n\n * attenuation configuration data.\n\n */\n\n Attenuation();\n\n\n\n bool LoadAttenuationDefinition(const std::string& attenuation);\n\n bool LoadAttenuationDefinitionFromFile(AmOsString filename);\n\n\n\n /**\n\n * @brief Returns the gain of the sound from the given distance to the listener.\n\n *\n\n * @param soundLocation The location of the sound source.\n\n * @param listener The listener which is hearing the sound.\n\n *\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 15, "score": 102195.66138483437 }, { "content": " class EntityInternalState;\n\n\n\n /**\n\n * @brief An Entity represent an object in the game.\n\n *\n\n * Amplitude use entities to link sound to an object in the game. Each sounds\n\n * played from an entity get the location and orientation data fom that entity.\n\n *\n\n * The Entity class is a lightweight reference to a EntityInternalState object\n\n * which is managed by the Engine.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 33, "score": 96714.63170564332 }, { "content": " class ListenerInternalState;\n\n\n\n /**\n\n * @brief An object whose distance from sounds determines their gain.\n\n *\n\n * The Listener class is a lightweight reference to a ListenerInternalState\n\n * which is managed by the Engine. Multiple Listener objects may point to\n\n * the same underlying data.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Listener.h", "rank": 34, "score": 96713.25283435184 }, { "content": " class SwitchContainer\n\n {\n\n public:\n\n SwitchContainer();\n\n ~SwitchContainer();\n\n\n\n bool LoadSwitchContainerDefinition(const std::string& source, EngineInternalState* state);\n\n bool LoadSwitchContainerDefinitionFromFile(AmOsString filename, EngineInternalState* state);\n\n void AcquireReferences(EngineInternalState* state);\n\n void ReleaseReferences(EngineInternalState* state);\n\n [[nodiscard]] const SwitchContainerDefinition* GetSwitchContainerDefinition() const;\n\n\n\n /**\n\n * @brief Gets the actual gain of the switch container.\n\n *\n\n * @return The SwitchContainer gain.\n\n */\n\n const RtpcValue& GetGain() const;\n\n\n\n /**\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 35, "score": 96691.15634463904 }, { "content": " [[nodiscard]] AmReal32 GetObstruction() const;\n\n\n\n /**\n\n * @brief Get the occlusion level of sounds played by this Entity.\n\n *\n\n * @return The occlusion amount.\n\n */\n\n [[nodiscard]] AmReal32 GetOcclusion() const;\n\n\n\n /**\n\n * @brief Returns the internal state of this Entity.\n\n *\n\n * @return The Entity internal state.\n\n */\n\n [[nodiscard]] EntityInternalState* GetState() const;\n\n\n\n private:\n\n EntityInternalState* _state;\n\n };\n\n} // namespace SparkyStudios::Audio::Amplitude\n\n\n\n#endif // SS_AMPLITUDE_AUDIO_ENTITY_H\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 36, "score": 91617.33586616952 }, { "content": " */\n\n [[nodiscard]] hmm_vec3 GetLocation() const;\n\n\n\n /**\n\n * @brief Set the location of this Listener.\n\n *\n\n * @param location The new location of this Listener.\n\n */\n\n void SetLocation(const hmm_vec3& location);\n\n\n\n /**\n\n * @brief Set the location, direction and up vector of this Listener.\n\n *\n\n * @param direction The direction of this Listener.\n\n * @param up THe up vector of this Listener.\n\n */\n\n void SetOrientation(const hmm_vec3& direction, const hmm_vec3& up);\n\n\n\n /**\n\n * @brief Returns the internal state of this Listener.\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Listener.h", "rank": 37, "score": 91616.0193013305 }, { "content": "\n\n /**\n\n * @brief Checks whether this Entity has been initialized.\n\n *\n\n * @return boolean true if this Entity has been initialized.\n\n */\n\n [[nodiscard]] bool Valid() const;\n\n\n\n /**\n\n * @brief Gets the ID of this Entity in game.\n\n *\n\n * @return The game Entity ID.\n\n */\n\n [[nodiscard]] AmEntityID GetId() const;\n\n\n\n /**\n\n * @brief Sets the location of this Entity.\n\n *\n\n * @param location The new location.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 38, "score": 91615.62349306046 }, { "content": " *\n\n * @return ListenerInternalState*\n\n */\n\n [[nodiscard]] ListenerInternalState* GetState() const\n\n {\n\n return _state;\n\n }\n\n\n\n private:\n\n ListenerInternalState* _state;\n\n };\n\n} // namespace SparkyStudios::Audio::Amplitude\n\n\n\n#endif // SPARK_AUDIO_LISTENER_H\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Listener.h", "rank": 39, "score": 91614.87786536365 }, { "content": " * @return The computed gain value fom the curve.\n\n */\n\n float GetGain(const hmm_vec3& soundLocation, const ListenerInternalState* listener) const;\n\n\n\n /**\n\n * @brief Returns the gain of the sound from the given distance to the listener.\n\n *\n\n * @param entity The entity which emits the sound.\n\n * @param listener The listener which is hearing the sound.\n\n *\n\n * @return The computed gain value fom the curve.\n\n */\n\n float GetGain(const EntityInternalState* entity, const ListenerInternalState* listener) const;\n\n\n\n /**\n\n * @brief Returns the unique ID of this Attenuation.\n\n *\n\n * @return The Attenuation ID.\n\n */\n\n [[nodiscard]] AmAttenuationID GetId() const;\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 40, "score": 91614.76340971605 }, { "content": " void Clear();\n\n\n\n /**\n\n * @brief Checks whether this Listener has been initialized.\n\n *\n\n * @return bool true if this Listener has been initialized.\n\n */\n\n [[nodiscard]] bool Valid() const;\n\n\n\n /**\n\n * @brief Gets the ID of this Listener in game.\n\n *\n\n * @return The game Listener ID.\n\n */\n\n [[nodiscard]] AmListenerID GetId() const;\n\n\n\n /**\n\n * @brief Returns the location of this Listener.\n\n *\n\n * @return hmm_vec3 The location of this Listener.\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Listener.h", "rank": 41, "score": 91614.55152653145 }, { "content": " * This method is used by position and orientation based sound sources.\n\n *\n\n * @param attenuation The Attenuator object to use for distance attenuation.\n\n * @param entity The entity which emits the sound.\n\n * @param listener The listener for which compute the attenuation.\n\n *\n\n * @return The attenuation factor.\n\n */\n\n virtual float GetAttenuationFactor(\n\n const Attenuation* attenuation, const EntityInternalState* entity, const ListenerInternalState* listener);\n\n\n\n /**\n\n * @brief Creates an AttenuationShape object from the definition.\n\n *\n\n * @param definition The attenuation shape definition.\n\n *\n\n * @return An AttenuationShape object.\n\n */\n\n static AttenuationShape* Create(const AttenuationShapeDefinition* definition);\n\n\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 42, "score": 91613.93075991412 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#pragma once\n\n\n\n#ifndef SS_AMPLITUDE_AUDIO_ENTITY_H\n\n#define SS_AMPLITUDE_AUDIO_ENTITY_H\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 43, "score": 91612.64964304243 }, { "content": " void SetLocation(const hmm_vec3& location);\n\n\n\n /**\n\n * @brief Gets the current location of this Entity.\n\n *\n\n * @return The current location of this Entity.\n\n */\n\n [[nodiscard]] const hmm_vec3& GetLocation() const;\n\n\n\n /**\n\n * @brief Sets the orientation of this Entity.\n\n *\n\n * @param direction The direction towards the Entity.\n\n * @param up The up vector.\n\n */\n\n void SetOrientation(const hmm_vec3& direction, const hmm_vec3& up);\n\n\n\n /**\n\n * @brief Get the direction vector of the Entity.\n\n *\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 44, "score": 91611.89318147331 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#pragma once\n\n\n\n#ifndef SPARK_AUDIO_LISTENER_H\n\n#define SPARK_AUDIO_LISTENER_H\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Listener.h", "rank": 45, "score": 91611.6276566267 }, { "content": " * @return The direction vector.\n\n */\n\n [[nodiscard]] const hmm_vec3& GetDirection() const;\n\n\n\n /**\n\n * @brief Get the up vector of the Entity.\n\n *\n\n * @return The up vector.\n\n */\n\n [[nodiscard]] const hmm_vec3& GetUp() const;\n\n\n\n /**\n\n * @brief Update the state of this Entity.\n\n *\n\n * This method is called automatically by the Engine\n\n * on each frames.\n\n */\n\n void Update();\n\n\n\n /**\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 46, "score": 91610.8871300695 }, { "content": "\n\n#include <SparkyStudios/Audio/Amplitude/Core/Entity.h>\n\n#include <SparkyStudios/Audio/Amplitude/Core/Listener.h>\n\n#include <SparkyStudios/Audio/Amplitude/Core/RefCounter.h>\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Math/Curve.h>\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n\n struct AttenuationDefinition;\n\n struct AttenuationShapeDefinition;\n\n\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 47, "score": 91610.82931525695 }, { "content": " * @brief Set the obstruction level of sounds played by this Entity.\n\n *\n\n * @param obstruction The obstruction amount. This is provided by the\n\n * game engine.\n\n */\n\n void SetObstruction(AmReal32 obstruction);\n\n\n\n /**\n\n * @brief Set the occlusion level of sounds played by this Entity.\n\n *\n\n * @param occlusion The occlusion amount. This is provided by the\n\n * game engine.\n\n */\n\n void SetOcclusion(AmReal32 occlusion);\n\n\n\n /**\n\n * @brief Get the obstruction level of sounds played by this Entity.\n\n *\n\n * @return The obstruction amount.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Core/Entity.h", "rank": 48, "score": 91610.7745900066 }, { "content": " protected:\n\n AttenuationShape();\n\n\n\n /**\n\n * @brief THe maximum attenuation factor to apply to the sound gain.\n\n */\n\n float m_maxAttenuationFactor;\n\n };\n\n\n\n /**\n\n * @brief An Attenuation materialize how the sound volume and other distance-based\n\n * parameters are calculated following the distance of the sound source to the listener.\n\n *\n\n * The Attenuation is an shared object between sound sources. They are used only\n\n * when the sound need to lower his volume due to the distance of from the listener,\n\n * and many other parameters.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 49, "score": 91608.54457730454 }, { "content": "\n\n /**\n\n * @brief Returns the name of this Attenuation.\n\n *\n\n * @return The Attenuation name.\n\n */\n\n [[nodiscard]] const std::string& GetName() const;\n\n\n\n /**\n\n * @brief Returns the shape object of this Attenuation.\n\n *\n\n * @return The Attenuation shape.\n\n */\n\n [[nodiscard]] AttenuationShape* GetShape() const;\n\n\n\n /**\n\n * @brief Returns the gain curve attached to this Attenuation.\n\n *\n\n * @return The attenuation's gain curve.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 50, "score": 91608.23276200757 }, { "content": " [[nodiscard]] const Curve& GetGainCurve() const;\n\n\n\n /**\n\n * @brief Returns the maximum distance for a fully attenuated sound\n\n *\n\n * @return The maximum sound attenuation distance.\n\n */\n\n [[nodiscard]] double GetMaxDistance() const;\n\n\n\n /**\n\n * @brief Get the attenuation definition which generated this attenuation.\n\n *\n\n * @return The attenuation definition.\n\n */\n\n [[nodiscard]] const AttenuationDefinition* GetAttenuationDefinition() const;\n\n\n\n RefCounter* GetRefCounter();\n\n\n\n private:\n\n std::string _source;\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 51, "score": 91606.17624753401 }, { "content": "\n\n AmAttenuationID _id;\n\n std::string _name;\n\n\n\n double _maxDistance;\n\n\n\n AttenuationShape* _shape;\n\n\n\n Curve _gainCurve;\n\n\n\n RefCounter _refCounter;\n\n };\n\n} // namespace SparkyStudios::Audio::Amplitude\n\n\n\n#endif // SS_AMPLITUDE_AUDIO_ATTENUATION_H\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 52, "score": 91605.64051211487 }, { "content": "#include <SparkyStudios/Audio/Amplitude/Core/RefCounter.h>\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n\n struct SwitchDefinition;\n\n\n\n /**\n\n * @brief A switch state.\n\n */\n\n struct SwitchState\n\n {\n\n /**\n\n * @brief The ID of this switch state.\n\n *\n\n * This ID is unique only in the parent switch.\n\n */\n\n AmObjectID m_id;\n\n\n\n /**\n\n * @brief The name of this switch state.\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 53, "score": 91602.02884480984 }, { "content": " * list of switch states.\n\n */\n\n void SetState(const std::string& name);\n\n\n\n /**\n\n * @brief Get the list of available SwitchStates in this Switch.\n\n *\n\n * @return The list of available SwitchStates.\n\n */\n\n [[nodiscard]] const std::vector<SwitchState>& GetSwitchStates() const;\n\n\n\n RefCounter* GetRefCounter();\n\n\n\n private:\n\n std::string _source;\n\n\n\n AmSwitchID _id;\n\n std::string _name;\n\n\n\n SwitchState _activeState;\n\n std::vector<SwitchState> _states;\n\n\n\n RefCounter _refCounter;\n\n };\n\n} // namespace SparkyStudios::Audio::Amplitude\n\n\n\n#endif // SS_AMPLITUDE_AUDIO_SWITCH_H\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 54, "score": 91595.06740267207 }, { "content": " /**\n\n * @brief Get the ID of this Switch.\n\n *\n\n * @return The switch ID.\n\n */\n\n [[nodiscard]] AmSwitchID GetId() const;\n\n\n\n /**\n\n * @brief Get the name of this Switch.\n\n *\n\n * @return The switch name.\n\n */\n\n [[nodiscard]] const std::string& GetName() const;\n\n\n\n /**\n\n * @brief Get the current state of the switch.\n\n *\n\n * @return The current state of the switch.\n\n */\n\n [[nodiscard]] const SwitchState& GetState() const;\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 55, "score": 91593.4397802627 }, { "content": " */\n\n std::string m_name;\n\n\n\n /**\n\n * @brief Checks whether this switch state is valid.\n\n *\n\n * @return true if the switch state is valid, false otherwise.\n\n */\n\n [[nodiscard]] bool Valid() const;\n\n\n\n bool operator==(const SwitchState& other) const;\n\n bool operator!=(const SwitchState& other) const;\n\n };\n\n\n\n /**\n\n * @brief A switch is a collection of states which can change the sound played during from a SwitchContainer the game.\n\n *\n\n * For example, you can have a switch named \"SurfaceType\" which have \"wood\", \"grass\", \"metal\" and \"water\" as states. A\n\n * SwitchContainer using this switch can group sounds per switch states, so when a state is active, all the sounds of\n\n * that state are played.\n\n *\n\n * The Switch is a shared object between sound sources. They are used only by SwitchContainer objects.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 56, "score": 91593.17933246148 }, { "content": "\n\n /**\n\n * @brief Set the current state of the switch.\n\n *\n\n * @param state The state to apply to the switch.\n\n */\n\n void SetState(const SwitchState& state);\n\n\n\n /**\n\n * @brief Set the current state of the switch using the state ID.\n\n *\n\n * @param id The ID of the state to apply. This ID should exist in the list\n\n * of switch states.\n\n */\n\n void SetState(AmObjectID id);\n\n\n\n /**\n\n * @brief Set the current state of the switch using the state name.\n\n *\n\n * @param name The name of the state to apply. This name should exist in the\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 57, "score": 91592.42864737849 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#pragma once\n\n\n\n#ifndef SS_AMPLITUDE_AUDIO_SWITCH_H\n\n#define SS_AMPLITUDE_AUDIO_SWITCH_H\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Switch.h", "rank": 58, "score": 91591.63801889843 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#pragma once\n\n\n\n#ifndef SS_AMPLITUDE_AUDIO_ATTENUATION_H\n\n#define SS_AMPLITUDE_AUDIO_ATTENUATION_H\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/Attenuation.h", "rank": 59, "score": 91590.49882702605 }, { "content": " /**\n\n * @brief Return the bus this SwitchContainer will play on.\n\n *\n\n * @return The bus this SwitchContainer will play on.\n\n */\n\n [[nodiscard]] BusInternalState* GetBus() const;\n\n\n\n /**\n\n * @brief Returns the effect attached to this SwitchContainer.\n\n *\n\n * @return The effect of this SwitchContainer if available or nullptr.\n\n */\n\n [[nodiscard]] const Effect* GetEffect() const;\n\n\n\n /**\n\n * @brief Returns the attenuation attached to this SwitchContainer.\n\n *\n\n * @return The attenuation of this SwitchContainer if available or nullptr.\n\n */\n\n [[nodiscard]] const Attenuation* GetAttenuation() const;\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 60, "score": 88356.65982626902 }, { "content": "#include <SparkyStudios/Audio/Amplitude/Core/RefCounter.h>\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Attenuation.h>\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Effect.h>\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Fader.h>\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Rtpc.h>\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Switch.h>\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n\n struct SwitchContainerDefinition;\n\n\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 61, "score": 88353.73280938121 }, { "content": "\n\n /**\n\n * @brief Returns the switch attached to this SwitchContainer.\n\n *\n\n * @return The switch of this SwitchContainer if available or nullptr.\n\n */\n\n [[nodiscard]] const Switch* GetSwitch() const;\n\n\n\n /**\n\n * @brief Get the fade in Fader for the given sound object ID.\n\n *\n\n * @param id The ID of the sound object.\n\n *\n\n * @return The fade in Fader.\n\n */\n\n Fader* GetFaderIn(AmObjectID id) const;\n\n\n\n /**\n\n * @brief Get the fade out Fader for the given sound object ID.\n\n *\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 62, "score": 88348.57799164554 }, { "content": " [[nodiscard]] const std::vector<SwitchContainerItem>& GetSoundObjects(AmObjectID stateId) const;\n\n\n\n private:\n\n // The bus this SwitchContainer will play on.\n\n BusInternalState* _bus;\n\n\n\n // The World scope sound scheduler\n\n Switch* _switch;\n\n\n\n std::string _source;\n\n std::map<AmObjectID, std::vector<SwitchContainerItem>> _sounds;\n\n std::map<AmObjectID, Fader*> _fadersIn;\n\n std::map<AmObjectID, Fader*> _fadersOut;\n\n\n\n AmSwitchContainerID _id;\n\n std::string _name;\n\n\n\n RtpcValue _gain;\n\n RtpcValue _priority;\n\n\n\n Effect* _effect;\n\n Attenuation* _attenuation;\n\n\n\n RefCounter _refCounter;\n\n };\n\n} // namespace SparkyStudios::Audio::Amplitude\n\n\n\n#endif // SS_AMPLITUDE_AUDIO_SWITCHCONTAINER_H\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 63, "score": 88348.22793343583 }, { "content": " * @brief Gets the actual priority of the switch container.\n\n *\n\n * @return The SwitchContainer priority.\n\n */\n\n const RtpcValue& GetPriority() const;\n\n\n\n /**\n\n * @brief Returns the unique ID of this SwitchContainer.\n\n *\n\n * @return The SwitchContainer unique ID.\n\n */\n\n [[nodiscard]] AmCollectionID GetId() const;\n\n\n\n /**\n\n * @brief Returns the name of this SwitchContainer.\n\n *\n\n * @return The SwitchContainer name.\n\n */\n\n [[nodiscard]] const std::string& GetName() const;\n\n\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 64, "score": 88347.22025052848 }, { "content": " * @param id The ID of the sound object.\n\n *\n\n * @return The fade out Fader.\n\n */\n\n Fader* GetFaderOut(AmObjectID id) const;\n\n\n\n /**\n\n * @brief Get the references counter of this instance.\n\n *\n\n * @return The references counter.\n\n */\n\n RefCounter* GetRefCounter();\n\n\n\n /**\n\n * @brief Returns the list of sound objects referenced in this SwitchContainer for the given state.\n\n *\n\n * @param state The switch state to get the objects for.\n\n *\n\n * @return The list of sound object IDs.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 65, "score": 88343.75779748979 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#pragma once\n\n\n\n#ifndef SS_AMPLITUDE_AUDIO_SWITCHCONTAINER_H\n\n#define SS_AMPLITUDE_AUDIO_SWITCHCONTAINER_H\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 66, "score": 88338.77531257487 }, { "content": " class CurveDefinition;\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Math/Curve.h", "rank": 67, "score": 85355.6052770595 }, { "content": " class CurvePartDefinition;\n\n\n\n /**\n\n * @brief A single point in a Curve.\n\n */\n\n struct CurvePoint\n\n {\n\n /**\n\n * @brief The coordinates of the point over the X axis.\n\n */\n\n double x;\n\n\n\n /**\n\n * @brief The coordinates of the point over the Y axis.\n\n */\n\n float y;\n\n\n\n bool operator==(const CurvePoint& rhs) const;\n\n bool operator!=(const CurvePoint& rhs) const;\n\n };\n\n\n\n /**\n\n * @brief A part of a Curve.\n\n *\n\n * CurveParts allows to a curve to have different fading algorithms at the same time.\n\n * Each CurvePart has a start and end point, and the fading algorithm which moves the value\n\n * from the start point to the end point.\n\n */\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Math/Curve.h", "rank": 68, "score": 82527.62308002886 }, { "content": " drwav_int32 delta[2];\n", "file_path": "src/Utils/miniaudio/miniaudio.h", "rank": 69, "score": 80755.62479326654 }, { "content": " float* pNewGains;\n", "file_path": "src/Utils/miniaudio/miniaudio.h", "rank": 70, "score": 80176.13771310567 }, { "content": " class BusInternalState;\n\n struct EngineInternalState;\n\n\n\n struct SwitchContainerItem\n\n {\n\n AmObjectID m_id;\n\n bool m_continueBetweenStates;\n\n AmTime m_fadeInDuration;\n\n AmUInt8 m_fadeInAlgorithm;\n\n AmTime m_fadeOutDuration;\n\n AmUInt8 m_fadeOutAlgorithm;\n\n RtpcValue m_gain;\n\n };\n\n\n", "file_path": "include/SparkyStudios/Audio/Amplitude/Sound/SwitchContainer.h", "rank": 71, "score": 79838.18304054478 }, { "content": " Curve gain;\n", "file_path": "src/Core/EngineInternalState.h", "rank": 72, "score": 79407.77331220993 }, { "content": " drwav_int32 delta[2];\n", "file_path": "src/Core/Codecs/WAV/dr_wav.h", "rank": 73, "score": 78180.89220724825 }, { "content": " float* pNewChannelGainsOut; /* An offset of _pHeap. Used by ma_spatializer_process_pcm_frames() to store new channel gains. The number of elements in this array is equal to config.channelsOut. */\n", "file_path": "src/Utils/miniaudio/miniaudio.h", "rank": 74, "score": 77690.6523500622 }, { "content": " size_t newGainsOffset;\n", "file_path": "src/Utils/miniaudio/miniaudio.h", "rank": 75, "score": 77684.84247560264 }, { "content": " size_t newChannelGainsOffset;\n", "file_path": "src/Utils/miniaudio/miniaudio.h", "rank": 76, "score": 75343.70436137967 }, { "content": " class EntityInternalState\n\n {\n\n public:\n\n EntityInternalState();\n\n\n\n /**\n\n * @brief Gets the ID of this Entity in game.\n\n *\n\n * @return The game Entity ID.\n\n */\n\n [[nodiscard]] AmEntityID GetId() const;\n\n\n\n /**\n\n * @brief Sets the ID of this Entity in game.\n\n *\n\n * @param id The game Entity ID.\n\n */\n\n void SetId(AmEntityID id);\n\n\n\n /**\n", "file_path": "src/Core/EntityInternalState.h", "rank": 77, "score": 58209.405099555705 }, { "content": " class ListenerInternalState\n\n {\n\n public:\n\n ListenerInternalState();\n\n\n\n /**\n\n * @brief Gets the ID of this Listener in game.\n\n *\n\n * @return The game Listener ID.\n\n */\n\n [[nodiscard]] AmListenerID GetId() const;\n\n\n\n /**\n\n * @brief Sets the ID of this Listener in game.\n\n *\n\n * @param id The game Listener ID.\n\n */\n\n void SetId(AmListenerID id);\n\n\n\n /**\n", "file_path": "src/Core/ListenerInternalState.h", "rank": 78, "score": 58207.962002543856 }, { "content": "namespace SparkyStudios::Audio::Amplitude\n\n{\n\n Listener::Listener()\n\n : _state(nullptr)\n\n {}\n\n\n\n Listener::Listener(ListenerInternalState* state)\n\n : _state(state)\n\n {}\n\n\n\n void Listener::Clear()\n\n {\n\n _state = nullptr;\n\n }\n\n\n\n bool Listener::Valid() const\n\n {\n\n return _state != nullptr && _state->GetId() != kAmInvalidObjectId && _state->node.in_list();\n\n }\n\n\n", "file_path": "src/Core/Listener.cpp", "rank": 79, "score": 51691.525093473225 }, { "content": " Entity::Entity()\n\n : _state(nullptr)\n\n {}\n\n\n\n Entity::Entity(EntityInternalState* state)\n\n : _state(state)\n\n {}\n\n\n\n void Entity::Clear()\n\n {\n\n _state = nullptr;\n\n }\n\n\n\n bool Entity::Valid() const\n\n {\n\n return _state != nullptr && _state->GetId() != kAmInvalidObjectId && _state->node.in_list();\n\n }\n\n\n\n AmEntityID Entity::GetId() const\n\n {\n", "file_path": "src/Core/Entity.cpp", "rank": 80, "score": 51690.16946763257 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Entity.h>\n\n\n\n#include <Core/EntityInternalState.h>\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n", "file_path": "src/Core/Entity.cpp", "rank": 81, "score": 51686.38015417035 }, { "content": " {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->SetObstruction(obstruction);\n\n }\n\n\n\n void Entity::SetOcclusion(AmReal32 occlusion)\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->SetOcclusion(occlusion);\n\n }\n\n\n\n AmReal32 Entity::GetObstruction() const\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n return _state->GetObstruction();\n\n }\n\n\n\n AmReal32 Entity::GetOcclusion() const\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n return _state->GetOcclusion();\n\n }\n\n\n\n EntityInternalState* Entity::GetState() const\n\n {\n\n return _state;\n\n }\n\n} // namespace SparkyStudios::Audio::Amplitude\n", "file_path": "src/Core/Entity.cpp", "rank": 82, "score": 51686.01833393406 }, { "content": "\n\n _gainCurve.Initialize(definition->gain_curve());\n\n\n\n _shape = AttenuationShape::Create(definition->shape());\n\n\n\n return true;\n\n }\n\n\n\n bool Attenuation::LoadAttenuationDefinitionFromFile(AmOsString filename)\n\n {\n\n std::string source;\n\n return LoadFile(filename, &source) && LoadAttenuationDefinition(source);\n\n }\n\n\n\n float Attenuation::GetGain(const hmm_vec3& soundLocation, const ListenerInternalState* listener) const\n\n {\n\n return _shape->GetAttenuationFactor(this, soundLocation, listener);\n\n }\n\n\n\n float Attenuation::GetGain(const EntityInternalState* entity, const ListenerInternalState* listener) const\n", "file_path": "src/Sound/Attenuation.cpp", "rank": 83, "score": 51685.52567511867 }, { "content": " AmListenerID Listener::GetId() const\n\n {\n\n return _state->GetId();\n\n }\n\n\n\n void Listener::SetOrientation(const hmm_vec3& direction, const hmm_vec3& up)\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->SetOrientation(direction, up);\n\n }\n\n\n\n hmm_vec3 Listener::GetLocation() const\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n return _state->GetLocation();\n\n }\n\n\n\n void Listener::SetLocation(const hmm_vec3& location)\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->SetLocation(location);\n\n }\n\n} // namespace SparkyStudios::Audio::Amplitude\n", "file_path": "src/Core/Listener.cpp", "rank": 84, "score": 51684.628065718134 }, { "content": "\n\n const hmm_vec3& Entity::GetDirection() const\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n return _state->GetDirection();\n\n }\n\n\n\n const hmm_vec3& Entity::GetUp() const\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n return _state->GetUp();\n\n }\n\n\n\n void Entity::Update()\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->Update();\n\n }\n\n\n\n void Entity::SetObstruction(AmReal32 obstruction)\n", "file_path": "src/Core/Entity.cpp", "rank": 85, "score": 51683.89400487297 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Common.h>\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Core/Listener.h>\n\n\n\n#include <Core/ListenerInternalState.h>\n\n\n", "file_path": "src/Core/Listener.cpp", "rank": 86, "score": 51683.86966246855 }, { "content": " return _state->GetId();\n\n }\n\n\n\n void Entity::SetLocation(const hmm_vec3& location)\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->SetLocation(location);\n\n }\n\n\n\n const hmm_vec3& Entity::GetLocation() const\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n return _state->GetLocation();\n\n }\n\n\n\n void Entity::SetOrientation(const hmm_vec3& direction, const hmm_vec3& up)\n\n {\n\n AMPLITUDE_ASSERT(Valid());\n\n _state->SetOrientation(direction, up);\n\n }\n", "file_path": "src/Core/Entity.cpp", "rank": 87, "score": 51682.9350351394 }, { "content": "namespace SparkyStudios::Audio::Amplitude\n\n{\n\n Attenuation::Attenuation()\n\n : _gainCurve()\n\n , _id(kAmInvalidObjectId)\n\n , _name()\n\n , _maxDistance(0.0f)\n\n , _shape(nullptr)\n\n , _refCounter()\n\n {}\n\n\n\n bool Attenuation::LoadAttenuationDefinition(const std::string& attenuation)\n\n {\n\n _source = attenuation;\n\n const AttenuationDefinition* definition = GetAttenuationDefinition();\n\n\n\n _id = definition->id();\n\n _name = definition->name()->str();\n\n\n\n _maxDistance = definition->max_distance();\n", "file_path": "src/Sound/Attenuation.cpp", "rank": 88, "score": 51680.83384928255 }, { "content": " {\n\n return &_refCounter;\n\n }\n\n\n\n AttenuationShape* Attenuation::GetShape() const\n\n {\n\n return _shape;\n\n }\n\n\n\n const Curve& Attenuation::GetGainCurve() const\n\n {\n\n return _gainCurve;\n\n }\n\n\n\n double Attenuation::GetMaxDistance() const\n\n {\n\n return _maxDistance;\n\n }\n\n} // namespace SparkyStudios::Audio::Amplitude", "file_path": "src/Sound/Attenuation.cpp", "rank": 89, "score": 51679.82511723951 }, { "content": " {\n\n return _shape->GetAttenuationFactor(this, entity, listener);\n\n }\n\n\n\n AmAttenuationID Attenuation::GetId() const\n\n {\n\n return _id;\n\n }\n\n\n\n const std::string& Attenuation::GetName() const\n\n {\n\n return _name;\n\n }\n\n\n\n const AttenuationDefinition* Attenuation::GetAttenuationDefinition() const\n\n {\n\n return Amplitude::GetAttenuationDefinition(_source.c_str());\n\n }\n\n\n\n RefCounter* Attenuation::GetRefCounter()\n", "file_path": "src/Sound/Attenuation.cpp", "rank": 90, "score": 51675.96375043355 }, { "content": " {\n\n _states[i].m_id = definition->states()->Get(i)->id();\n\n _states[i].m_name = definition->states()->Get(i)->name()->str();\n\n }\n\n\n\n return true;\n\n }\n\n\n\n bool Switch::LoadSwitchDefinitionFromFile(AmOsString filename)\n\n {\n\n std::string source;\n\n return Amplitude::LoadFile(filename, &source) && LoadSwitchDefinition(source);\n\n }\n\n\n\n const SwitchDefinition* Switch::GetSwitchDefinition() const\n\n {\n\n return Amplitude::GetSwitchDefinition(_source.c_str());\n\n }\n\n\n\n AmSwitchID Switch::GetId() const\n", "file_path": "src/Sound/Switch.cpp", "rank": 91, "score": 51668.332351701014 }, { "content": " , _name()\n\n , _activeState()\n\n , _states()\n\n , _refCounter()\n\n {}\n\n\n\n bool Switch::LoadSwitchDefinition(const std::string& switchDefinition)\n\n {\n\n AMPLITUDE_ASSERT(_id == kAmInvalidObjectId);\n\n\n\n _source = switchDefinition;\n\n const SwitchDefinition* definition = GetSwitchDefinition();\n\n\n\n _id = definition->id();\n\n _name = definition->name()->str();\n\n\n\n flatbuffers::uoffset_t size = definition->states() ? definition->states()->size() : 0;\n\n _states.resize(size);\n\n\n\n for (flatbuffers::uoffset_t i = 0; i < size; ++i)\n", "file_path": "src/Sound/Switch.cpp", "rank": 92, "score": 51667.7586547279 }, { "content": "\n\n const std::vector<SwitchState>& Switch::GetSwitchStates() const\n\n {\n\n return _states;\n\n }\n\n\n\n RefCounter* Switch::GetRefCounter()\n\n {\n\n return &_refCounter;\n\n }\n\n} // namespace SparkyStudios::Audio::Amplitude\n", "file_path": "src/Sound/Switch.cpp", "rank": 93, "score": 51666.35644555039 }, { "content": "namespace SparkyStudios::Audio::Amplitude\n\n{\n\n bool SwitchState::Valid() const\n\n {\n\n return m_id != kAmInvalidObjectId && !m_name.empty();\n\n }\n\n\n\n bool SwitchState::operator==(const SwitchState& other) const\n\n {\n\n return m_id == other.m_id && m_name == other.m_name;\n\n }\n\n\n\n bool SwitchState::operator!=(const SwitchState& other) const\n\n {\n\n return !(*this == other);\n\n }\n\n\n\n Switch::Switch()\n\n : _source()\n\n , _id(kAmInvalidObjectId)\n", "file_path": "src/Sound/Switch.cpp", "rank": 94, "score": 51665.66947704277 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Switch.h>\n\n\n\n#include <Core/EngineInternalState.h>\n\n\n\n#include \"switch_definition_generated.h\"\n\n\n", "file_path": "src/Sound/Switch.cpp", "rank": 95, "score": 51665.46586218318 }, { "content": "// Copyright (c) 2021-present Sparky Studios. All rights reserved.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#include <SparkyStudios/Audio/Amplitude/Sound/Attenuation.h>\n\n\n\n#include <Core/EngineInternalState.h>\n\n\n\n#include \"attenuation_definition_generated.h\"\n\n\n", "file_path": "src/Sound/Attenuation.cpp", "rank": 96, "score": 51664.18495521791 }, { "content": " const ListenerList& listeners,\n\n const float userGain,\n\n ListenerFetchMode fetchMode)\n\n {\n\n *gain = soundGain * bus->GetGain() * userGain;\n\n if (spatialization == Spatialization_Position || spatialization == Spatialization_PositionOrientation)\n\n {\n\n ListenerList::const_iterator listener;\n\n float distanceSquared;\n\n hmm_vec3 listenerSpaceLocation;\n\n if (BestListener(&listener, &distanceSquared, &listenerSpaceLocation, listeners, location, fetchMode))\n\n {\n\n if (attenuation != nullptr)\n\n {\n\n if (spatialization == Spatialization_PositionOrientation)\n\n {\n\n AMPLITUDE_ASSERT(entity.Valid());\n\n *gain *= attenuation->GetGain(entity.GetState(), &*listener);\n\n }\n\n else\n", "file_path": "src/Core/Engine.cpp", "rank": 97, "score": 27.06366181208948 }, { "content": " &gain, &pan, switchContainer->GetGain().GetValue(), switchContainer->GetBus(), definition->spatialization(),\n\n switchContainer->GetAttenuation(), channel->GetEntity(), channel->GetLocation(), state->listener_list,\n\n channel->GetUserGain(), state->listener_fetch_mode);\n\n channel->SetGain(gain);\n\n channel->SetPan(pan);\n\n }\n\n else if (const Collection* collection = channel->GetCollection(); collection != nullptr)\n\n {\n\n const CollectionDefinition* definition = collection->GetCollectionDefinition();\n\n\n\n float gain;\n\n hmm_vec2 pan;\n\n CalculateGainAndPan(\n\n &gain, &pan, collection->GetGain().GetValue(), collection->GetBus(), definition->spatialization(),\n\n collection->GetAttenuation(), channel->GetEntity(), channel->GetLocation(), state->listener_list, channel->GetUserGain(),\n\n state->listener_fetch_mode);\n\n channel->SetGain(gain);\n\n channel->SetPan(pan);\n\n }\n\n else if (const Sound* sound = channel->GetSound(); sound != nullptr)\n", "file_path": "src/Core/Engine.cpp", "rank": 98, "score": 23.520858133963145 }, { "content": "#include <Sound/Schedulers/RandomScheduler.h>\n\n#include <Sound/Schedulers/SequenceScheduler.h>\n\n\n\n#include \"collection_definition_generated.h\"\n\n\n\nnamespace SparkyStudios::Audio::Amplitude\n\n{\n\n Collection::Collection()\n\n : _bus(nullptr)\n\n , _worldScopeScheduler(nullptr)\n\n , _entityScopeSchedulers()\n\n , _source()\n\n , _sounds()\n\n , _soundSettings()\n\n , _id(kAmInvalidObjectId)\n\n , _name()\n\n , _gain()\n\n , _priority()\n\n , _effect(nullptr)\n\n , _attenuation(nullptr)\n", "file_path": "src/Sound/Collection.cpp", "rank": 99, "score": 23.145163025885342 } ]
C++
LargeBarrelAnalysis/tests/TimeWindowCreatorToolsTest.cpp
kdulski/j-pet-framework-examples
ab2592a2c6cf8f901f5732f8878b750b9a7b6a49
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE TimeWindowCreatorToolsTest #include "../TimeWindowCreatorTools.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(TimeWindowCreatorToolsTestSuite) BOOST_AUTO_TEST_CASE(sortByValue_test) { JPetPM pm1(1, "first"); JPetSigCh sigCh1(JPetSigCh::Leading, 1.0); JPetSigCh sigCh2(JPetSigCh::Trailing, 4.0); JPetSigCh sigCh3(JPetSigCh::Leading, 2.0); JPetSigCh sigCh4(JPetSigCh::Leading, 6.0); JPetSigCh sigCh5(JPetSigCh::Trailing, 5.0); JPetSigCh sigCh6(JPetSigCh::Leading, 3.0); sigCh1.setPM(pm1); sigCh2.setPM(pm1); sigCh3.setPM(pm1); sigCh4.setPM(pm1); sigCh5.setPM(pm1); sigCh6.setPM(pm1); std::vector<JPetSigCh> sigChs; sigChs.push_back(sigCh1); sigChs.push_back(sigCh2); sigChs.push_back(sigCh3); sigChs.push_back(sigCh4); sigChs.push_back(sigCh5); sigChs.push_back(sigCh6); BOOST_REQUIRE_EQUAL(sigChs.at(0).getValue(), 1.0); BOOST_REQUIRE_EQUAL(sigChs.at(1).getValue(), 4.0); BOOST_REQUIRE_EQUAL(sigChs.at(2).getValue(), 2.0); BOOST_REQUIRE_EQUAL(sigChs.at(3).getValue(), 6.0); BOOST_REQUIRE_EQUAL(sigChs.at(4).getValue(), 5.0); BOOST_REQUIRE_EQUAL(sigChs.at(5).getValue(), 3.0); TimeWindowCreatorTools::sortByValue(sigChs); BOOST_REQUIRE_EQUAL(sigChs.at(0).getValue(), 1.0); BOOST_REQUIRE_EQUAL(sigChs.at(1).getValue(), 2.0); BOOST_REQUIRE_EQUAL(sigChs.at(2).getValue(), 3.0); BOOST_REQUIRE_EQUAL(sigChs.at(3).getValue(), 4.0); BOOST_REQUIRE_EQUAL(sigChs.at(4).getValue(), 5.0); BOOST_REQUIRE_EQUAL(sigChs.at(5).getValue(), 6.0); } BOOST_AUTO_TEST_CASE(generateSigCh_test) { JPetFEB feb(1, true, "just great", "very nice front-end board", 1, 1, 4, 4); JPetTRB trb(2, 555, 333); std::pair<float, float> hvGains(23.4, 43.2); JPetPM pm(JPetPM::SideA, 23, 123, 321, hvGains, "average pm"); JPetTOMBChannel channel(123); channel.setFEB(feb); channel.setTRB(trb); channel.setPM(pm); channel.setThreshold(34.5); channel.setLocalChannelNumber(1); std::map<unsigned int, std::vector<double>> thresholdsMap; std::map<unsigned int, std::vector<double>> timeCalibrationMap; std::vector<double> calibVec; calibVec.push_back(22.0); calibVec.push_back(33.0); calibVec.push_back(44.0); timeCalibrationMap[123] = calibVec; auto sigCh = TimeWindowCreatorTools::generateSigCh( 50.0, channel, timeCalibrationMap, thresholdsMap, JPetSigCh::Trailing, true); auto epsilon = 0.0001; BOOST_REQUIRE_EQUAL(sigCh.getType(), JPetSigCh::Trailing); BOOST_REQUIRE_EQUAL(sigCh.getPM().getID(), 23); BOOST_REQUIRE_EQUAL(sigCh.getFEB().getID(), 1); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getID(), 2); BOOST_REQUIRE_EQUAL(sigCh.getDAQch(), 123); BOOST_REQUIRE_EQUAL(sigCh.getThresholdNumber(), 1); BOOST_REQUIRE_CLOSE(sigCh.getThreshold(), 34.5, epsilon); BOOST_REQUIRE_CLOSE(sigCh.getValue(), 1000.0 * (50.0 + 22.0), epsilon); } BOOST_AUTO_TEST_CASE(flagSigChs_test) { JPetSigCh sigCh00(JPetSigCh::Leading, 10.0); JPetSigCh sigCh01(JPetSigCh::Trailing, 11.0); JPetSigCh sigCh02(JPetSigCh::Leading, 12.0); JPetSigCh sigCh03(JPetSigCh::Leading, 13.0); JPetSigCh sigCh04(JPetSigCh::Trailing, 14.0); JPetSigCh sigCh05(JPetSigCh::Leading, 15.0); JPetSigCh sigCh06(JPetSigCh::Trailing, 16.0); JPetSigCh sigCh07(JPetSigCh::Leading, 17.0); JPetSigCh sigCh08(JPetSigCh::Trailing, 18.0); JPetSigCh sigCh09(JPetSigCh::Leading, 19.0); JPetSigCh sigCh10(JPetSigCh::Trailing, 20.0); JPetSigCh sigCh11(JPetSigCh::Trailing, 21.0); JPetSigCh sigCh12(JPetSigCh::Leading, 22.0); JPetSigCh sigCh13(JPetSigCh::Trailing, 23.0); JPetSigCh sigCh14(JPetSigCh::Leading, 24.0); JPetSigCh sigCh15(JPetSigCh::Leading, 25.0); JPetSigCh sigCh16(JPetSigCh::Leading, 26.0); JPetSigCh sigCh17(JPetSigCh::Trailing, 27.0); JPetSigCh sigCh18(JPetSigCh::Leading, 28.0); JPetSigCh sigCh19(JPetSigCh::Trailing, 29.0); JPetSigCh sigCh20(JPetSigCh::Leading, 30.0); JPetSigCh sigCh21(JPetSigCh::Trailing, 31.0); JPetSigCh sigCh22(JPetSigCh::Trailing, 32.0); JPetSigCh sigCh23(JPetSigCh::Trailing, 33.0); JPetSigCh sigCh24(JPetSigCh::Trailing, 33.0); JPetSigCh sigCh25(JPetSigCh::Leading, 34.0); JPetSigCh sigCh26(JPetSigCh::Trailing, 35.0); JPetSigCh sigCh27(JPetSigCh::Leading, 36.0); JPetPM pm1(1, "first"); sigCh00.setPM(pm1); sigCh01.setPM(pm1); sigCh02.setPM(pm1); sigCh03.setPM(pm1); sigCh04.setPM(pm1); sigCh05.setPM(pm1); sigCh06.setPM(pm1); sigCh07.setPM(pm1); sigCh08.setPM(pm1); sigCh09.setPM(pm1); sigCh10.setPM(pm1); sigCh11.setPM(pm1); sigCh12.setPM(pm1); sigCh13.setPM(pm1); sigCh14.setPM(pm1); sigCh15.setPM(pm1); sigCh16.setPM(pm1); sigCh17.setPM(pm1); sigCh18.setPM(pm1); sigCh19.setPM(pm1); sigCh20.setPM(pm1); sigCh21.setPM(pm1); sigCh22.setPM(pm1); sigCh23.setPM(pm1); sigCh24.setPM(pm1); sigCh25.setPM(pm1); sigCh26.setPM(pm1); sigCh27.setPM(pm1); std::vector<JPetSigCh> thrSigCh; thrSigCh.push_back(sigCh00); thrSigCh.push_back(sigCh01); thrSigCh.push_back(sigCh02); thrSigCh.push_back(sigCh03); thrSigCh.push_back(sigCh04); thrSigCh.push_back(sigCh05); thrSigCh.push_back(sigCh06); thrSigCh.push_back(sigCh07); thrSigCh.push_back(sigCh08); thrSigCh.push_back(sigCh09); thrSigCh.push_back(sigCh10); thrSigCh.push_back(sigCh11); thrSigCh.push_back(sigCh12); thrSigCh.push_back(sigCh13); thrSigCh.push_back(sigCh14); thrSigCh.push_back(sigCh15); thrSigCh.push_back(sigCh16); thrSigCh.push_back(sigCh17); thrSigCh.push_back(sigCh18); thrSigCh.push_back(sigCh19); thrSigCh.push_back(sigCh20); thrSigCh.push_back(sigCh21); thrSigCh.push_back(sigCh22); thrSigCh.push_back(sigCh23); thrSigCh.push_back(sigCh24); thrSigCh.push_back(sigCh25); thrSigCh.push_back(sigCh26); thrSigCh.push_back(sigCh27); JPetStatistics stats; TimeWindowCreatorTools::flagSigChs(thrSigCh, stats, false); BOOST_REQUIRE_EQUAL(thrSigCh.at(0).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(1).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(2).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(3).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(4).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(5).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(6).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(7).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(8).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(9).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(10).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(11).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(12).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(13).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(14).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(15).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(16).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(17).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(18).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(19).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(20).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(21).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(22).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(23).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(24).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(25).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(26).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(27).getRecoFlag(), JPetSigCh::Good); } BOOST_AUTO_TEST_SUITE_END()
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE TimeWindowCreatorToolsTest #include "../TimeWindowCreatorTools.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(TimeWindowCreatorToolsTestSuite) BOOST_AUTO_TEST_CASE(sortByValue_test) { JPetPM pm1(1, "first"); JPetSigCh sigCh1(JPetSigCh::Leading, 1.0); JPetSigCh sigCh2(JPetSigCh::Trailing, 4.0); JPetSigCh sigCh3(JPetSigCh::Leading, 2.0); JPetSigCh sigCh4(JPetSigCh::Leading, 6.0); JPetSigCh sigCh5(JPetSigCh::Trailing, 5.0); JPetSigCh sigCh6(JPetSigCh::Leading, 3.0); sigCh1.setPM(pm1); sigCh2.setPM(pm1); sigCh3.setPM(pm1); sigCh4.setPM(pm1); sigCh5.setPM(pm1); sigCh6.setPM(pm1); std::vector<JPetSigCh> sigChs; sigChs.push_back(sigCh1); sigChs.push_back(sigCh2); sigChs.push_back(sigCh3); sigChs.push_back(sigCh4); sigChs.push_back(sigCh5); sigChs.push_back(sigCh6); BOOST_REQUIRE_EQUAL(sigChs.at(0).getValue(), 1.0); BOOST_REQUIRE_EQUAL(sigChs.at(1).getValue(), 4.0); BOOST_REQUIRE_EQUAL(sigChs.at(2).getValue(), 2.0); BOOST_REQUIRE_EQUAL(sigChs.at(3).getValue(), 6.0); BOOST_REQUIRE_EQUAL(sigChs.at(4).getValue(), 5.0); BOOST_REQUIRE_EQUAL(sigChs.at(5).getValue(), 3.0); TimeWindowCreatorTools::sortByValue(sigChs); BOOST_REQUIRE_EQUAL(sigChs.at(0).getValue(), 1.0); BOOST_REQUIRE_EQUAL(sigChs.at(1).getValue(), 2.0); BOOST_REQUIRE_EQUAL(sigChs.at(2).getValue(), 3.0); BOOST_REQUIRE_EQUAL(sigChs.at(3).getValue(), 4.0); BOOST_REQUIRE_EQUAL(sigChs.at(4).getValue(), 5.0); BOOST_REQUIRE_EQUAL(sigChs.at(5).getValue(), 6.0); } BOOST_AUTO_TEST_CASE(generateSigCh_test) { JPetFEB feb(1, true, "just great", "very nice front-end board", 1, 1, 4, 4); JPetTRB trb(2, 555, 333); std::pair<float, float> hvGains(23.4, 43.2); JPetPM pm(JPetPM::SideA, 23, 123, 321, hvGains, "average pm"); JPetTOMBChannel channel(123); channel.setFEB(feb); channel.setTRB(trb); channel.setPM(pm); channel.setThreshold(34.5); channel.setLocalChannelNumber(1); std::map<unsigned int, std::vector<double>> thresholdsMap; std::map<unsigned int, std::vector<double>> timeCalibrationMap; std::vector<double> calibVec; calibVec.push_back(22.0); calibVec.push_back(33.0); calibVec.push_back(44.0); timeCalibrationMap[123] = calibVec; auto sigCh = TimeWindowCreatorTools::generateSigCh( 50.0, channel, timeCalibrationMap, thresholdsMap, JPetSigCh::Trai
BOOST_AUTO_TEST_CASE(flagSigChs_test) { JPetSigCh sigCh00(JPetSigCh::Leading, 10.0); JPetSigCh sigCh01(JPetSigCh::Trailing, 11.0); JPetSigCh sigCh02(JPetSigCh::Leading, 12.0); JPetSigCh sigCh03(JPetSigCh::Leading, 13.0); JPetSigCh sigCh04(JPetSigCh::Trailing, 14.0); JPetSigCh sigCh05(JPetSigCh::Leading, 15.0); JPetSigCh sigCh06(JPetSigCh::Trailing, 16.0); JPetSigCh sigCh07(JPetSigCh::Leading, 17.0); JPetSigCh sigCh08(JPetSigCh::Trailing, 18.0); JPetSigCh sigCh09(JPetSigCh::Leading, 19.0); JPetSigCh sigCh10(JPetSigCh::Trailing, 20.0); JPetSigCh sigCh11(JPetSigCh::Trailing, 21.0); JPetSigCh sigCh12(JPetSigCh::Leading, 22.0); JPetSigCh sigCh13(JPetSigCh::Trailing, 23.0); JPetSigCh sigCh14(JPetSigCh::Leading, 24.0); JPetSigCh sigCh15(JPetSigCh::Leading, 25.0); JPetSigCh sigCh16(JPetSigCh::Leading, 26.0); JPetSigCh sigCh17(JPetSigCh::Trailing, 27.0); JPetSigCh sigCh18(JPetSigCh::Leading, 28.0); JPetSigCh sigCh19(JPetSigCh::Trailing, 29.0); JPetSigCh sigCh20(JPetSigCh::Leading, 30.0); JPetSigCh sigCh21(JPetSigCh::Trailing, 31.0); JPetSigCh sigCh22(JPetSigCh::Trailing, 32.0); JPetSigCh sigCh23(JPetSigCh::Trailing, 33.0); JPetSigCh sigCh24(JPetSigCh::Trailing, 33.0); JPetSigCh sigCh25(JPetSigCh::Leading, 34.0); JPetSigCh sigCh26(JPetSigCh::Trailing, 35.0); JPetSigCh sigCh27(JPetSigCh::Leading, 36.0); JPetPM pm1(1, "first"); sigCh00.setPM(pm1); sigCh01.setPM(pm1); sigCh02.setPM(pm1); sigCh03.setPM(pm1); sigCh04.setPM(pm1); sigCh05.setPM(pm1); sigCh06.setPM(pm1); sigCh07.setPM(pm1); sigCh08.setPM(pm1); sigCh09.setPM(pm1); sigCh10.setPM(pm1); sigCh11.setPM(pm1); sigCh12.setPM(pm1); sigCh13.setPM(pm1); sigCh14.setPM(pm1); sigCh15.setPM(pm1); sigCh16.setPM(pm1); sigCh17.setPM(pm1); sigCh18.setPM(pm1); sigCh19.setPM(pm1); sigCh20.setPM(pm1); sigCh21.setPM(pm1); sigCh22.setPM(pm1); sigCh23.setPM(pm1); sigCh24.setPM(pm1); sigCh25.setPM(pm1); sigCh26.setPM(pm1); sigCh27.setPM(pm1); std::vector<JPetSigCh> thrSigCh; thrSigCh.push_back(sigCh00); thrSigCh.push_back(sigCh01); thrSigCh.push_back(sigCh02); thrSigCh.push_back(sigCh03); thrSigCh.push_back(sigCh04); thrSigCh.push_back(sigCh05); thrSigCh.push_back(sigCh06); thrSigCh.push_back(sigCh07); thrSigCh.push_back(sigCh08); thrSigCh.push_back(sigCh09); thrSigCh.push_back(sigCh10); thrSigCh.push_back(sigCh11); thrSigCh.push_back(sigCh12); thrSigCh.push_back(sigCh13); thrSigCh.push_back(sigCh14); thrSigCh.push_back(sigCh15); thrSigCh.push_back(sigCh16); thrSigCh.push_back(sigCh17); thrSigCh.push_back(sigCh18); thrSigCh.push_back(sigCh19); thrSigCh.push_back(sigCh20); thrSigCh.push_back(sigCh21); thrSigCh.push_back(sigCh22); thrSigCh.push_back(sigCh23); thrSigCh.push_back(sigCh24); thrSigCh.push_back(sigCh25); thrSigCh.push_back(sigCh26); thrSigCh.push_back(sigCh27); JPetStatistics stats; TimeWindowCreatorTools::flagSigChs(thrSigCh, stats, false); BOOST_REQUIRE_EQUAL(thrSigCh.at(0).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(1).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(2).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(3).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(4).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(5).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(6).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(7).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(8).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(9).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(10).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(11).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(12).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(13).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(14).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(15).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(16).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(17).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(18).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(19).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(20).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(21).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(22).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(23).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(24).getRecoFlag(), JPetSigCh::Corrupted); BOOST_REQUIRE_EQUAL(thrSigCh.at(25).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(26).getRecoFlag(), JPetSigCh::Good); BOOST_REQUIRE_EQUAL(thrSigCh.at(27).getRecoFlag(), JPetSigCh::Good); } BOOST_AUTO_TEST_SUITE_END()
ling, true); auto epsilon = 0.0001; BOOST_REQUIRE_EQUAL(sigCh.getType(), JPetSigCh::Trailing); BOOST_REQUIRE_EQUAL(sigCh.getPM().getID(), 23); BOOST_REQUIRE_EQUAL(sigCh.getFEB().getID(), 1); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getID(), 2); BOOST_REQUIRE_EQUAL(sigCh.getDAQch(), 123); BOOST_REQUIRE_EQUAL(sigCh.getThresholdNumber(), 1); BOOST_REQUIRE_CLOSE(sigCh.getThreshold(), 34.5, epsilon); BOOST_REQUIRE_CLOSE(sigCh.getValue(), 1000.0 * (50.0 + 22.0), epsilon); }
function_block-function_prefixed
[ { "content": "Description of available parameters in TimeCalibration example.\n\nNote that configuration/calibration filed can be obtained from PetWiki:\n\nhttp://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses\n\n--------\n\n\n\nSave_Control_Histograms_bool\n\n--- Common for each module, if set to true, in the output ROOT files folder with\n\nstatistics will contain control histograms. Set to false if histograms not needed.\n\n\n\nStopIteration_bool\n\n---A flag indicating, that the module is called in the iterative mode with number of iterations defined in\n\nmain.cpp as the last argument (true) or with user-defined condition to exit the loop (false). In the latter case\n\none needs to put -1 as the last argument of manager.useTask (see the description of the TimeCalibration_NiterMax_int)\n\n---Default value: true\n\n\n\nUnpacker_TOToffsetCalib_std::string \n\n---Path to and name of a `ROOT` file with `TOT` offset calibrations (stretcher) applied during unpacking of `HLD` file.\n\n\n\nUnpacker_TDCnonlinearityCalib_std::string \n\n---Path to and name of a `ROOT` file with calibrations of nonlinearities occurring on `TDC` boards, applied during unpacking of `HLD` file.\n\n\n\nTimeWindowCreator_MainStrip_int\n\n--- Dedicated for files with data from measurement with Reference Detector:\n\nIn order to speed up the processing of a single position from a reference detector scan,\n\none can provide a user option indicating which scintillator strip was targeted by the reference detector.\n\nThis means that signals from any other strips will be ignored at the lowest possible level,\n\nresulting in much faster processing. For more detailes please read README\n\n\n\nTimeWindowCreator_MinTime_float\n\n--- Time Slots have certain duration for specific runs, minimum time is usually\n\nnegative.\n\n--- Default value -1*10^6 ps\n\n\n\nTimeWindowCreator_MaxTime_float\n\n--- Default value 0.0 ps\n\n\n\nSignalFinder_EdgeMaxTime_float\n\n--- time window for matching Signal Channels on Leading Edge.\n", "file_path": "TimeCalibration_iter/PARAMETERS.md", "rank": 1, "score": 22.132663128622546 }, { "content": " if (fSaveControlHistos) {\n\n initialiseHistograms();\n\n }\n\n return true;\n\n}\n\n\n\nbool TimeWindowCreator::exec() {\n\n if (auto event = dynamic_cast<EventIII *const>(fEvent)) {\n\n int kTDCChannels = event->GetTotalNTDCChannels();\n\n if (fSaveControlHistos) {\n\n getStatistics().fillHistogram(\"sig_ch_per_time_slot\", kTDCChannels);\n\n }\n\n // Loop over all TDC channels in file\n\n auto tdcChannels = event->GetTDCChannelsArray();\n\n for (int i = 0; i < kTDCChannels; ++i) {\n\n auto tdcChannel = dynamic_cast<TDCChannel *const>(tdcChannels->At(i));\n\n auto tombNumber = tdcChannel->GetChannel();\n\n // Skip trigger signals from TRB - every 65th\n\n if (tombNumber % 65 == 0)\n\n continue;\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreator.cpp", "rank": 2, "score": 20.596286166294924 }, { "content": "\n\n channels[i].setPM(pm1);\n\n channels[4+i].setPM(pm2);\n\n\n\n bank.addTOMBChannel(channels[i]);\n\n bank.addTOMBChannel(channels[4+i]);\n\n }\n\n\n\n SignalFinderTools::ThresholdOrderings orderings = SignalFinderTools::findThresholdOrders(bank);\n\n BOOST_REQUIRE_EQUAL(orderings.size(), 2);\n\n\n\n for(auto& pm: orderings){\n\n SignalFinderTools::ThresholdValues sorted_values;\n\n SignalFinderTools::ThresholdValues& orig_values = (pm.first==221 ? values_pm1 : values_pm2);\n\n for(int i=0;i<4;++i){\n\n sorted_values[pm.second[i]] = orig_values[i];\n\n }\n\n\n\n BOOST_REQUIRE_LE(sorted_values[0], sorted_values[1]);\n\n BOOST_REQUIRE_LE(sorted_values[1], sorted_values[2]);\n\n BOOST_REQUIRE_LE(sorted_values[2], sorted_values[3]);\n\n }\n\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "file_path": "LargeBarrelAnalysis/tests/SignalFinderToolsTest.cpp", "rank": 3, "score": 20.155447983252184 }, { "content": " JPetStatistics& stats, bool saveHistos\n\n){\n\n vector<JPetSigCh> allTDCSigChs;\n\n // Loop over all entries on leading edge in current TOMBChannel and create SigCh\n\n for (int j = 0; j < tdcChannel->GetLeadHitsNum(); j++) {\n\n auto leadTime = tdcChannel->GetLeadTime(j);\n\n if (leadTime > maxTime || leadTime < minTime ) { continue; }\n\n auto leadSigCh = generateSigCh(\n\n leadTime, tombChannel, timeCalibrationMap, thresholdsMap,\n\n JPetSigCh::Leading, setTHRValuesFromChannels\n\n );\n\n allTDCSigChs.push_back(leadSigCh);\n\n if (saveHistos){\n\n stats.fillHistogram(Form(\"pm_occupation_thr%d\", tombChannel.getLocalChannelNumber()),\n\n tombChannel.getPM().getID());\n\n }\n\n }\n\n // Loop over all entries on trailing edge in current TOMBChannel and create SigCh\n\n for (int j = 0; j < tdcChannel->GetTrailHitsNum(); j++) {\n\n auto trailTime = tdcChannel->GetTrailTime(j);\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreatorTools.cpp", "rank": 4, "score": 20.025408800244747 }, { "content": "`Unpacker_TOToffsetCalib_std::string` - Path to and name of a ROOT file with TOT offset calibrations (stretcher) applied during unpacking of HLD file;\n\n\n\n`Unpacker_TDCnonlinearityCalib_std::string` - Path to and name of a `ROOT` file with calibrations of nonlinearities occurring on `TDC` boards, applied during unpacking of `HLD` file.\n\n\n\n`TimeWindowCreator_MinTime_float` - Time Slots have certain duration for specific runs, minimum time is usually negative, default value `-1*10^6 ps`\n\n\n\n`TimeWindowCreator_MaxTime_float` - default value `0.0 ps`\n\n\n\n`TimeCalibLoader_ConfigFile_std::string` - Path to and name of ASCII file of required structure, containing time calibrations, specific for each run\n\n\n\n`ThresholdLoader_ConfigFile_std::string` - Path to and name of ASCII file of required structure, containing thresholds values, specific for each run\n\n\n\n`SignalFinder_UseCorruptedSigCh_bool` - if set to `true`, signal channels flagged as corrupted will be used in SignalFinder analysis, if set to `false` they will be filtered out\n\n\n\n`SignalFinder_EdgeMaxTime_float` - time window for matching Signal Channels on Leading Edge. Default value: `5 000 ps`\n\n\n\n`SignalFinder_LeadTrailMaxTime_float` - time window for matching Signal Channels on the same thresholds from Leading and Trailing edge. Default value: `25 000 ps`\n\n\n\n`SignalTransformer_UseCorruptedSignals_bool` - if set to `true`, signals flagged as corrupted will be used in SignalTransformer analysis, if set to `false` they will be filtered out\n\n\n\n`HitFinder_UseCorruptedSignals_bool` - if set to `true`, signals flagged as corrupted will be used in HitFinder analysis, if set to `false` they will be filtered out\n\n\n\n`HitFinder_VelocityFile_std::string` - name of ASCII file of required format, containing values of effective velocities of light in each scintillator\n\n\n\n`HitFinder_ABTimeDiff_float` - time window for matching Signals on the same scintillator and different sides. Default value: `6 000 ps`\n\n\n", "file_path": "VelocityCalibration/README.md", "rank": 5, "score": 19.37044358504059 }, { "content": " if(tc.second->getLocalChannelNumber() > kNumberOfThresholds){\n\n ERROR(\"Threshold sorting is meant to work with 4 thresholds only!\");\n\n return orderings;\n\n }\n\n\n\n thr_values_per_pm[pm_id][tc.second->getLocalChannelNumber()-1] = tc.second->getThreshold();\n\n }\n\n\n\n for(auto& pm: thr_values_per_pm){\n\n permuteThresholdsByValue(pm.second, orderings[pm.first]);\n\n }\n\n\n\n return orderings;\n\n}\n\n\n\n/**\n\n * Helper method for findThresholdOrders which constructs a single permutation\n\n * based on the threshold values on a single PMT\n\n *\n\n * @param threshold_values array of floating-point values of voltage thresholds set on\n", "file_path": "LargeBarrelAnalysis/SignalFinderTools.cpp", "rank": 6, "score": 19.176386843671747 }, { "content": "Description of available parameters in TimeCalibration example.\n\nNote that configuration/calibration files can be obtained from PetWiki:\n\nhttp://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses\n\n--------\n\n\n\n-------------------------userParams.json-------------------------\n\n\n\nSave_Control_Histograms_bool\n\n--- Common for each module, if set to true, in the output ROOT files folder with\n\nstatistics will contain control histograms. Set to false if histograms not needed.\n\n\n\nStopIteration_bool\n\n--- A flag indicating, that the module is called in the iterative mode with number of iterations defined in\n\nmain.cpp as the last argument (true) or with user-defined condition to exit the loop (false). In the latter case\n\none needs to put -1 as the last argument of manager.useTask (see the description of the TimeCalibration_NiterMax_int)\n\n--- Default value: true\n\n\n\nUnpacker_TOToffsetCalib_std::string \n\n--- Path to and name of a `ROOT` file with `TOT` offset calibrations (stretcher) applied during unpacking of `HLD` file.\n\n\n\nUnpacker_TDCnonlinearityCalib_std::string \n\n--- Path to and name of a `ROOT` file with calibrations of nonlinearities occurring on `TDC` boards, applied during unpacking of `HLD` file.\n\n\n\nTimeWindowCreator_MainStrip_int\n\n--- Dedicated for files with data from measurement with Reference Detector:\n\nIn order to speed up the processing of a single position from a reference detector scan,\n\none can provide a user option indicating which scintillator strip was targeted by the reference detector.\n\nThis means that signals from any other strips will be ignored at the lowest possible level,\n\nresulting in much faster processing. For more detailes please read README\n\n\n\nTimeWindowCreator_MinTime_float\n\n--- Time Slots have certain duration for specific runs, minimum time is usually\n\nnegative.\n\n--- Default value -1*10^6 ps\n\n\n\nTimeWindowCreator_MaxTime_float\n", "file_path": "TimeCalibration_lifetime/PARAMETERS.md", "rank": 7, "score": 19.14071036878237 }, { "content": "Description of available parameters in TimeCalibration example.\n\nNote that configuration/calibration filed can be obtained from PetWiki:\n\nhttp://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses\n\n--------\n\n\n\nSave_Cotrol_Histograms_bool\n\n--- Common for each module, if set to true, in the output ROOT files folder with\n\nstatistics will contain control histograms. Set to false if histograms not needed.\n\n\n\nTimeWindowCreator_MainStrip_int\n\n--- Dedicated for files with data from measurement with Reference Detector:\n\nIn order to speed up the processing of a single position from a reference detector scan,\n\none can provide a user option indicating which scintillator strip was targeted by the reference detector.\n\nThis means that signals from any other strips will be ignored at the lowest possible level,\n\nresulting in much faster processing. For more detailes please read README\n\n\n\nTimeWindowCreator_MinTime_float\n\n--- Time Slots have certain duration for specific runs, minimum time is usually\n\nnegative.\n\n--- Default value -1*10^6 ps\n\n\n\nTimeWindowCreator_MaxTime_float\n\n--- Default value 0.0 ps\n\n\n\nSignalFinder_EdgeMaxTime_float\n\n--- time window for matching Signal Channels on Leading Edge.\n\n--- Default value: 5 000 ps.\n\n\n\nSignalFinder_LeadTrailMaxTime_float\n\n--- time window for matching Signal Channels on the same thresholds from\n\nLeading and Trailing edge. Default value: 25 000 ps.\n\n\n\nHitFinder_VelocityFile_std::string\n\n--- name of ASCII file of required format, containing values of effective velocities\n\nof light in each scintillator.\n\n\n\nHitFinder_ABTimeDiff_float\n\n--- time window for matching Signals on the same scintillator and different sides\n\n--- Default value: 6 000 ps.\n\n\n\nHitFinder_RefDetScinID_int\n\n--- ID of Reference Detector Scintillator, needed for creating reference hits.\n\n--- The only value used so far: 193\n\n\n\nTimeCalibration_PMIdRef_int\n\n--- Id of the photomultiplier of the refference detector.\n", "file_path": "TimeCalibration/PARAMETERS.md", "rank": 8, "score": 18.689551605460913 }, { "content": "\n\nbool SDARecoDrawAllOffsets::exec() {\n\n if (auto signal = dynamic_cast<const JPetRecoSignal *const>(fEvent))\n\n for (unsigned int j = 0; j < fNumberOfPMTs; j++)\n\n if ((signal->getPM().getID()) == fIDs[j]) {\n\n fOffset = signal->getOffset();\n\n fOffsets[j].push_back(fOffset);\n\n break;\n\n }\n\n return true;\n\n}\n\n\n\nbool SDARecoDrawAllOffsets::terminate() {\n\n auto c1 = new TCanvas();\n\n vector<double> minimums, maximums;\n\n for (unsigned int j = 0; j < fNumberOfPMTs; j++) {\n\n minimums.push_back(JPetRecoSignalTools::min(fOffsets[j]));\n\n maximums.push_back(JPetRecoSignalTools::max(fOffsets[j]));\n\n }\n\n double maximum = JPetRecoSignalTools::max(maximums);\n", "file_path": "modules/SDA/JPetRecoDrawAllOffsets/SDARecoDrawAllOffsets.cpp", "rank": 9, "score": 18.645224415476157 }, { "content": "\n\n#include \"JPetRecoDrawAllOffsets/SDARecoDrawAllOffsets.h\"\n\n#include \"JPetRecoSignalTools/JPetRecoSignalTools.h\"\n\n#include <TLegend.h>\n\n#include <sstream>\n\nusing namespace std;\n\nSDARecoDrawAllOffsets::SDARecoDrawAllOffsets(const char *name)\n\n : JPetUserTask(name) {}\n\nSDARecoDrawAllOffsets::~SDARecoDrawAllOffsets() {}\n\nbool SDARecoDrawAllOffsets::init() {\n\n const auto &paramBank = getParamBank();\n\n fNumberOfPMTs = paramBank.getPMsSize();\n\n cout << \"Found \" << fNumberOfPMTs << \" PMTs in paramBank\\n\";\n\n for (size_t i = 0; i < fNumberOfPMTs; i++) {\n\n fIDs.push_back(paramBank.getPM(i).getID());\n\n vector<double> k;\n\n fOffsets.push_back(k);\n\n }\n\n return true;\n\n}\n", "file_path": "modules/SDA/JPetRecoDrawAllOffsets/SDARecoDrawAllOffsets.cpp", "rank": 10, "score": 18.532630370804718 }, { "content": " sigCh2.setRecoFlag(JPetSigCh::Corrupted);\n\n if(saveHistos){\n\n stats.fillHistogram(\"good_vs_bad_sigch\", 2);\n\n stats.fillHistogram(\"TT_per_PM\", sigCh1.getPM().getID());\n\n stats.fillHistogram(\"TT_per_THR\", sigCh1.getThresholdNumber());\n\n stats.fillHistogram(\"TT_time_diff\", sigCh2.getValue()-sigCh1.getValue());\n\n }\n\n }\n\n if(sigCh1.getRecoFlag() == JPetSigCh::Unknown && saveHistos){\n\n stats.fillHistogram(\"good_vs_bad_sigch\", 3);\n\n }\n\n }\n\n}\n\n\n\n/**\n\n* Sets up Signal Channel fields\n\n*/\n\nJPetSigCh TimeWindowCreatorTools::generateSigCh(\n\n double tdcChannelTime, const JPetTOMBChannel& channel,\n\n map<unsigned int, vector<double>>& timeCalibrationMap,\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreatorTools.cpp", "rank": 11, "score": 18.49444821819496 }, { "content": "# ImageReconstruction parameters description\n\n\n\n## Contents\n\n\n\nDescription of available parameters in ImageReconstruction example.\n\n\n\n- `FilterEvents_Cut_On_Z_Value_float` \n\n Events with Z value greater then this value will not be included in output file. [cm]\n\n\n\n- `FilterEvents_Cut_On_LOR_Distance_From_Center_float`\n\n Events with LOR distance greater then this value will not be included in output file [cm]\n\n\n\n- `FilterEvents_TOT_Min_Value_In_Ns_float`\n\n Events with sum of TOT with value less then this value will not be included in output file [ns]\n\n\n\n- `FilterEvents_TOT_Max_Value_In_Ns_float`\n\n Events with sum of TOT with value greater then this value will not be included in output file [ns]\n\n\n\n- `FilterEvents_Angle_Delta_Min_Value_float`\n\n Events that hits have angle differences value less then this value will not be included in output file [degrees]\n\n\n\n- `MLEMRunner_OutFileName_std::string`\n\n Path to file where will be saved converted data for futher reconstruction in j-pet-mlem [string]\n\n\n\n- `MLEMRunner_NumberOfPixelsInOneDimension_int`\n\n Number of pixels in reconstructed image in one demension [px]\n\n\n\n- `MLEMRunner_PixelSize_double`\n\n Size of 1 pixel in reconstructed image [m]\n\n\n\n- `MLEMRunner_StartPixelForPartialMatrix_int`\n\n Start pixel of partial matrix.\n\n\n\n- `MLEMRunner_NumberOfEmissionsPerPixel_int`\n\n Number of emmisions per pixel for system matrix.\n\n\n\n- `MLEMRunner_TOFStepSize_double`\n\n TOF step size [m]\n\n\n\n- `MLEMRunner_TOFSigmaAxis_float`\n\n TOF sigma [m]\n\n\n\n- `MLEMRunner_TOFSigmaAlongZAxis_float`\n\n TOF sigma along Z axis [m]\n\n\n\n- `MLEMRunner_DisplayInfo_bool`\n\n If true display extra info about reconstruction into cerr\n\n\n\n- `MLEMRunner_SystemMatrixOutputPath_std::string`\n\n Path to file where system matrix will be saved and from what file read system matrix if already generated\n\n\n\n- `MLEMRunner_SystemMatrixSaveFull_bool`\n", "file_path": "ImageReconstruction/PARAMETERS.md", "rank": 12, "score": 18.39695378852926 }, { "content": " return ok;\n\n });\n\n if (allOptionsExist) {\n\n TOTcut[0] = getOptionAsFloat(opts, kTOTCutLowOptName);\n\n TOTcut[1] = getOptionAsFloat(opts, kTOTCutHighOptName);\n\n int code = getOptionAsInt(opts, kMainStripOptName);\n\n fLayerToCalib = code / 100;\n\n fStripToCalib = code % 100;\n\n fIsCorrection = getOptionAsBool(opts, kLoadConstantsOptName);\n\n fTimeConstantsCalibFileNameTmp = getOptionAsString(opts, kCalibFileTmpOptName );\n\n fTimeConstantsCalibFileName = getOptionAsString(opts, kCalibFileFinalOptName );\n\n kPMIdRef = getOptionAsInt(opts, kPMIdRefOptName);\n\n NiterMax = getOptionAsInt(opts,MaxIterNumOptName); \n\n return true;\n\n } else {\n\n return false;\n\n }\n\n}\n\n\n\nvoid TimeCalibration::createHistograms()\n", "file_path": "TimeCalibration_iter/TimeCalibration.cpp", "rank": 13, "score": 18.22673943964369 }, { "content": " hit.setQualityOfTimeDiff(-1.0);\n\n hit.setEnergy(-1.0);\n\n hit.setQualityOfEnergy(-1.0);\n\n hit.setScintillator(signalB.getPM().getScin());\n\n hit.setBarrelSlot(signalB.getPM().getBarrelSlot());\n\n return hit;\n\n}\n\n\n\n/**\n\n * Helper method for getting TOMB channel\n\n */\n\nint HitFinderTools::getProperChannel(const JPetPhysSignal& signal)\n\n{\n\n auto someSigCh = signal.getRecoSignal().getRawSignal()\n\n .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrValue)[0];\n\n return someSigCh.getTOMBChannel().getChannel();\n\n}\n\n\n\n/**\n\n* Helper method for checking if theta is in radians\n", "file_path": "LargeBarrelAnalysis/HitFinderTools.cpp", "rank": 14, "score": 18.02910040750766 }, { "content": " }\n\n return false;\n\n}\n\n\n\nvoid TimeWindowCreator::initialiseHistograms() {\n\n getStatistics().createHistogramWithAxes(new TH1D(\"sig_ch_per_time_slot\", \"Signal Channels Per Time Slot\", 250, -0.125, 999.875),\n\n \"Signal Channels in Time Slot\", \"Number of Time Slots\");\n\n\n\n for (int i = 1; i <= kNumOfThresholds; i++) {\n\n getStatistics().createHistogramWithAxes(new TH1D(Form(\"pm_occupation_thr%d\", i), Form(\"Signal Channels per PM on THR %d\", i), \n\n 385, 0.5, 385.5), \"PM ID)\", \"Number of Signal Channels\");\n\n }\n\n\n\n getStatistics().createHistogramWithAxes(\n\n new TH1D(\"good_vs_bad_sigch\", \"Number of good and corrupted SigChs created\",\n\n 3, 0.5, 3.5), \"Quality\", \"Number of SigChs\");\n\n std::vector<std::pair<unsigned, std::string>> binLabels;\n\n binLabels.push_back(std::make_pair(1,\"GOOD\"));\n\n binLabels.push_back(std::make_pair(2,\"CORRUPTED\"));\n\n binLabels.push_back(std::make_pair(3,\"UNKNOWN\"));\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreator.cpp", "rank": 15, "score": 17.908377330220183 }, { "content": "/**\n\n * Method returns a map of vectors of JPetSigCh ordered by photomultiplier ID\n\n */\n\nconst map<int, vector<JPetSigCh>> SignalFinderTools::getSigChByPM(\n\n const JPetTimeWindow* timeWindow, bool useCorrupts, int refPMID\n\n){\n\n map<int, vector<JPetSigCh>> sigChsPMMap;\n\n if (!timeWindow) {\n\n WARNING(\"Pointer of Time Window object is not set, returning empty map\");\n\n return sigChsPMMap;\n\n }\n\n // Map Signal Channels according to PM they belong to\n\n const unsigned int nSigChs = timeWindow->getNumberOfEvents();\n\n for (unsigned int i = 0; i < nSigChs; i++) {\n\n auto sigCh = dynamic_cast<const JPetSigCh&>(timeWindow->operator[](i));\n\n // If it is set not to use Corrupted SigChs, such flagged objects will be skipped\n\n // Here we ignore the corrupted flag of signals from Refference detector\n\n // since removing them results in double peak structures in the calibration spectra\n\n int pmtID = sigCh.getPM().getID();\n\n if(pmtID == refPMID) {\n", "file_path": "LargeBarrelAnalysis/SignalFinderTools.cpp", "rank": 16, "score": 17.903688730836873 }, { "content": " }\n\n if (fOrderThresholdsByValue){\n\n INFO(\"Threshold reordering was requested. Thresholds will be ordered by their values according to provided detector setup file.\");\n\n fThresholdOrderings = SignalFinderTools::findThresholdOrders(getParamBank());\n\n }\n\n\n\n // Creating control histograms\n\n if(fSaveControlHistos) { initialiseHistograms(); }\n\n return true;\n\n}\n\n\n\nbool SignalFinder::exec()\n\n{\n\n // Getting the data from event in an apropriate format\n\n if(auto timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {\n\n // Distribute signal channels by PM IDs and filter out Corrupted SigChs if requested\n\n auto& sigChByPM = SignalFinderTools::getSigChByPM(timeWindow, fUseCorruptedSigCh, fRefPMID);\n\n // Building signals\n\n auto allSignals = SignalFinderTools::buildAllSignals(\n\n sigChByPM, fSigChEdgeMaxTime, fSigChLeadTrailMaxTime,\n", "file_path": "LargeBarrelAnalysis/SignalFinder.cpp", "rank": 17, "score": 17.856048227284617 }, { "content": " void fitAndSaveParametersToFile(const std::string& filename, const std::string& filenameTmp);\n\n bool CheckIfExit(int Niter);\n\n\n\n /// Required options to be loaded from the json file.\n\n const std::string kPMIdRefOptName = \"TimeCalibration_PMIdRef_int\";\n\n const std::string kTOTCutLowOptName = \"TimeCalibration_TOTCutLow_float\";\n\n const std::string kTOTCutHighOptName = \"TimeCalibration_TOTCutHigh_float\";\n\n // const std::string kMainStripOptName = \"TimeCalibration_MainStrip_int\";\n\n const std::string kMainStripOptName = \"TimeWindowCreator_MainStrip_int\"; \n\n const std::string kLoadConstantsOptName = \"TimeCalibration_LoadConstants_bool\";\n\n const std::string kCalibFileTmpOptName = \"TimeCalibration_OutputFileTmp_std::string\";\n\n const std::string kCalibFileFinalOptName = \"TimeCalibration_OutputFileFinal_std::string\";\n\n const std::string MaxIterNumOptName = \"TimeCalibration_NiterMax_int\";\n\n int kPMIdRef = 385;\n\n std::array<float, 2> TOTcut{{ -300000000., 300000000.}}; //TOT cuts for slot hits (sum of TOTs from both sides)\n\n int fLayerToCalib = -1; //Layer of calibrated slot\n\n int fStripToCalib = -1; //Slot to be calibrated\n\n bool fIsCorrection = true; //Flag for choosing the correction of times at the level of calibration module (use only if the calibration loader is not used)\n\n std::string fTimeConstantsCalibFileName = \"TimeConstantsCalib.txt\";\n\n std::string fTimeConstantsCalibFileNameTmp = \"TimeConstantsCalibTmp.txt\";\n", "file_path": "TimeCalibration_iter/TimeCalibration.h", "rank": 18, "score": 17.594180555451818 }, { "content": "# Large Barrel Analysis parameters description\n\n\n\n## Contents\n\nDescription of available parameters in LargeBarrelAnalysis example. Note that configuration/calibration files can be obtained from [PetWiki](http://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses)\n\n\n\n- `Save_Control_Histograms_bool` \n\nCommon for each module, if set to `true`, in the output `ROOT` files folder with statistics will contain control histograms. Set to `false` if histograms are not needed.\n\n\n\n- `Unpacker_TOToffsetCalib_std::string` \n\nPath to and name of a `ROOT` file with `TOT` offset calibrations (stretcher) applied during unpacking of `HLD` file.\n\n\n\n- `Unpacker_TDCnonlinearityCalib_std::string` \n\nPath to and name of a `ROOT` file with calibrations of nonlinearities occurring on `TDC` boards, applied during unpacking of `HLD` file.\n\n\n\n- `TimeWindowCreator_MainStrip_int` \n\nDedicated for files with data from measurement with Reference Detector - it denotes which `ID` has the scintillator we calibrate. If option is absent in the user parameters file, part with reference detector is ignored\n\n\n\n- `TimeWindowCreator_MinTime_float` \n\nTime Slots have certain duration for specific runs, minimum time is usually negative, default value `-1*10^6 ps`\n\n\n\n- `TimeWindowCreator_MaxTime_float` \n\ndefault value `0.0 ps`\n\n\n\n- `TimeCalibLoader_ConfigFile_std::string` \n\nPath to and name of ASCII file of required structure, containing time calibrations, specific for each run\n\n\n\n- `SignalFinder_UseCorruptedSigCh_bool` \n\nIndication if Signal Finder module should use signal channels flagged as Corrupted in the previous task. Default value: `false`\n\n\n\n- `SignalFinder_EdgeMaxTime_float` \n\ntime window for matching Signal Channels on Leading Edge. Default value: `5 000 ps`\n\n\n\n- `SignalFinder_LeadTrailMaxTime_float` \n", "file_path": "LargeBarrelAnalysis/PARAMETERS.md", "rank": 19, "score": 17.525536875290165 }, { "content": "\n\n return true;\n\n}\n\n\n\nbool SinogramCreator::atenuation(const float value) { return distribution(generator) <= value; }\n\n\n\nvoid SinogramCreator::setUpOptions()\n\n{\n\n auto opts = getOptions();\n\n if (isOptionSet(opts, kOutFileNameKey))\n\n {\n\n fOutFileName = getOptionAsString(opts, kOutFileNameKey);\n\n }\n\n if (isOptionSet(opts, kReconstructionDistanceAccuracy))\n\n {\n\n fReconstructionDistanceAccuracy = getOptionAsFloat(opts, kReconstructionDistanceAccuracy);\n\n }\n\n if (isOptionSet(opts, kZSplitNumber))\n\n {\n\n fZSplitNumber = getOptionAsInt(opts, kZSplitNumber);\n", "file_path": "ImageReconstruction/SinogramCreator.cpp", "rank": 20, "score": 16.97201160822847 }, { "content": " // Build a list of allowed channels\n\n JPetGeomMapping mapper(getParamBank());\n\n for (int thr = 1; thr <= 4; ++thr) {\n\n int tombNumber = mapper.getTOMB(fMainStrip.first, fMainStrip.second,\n\n JPetPM::SideA, thr);\n\n fAllowedChannels.insert(tombNumber);\n\n tombNumber = mapper.getTOMB(fMainStrip.first, fMainStrip.second,\n\n JPetPM::SideB, thr);\n\n fAllowedChannels.insert(tombNumber);\n\n }\n\n // Add all reference detector channels to allowed channels list\n\n for (int thr = 1; thr <= 4; ++thr) {\n\n int tombNumber = mapper.getTOMB(4, 1, JPetPM::SideA, thr);\n\n fAllowedChannels.insert(tombNumber);\n\n tombNumber = mapper.getTOMB(4, 1, JPetPM::SideB, thr);\n\n fAllowedChannels.insert(tombNumber);\n\n }\n\n }\n\n\n\n // Control histograms\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreator.cpp", "rank": 21, "score": 16.938193135179212 }, { "content": " std::map<std::tuple<int, int, JPetPM::Side, int>, int> fCorrectTombMap = {\n\n {std::make_tuple(1, 1, JPetPM::SideA, 1), 22},\n\n {std::make_tuple(3, 2, JPetPM::SideB, 4), 13},\n\n {std::make_tuple(2, 90, JPetPM::SideB, 2), 73}};\n\n};\n\n\n\nBOOST_AUTO_TEST_SUITE(UniversalFileLoaderSuite)\n\n\n\nBOOST_AUTO_TEST_CASE(getConfigurationParameter) {\n\n UniversalFileLoader::TOMBChToParameter configuration = {\n\n {0, std::vector<double>{0.5, 0.1, 0.0, 0.5, 0.0, 6.1, 0.0, 2.1}},\n\n {1, std::vector<double>{-1.2, 0.1, 0.0, 0.5, 0.0, 6.1, 0.0, 2.1}},\n\n {3, std::vector<double>{0.2, 0.1, 0.0, 0.5, 0.0, 6.1, 0.0, 2.1}},\n\n {4, std::vector<double>{-0.1, 0.1, 0.0, 0.5, 0.0, 6.1, 0.0, 2.1}}};\n\n auto epsilon = 0.00001;\n\n BOOST_REQUIRE_CLOSE(\n\n UniversalFileLoader::getConfigurationParameter(configuration, 0), 0.5,\n\n epsilon);\n\n BOOST_REQUIRE_CLOSE(\n\n UniversalFileLoader::getConfigurationParameter(configuration, 1), -1.2,\n", "file_path": "LargeBarrelAnalysis/tests/UniversalFileLoaderTest.cpp", "rank": 22, "score": 16.204589928387737 }, { "content": "\tstd::map<unsigned int, std::vector<double>> fTimeCalibration;\n\n\tstd::map<unsigned int, std::vector<double>> fThresholds;\n\n\tbool fSetTHRValuesFromChannels = true;\n\n\tlong long int fCurrEventNumber = 0;\n\n\tstd::set<int> fAllowedChannels;\n\n\tbool fSaveControlHistos = true;\n\n\tstd::pair<int,int> fMainStrip;\n\n\tbool fMainStripSet = false;\n\n\tdouble fMinTime = -1.e6;\n\n\tdouble fMaxTime = 0.;\n\n};\n\n\n\n#endif /* !TIMEWINDOWCREATOR_H */\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreator.h", "rank": 23, "score": 16.196220822938358 }, { "content": " JPetPM pm2(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f), \"test_pm2\");\n\n\n\n bank.addPM(pm1);\n\n bank.addPM(pm2);\n\n\n\n SignalFinderTools::ThresholdValues values_pm1 = {40., 3., 20., 10.};\n\n SignalFinderTools::ThresholdValues values_pm2 = {100., 400., 200., 300.};\n\n\n\n JPetTOMBChannel channels[8];\n\n\n\n for(int i=0;i<4;++i){\n\n\n\n channels[i] = JPetTOMBChannel(i);\n\n channels[4+i] = JPetTOMBChannel(4+i);\n\n\n\n channels[i].setLocalChannelNumber(i+1);\n\n channels[4+i].setLocalChannelNumber(i+1);\n\n\n\n channels[i].setThreshold(values_pm1[i]);\n\n channels[4+i].setThreshold(values_pm2[i]);\n", "file_path": "LargeBarrelAnalysis/tests/SignalFinderToolsTest.cpp", "rank": 24, "score": 16.082361296142814 }, { "content": "--- Default value: 5 000 ps.\n\n\n\nSignalFinder_LeadTrailMaxTime_float\n\n--- time window for matching Signal Channels on the same thresholds from\n\nLeading and Trailing edge. Default value: 25 000 ps.\n\n\n\nSignalFinder_UseCorruptedSigCh_bool\n\n---Indication if Signal Finder module should use signal channels flagged as Corrupted in the previous task.\n\nDefault value: false\n\n\n\nHitFinder_VelocityFile_std::string\n\n--- name of ASCII file of required format, containing values of effective velocities\n\nof light in each scintillator.\n\n\n\nHitFinder_ABTimeDiff_float\n\n--- time window for matching Signals on the same scintillator and different sides\n\n--- Default value: 6 000 ps.\n\n\n\nHitFinder_RefDetScinID_int\n\n--- ID of Reference Detector Scintillator, needed for creating reference hits.\n\n--- The only value used so far: 193\n\n\n\nHitFinder_UseCorruptedSignals_bool \n\n--- Indication if Hit Finder module should use signals flagged as Corrupted in the previous task.\n\n--- Default value: `false`\n\n\n\nTimeCalibration_PMIdRef_int\n\n--- Id of the photomultiplier of the refference detector.\n\n--- So far we used always number 385\n\n\n\nTimeCalibration_TOTCutLow_float (in the older versions\tof Framework: TOTCutLow)\n\n--- Lower bound of TOT for signals used to calibrate slots with refference detector.\n\nWe do not use it so far since the results with cuts were not better then without.\n\n--- Default value: -300000000\n\n\n\nTimeCalibration_TOTCutHigh_float (in the older versions of Framework: TOTCutHigh)\n\n---Upper bound of TOT for signals used to calibrate slots with refference detector.\n\nWe do not use it so far since the results with cuts were not better then without.\n", "file_path": "TimeCalibration_iter/PARAMETERS.md", "rank": 25, "score": 16.050410921436136 }, { "content": " return true;\n\n}\n\n\n\nvoid TimeWindowCreator::saveSigChs(const vector<JPetSigCh> &sigChVec) {\n\n for (auto &sigCh : sigChVec) {\n\n fOutputEvents->add<JPetSigCh>(sigCh);\n\n }\n\n}\n\n\n\n/**\n\n * Reference Detector\n\n * Returns true if signal from the channel given as argument should be passed\n\n */\n\nbool TimeWindowCreator::isAllowedChannel(JPetTOMBChannel &tombChannel) const {\n\n // If main strip was not defined, pass all channels\n\n if (!fMainStripSet)\n\n return true;\n\n if (fAllowedChannels.find(tombChannel.getChannel()) !=\n\n fAllowedChannels.end()) {\n\n return true;\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreator.cpp", "rank": 26, "score": 16.03121131713219 }, { "content": "# Imaging stream parameters description\n\n\n\n## Contents\n\nDescription of available parameters in Imaging example. Note that configuration/calibration files can be obtained from [PetWiki](http://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses)\n\n\n\n- `Save_Control_Histograms_bool` \n\nCommon for each module, if set to `true`, in the output `ROOT` files folder with statistics will contain control histograms. Set to `false` if histograms not needed.\n\n\n\n- `TimeWindowCreator_MainStrip_int` \n\nDedicated for files with data from measurement with Reference Detector - it denotes which `ID` has the reference scintillator. If option not set, part with reference detector is ignored\n\n\n\n- `TimeWindowCreator_MinTime_float` \n\nTime Slots have certain duration for specific runs, minimum time is usually negative, default value `-1*10^6 ps`\n\n\n\n- `TimeWindowCreator_MaxTime_float` \n\ndefault value `0.0 ps`\n\n\n\n- `TimeCalibLoader_ConfigFile_std::string` \n\nname of ASCII file of required structure, containing time calibrations, specific for each run\n\n\n\n- `SignalFinder_EdgeMaxTime_float` \n\ntime window for matching Signal Channels on Leading Edge. Default value: `5 000 ps`\n\n\n\n- `SignalFinder_LeadTrailMaxTime_float` \n\ntime window for matching Signal Channels on the same thresholds from Leading and Trailing edge. Default value: `25 000 ps`\n\n\n\n- `HitFinder_VelocityFile_std::string` \n\nname of ASCII file of required format, containing values of effective velocities of light in each scintillator\n\n\n\n- `HitFinder_ABTimeDiff_float` \n\ntime window for matching Signals on the same scintillator and different sides. Default value: `6 000 ps`\n\n\n\n- `HitFinder_RefDetScinID_int` \n\n`ID` of Reference Detector Scintillator, needed for creating reference hits\n\n\n\n- `EventFinder_EventTime_float` \n\ntime window for grouping hits in one event. Default value `5 000 ps`\n\n\n\n- `EventFinder_MinEventMultiplicity_int` \n", "file_path": "Imaging/PARAMETERS.md", "rank": 27, "score": 16.003532185469403 }, { "content": "\n\n std::string fOutFileName = \"mlem_reconstruction_output.txt\";\n\n float fHalfStripLenght = 0.f;\n\n\n\n Scanner2D fScanner;\n\n\n\n std::ofstream fOutputStream; // outputs data in format accepted by 3d_hybrid_reconstruction\n\n std::stringstream fReconstructionStringStream; // connection between parsing events and reconstruction\n\n\n\n int fNumberOfPixelsInOneDimension = 160; // Dimension of 1 axis in 3d reconstructed image(n-pixels)\n\n double fPixelSize = 0.004; // Size of 1 pixel in m(s-pixel)\n\n unsigned int fStartPixelForPartialMatrix = 0u; // Starting position of matrix\n\n unsigned int fNumberOfEmissionsPerPixel = 100000000; // Number of emissions per pixel for system matrix\n\n double fTOFStep = 0.;\n\n float fTOFSigmaAxis = 0.06f;\n\n float fTOFSigmaAlongZAxis = 0.015f;\n\n\n\n bool fVerbose = true; // if true prints extra information about reconstruction to cerr\n\n bool fSystemMatrixSaveFull = true; // if true generate and save full system matrix, if not only 1/8 of it and then converts to full\n\n int fReconstructionIterations = 10; // number of iterations in reconstruction\n", "file_path": "ImageReconstruction/MLEMRunner.h", "rank": 28, "score": 15.891667004458919 }, { "content": "# Physics stream parameters description\n\n\n\n## Contents\n\nDescription of available parameters in Physics example. Note that configuration/calibration files can be obtained from [PetWiki](http://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses)\n\n\n\n- `Save_Control_Histograms_bool` \n\nCommon for each module, if set to `true`, in the output `ROOT` files folder with statistics will contain control histograms. Set to `false` if histograms not needed.\n\n\n\n- `TimeWindowCreator_MainStrip_int` \n\nDedicated for files with data from measurement with Reference Detector - it denotes which `ID` has the reference scintillator. If option not set, part with reference detector is ignored\n\n\n\n- `TimeWindowCreator_MinTime_float` \n\nTime Slots have certain duration for specific runs, minimum time is usually negative, default value `-1*10^6 ps`\n\n\n\n- `TimeWindowCreator_MaxTime_float` \n\ndefault value `0.0 ps`\n\n\n\n- `TimeCalibLoader_ConfigFile_std::string` \n\nname of ASCII file of required structure, containing time calibrations, specific for each run\n\n\n\n- `SignalFinder_EdgeMaxTime_float` \n\ntime window for matching Signal Channels on Leading Edge. Default value: `5 000 ps`\n\n\n\n- `SignalFinder_LeadTrailMaxTime_float` \n\ntime window for matching Signal Channels on the same thresholds from Leading and Trailing edge. Default value: `25 000 ps`\n\n\n\n- `HitFinder_VelocityFile_std::string` \n\nname of ASCII file of required format, containing values of effective velocities of light in each scintillator\n\n\n\n- `HitFinder_ABTimeDiff_float` \n\ntime window for matching Signals on the same scintillator and different sides. Default value: `6 000 ps`\n\n\n\n- `HitFinder_RefDetScinID_int` \n", "file_path": "PhysicAnalysis/PARAMETERS.md", "rank": 29, "score": 15.862252954976382 }, { "content": "# Cosmics stream - data selection of cosmic radiation events parameters\n\n\n\n## Contents\n\nDescription of available parameters in CosmicAnalysis example.\n\nNote that configuration/calibration files can be obtained from [PetWiki](http://koza.if.uj.edu.pl/petwiki/index.php/Default_settings_and_parameters_used_in_the_analyses)\n\n\n\n- `Save_Control_Histograms_bool` \n\nCommon for each module, if set to `true`, in the output `ROOT` files folder with statistics will contain control histograms. Set to `false` if histograms not needed.\n\n\n\n- `TimeWindowCreator_MainStrip_int` \n\nDedicated for files with data from measurement with Reference Detector - it denotes which `ID` has the reference scintillator. If option not set, part with reference detector is ignored\n\n\n\n- `TimeWindowCreator_MinTime_float` \n\nTime Slots have certain duration for specific runs, minimum time is usually negative, default value `-1*10^6 ps`\n\n\n\n- `TimeWindowCreator_MaxTime_float` \n\ndefault value `0.0 ps`\n\n\n\n- `TimeCalibLoader_ConfigFile_std::string` \n\nname of ASCII file of required structure, containing time calibrations, specific for each run\n\n\n\n- `SignalFinder_EdgeMaxTime_float` \n\ntime window for matching Signal Channels on Leading Edge. Default value: `5 000 ps`\n\n\n\n- `SignalFinder_LeadTrailMaxTime_float` \n\ntime window for matching Signal Channels on the same thresholds from Leading and Trailing edge. Default value: `25 000 ps`\n\n\n\n- `HitFinder_VelocityFile_std::string` \n\nname of ASCII file of required format, containing values of effective velocities of light in each scintillator\n\n\n\n- `HitFinder_ABTimeDiff_float` \n\ntime window for matching Signals on the same scintillator and different sides. Default value: `6 000 ps`\n\n\n\n- `HitFinder_RefDetScinID_int` \n", "file_path": "CosmicAnalysis/PARAMETERS.md", "rank": 30, "score": 15.745731457498097 }, { "content": "#include \"JPetLoggerInclude.h\"\n\n\n\nBOOST_AUTO_TEST_SUITE(SignalFinderTestSuite)\n\n\n\nBOOST_AUTO_TEST_CASE(getSigChByPM_nullPointer_test)\n\n{\n\n auto results = SignalFinderTools::getSigChByPM(nullptr, false, -1);\n\n BOOST_REQUIRE(results.empty());\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(getSigChByPM_Test) {\n\n JPetPM pm1(1, \"first\");\n\n JPetSigCh sigChA1(JPetSigCh::Leading, 10.0);\n\n JPetSigCh sigChA2(JPetSigCh::Leading, 11.0);\n\n JPetSigCh sigChA3(JPetSigCh::Leading, 12.5);\n\n sigChA1.setPM(pm1);\n\n sigChA2.setPM(pm1);\n\n sigChA3.setPM(pm1);\n\n sigChA1.setRecoFlag(JPetSigCh::Good);\n\n sigChA2.setRecoFlag(JPetSigCh::Good);\n", "file_path": "LargeBarrelAnalysis/tests/SignalFinderToolsTest.cpp", "rank": 31, "score": 15.669096718678173 }, { "content": "--- Default value 0.0 ps\n\n\n\nSignalFinder_EdgeMaxTime_float\n\n--- time window for matching Signal Channels on Leading Edge.\n\n--- Default value: 5 000 ps.\n\n\n\nSignalFinder_LeadTrailMaxTime_float\n\n--- time window for matching Signal Channels on the same thresholds from\n\nLeading and Trailing edge. Default value: 25 000 ps.\n\n\n\nSignalFinder_UseCorruptedSigCh_bool\n\n--- Indication if Signal Finder module should use signal channels flagged as Corrupted in the previous task.\n\nDefault value: false\n\n\n\nHitFinder_VelocityFile_std::string\n\n--- name of ASCII file of required format, containing values of effective velocities\n\nof light in each scintillator.\n\n\n\nHitFinder_ABTimeDiff_float\n\n--- time window for matching Signals on the same scintillator and different sides\n\n--- Default value: 6 000 ps.\n\n\n\nHitFinder_RefDetScinID_int\n\n--- ID of Reference Detector Scintillator, needed for creating reference hits.\n\n--- The only value used so far: -1\n\n\n\nHitFinder_UseCorruptedSignals_bool\n\n--- Indication if Hit Finder module should use signals flagged as Corrupted in the previous task.\n\n--- Default value: `false`\n\n\n\nPALSCalibrationTask_Anni_TOT_Cut_Min_float\n\n--- minimal TOT for the hit that come from the annihilation of the positron-electron\n\n--- Default value: 23 000 ps\n\n\n\nPALSCalibrationTask_Anni_TOT_Cut_Max_float\n\n--- maximal TOT for the hit that come from the annihilation of the positron-electron\n\n--- Default value: 30 000 ps\n\n\n\nPALSCalibrationTask_Deex_TOT_Cut_Min_float\n\n--- minimal TOT for the hit that come from the deexcitation of the source\n\n--- Default value: 35 000 ps\n\n\n\nPALSCalibrationTask_Deex_TOT_Cut_Max_float\n\n--- maximal TOT for the hit that come from the deexcitation of the source\n\n--- Default value: 35 000 ps\n\n\n\nPALSCalibrationTask_ZpositionCut_float\n\n--- maximal Z position accepted for a hit\n\n--- Default value: 23 cm\n\n\n\nPALSCalibrationTask_EffectiveLength_float\n\n--- effective length assumed for a first threshold\n", "file_path": "TimeCalibration_lifetime/PARAMETERS.md", "rank": 32, "score": 15.569662733507785 }, { "content": "BOOST_AUTO_TEST_CASE(test_angle_middle)\n\n{\n\n const float EPSILON = 0.01f;\n\n const float r = 10;\n\n const float maxDistance = 20.f;\n\n const float accuracy = 0.1f;\n\n\n\n for (int i = 0; i < 360; i++)\n\n {\n\n const float x1 = r * std::cos((i) * (M_PI / 180.f));\n\n const float y1 = r * std::sin((i) * (M_PI / 180.f));\n\n const float x2 = r * std::cos((i + 180) * (M_PI / 180.f));\n\n const float y2 = r * std::sin((i + 180) * (M_PI / 180.f));\n\n const auto result =\n\n SinogramCreatorTools::getSinogramRepresentation(x1, y1, x2, y2, maxDistance, accuracy, std::ceil(maxDistance * 2.f * (1.f / accuracy)), 180);\n\n int resultAngle = i < 90 ? 90 + i : i < 180 ? i - 90 : i < 270 ? i - 90 : i - 270;\n\n BOOST_REQUIRE_EQUAL(result.second, resultAngle);\n\n const float distanceResult = SinogramCreatorTools::roundToNearesMultiplicity(maxDistance, accuracy);\n\n BOOST_REQUIRE_CLOSE(result.first, distanceResult, EPSILON);\n\n }\n", "file_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "rank": 34, "score": 15.532147583678151 }, { "content": "#include \"JPetLoggerInclude.h\"\n\n\n\n/**\n\n * Method returns a patameter for given TOMB channel\n\n */\n\ndouble UniversalFileLoader::getConfigurationParameter(\n\n const TOMBChToParameter& confParameters,\n\n const unsigned int channel)\n\n{\n\n if (confParameters.find(channel) == confParameters.end()) {\n\n DEBUG(\"No parameter available for the channel\" + std::to_string(channel));\n\n return 0.0;\n\n } else {\n\n return confParameters.at(channel)[0];\n\n }\n\n}\n\n\n\n/**\n\n * Method loading parameters from ASCII file\n\n * Arguments: file name string, TOMBChMap object containing the dependency\n", "file_path": "LargeBarrelAnalysis/UniversalFileLoader.cpp", "rank": 35, "score": 15.401899210684807 }, { "content": "\n\n BOOST_REQUIRE_EQUAL(result1.size(), 2);\n\n BOOST_REQUIRE_EQUAL(result2.size(), 1);\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(createHit_test)\n\n{\n\n JPetLayer layer1(1, true, \"layer1\", 10.0);\n\n JPetBarrelSlot slot1(2, true, \"barel1\", 30.0, 23);\n\n slot1.setLayer(layer1);\n\n\n\n JPetScin scin1(1);\n\n scin1.setBarrelSlot(slot1);\n\n\n\n JPetPM pmA(11, \"first\"), pmB(22, \"second\");\n\n pmA.setScin(scin1);\n\n pmB.setScin(scin1);\n\n pmA.setBarrelSlot(slot1);\n\n pmB.setBarrelSlot(slot1);\n\n pmA.setSide(JPetPM::SideA);\n", "file_path": "LargeBarrelAnalysis/tests/HitFinderToolsTest.cpp", "rank": 36, "score": 15.05575782067111 }, { "content": "#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE JPetRecoImageToolsTests\n\n#include <boost/test/unit_test.hpp>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <utility>\n\n#include <vector>\n\n\n\n#include \"JPetCommonTools/JPetCommonTools.h\"\n\n#include \"./JPetFilterCosine.h\"\n\n#include \"./JPetFilterHamming.h\"\n\n#include \"./JPetFilterNone.h\"\n\n#include \"./JPetFilterRamLak.h\"\n\n#include \"./JPetFilterRidgelet.h\"\n\n#include \"./JPetFilterSheppLogan.h\"\n\n#include \"./JPetRecoImageTools.h\"\n\n\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\n\n\nBOOST_AUTO_TEST_CASE(rescale_0)\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoImageToolsTest.cpp", "rank": 37, "score": 14.950708237928836 }, { "content": " in >> height;\n\n int val;\n\n in >> val; // skip max val\n\n JPetRecoImageTools::Matrix2DProj sinogram(height, std::vector<double>(width));\n\n for (unsigned int i = 0; i < height; i++) {\n\n for (unsigned int j = 0; j < width; j++) {\n\n in >> val;\n\n sinogram[i][j] = val;\n\n }\n\n }\n\n return sinogram;\n\n}\n\n\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\n\n\nBOOST_AUTO_TEST_CASE(backProjectSinogramNone)\n\n{\n\n const auto outFile = \"backprojectSinogramNone.ppm\";\n\n\n\n JPetRecoImageTools::Matrix2DProj sinogram = readFile(inFile);\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoTest.cpp", "rank": 38, "score": 14.889937444152798 }, { "content": "--- Default value: 300000000.\n\n\n\nTimeCalibration_LoadConstants_bool\n\n---The flag indicating if the temporary calibration constants should be loaded after each iteration of the calibration.\n\nUse it only if You disable the calibration loading module (by default it is off), by default it is set to \"true\"\n\nsince this is much faster than the full analysis done starting from unpacker stage. If You really want to use corrections\n\nat that level first uncomment in main.cpp the CalibLoader module and change TimeCalibration_LoadConstants_bool to false.\n\n--- Default value: true\n\n\n\nTimeCalibration_OutputFileTmp_std::string\n\n---The file which is used to store the temporary calibration constants after each iteration.\n\n--- Default value: TimeConstantsCalibTmp.txt\n\n\n\nTimeCalibration_OutputFileFinal_std::string\n\n---The final output file with calibration constants\n\n--- Default value: TimeConstantsCalib.txt\n\n\n\nTimeCalibration_NiterMax_int\n\n--- The user defined number of iterations of calibration. Use it with option \"StopIteration_bool\" set to false and with\n\nmanager.useTask(\"TimeCalibration\", \"hits\", \"calib\",-1) in the main.cpp\n\n--- Default value: 1\n", "file_path": "TimeCalibration_iter/PARAMETERS.md", "rank": 39, "score": 14.870611137440049 }, { "content": " //take slot number for the hit\n\n int slot_number = hit.getBarrelSlot().getID();\n\n int layer_number = hit.getBarrelSlot().getLayer().getID();\n\n int slot_nr;\n\n\n\n if (layer_number == 1) slot_nr = slot_number;\n\n if (layer_number == 2) slot_nr = slot_number - 48;\n\n if (layer_number == 3) slot_nr = slot_number - 96;\n\n\n\n double thr_time_diff_t_A[5], thr_time_diff_A[5];\n\n double thr_time_diff_t_B[5], thr_time_diff_B[5];\n\n double lead_times_first_A, lead_times_first_B;\n\n double trail_times_first_A, trail_times_first_B;\n\n\n\n // leading edge\n\n\n\n // A\n\n for (auto& thr_time_pair : lead_times_A) {\n\n \n\n int thr = thr_time_pair.first;\n", "file_path": "InterThresholdCalibration/InterThresholdCalibration.cpp", "rank": 40, "score": 14.748995863703433 }, { "content": " std::vector <JPetHit> histCalib;\n\n std::vector <double> refTimesL;\n\n std::vector <double> refTimesT;\n\n\n\n if (auto timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {\n\n auto n = timeWindow->getNumberOfEvents();\n\n for (auto i = 0u; i < n; ++i) {\n\n const JPetHit& hit = dynamic_cast<const JPetHit&>(timeWindow->operator[](i));\n\n int PMid = hit.getSignalB().getRecoSignal().getRawSignal().getPM().getID();\n\n if (PMid == kPMIdRef) {\n\n auto lead_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n auto trail_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n //\n\n for (auto& thr_time_pair : lead_times_B) {\n\n int thr = thr_time_pair.first;\n\n RefTimeLead[thr] = thr_time_pair.second;\n\n\n\n }\n\n for (auto& thr_time_pair : trail_times_B) {\n\n int thr = thr_time_pair.first;\n", "file_path": "TimeCalibration_iter/TimeCalibration.cpp", "rank": 41, "score": 14.668530202343074 }, { "content": " auto trail_times_A = hit.getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n\n\n auto lead_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n auto trail_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n//\n\n//-----------TOT calculation for the slot hit\n\n float TOT_A = 0.;\n\n float TOT_B = 0.;\n\n double timeDiffTmin = 0;\n\n double timeDiffLmin = 0;\n\n //\n\n\n\n //**\tint StripToCalibTemp = hit.getScintillator().getID();\n\n //**\tint LayerToCalibTemp = hit.getBarrelSlot().getLayer().getID();\n\n //\n\n for (auto& thr_time_pair : lead_times_A) {\n\n int thr = thr_time_pair.first;\n\n\n\n if (trail_times_A.count(thr) > 0 ) {\n\n TOT_A = TOT_A + trail_times_A[thr] - lead_times_A[thr];\n", "file_path": "TimeCalibration/TimeCalibration.cpp", "rank": 42, "score": 14.505673206255912 }, { "content": "BOOST_AUTO_TEST_CASE(generateConfigurationParameters_empty) {\n\n std::vector<ConfRecord> records;\n\n std::map<std::tuple<int, int, JPetPM::Side, int>, int> tombMap;\n\n auto configuration =\n\n UniversalFileLoader::generateConfigurationParameters(records, tombMap);\n\n BOOST_REQUIRE(configuration.empty());\n\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE(generateConfigurationParameters, myFixtures) {\n\n auto epsilon = 0.0001;\n\n auto configuration = UniversalFileLoader::generateConfigurationParameters(\n\n fCorrectRecords, fCorrectTombMap);\n\n BOOST_REQUIRE_EQUAL(configuration.size(), 3);\n\n BOOST_REQUIRE_EQUAL(configuration.count(22), 1);\n\n BOOST_REQUIRE_EQUAL(configuration.count(13), 1);\n\n BOOST_REQUIRE_EQUAL(configuration.count(73), 1);\n\n BOOST_REQUIRE_CLOSE(configuration.at(22).at(0), 7, epsilon);\n\n BOOST_REQUIRE_CLOSE(configuration.at(13).at(0), 5, epsilon);\n\n BOOST_REQUIRE_CLOSE(configuration.at(73).at(0), -3, epsilon);\n\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "file_path": "LargeBarrelAnalysis/tests/UniversalFileLoaderTest.cpp", "rank": 43, "score": 14.499584647583427 }, { "content": " BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(0.01f, 0.01f), 1u);\n\n BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(0.02f, 0.01f), 2u);\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(test_angle_middle) {\n\n const float EPSILON = 0.01f;\n\n const float r = 10;\n\n const float maxDistance = 20.f;\n\n const float accuracy = 0.1f;\n\n \n\n float distanceSign = 1;\n\n\n\n for (int i = 0; i < 360; i++) {\n\n const float angle1 = (i + 45) * 0.0174532925;\n\n const float angle2 = (i + 135) * 0.0174532925;\n\n const float x1 = r * std::cos(angle1);\n\n const float y1 = r * std::sin(angle1);\n\n const float x2 = r * std::cos(angle2);\n", "file_path": "ImageReconstruction/tests/SinogramCreatorToolsTest.cpp", "rank": 44, "score": 14.474039325348091 }, { "content": " if (signal1.getPM().getSide() == JPetPM::SideA) {\n\n signalA = signal1;\n\n signalB = signal2;\n\n } else {\n\n signalA = signal2;\n\n signalB = signal1;\n\n }\n\n auto radius = signalA.getPM().getBarrelSlot().getLayer().getRadius();\n\n auto theta = TMath::DegToRad() * signalA.getPM().getBarrelSlot().getTheta();\n\n auto velocity = UniversalFileLoader::getConfigurationParameter(\n\n velocitiesMap, getProperChannel(signalA)\n\n );\n\n checkTheta(theta);\n\n\n\n JPetHit hit;\n\n hit.setSignalA(signalA);\n\n hit.setSignalB(signalB);\n\n hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0);\n\n hit.setQualityOfTime(-1.0);\n\n hit.setTimeDiff(signalB.getTime() - signalA.getTime());\n", "file_path": "LargeBarrelAnalysis/HitFinderTools.cpp", "rank": 45, "score": 14.424227693923761 }, { "content": " BOOST_REQUIRE_EQUAL(results1[234].size(), 3);\n\n BOOST_REQUIRE_EQUAL(results2[234].size(), 3);\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(buildRawSignals_empty)\n\n{\n\n JPetStatistics stats;\n\n std::vector<JPetSigCh> sigChByPM;\n\n auto results = SignalFinderTools::buildRawSignals(\n\n sigChByPM, 5.0, 5.0, stats, false\n\n );\n\n BOOST_REQUIRE(results.empty());\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(buildRawSignals_one_signal) {\n\n JPetStatistics stats;\n\n JPetBarrelSlot bs1(1, true, \"some_slot\", 57.7, 123);\n\n JPetPM pm1(1, \"first\");\n\n pm1.setBarrelSlot(bs1);\n\n JPetSigCh sigCh1(JPetSigCh::Leading, 10);\n", "file_path": "LargeBarrelAnalysis/tests/SignalFinderToolsTest.cpp", "rank": 46, "score": 14.377741937844704 }, { "content": " map<unsigned int, vector<double>>& thresholdsMap,\n\n JPetSigCh::EdgeType edge, bool setTHRValuesFromChannels\n\n) {\n\n JPetSigCh sigCh;\n\n sigCh.setValue(1000.*(tdcChannelTime\n\n + UniversalFileLoader::getConfigurationParameter(timeCalibrationMap, channel.getChannel())\n\n ));\n\n sigCh.setType(edge);\n\n sigCh.setTOMBChannel(channel);\n\n sigCh.setPM(channel.getPM());\n\n sigCh.setFEB(channel.getFEB());\n\n sigCh.setTRB(channel.getTRB());\n\n sigCh.setDAQch(channel.getChannel());\n\n sigCh.setThresholdNumber(channel.getLocalChannelNumber());\n\n if(setTHRValuesFromChannels) {\n\n sigCh.setThreshold(channel.getThreshold());\n\n } else {\n\n sigCh.setThreshold(\n\n UniversalFileLoader::getConfigurationParameter(thresholdsMap, channel.getChannel())\n\n );\n\n }\n\n return sigCh;\n\n}\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreatorTools.cpp", "rank": 47, "score": 14.321017928654936 }, { "content": "\n\nBOOST_AUTO_TEST_CASE(matchAllSignals_test_refDetID)\n\n{\n\n JPetBarrelSlot slot(1, true, \"one\", 15.0, 1);\n\n JPetBarrelSlot refSlot(193, true, \"refDet\", 15.0, 1);\n\n JPetPM pm(11, \"first\");\n\n JPetPM refPM(385, \"reference\");\n\n pm.setBarrelSlot(slot);\n\n refPM.setBarrelSlot(refSlot);\n\n JPetPhysSignal physSig1, physSig2, physSig3;\n\n physSig1.setBarrelSlot(slot);\n\n physSig2.setBarrelSlot(refSlot);\n\n physSig3.setBarrelSlot(refSlot);\n\n physSig1.setPM(pm);\n\n physSig2.setPM(refPM);\n\n physSig3.setPM(refPM);\n\n physSig1.setTime(1.0);\n\n physSig2.setTime(2.0);\n\n physSig3.setTime(3.0);\n\n std::vector<JPetPhysSignal> slotSignals;\n", "file_path": "LargeBarrelAnalysis/tests/HitFinderToolsTest.cpp", "rank": 48, "score": 14.307804276716565 }, { "content": " for (int x = 0; x < imageSize; x++)\n\n {\n\n for (int y = 0; y < imageSize; y++) { reconstructedProjection(y, x) *= M_PI / 360.; }\n\n }\n\n rescaleFunc(reconstructedProjection, rescaleMinCutoff, rescaleFactor);\n\n return reconstructedProjection;\n\n}\n\n\n\nJPetSinogramType::SparseMatrix JPetRecoImageTools::backProjectMatlab(const JPetSinogramType::Matrix3D& sinogram, float sinogramAccuracy, float tofWindow,\n\n float lorTOFSigma, FilteredBackProjectionWeightingFunction fbpwf, RescaleFunc rescaleFunc,\n\n int rescaleMinCutoff, int rescaleFactor)\n\n{\n\n if (sinogram.size() == 0)\n\n return JPetSinogramType::SparseMatrix(0, 0);\n\n const auto sinogramBegin = sinogram.cbegin();\n\n const int projectionLenght = sinogramBegin->second.size1();\n\n const int projectionAngles = sinogramBegin->second.size2();\n\n const double angleStep = M_PI / (double)projectionAngles;\n\n\n\n const int N = 2 * std::floor((double)projectionLenght / (2. * std::sqrt(2)));\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoImageTools.cpp", "rank": 49, "score": 14.284457795598964 }, { "content": " if(rawSignal.getRecoFlag()==JPetBaseSignal::Good){\n\n getStatistics().fillHistogram(\"good_vs_bad_signals\", 1);\n\n for(unsigned int i=0;i<leads.size();i++){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_good\", 2*i+1);\n\n }\n\n for(unsigned int i=0;i<trails.size();i++){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_good\", 2*(i+1));\n\n }\n\n } else if(rawSignal.getRecoFlag()==JPetBaseSignal::Corrupted){\n\n\t //\n\n\t int PMid = leads.at(0).getPM().getID();\n\n\t \n\n\t getStatistics().fillHistogram(\"PmIdCorrupted\", PMid);\n\n getStatistics().fillHistogram(\"good_vs_bad_signals\", 2);\n\n for(unsigned int i=0;i<leads.size();i++){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_corr\", 2*i+1);\n\n if(leads.at(i).getRecoFlag()==JPetSigCh::Good){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_corr_sigch_good\", 2*i+1);\n\n } else if(leads.at(i).getRecoFlag()==JPetSigCh::Corrupted){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_corr_sigch_corr\", 2*i+1);\n", "file_path": "LargeBarrelAnalysis/SignalTransformer.cpp", "rank": 50, "score": 14.277748136198081 }, { "content": " int layer = -1;\n\n int slot = -1;\n\n char side = 'A';\n\n int thr = -1;\n\n vector<double> inputParameters = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};\n\n istringstream stream(input);\n\n stream >> layer >> slot >> side >> thr\n\n >> inputParameters.at(0) >> inputParameters.at(1) >> inputParameters.at(2)\n\n >> inputParameters.at(3) >> inputParameters.at(4) >> inputParameters.at(5)\n\n >> inputParameters.at(6) >> inputParameters.at(7);\n\n if (stream.fail() || (side != 'A' && side != 'B')) return false;\n\n else {\n\n outRecord.layer = layer;\n\n outRecord.slot = slot;\n\n if (side == 'A') outRecord.side = JPetPM::SideA;\n\n else outRecord.side = JPetPM::SideB;\n\n outRecord.thresholdNumber = thr;\n\n outRecord.parameters = inputParameters;\n\n return true;\n\n }\n\n}\n", "file_path": "LargeBarrelAnalysis/UniversalFileLoader.cpp", "rank": 51, "score": 14.275677279217163 }, { "content": " getStatistics().createHistogram(new TH1D(\"annihilation_point_z\",\n\n \"Annihilation point Z\",\n\n fZRange, -fZRange, fZRange));\n\n\n\n getStatistics().createHistogram(new TH1D(\"annihilation_point_z_cutted\",\n\n \"Annihilation point Z\",\n\n fZRange, -fZRange, fZRange));\n\n\n\n return true;\n\n}\n\n\n\nbool ImageReco::exec()\n\n{\n\n if (const auto &timeWindow = dynamic_cast<const JPetTimeWindow *const>(fEvent))\n\n {\n\n unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();\n\n for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++)\n\n {\n\n auto event = dynamic_cast<const JPetEvent &>(timeWindow->operator[](static_cast<int>(i)));\n\n auto numberOfHits = event.getHits().size();\n", "file_path": "ImageReconstruction/ImageReco.cpp", "rank": 52, "score": 14.136689056779321 }, { "content": " if (trailTime > maxTime || trailTime < minTime ) { continue; }\n\n auto trailSigCh = generateSigCh(\n\n trailTime, tombChannel, timeCalibrationMap, thresholdsMap,\n\n JPetSigCh::Trailing, setTHRValuesFromChannels\n\n );\n\n allTDCSigChs.push_back(trailSigCh);\n\n if (saveHistos){\n\n stats.fillHistogram(Form(\"pm_occupation_thr%d\", tombChannel.getLocalChannelNumber()),\n\n tombChannel.getPM().getID());\n\n }\n\n }\n\n return allTDCSigChs;\n\n}\n\n\n\n/**\n\n * Method for investigation of repetated edges - setting RecoFlag for each SigCh.\n\n * SigChs are flagged as GOOD if they appear in the sequence LTLTLTLT ->\n\n * in other words, each found LT pair is marked as GOOD. If sequence of one type of\n\n * the edge is encountered, repeated ones are flagged CORRUPTED. Examples:\n\n * edge type -> LTLTLT LLT LLTT LLLLTTTT LLTTLTLTTTLLLLTT\n", "file_path": "LargeBarrelAnalysis/TimeWindowCreatorTools.cpp", "rank": 53, "score": 14.117021650393113 }, { "content": " 4, cos, sin, imageSize, center, length, matrixGet),\n\n 15, epsilon); // 5 + 4 + 3 + 2 + 1\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(projection4)\n\n{\n\n double epsilon = 0.00001;\n\n JPetRecoImageTools::Matrix2D matrix = {\n\n {1, 10, 100, 1000, 10000, 100000, 1000000},\n\n {2, 20, 200, 2000, 20000, 200000, 2000000},\n\n {3, 30, 300, 3000, 30000, 300000, 3000000},\n\n {4, 40, 400, 4000, 40000, 400000, 4000000},\n\n {5, 50, 500, 5000, 50000, 500000, 5000000},\n\n {6, 60, 600, 6000, 60000, 600000, 6000000},\n\n {7, 70, 700, 7000, 70000, 700000, 7000000}\n\n };\n\n int imageSize = matrix.size();\n\n double center = (float)(imageSize - 1) / 2.0;\n\n double length = center * center;\n\n std::function< double(int, int) > matrixGet;\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoImageToolsTest.cpp", "rank": 54, "score": 14.0667316648606 }, { "content": "#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE SinogramCreatorTest\n\n#include <boost/test/unit_test.hpp>\n\n\n\n#include \"../SinogramCreatorTools.h\"\n\n#include <iostream>\n\n\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\n\n\nBOOST_AUTO_TEST_CASE(roundToNearesMultiplicity_test) {\n\n BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(0.0f, 1.f), 0u);\n\n BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(0.4f, 1.f), 0u);\n\n BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(0.5f, 1.f), 1u);\n\n BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(30.f, 1.f), 30u);\n\n BOOST_REQUIRE_EQUAL(\n\n SinogramCreatorTools::roundToNearesMultiplicity(0.00f, 0.01f), 0u);\n", "file_path": "ImageReconstruction/tests/SinogramCreatorToolsTest.cpp", "rank": 55, "score": 14.06310799028819 }, { "content": "//nevertheless it's needed for checking if the structure of project is correct\n\n#define override\n\n#endif\n\n\n\n#include \"JPetUserTask/JPetUserTask.h\"\n\n#include <memory>\n\n\n\n/**\n\n * @brief Image reconstruction module which should be used for quick, rough data tests.\n\n *\n\n * It implements a simple image reconstruction algorithm adapted from G. Korcyl's code.\n\n * It is equivalent to one back-projection without any filtering but including TOF information,\n\n * with the assumption that TOF error = 0. Before reconstructruction, the data are not preselected\n\n * it should be preselected using FilterEvents Task.\n\n * The point of annihilation is reconstructed for all combination of registered hits in given events.\n\n * Additional optional options:\n\n * - ImageReco_Annihilation_Point_Z_float\n\n * - ImageReco_Xrange_On_3D_Histogram_int\n\n * - ImageReco_Yrange_On_3D_Histogram_int\n\n * - ImageReco_Zrange_On_3D_Histogram_int\n\n * - ImageReco_Bin_Multiplier_double\n\n */\n", "file_path": "ImageReconstruction/ImageReco.h", "rank": 56, "score": 13.999653401099762 }, { "content": " getStatistics().getObject<TH1I>(\"number_of_hits_filtered_by_condition\")->Fill(\"Cut on delta angle\", 1);\n\n getStatistics().getObject<TH1I>(\"number_of_hits_filtered_by_condition\")->Fill(\"Cut on first hit TOT\", 1);\n\n getStatistics().getObject<TH1I>(\"number_of_hits_filtered_by_condition\")->Fill(\"Cut on second hit TOT\", 1);\n\n getStatistics().getObject<TH1I>(\"number_of_hits_filtered_by_condition\")->Fill(\"Cut on annihilation point Z\", 1);\n\n\n\n return true;\n\n}\n\n\n\nbool FilterEvents::exec()\n\n{\n\n if (const auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {\n\n unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();\n\n for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {\n\n auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));\n\n auto numberOfHits = event.getHits().size();\n\n if (numberOfHits <= 1)\n\n continue;\n\n else {\n\n auto hits = event.getHits();\n\n for (unsigned int i = 0; i < hits.size() - 1; i++) {\n", "file_path": "ImageReconstruction/FilterEvents.cpp", "rank": 57, "score": 13.96828816992743 }, { "content": "\n\n\n\nJPetSinogramType::SparseMatrix JPetRecoImageTools::backProject(const JPetSinogramType::Matrix3D& sinogram, float sinogramAccuracy, float tofWindow,\n\n float lorTOFSigma, FilteredBackProjectionWeightingFunction fbpwf,\n\n RescaleFunc rescaleFunc, int rescaleMinCutoff, int rescaleFactor)\n\n{\n\n if (sinogram.size() == 0)\n\n return JPetSinogramType::SparseMatrix(0, 0);\n\n const auto sinogramBegin = sinogram.cbegin();\n\n int imageSize = sinogramBegin->second.size1();\n\n double center = (double)(imageSize - 1) / 2.0;\n\n double center2 = center * center;\n\n double angleStep = M_PI / (double)sinogramBegin->second.size2();\n\n\n\n JPetSinogramType::SparseMatrix reconstructedProjection(imageSize, imageSize);\n\n const double speed_of_light = 2.99792458 * sinogramAccuracy; // in reconstruction space, accuracy * ps/cm\n\n\n\n const int max_sigma_multi = 3;\n\n\n\n for (int angle = 0; angle < sinogramBegin->second.size2(); angle++)\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoImageTools.cpp", "rank": 58, "score": 13.878744032409815 }, { "content": "\tbuf << strip << \"_\" << thresholdLabel;\n\n\tc->SaveAs( (buf.str() + \".png\").c_str() );\n\n\tstd::pair<double,double> resultOfFit = std::make_pair<double,double> ( (fit->GetParameter(1))*-0.2, (fit->GetParError(1))*-0.2 );\n\n\treturn resultOfFit;\n\n}\n\n\n\nbool ifScintillatorIsIn( std::vector<scintData>& data, int ID)\n\n{\n\n\tfor( auto scintillator : data )\n\n\t{\n\n\t\tif( ID == scintillator.ID )\n\n\t\t\treturn true;\n\n\t}\n\n\treturn false;\n\n}\n\n\n\nint findScintillatorIn( std::vector<scintData>& data, int ID)\n\n{\n\n\tfor( unsigned int i = 0; i < data.size(); i++ )\n\n\t{\n", "file_path": "VelocityCalibration/estimateVelocity.cpp", "rank": 59, "score": 13.846879208178517 }, { "content": "using namespace std;\n\nSDARecoDrawAllCharges::SDARecoDrawAllCharges(const char *name)\n\n : JPetUserTask(name) {}\n\nSDARecoDrawAllCharges::~SDARecoDrawAllCharges() {}\n\n\n\nbool SDARecoDrawAllCharges::init() {\n\n DEBUG(\"bool SDARecoDrawAllCharges::init\");\n\n const auto &paramBank = getParamBank();\n\n fNumberOfPMTs = paramBank.getPMsSize();\n\n for (const auto &id_pm_pair : getParamBank().getPMs()) {\n\n fIDs.push_back(id_pm_pair.first);\n\n std::vector<double> k;\n\n fCharges[id_pm_pair.first] = k;\n\n }\n\n fOutputEvents = new JPetTimeWindow(\"JPetRecoSignal\");\n\n return true;\n\n}\n\n\n\nbool SDARecoDrawAllCharges::exec() {\n\n DEBUG(\"bool SDARecoDrawAllCharges::exec\");\n", "file_path": "modules/SDA/JPetRecoDrawAllCharges/SDARecoDrawAllCharges.cpp", "rank": 60, "score": 13.78209511238317 }, { "content": " const float y2 = r * std::sin(angle2);\n\n const auto result = SinogramCreatorTools::getSinogramRepresentation(\n\n x1, y1, x2, y2, maxDistance, accuracy,\n\n std::ceil(maxDistance * 2.f * (1.f / accuracy)), 180);\n\n int resultAngle =\n\n i < 90 ? 90 + i : i < 180 ? i - 90 : i < 270 ? i - 90 : i - 270;\n\n BOOST_REQUIRE_EQUAL(result.second, resultAngle);\n\n if(i > 0 && i <= 180)\n\n distanceSign = -1;\n\n else\n\n distanceSign = 1;\n\n const float distanceResult =\n\n SinogramCreatorTools::roundToNearesMultiplicity(maxDistance + distanceSign * (r / std::sqrt(2)), accuracy);\n\n \n\n\n\n BOOST_REQUIRE_CLOSE(result.first, distanceResult, EPSILON);\n\n }\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(test_lor_slice) {\n", "file_path": "ImageReconstruction/tests/SinogramCreatorToolsTest.cpp", "rank": 61, "score": 13.76305430045695 }, { "content": " }\n\n }\n\n return true;\n\n}\n\n\n\nbool MLEMRunner::terminate()\n\n{\n\n INFO(\"Reconstructed \" + std::to_string(fReconstructedEvents) + \" events out of \" + std::to_string(fReconstructedEvents + fMissedEvents) +\n\n \" total(\" + std::to_string(fMissedEvents) + \" missed)\");\n\n runReconstruction();\n\n return true;\n\n}\n\n\n\nbool MLEMRunner::parseEvent(const JPetEvent& event)\n\n{\n\n const auto hits = event.getHits();\n\n if (hits.size() != 2) {\n\n return false;\n\n }\n\n const float x1 = hits[0].getPosX();\n", "file_path": "ImageReconstruction/MLEMRunner.cpp", "rank": 62, "score": 13.730287804673775 }, { "content": "}\n\n\n\nbool TimeCalibration::terminate()\n\n{\n\n fitAndSaveParametersToFile(fTimeConstantsCalibFileName, fTimeConstantsCalibFileNameTmp);\n\n if (CheckIfExit(Niter)) {\n\n auto newOpts = getOptions();\n\n newOpts[\"StopIteration_bool\"] = true;\n\n fParams = JPetParams(newOpts, fParams.getParamManagerAsShared());\n\n}\n\n return true;\n\n}\n\nbool TimeCalibration::CheckIfExit(int Niter)\n\n{\n\n if(Niter>=NiterMax){\n\n return true;\n\n }\n\n else\n\n {\n\n return false; \n", "file_path": "TimeCalibration_iter/TimeCalibration.cpp", "rank": 63, "score": 13.71634225471987 }, { "content": " * \"MLEMRunner_PixelSize_double\" : size of single pixel (in meters: e.g: 0.004 means 1 px corresponds 4mm)\n\n * \"MLEMRunner_StartPixelForPartialMatrix_int\" : start pixel for system matrix\n\n * \"MLEMRunner_NumberOfEmissionsPerPixel_int\" : number of emmisions per pixel for system matrix\n\n * \"MLEMRunner_TOFStepSize_double\" : TOF step size\n\n * \"MLEMRunner_DisplayInfo_bool\" : if true prints extra information about reconstruction on terminal\n\n * \"MLEMRunner_SystemMatrixOutputPath_std::string\" : path where system matrix will be/is saved\n\n * \"MLEMRunner_SystemMatrixSaveFull_bool\" : if true full system matrix will be saved\n\n * \"MLEMRunner_ReconstructionOutputPath_std::string\" : path where reconstructed image will be saved\n\n * \"MLEMRunner_ReconstuctionIterations_int\" : number of iterations in reconstruction\n\n * \"MLEMRunner_TOFSigmaAlongZAxis_float\" : error of measurement of Z position along scintillator in meters\n\n * \"MLEMRunner_TOFSigmaAxis_float\" : error of measurement TOF along LOR (or TOR in case of 3D) in meters\n\n */\n\n\n", "file_path": "ImageReconstruction/MLEMRunner.h", "rank": 64, "score": 13.702346145944711 }, { "content": " auto opts = getOptions();\n\n if (isOptionSet(opts, kOutFileNameKey)) {\n\n fOutFileName = getOptionAsString(opts, kOutFileNameKey);\n\n }\n\n\n\n fOutputStream.open(fOutFileName, std::ofstream::out | std::ofstream::app);\n\n std::vector<float> radius;\n\n radius.reserve(3);\n\n std::vector<int> scintillators;\n\n scintillators.reserve(3);\n\n\n\n const std::vector<float> rotation{0.f, 0.5f, 0.5f}; // rotation for BigBarrel\n\n\n\n const JPetParamBank& bank = getParamBank();\n\n const JPetGeomMapping mapping(bank);\n\n for (unsigned int i = 1; i < mapping.getLayersCount(); i++) {\n\n radius.push_back(mapping.getRadiusOfLayer(i) * kCentimetersToMeters);\n\n scintillators.push_back(static_cast<int>(mapping.getSlotsCount(i)));\n\n }\n\n\n", "file_path": "ImageReconstruction/MLEMRunner.cpp", "rank": 65, "score": 13.67774957006402 }, { "content": " fHitsArray)); // create LORs from Hits from the same Time Window\n\n } else {\n\n return false;\n\n }\n\n return true;\n\n}\n\n\n\nbool SDAMatchLORs::terminate() {\n\n int fEventNb = fCurrentEventNumber;\n\n INFO(Form(\"Matching complete \\nAmount of LORs mathed: %d out of %d hits\",\n\n fMatched, fEventNb));\n\n double goodPercent = fMatched * 100.0 / fEventNb;\n\n INFO(Form(\"%f %% of data was matched \\n \", goodPercent));\n\n return true;\n\n}\n\n\n\nvector<JPetLOR> SDAMatchLORs::createLORs(vector<JPetHit> &hits) {\n\n vector<JPetLOR> lors;\n\n for (auto i = hits.begin(); i != hits.end(); ++i) {\n\n for (auto j = i + 1; j != hits.end(); ++j) {\n", "file_path": "modules/SDA/JPetMatchLORs/SDAMatchLORs.cpp", "rank": 66, "score": 13.628598460704149 }, { "content": " if (auto oldTimeWindow = dynamic_cast<const JPetTimeWindow *const>(fEvent)) {\n\n auto n = oldTimeWindow->getNumberOfEvents();\n\n for (uint i = 0; i < n; ++i) {\n\n auto signal =\n\n dynamic_cast<const JPetRecoSignal &>(oldTimeWindow->operator[](i));\n\n fCharges[signal.getPM().getID()].push_back(signal.getCharge());\n\n }\n\n } else {\n\n return false;\n\n }\n\n return true;\n\n}\n\n\n\nbool SDARecoDrawAllCharges::terminate() {\n\n DEBUG(\"bool SDARecoDrawAllCharges::terminate\");\n\n auto c1 = new TCanvas();\n\n // looking for max and min value for all offsets\n\n double maximum = -1.e20;\n\n double minimum = 1.e20;\n\n for (const auto &id_vec_pair : fCharges) {\n", "file_path": "modules/SDA/JPetRecoDrawAllCharges/SDARecoDrawAllCharges.cpp", "rank": 67, "score": 13.594304329573305 }, { "content": "Aim\n\n---\n\nThis is an example analysis producing J-PET time calibration using data taken with a reference detector with option of iterative calibration constants determination. \n\n\n\nInput Data\n\n-----------\n\nFor a single execution of the program, a HLD file should be used, recorded when a single scintillator strip of the J-PET barrel was targeted by the reference detector.\n\n\n\nExpected output\n\n---------------\n\nNo output to stdout.\n\nJPet.log file appears with the log of the processing and ROOT files with the following etensions are produced:\n\n *.tslot.raw.root\n\n *.raw.sig.root\n\n *.phys.sig.root\n\n *.hits.root\n\n *.calib.root\n\nwhere \"*\" stands for the name of the output file (constructed as LayerId_slotId_FileId, e.g. for the first file measured for first scintillator in the first layer: \"Layer1_slot01_1\")\n\n\n\nMoreover, a text file \"TimeConstantsCalib.txt\" is created in the working directory, which contains time calibration information.\n\nFor the iterative version we create also temporary file \"ScintId_LayerId_TimeConstantsCalibTmp.txt\" where we save calibration constants after each iteration\n\n(again for the first scintillator in the first layer the filename is 1_1_TimeConstantsCalibTmp.txt.)\n\n\n\nDescription\n\n--------------\n\nThe analysis is using the same set of tasks as the \"LargeBarrelAnalysis\" example up to the level of creation of hits (included). On top of these tasks, an additional module called\n\n\"TimeCalibration\" is run, which prepares spectra of time differences between signals on the left and fight side of a scintillator and determines the necessary shifts of\n\ntimes at respective TDC channels.\n\n\n\nAdditional info\n\n--------------\n\nIn order to speed up the processing of a single position from a reference detector scan, one can provide a user option indicating which scintillator strip was targeted by the reference detector.\n\nThis was, signals from any other strips will be ignored at the lowest possible level, resulting in much faster processing.\n\n\n\nThis user option is:\n", "file_path": "TimeCalibration_iter/README.md", "rank": 68, "score": 13.561762586339011 }, { "content": "#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE SinogramCreatorTest\n\n#include <boost/test/unit_test.hpp>\n\n\n\n#include \"SinogramCreatorTools.h\"\n\n#include <iostream>\n\n\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\n\n\nBOOST_AUTO_TEST_CASE(roundToNearesMultiplicity_test)\n\n{\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.0f, 1.f), 0u);\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.4f, 1.f), 0u);\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.5f, 1.f), 1u);\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(30.f, 1.f), 30u);\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.00f, 0.01f), 0u);\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.01f, 0.01f), 1u);\n\n BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.02f, 0.01f), 2u);\n\n}\n\n\n", "file_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "rank": 69, "score": 13.549932336466233 }, { "content": " auto n_iterations = fReconstructionIterations;\n\n int start_iteration = 0;\n\n util::progress progress(fVerbose, n_iterations, 1, start_iteration);\n\n\n\n for (int block = 0; block < n_blocks; ++block) {\n\n for (int i = 0; i < n_iterations_in_block; i++) {\n\n const auto iteration = block * n_iterations_in_block + i;\n\n if (iteration < start_iteration)\n\n continue;\n\n progress(iteration);\n\n (*fReconstruction)();\n\n progress(iteration, true);\n\n }\n\n const auto iteration = (block + 1) * n_iterations_in_block;\n\n if (iteration <= start_iteration)\n\n continue;\n\n util::nrrd_writer nrrd(fReconstructionOutputPath + \"_\" + std::to_string(iteration) + \".nrrd\",\n\n fReconstructionOutputPath + \"_\" + std::to_string(iteration), false);\n\n nrrd << fReconstruction->rho;\n\n util::obstream bin(fReconstructionOutputPath + \"_\" + std::to_string(iteration));\n\n bin << fReconstruction->rho;\n\n }\n\n // final reconstruction statistics\n\n const auto st = fReconstruction->statistics();\n\n std::cerr << \" event count = \" << st.used_events << std::endl;\n\n std::cerr << \" voxel count = \" << st.used_voxels << \"(\" << (double)st.used_voxels / st.used_events << \" / event)\" << std::endl;\n\n std::cerr << \" pixel count = \" << st.used_pixels << \"(\" << (double)st.used_pixels / st.used_events << \" / event)\" << std::endl;\n\n}\n", "file_path": "ImageReconstruction/MLEMRunner.cpp", "rank": 70, "score": 13.499894100118915 }, { "content": " int PMid = hit.getSignalB().getRecoSignal().getRawSignal().getPM().getID();\n\n //\n\n //taking refference detector hits times (scin=193, Pmt=385)\n\n //\n\n\n\n if (PMid == kPMidRef) {\n\n auto lead_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n auto trail_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n //\n\n for (auto& thr_time_pair : lead_times_B) {\n\n int thr = thr_time_pair.first;\n\n RefTimeLead[thr] = thr_time_pair.second;\n\n\n\n }\n\n\n\n for (auto& thr_time_pair : trail_times_B) {\n\n int thr = thr_time_pair.first;\n\n RefTimeTrail[thr] = thr_time_pair.second;\n\n }\n\n fRefTimesL.push_back(RefTimeLead[1]);\n", "file_path": "TimeCalibration/TimeCalibration.cpp", "rank": 71, "score": 13.497965049109517 }, { "content": " slotSignals.push_back(physSig2);\n\n slotSignals.push_back(physSig3);\n\n\n\n JPetStatistics stats;\n\n std::map<unsigned int, std::vector<double>> velocitiesMap;\n\n JPetCachedFunctionParams params(\"pol1\", {0.0, 10.0});\n\n ToTEnergyConverter conv(params, Range(10000, 0., 100.));\n\n\n\n auto result = HitFinderTools::matchSignals(\n\n slotSignals, velocitiesMap, 5.0, false, conv, stats, false\n\n );\n\n BOOST_REQUIRE(result.empty());\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(matchSignals_test)\n\n{\n\n JPetLayer layer1(1, true, \"layer1\", 10.0);\n\n JPetBarrelSlot slot1(23, true, \"barel1\", 30.0, 23);\n\n slot1.setLayer(layer1);\n\n\n", "file_path": "LargeBarrelAnalysis/tests/HitFinderToolsTest.cpp", "rank": 72, "score": 13.406944163188179 }, { "content": " sigCh.setRecoFlag(JPetSigCh::Good);\n\n }\n\n\n\n if(!useCorrupts && sigCh.getRecoFlag() == JPetSigCh::Corrupted) { continue; }\n\n\n\n auto search = sigChsPMMap.find(pmtID);\n\n if (search == sigChsPMMap.end()) {\n\n vector<JPetSigCh> tmp;\n\n tmp.push_back(sigCh);\n\n sigChsPMMap.insert(pair<int, vector<JPetSigCh>>(pmtID, tmp));\n\n } else {\n\n search->second.push_back(sigCh);\n\n }\n\n }\n\n return sigChsPMMap;\n\n}\n\n\n\n/**\n\n * Method invoking Raw Signal building method for each PM separately\n\n */\n", "file_path": "LargeBarrelAnalysis/SignalFinderTools.cpp", "rank": 73, "score": 13.37446026478975 }, { "content": " map<int, vector<JPetPhysSignal>> signalsBySlot;\n\n for (auto const &signal : signals) {\n\n int barrelSlotID = signal.getRecoSignal().getBarrelSlot().getID();\n\n signalsBySlot[barrelSlotID].push_back(signal);\n\n }\n\n\n\n // discard entries for PMTs with smalller number of signals than two for each\n\n // barrel slot since they cannot be merged into JPetHit and later for JPetLOR\n\n for (auto it = signalsBySlot.begin(); it != signalsBySlot.end(); ++it) {\n\n if (it->second.size() < 2) {\n\n signalsBySlot.erase(it);\n\n }\n\n }\n\n\n\n // iterate over barrel slots which had a sufficient number\n\n // of signals to match a hit\n\n for (auto it = signalsBySlot.begin(); it != signalsBySlot.end(); ++it) {\n\n vector<JPetHit> hitsFromSingleSlot = matchHitsWithinSlot(it->second);\n\n // append the hits found for one specific barrel slot to all hits from this\n\n // time window\n", "file_path": "modules/SDA/JPetMatchHits/SDAMatchHits.cpp", "rank": 74, "score": 13.347729969200405 }, { "content": " getStatistics().getObject<TH1I>(\"number_of_events\")->Fill(numberOfHits);\n\n if (numberOfHits <= 1)\n\n continue;\n\n else\n\n {\n\n auto hits = event.getHits();\n\n for (unsigned int i = 0; i < hits.size() - 1; i++)\n\n {\n\n calculateAnnihilationPoint(hits[i], hits[i + 1]);\n\n }\n\n }\n\n }\n\n }\n\n else\n\n {\n\n ERROR(\"Returned event is not TimeWindow\");\n\n return false;\n\n }\n\n return true;\n\n}\n", "file_path": "ImageReconstruction/ImageReco.cpp", "rank": 75, "score": 13.301100990885233 }, { "content": "#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE JPetRecoImageToolsTests\n\n#include <boost/test/unit_test.hpp>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <utility>\n\n#include <vector>\n\n\n\n#include \"./JPetFilterCosine.h\"\n\n#include \"./JPetFilterHamming.h\"\n\n#include \"./JPetFilterNone.h\"\n\n#include \"./JPetFilterRamLak.h\"\n\n#include \"./JPetFilterRidgelet.h\"\n\n#include \"./JPetFilterSheppLogan.h\"\n\n#include \"./JPetRecoImageTools.h\"\n\n#include \"JPetCommonTools/JPetCommonTools.h\"\n\n\n\nconst auto inFile = \"unitTestData/JPetRecoImageToolsTest/sinogramBackproject.ppm\";\n\n\n\nint getMaxValue(const JPetRecoImageTools::Matrix2DProj& result)\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoSheppLoganThresholdsTest.cpp", "rank": 76, "score": 13.270982547352563 }, { "content": "#define BOOST_TEST_DYN_LINK\n\n#define BOOST_TEST_MODULE JPetRecoImageToolsTests\n\n#include <boost/test/unit_test.hpp>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <utility>\n\n#include <vector>\n\n\n\n#include \"JPetCommonTools/JPetCommonTools.h\"\n\n#include \"./JPetFilterCosine.h\"\n\n#include \"./JPetFilterHamming.h\"\n\n#include \"./JPetFilterNone.h\"\n\n#include \"./JPetFilterRamLak.h\"\n\n#include \"./JPetFilterRidgelet.h\"\n\n#include \"./JPetFilterSheppLogan.h\"\n\n#include \"./JPetRecoImageTools.h\"\n\n\n\nconst auto inFile = \"unitTestData/JPetRecoImageToolsTest/sinogramBackproject.ppm\";\n\n\n\nint getMaxValue(const JPetRecoImageTools::Matrix2DProj& result)\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoTest.cpp", "rank": 77, "score": 13.270982547352562 }, { "content": " If true generate full system matrix, not faster 1/8 of the system matrix and using symetries reconstruct full matrix\n\n\n\n- `MLEMRunner_ReconstructionOutputPath_std::string`\n\n Path to file where reconstruction will be saved\n\n\n\n- `MLEMRunner_ReconstuctionIterations_int`\n\n Number of MLEM iterations\n\n\n\n- `ImageReco_Annihilation_Point_Z_float`\n\n Maximum value of Z of reconstructed annihilation point to be included in reconstruction\n\n\n\n- `ImageReco_Xrange_On_3D_Histogram_int`\n\n Range of X axis on 3D Histogram\n\n\n\n- `ImageReco_Yrange_On_3D_Histogram_int`\n\n Range of Y axis on 3D Histogram\n\n\n\n- `ImageReco_Zrange_On_3D_Histogram_int`\n\n Range of Z axis on 3D Histogram\n\n\n\n- `ImageReco_Bin_Multiplier_double`\n\n Used to decrease size of bin, if bin multiplier is 1: 1 bin correspondes to 1 cm.\n\n\n\n- `SinogramCreator_OutFileName_std::string`\n\n Path to file where sinogram will be saved.\n\n\n\n- `SinogramCreator_ReconstructionDistanceAccuracy_float`\n\n Used to decrease size of bin, if reconstruction distance accuracy is 1: 1 bin correspondes to 1cm\n\n\n\n- `SinogramCreator_SinogramZSplitNumber_int`\n\n Number of sinograms along Z axis. Z axis is divided by this number and then evenly split.\n\n\n\n- `SinogramCreator_ScintillatorLenght_float`\n\n Lenght of the scintillator. [cm]\n\n\n\n- `SinogramCreatorMC_OutFileName_std::string`\n\n Path to file where sinogram will be saved.\n\n\n\n- `SinogramCreatorMC_ReconstructionDistanceAccuracy_float`\n\n Used to decrease size of bin, if reconstruction distance accuracy is 1: 1 bin correspondes to 1cm\n\n\n\n- `SinogramCreatorMC_SinogramZSplitNumber_int`\n\n Number of sinograms along Z axis. Z axis is divided by this number and then evenly split.\n\n\n\n- `SinogramCreatorMC_ScintillatorLenght_float`\n\n Lenght of the scintillator. [cm]\n\n\n\n- `SinogramCreatorMC_MaxReconstructionRadius_float`\n\n Maximal possible reconstruction radius. [cm]\n\n\n\n- `SinogramCreatorMC_InputDataPath_std::string`\n\n Path to file where input data is stored.\n", "file_path": "ImageReconstruction/PARAMETERS.md", "rank": 78, "score": 13.267429366375119 }, { "content": "--- Default value: 192\n\n\n\nNumber_of_points_to_filter_int\n\n--- Number of points that linear filter should work on. Filter is used to smooth derivatives and to estimate corrections better\n\n--- Default value: 6\n\n\n\nThreshold_for_derivative_int\n\n--- Value used for finding the first estimation of the extremum on the derivatives. If it is too high, Calibrate.exe would\n\nshow for many modules that the threshold is too high. If it is too low, extremum estimates will be wrongly estimated.\n\n--- Default value: 6\n\n\n\nEffective_Length_float\n\n--- Value of the effective length that are used to estimate velocity of every module. It can be changed and different PALS\n\ncorrections can be calculated. So, the effective length scan can be done from the EventFinder taks, speeding up the whole process\n\n\n\n-------------------------effLenParams.json-------------------------\n\n\n\nNumber_of_files_int\n\n--- Number of files that are used for the effective length scan. Every file should ocrrespond to different effective length value\n\nfor which calibration was done. It is used to scan the effLenParams.json file in order to find every file and length. \n\nIf the number will be equal to 3, EstimateEffectiveLength.exe will look for options:\n\nFile_1_std::string\n\nFile_2_std::string\n\nFile_3_std::string\n\nLength_1_float\n\nLength_2_float\n\nLength_3_float\n\nif it will be equal to 2:\n\nFile_1_std::string\n\nFile_2_std::string\n\nLength_1_float\n\nLength_2_float\n\nso the number of options are fluent and can change with different number of files\n\n\n\nFile_%d_std::string\n\n--- Path to and name of a `txt` file that contains corrections for a given effective length indicated by \n\nLength_%d_float option. %d should be equal to the number of a given file, for example: File_1_std::string\n\n\n\nLength_%d_float\n\n--- value of a effective length that was used during calibration. %d should be equal to the number of a given file\n", "file_path": "TimeCalibration_lifetime/PARAMETERS.md", "rank": 79, "score": 13.25426386114881 }, { "content": " std::map<int, double> leadingPoints, trailingPoints;\n\n leadingPoints = signal.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n trailingPoints = signal.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n for (int i = 1; i < 5; i++) {\n\n auto leadSearch = leadingPoints.find(i);\n\n auto trailSearch = trailingPoints.find(i);\n\n\n\n if (leadSearch != leadingPoints.end() && trailSearch != trailingPoints.end())\n\n tot += (trailSearch->second - leadSearch->second);\n\n }\n\n return tot / 1000.;\n\n}\n\n\n\nvoid FilterEvents::setUpOptions()\n\n{\n\n auto opts = getOptions();\n\n\n\n if (isOptionSet(opts, kCutOnZValueKey)) {\n\n fCutOnZValue = getOptionAsFloat(opts, kCutOnZValueKey);\n\n }\n", "file_path": "ImageReconstruction/FilterEvents.cpp", "rank": 80, "score": 13.248660836640846 }, { "content": " }\n\n }\n\n // Adding created Raw Signal to vector\n\n rawSigVec.push_back(rawSig);\n\n thrLeadingSigCh.at(0).erase(thrLeadingSigCh.at(0).begin());\n\n }\n\n // Filling control histograms\n\n if(saveHistos){\n\n for(unsigned int jj=0;jj<kNumberOfThresholds;jj++){\n\n for(auto sigCh : thrLeadingSigCh.at(jj)){\n\n stats.fillHistogram(\"unused_sigch_all\", 2*sigCh.getThresholdNumber()-1);\n\n if(sigCh.getRecoFlag()==JPetSigCh::Good){\n\n stats.fillHistogram(\"unused_sigch_good\", 2*sigCh.getThresholdNumber()-1);\n\n } else if(sigCh.getRecoFlag()==JPetSigCh::Corrupted){\n\n stats.fillHistogram(\"unused_sigch_corr\", 2*sigCh.getThresholdNumber()-1);\n\n }\n\n }\n\n for(auto sigCh : thrTrailingSigCh.at(jj)){\n\n stats.fillHistogram(\"unused_sigch_all\", 2*sigCh.getThresholdNumber());\n\n if(sigCh.getRecoFlag()==JPetSigCh::Good){\n", "file_path": "LargeBarrelAnalysis/SignalFinderTools.cpp", "rank": 81, "score": 13.248516387959569 }, { "content": " * between layer, barrel slot, PM side, threshold and TOMB channel number.\n\n */\n\nUniversalFileLoader::TOMBChToParameter UniversalFileLoader::loadConfigurationParameters(\n\n const std::string& confFile,\n\n const UniversalFileLoader::TOMBChMap& tombMap)\n\n{\n\n INFO(\"Loading parameters from file: \" + confFile);\n\n if (!boost::filesystem::exists(confFile)) {\n\n ERROR(\"Configuration file does not exist: \" + confFile + \" Returning empty configuration.\");\n\n TOMBChToParameter cofigurationParamteres;\n\n return cofigurationParamteres;\n\n }\n\n auto confRecords = readConfigurationParametersFromFile(confFile);\n\n return generateConfigurationParameters(confRecords, tombMap);\n\n}\n\n\n\n/**\n\n * Method generates a dependedce map between TOMB channel numbers and\n\n * configuration paramters. Arguments: vector of configuration records,\n\n * map of TOMBs with dependency between layer, barrel slot, PM side, threshold\n", "file_path": "LargeBarrelAnalysis/UniversalFileLoader.cpp", "rank": 82, "score": 13.143244579388517 }, { "content": " epsilon); // 3* 0.6 + 4 * 0.4\n\n auto getterT =\n\n JPetRecoImageTools::matrixGetterFactory(matrix, true); /// transposed\n\n /// first argument is j second i (j,i)\n\n BOOST_REQUIRE_CLOSE(JPetRecoImageTools::linear(0, 0, getterT), 1, epsilon);\n\n BOOST_REQUIRE_CLOSE(JPetRecoImageTools::linear(1, 0, getterT), 2, epsilon);\n\n BOOST_REQUIRE_CLOSE(JPetRecoImageTools::linear(0, 0.6, getterT), 2.2,\n\n epsilon); // 1*0.4 + 3 *0.6\n\n}\n\n/*\n\nBOOST_AUTO_TEST_CASE(calculateProjection)\n\n{\n\n double epsilon = 0.00001;\n\n JPetRecoImageTools::Matrix2D matrix = {{4}};\n\n //static double calculateProjection(const Matrix2D& emissionMatrix,\n\n //double phi,\n\n //int scanNumber,\n\n //int nScans,\n\n //InterpolationFunc& interpolationFunction\n\n //);\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoImageToolsTest.cpp", "rank": 83, "score": 13.11012578417714 }, { "content": " if (trailingFoundIdices.size() == 0) { return -1; }\n\n sort(trailingFoundIdices.begin(), trailingFoundIdices.end());\n\n return trailingFoundIdices.at(0);\n\n}\n\n\n\n/**\n\n * Method finds a 4-element permutation which has to be applied to threshold numbers\n\n * to have them sorted by increasing threshold values.\n\n *\n\n * The ordering may be different for each PMT, therefore the method creates a map\n\n * with PMT ID numbers as keys and 4-element permutations as values.\n\n */\n\nSignalFinderTools::ThresholdOrderings SignalFinderTools::findThresholdOrders(const JPetParamBank& bank){\n\n\n\n ThresholdOrderings orderings;\n\n std::map<PMid, ThresholdValues> thr_values_per_pm;\n\n\n\n for(auto& tc: bank.getTOMBChannels()){\n\n PMid pm_id = tc.second->getPM().getID();\n\n\n", "file_path": "LargeBarrelAnalysis/SignalFinderTools.cpp", "rank": 84, "score": 12.988924568371967 }, { "content": " JPetEvent event3;\n\n event3.addHit(firstHit);\n\n event3.addHit(secondHit);\n\n event3.addHit(thirdHit);\n\n event3.addHit(fourthHit);\n\n\n\n JPetStatistics stats;\n\n BOOST_REQUIRE(!EventCategorizerTools::checkFor3Gamma(event0, stats, false));\n\n BOOST_REQUIRE(!EventCategorizerTools::checkFor3Gamma(event1, stats, false));\n\n BOOST_REQUIRE(EventCategorizerTools::checkFor3Gamma(event2, stats, false));\n\n BOOST_REQUIRE(EventCategorizerTools::checkFor3Gamma(event3, stats, false));\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(checkForPromptTest) {\n\n JPetBarrelSlot barrelSlot(666, true, \"Some Slot\", 66.0, 666);\n\n JPetPM pmA(1, \"A\");\n\n JPetPM pmB(2, \"B\");\n\n pmA.setSide(JPetPM::SideA);\n\n pmB.setSide(JPetPM::SideB);\n\n pmA.setBarrelSlot(barrelSlot);\n", "file_path": "LargeBarrelAnalysis/tests/EventCategorizerToolsTest.cpp", "rank": 85, "score": 12.976447481115112 }, { "content": "#include <TCanvas.h>\n\n#include <TFile.h>\n\n#include <TLegend.h>\n\n#include <TLine.h>\n\n#include <TUnixSystem.h>\n\n\n\nvoid JPetRecoSignalTools::saveBadSignalIntoRootFile(\n\n const JPetRecoSignal &signal, const int numberOfBadSignals,\n\n const std::string fileName) {\n\n TCanvas *c1 = new TCanvas();\n\n TGraph *badSignal = JPetRecoSignalTools::plotJPetRecoSignal(signal);\n\n badSignal->Draw(\"AP\");\n\n std::string title;\n\n std::stringstream ss;\n\n ss << numberOfBadSignals;\n\n std::string str = ss.str();\n\n ss.str(std::string());\n\n ss.clear();\n\n ss << signal.getPM().getID();\n\n std::string PMT = ss.str();\n", "file_path": "modules/tools/JPetRecoSignalTools/JPetRecoSignalTools.cpp", "rank": 86, "score": 12.968290378059923 }, { "content": " }\n\n return true;\n\n}\n\n\n\nbool SinogramCreator::analyzeHits(const JPetHit& firstHit, const JPetHit& secondHit)\n\n{\n\n return analyzeHits(firstHit.getPos(), firstHit.getTime(), secondHit.getPos(), secondHit.getTime());\n\n}\n\n\n\nbool SinogramCreator::analyzeHits(const float firstX, const float firstY, const float firstZ, const double firstTOF, const float secondX,\n\n const float secondY, const float secondZ, const double secondTOF)\n\n{\n\n int i = -1;\n\n if (!fEnableObliqueLORRemapping)\n\n {\n\n i = SinogramCreatorTools::getSplitRangeNumber(firstZ, secondZ, fZSplitRange);\n\n }\n\n else\n\n {\n\n i = SinogramCreatorTools::getSinogramSlice(firstX, firstY, firstZ, firstTOF, secondX, secondY, secondZ, secondTOF, fZSplitRange);\n", "file_path": "ImageReconstruction/SinogramCreator.cpp", "rank": 87, "score": 12.872541592803795 }, { "content": " bool convertToT, const ToTEnergyConverter& totConverter, JPetStatistics& stats,\n\n bool saveHistos\n\n) {\n\n vector<JPetHit> slotHits;\n\n vector<JPetPhysSignal> remainSignals;\n\n sortByTime(slotSignals);\n\n while (slotSignals.size() > 0) {\n\n auto physSig = slotSignals.at(0);\n\n if(slotSignals.size() == 1){\n\n remainSignals.push_back(physSig);\n\n break;\n\n }\n\n for (unsigned int j = 1; j < slotSignals.size(); j++) {\n\n if (slotSignals.at(j).getTime() - physSig.getTime() < timeDiffAB) {\n\n if (physSig.getPM().getSide() != slotSignals.at(j).getPM().getSide()) {\n\n auto hit = createHit(\n\n physSig, slotSignals.at(j), velocitiesMap,\n\n convertToT, totConverter, stats, saveHistos\n\n );\n\n slotHits.push_back(hit);\n", "file_path": "LargeBarrelAnalysis/HitFinderTools.cpp", "rank": 88, "score": 12.869554684497407 }, { "content": "vector<JPetRawSignal> SignalFinderTools::buildAllSignals(\n\n const map<int, vector<JPetSigCh>>& sigChByPM,\n\n double sigChEdgeMaxTime, double sigChLeadTrailMaxTime,\n\n JPetStatistics& stats, bool saveHistos,\n\n ThresholdOrderings thresholdOrderings\n\n) {\n\n vector<JPetRawSignal> allSignals;\n\n \n\n for (auto& sigChPair : sigChByPM) {\n\n Permutation P;\n\n if(thresholdOrderings.empty()){\n\n P = kIdentity;\n\n }else{\n\n P = thresholdOrderings.at(sigChPair.first);\n\n }\n\n\n\n auto signals = buildRawSignals(\n\n sigChPair.second, sigChEdgeMaxTime, sigChLeadTrailMaxTime, stats, saveHistos, P\n\n );\n\n allSignals.insert(allSignals.end(), signals.begin(), signals.end());\n", "file_path": "LargeBarrelAnalysis/SignalFinderTools.cpp", "rank": 89, "score": 12.841124653548093 }, { "content": " }\n\n }\n\n for(unsigned int i=0;i<trails.size();i++){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_corr\", 2*(i+1));\n\n if(trails.at(i).getRecoFlag()==JPetSigCh::Good){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_corr_sigch_good\", 2*(i+1));\n\n } else if(trails.at(i).getRecoFlag()==JPetSigCh::Corrupted){\n\n getStatistics().fillHistogram(\"raw_sigs_multi_corr_sigch_corr\", 2*(i+1));\n\n }\n\n }\n\n } else if(rawSignal.getRecoFlag()==JPetBaseSignal::Unknown){\n\n getStatistics().fillHistogram(\"good_vs_bad_signals\", 3);\n\n }\n\n }\n\n // Make Reco Signal from Raw Signal\n\n auto recoSignal = createRecoSignal(rawSignal);\n\n // Make Phys Signal from Reco Signal and save\n\n auto physSignal = createPhysSignal(recoSignal);\n\n fOutputEvents->add<JPetPhysSignal>(physSignal);\n\n }\n", "file_path": "LargeBarrelAnalysis/SignalTransformer.cpp", "rank": 90, "score": 12.826642499972085 }, { "content": "\n\n if (lead_times_A.count(thr) > 0 && trail_times_A.count(thr) > 0 && lead_times_A.size() == 4 && trail_times_A.size() == 4) { //exactly 4 thresholds\n\n\n\n lead_times_first_A = lead_times_A[1];\n\n\n\n if (thr >= 2) {\n\n\t\n\n thr_time_diff_A[thr] = lead_times_A[thr] / 1000 - lead_times_first_A / 1000;\n\n\t\n\n char* histo_name_l_A = Form(\"timeDiffA_leading_layer_%d_slot_%d_thr_1%d\", layer_number, slot_nr, thr);\n\n getStatistics().fillHistogram(histo_name_l_A, thr_time_diff_A[thr]);\n\n }\n\n }\n\n }\n\n \n\n // B\n\n for (auto& thr_time_pair : lead_times_B) {\n\n\n\n int thr = thr_time_pair.first;\n\n\n", "file_path": "InterThresholdCalibration/InterThresholdCalibration.cpp", "rank": 91, "score": 12.81444601138087 }, { "content": "BOOST_AUTO_TEST_CASE(matchSignals_test_sameSide)\n\n{\n\n JPetBarrelSlot slot1(1, true, \"one\", 15.0, 1);\n\n JPetScin scin1(1);\n\n JPetPM pm1(11, \"first\");\n\n pm1.setBarrelSlot(slot1);\n\n pm1.setScin(scin1);\n\n pm1.setSide(JPetPM::SideA);\n\n JPetPhysSignal physSig1, physSig2, physSig3;\n\n physSig1.setBarrelSlot(slot1);\n\n physSig2.setBarrelSlot(slot1);\n\n physSig3.setBarrelSlot(slot1);\n\n physSig1.setPM(pm1);\n\n physSig2.setPM(pm1);\n\n physSig3.setPM(pm1);\n\n physSig1.setTime(1.0);\n\n physSig2.setTime(2.0);\n\n physSig3.setTime(3.0);\n\n std::vector<JPetPhysSignal> slotSignals;\n\n slotSignals.push_back(physSig1);\n", "file_path": "LargeBarrelAnalysis/tests/HitFinderToolsTest.cpp", "rank": 92, "score": 12.789320182082593 }, { "content": " }\n\n}\n\n\n\nvoid TimeCalibration::fillHistosForHit(const JPetHit& hit, const std::vector<double>& refTimesL, const std::vector<double>& refTimesT)\n\n{\n\n auto lead_times_A = hit.getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n auto trail_times_A = hit.getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n\n\n auto lead_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n auto trail_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Trailing);\n\n float TOT_A = 0.;\n\n float TOT_B = 0.;\n\n double timeDiffTmin = 0;\n\n double timeDiffLmin = 0;\n\n\n\n for (auto& thr_time_pair : lead_times_A) {\n\n int thr = thr_time_pair.first;\n\n\n\n if (trail_times_A.count(thr) > 0 ) {\n\n TOT_A = TOT_A + trail_times_A[thr] - lead_times_A[thr];\n", "file_path": "TimeCalibration_iter/TimeCalibration.cpp", "rank": 93, "score": 12.713150699337715 }, { "content": " const auto scin = bank.getScintillator(1);\n\n\n\n const float detectorWidth = scin.getScinSize(JPetScin::Dimension::kWidth);\n\n const float detectorHeight = scin.getScinSize(JPetScin::Dimension::kHeight);\n\n fHalfStripLenght = scin.getScinSize(JPetScin::Dimension::kLength) / 2.f;\n\n const float detectorD = 0.f;\n\n const float fowRadius = 0.4f;\n\n\n\n fScanner = ScannerBuilder<SquareScanner>::build_multiple_rings(__PET2D_BARREL(radius, // radius\n\n rotation, // rotation\n\n scintillators, // n-detectors\n\n detectorWidth, // w-detector\n\n detectorHeight, // h-detector\n\n detectorD, // should be d-detector\n\n fowRadius // fow radius\n\n ));\n\n\n\n if (isOptionSet(opts, kNumberOfPixelsInOneDimensionKey)) {\n\n fNumberOfPixelsInOneDimension = getOptionAsInt(opts, kNumberOfPixelsInOneDimensionKey);\n\n }\n", "file_path": "ImageReconstruction/MLEMRunner.cpp", "rank": 94, "score": 12.697429506737837 }, { "content": " \"badOffsets.root\");\n\n fBadSignals++;\n\n } else {\n\n auto signalWithOffset = signal;\n\n signalWithOffset.setOffset(fOffset);\n\n fOutputEvents->add<JPetRecoSignal>(signalWithOffset);\n\n }\n\n fCurrentEventNumber++;\n\n }\n\n } else {\n\n return false;\n\n }\n\n\n\n return true;\n\n}\n\n\n\nbool SDARecoOffsetsCalc::terminate() {\n\n int fEventNb = fCurrentEventNumber;\n\n double goodPercent = (fEventNb - fBadSignals) * 100.0 / fEventNb;\n\n INFO(Form(\"Amount of signals in input file: %d\", fEventNb));\n\n INFO(Form(\"Offset calculation complete \\nAmount of bad signals: %d \\n %f %% \"\n\n \"of data is good\",\n\n fBadSignals, goodPercent));\n\n return true;\n\n}\n", "file_path": "modules/SDA/JPetRecoOffsetCalc/SDARecoOffsetsCalc.cpp", "rank": 95, "score": 12.689247375228579 }, { "content": " }\n\n }\n\n for (auto& thr_time_pair : lead_times_B) {\n\n int thr = thr_time_pair.first;\n\n if ( trail_times_B.count(thr) > 0 ) {\n\n TOT_B = TOT_B + trail_times_B[thr] - lead_times_B[thr];\n\n }\n\n }\n\n float tTOT = (TOT_A + TOT_B) / 1000.; //total TOT in ns\n\n//\n\n//----------cut the hit if TOT is out of accepted range (cuts given in ns)\n\n if (tTOT >= TOTcut[0] && tTOT <= TOTcut[1]) {\n\n//\n\n//leading edge\n\n for (auto& thr_time_pair : lead_times_A) {\n\n\n\n int thr = thr_time_pair.first;\n\n //**\t\tconst char * histo_name_l = Form(\"%slayer_%d_slot_%d_thr_%d\",\"timeDiffAB_leading_\",LayerToCalib,StripToCalib,thr);\n\n //**const char * histo_name_Ref_l = Form(\"%slayer_%d_slot_%d_thr_%d\",\"timeDiffRef_leading_\",LayerToCalib,StripToCalib,thr);\n\n //**std::cout << histo_name_l<<\" \"<<histo_name_l<< std::endl;\n", "file_path": "TimeCalibration/TimeCalibration.cpp", "rank": 96, "score": 12.678112044542154 }, { "content": "BOOST_AUTO_TEST_CASE(projection2)\n\n{\n\n double epsilon = 0.00001;\n\n JPetRecoImageTools::Matrix2D matrix = {{1, 2}, {3, 4}};\n\n /// 1 2\n\n /// 3 4\n\n\n\n int imageSize = matrix.size();\n\n double center = (float)(imageSize - 1) / 2.0;\n\n double length = center * center;\n\n std::function< double(int, int) > matrixGet;\n\n matrixGet = JPetRecoImageTools::matrixGetterFactory(\n\n matrix, false); // The matrix elements will be taken as (x,y).\n\n double step = (M_PI / 180);\n\n\n\n double cos = std::cos(step * 0); // 0 degree\n\n double sin = std::sin(step * 0); // 0 degree\n\n BOOST_REQUIRE_CLOSE(JPetRecoImageTools::calculateProjection2(\n\n 0, cos, sin, imageSize, center, length, matrixGet),\n\n 4, epsilon); // 1 + 3\n", "file_path": "ImageReconstruction/Reconstruction/JPetRecoImageTools/JPetRecoImageToolsTest.cpp", "rank": 97, "score": 12.611482405460636 }, { "content": " auto opts = getOptions();\n\n\n\n if (isOptionSet(opts, kXRangeOn3DHistogramKey))\n\n {\n\n fXRange = getOptionAsInt(opts, kXRangeOn3DHistogramKey);\n\n }\n\n\n\n if (isOptionSet(opts, kYRangeOn3DHistogramKey))\n\n {\n\n fYRange = getOptionAsInt(opts, kYRangeOn3DHistogramKey);\n\n }\n\n\n\n if (isOptionSet(opts, kZRangeOn3DHistogramKey))\n\n {\n\n fZRange = getOptionAsInt(opts, kZRangeOn3DHistogramKey);\n\n }\n\n\n\n if (isOptionSet(opts, kCutOnAnnihilationPointZKey))\n\n {\n\n fANNIHILATION_POINT_Z = getOptionAsFloat(opts, kCutOnAnnihilationPointZKey);\n", "file_path": "ImageReconstruction/ImageReco.cpp", "rank": 98, "score": 12.611482405460636 }, { "content": " }\n\n }\n\n for (auto& thr_time_pair : lead_times_B) {\n\n int thr = thr_time_pair.first;\n\n if ( trail_times_B.count(thr) > 0 ) {\n\n TOT_B = TOT_B + trail_times_B[thr] - lead_times_B[thr];\n\n }\n\n }\n\n float tTOT = (TOT_A + TOT_B) / 1000.;\n\n if (tTOT >= TOTcut[0] && tTOT <= TOTcut[1]) {\n\n for (auto& thr_time_pair : lead_times_A) {\n\n\n\n int thr = thr_time_pair.first;\n\n if ( lead_times_B.count(thr) > 0 ) {\n\n double timeDiffAB_l = (lead_times_B[thr] / 1000. + CBlCor[thr]) - (lead_times_A[thr] / 1000. + CAlCor[thr]);\n\n const char* histo_name_l = formatUniqueSlotDescription(hit.getBarrelSlot(), thr, \"timeDiffAB_leading_\");\n\n getStatistics().fillHistogram(histo_name_l, timeDiffAB_l);\n\n timeDiffLmin = 10000000000000.;\n\n for (unsigned int i = 0; i < refTimesL.size(); i++) {\n\n double timeDiffHit_L = (lead_times_A[thr] / 1000. + CAlCor[thr]) + (lead_times_B[thr] / 1000. + CBlCor[thr]);\n", "file_path": "TimeCalibration_iter/TimeCalibration.cpp", "rank": 99, "score": 12.553968654819666 } ]
C++
UnitTests/Physics/HeightFieldShapeTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
#include "UnitTestFramework.h" #include "PhysicsTestContext.h" #include <Physics/Collision/RayCast.h> #include <Physics/Collision/CastResult.h> #include <Physics/Collision/Shape/HeightFieldShape.h> #include <Physics/Collision/PhysicsMaterialSimple.h> TEST_SUITE("HeightFieldShapeTests") { static void sRandomizeMaterials(HeightFieldShapeSettings &ioSettings, uint inMaxMaterials) { for (uint i = 0; i < inMaxMaterials; ++i) ioSettings.mMaterials.push_back(new PhysicsMaterialSimple("Material " + ConvertToString(i), Color::sGetDistinctColor(i))); if (inMaxMaterials > 1) { UnitTestRandom random; uniform_int_distribution<uint> index_distribution(0, inMaxMaterials - 1); ioSettings.mMaterialIndices.resize(Square(ioSettings.mSampleCount - 1)); for (uint y = 0; y < ioSettings.mSampleCount - 1; ++y) for (uint x = 0; x < ioSettings.mSampleCount - 1; ++x) ioSettings.mMaterialIndices[y * (ioSettings.mSampleCount - 1) + x] = uint8(index_distribution(random)); } } static Ref<HeightFieldShape> sValidateGetPosition(const HeightFieldShapeSettings &inSettings, float inMaxError) { Ref<HeightFieldShape> shape = static_cast<HeightFieldShape *>(inSettings.Create().Get().GetPtr()); float max_diff = -1.0f; for (uint y = 0; y < inSettings.mSampleCount; ++y) for (uint x = 0; x < inSettings.mSampleCount; ++x) { RayCast ray { inSettings.mOffset + inSettings.mScale * Vec3((float)x, 100.0f, (float)y), inSettings.mScale.GetY() * Vec3(0, -200, 0) }; RayCastResult hit; shape->CastRay(ray, SubShapeIDCreator(), hit); float height = inSettings.mHeightSamples[y * inSettings.mSampleCount + x]; if (height != HeightFieldShapeConstants::cNoCollisionValue) { CHECK(!shape->IsNoCollision(x, y)); Vec3 original_pos = inSettings.mOffset + inSettings.mScale * Vec3((float)x, height, (float)y); Vec3 shape_pos = shape->GetPosition(x, y); float diff = (original_pos - shape_pos).Length(); max_diff = max(max_diff, diff); if (x < inSettings.mSampleCount - 1 && y < inSettings.mSampleCount - 1) { const PhysicsMaterial *m1 = PhysicsMaterial::sDefault; if (!inSettings.mMaterialIndices.empty()) m1 = inSettings.mMaterials[inSettings.mMaterialIndices[y * (inSettings.mSampleCount - 1) + x]]; else if (!inSettings.mMaterials.empty()) m1 = inSettings.mMaterials.front(); const PhysicsMaterial *m2 = shape->GetMaterial(x, y); CHECK(m1 == m2); } if (x > 0 && y > 0 && x < inSettings.mSampleCount - 1 && y < inSettings.mSampleCount - 1) { Vec3 hit_pos = ray.mOrigin + ray.mDirection * hit.mFraction; CHECK_APPROX_EQUAL(hit_pos, shape_pos, 1.0e-3f); } } else { CHECK(shape->IsNoCollision(x, y)); CHECK(hit.mFraction > 1.0f); } } CHECK(max_diff <= inMaxError); return shape; } TEST_CASE("TestPlane") { HeightFieldShapeSettings settings; settings.mOffset = Vec3(3, 5, 7); settings.mScale = Vec3(9, 13, 17); settings.mSampleCount = 32; settings.mBitsPerSample = 1; settings.mBlockSize = 4; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = 1.0f; UnitTestRandom random; uniform_int_distribution<uint> index_distribution(0, (uint)settings.mHeightSamples.size() - 1); for (int i = 0; i < 10; ++i) settings.mHeightSamples[index_distribution(random)] = HeightFieldShapeConstants::cNoCollisionValue; CHECK(settings.CalculateBitsPerSampleForError(0.0f) == 1); sRandomizeMaterials(settings, 256); sValidateGetPosition(settings, 0.0f); } TEST_CASE("TestPlaneCloseToOrigin") { HeightFieldShapeSettings settings; settings.mSampleCount = 32; settings.mBitsPerSample = 1; settings.mBlockSize = 4; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = 1.0e-6f; CHECK(settings.CalculateBitsPerSampleForError(0.0f) == 1); sRandomizeMaterials(settings, 50); sValidateGetPosition(settings, 0.0f); } TEST_CASE("TestRandomHeightField") { const float cMinHeight = -5.0f; const float cMaxHeight = 10.0f; UnitTestRandom random; uniform_real_distribution<float> height_distribution(cMinHeight, cMaxHeight); HeightFieldShapeSettings settings; settings.mOffset = Vec3(0.3f, 0.5f, 0.7f); settings.mScale = Vec3(1.1f, 1.2f, 1.3f); settings.mSampleCount = 32; settings.mBitsPerSample = 8; settings.mBlockSize = 4; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = height_distribution(random); for (uint32 bits_per_sample = 1; bits_per_sample <= 8; ++bits_per_sample) { float max_error = 0.5f * (cMaxHeight - cMinHeight) / ((1 << bits_per_sample) - 1); uint32 calculated_bits_per_sample = settings.CalculateBitsPerSampleForError(max_error); CHECK(calculated_bits_per_sample <= bits_per_sample); } sRandomizeMaterials(settings, 1); sValidateGetPosition(settings, settings.mScale.GetY() * (cMaxHeight - cMinHeight) / ((1 << settings.mBitsPerSample) - 1)); } TEST_CASE("TestEmptyHeightField") { HeightFieldShapeSettings settings; settings.mSampleCount = 32; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = HeightFieldShapeConstants::cNoCollisionValue; CHECK(settings.CalculateBitsPerSampleForError(0.0f) == 1); sRandomizeMaterials(settings, 50); Ref<HeightFieldShape> shape = sValidateGetPosition(settings, 0.0f); Shape::Stats stats = shape->GetStats(); CHECK(stats.mNumTriangles == 0); CHECK(stats.mSizeBytes == sizeof(HeightFieldShape)); } }
#include "UnitTestFramework.h" #include "PhysicsTestContext.h" #include <Physics/Collision/RayCast.h> #include <Physics/Collision/CastResult.h> #include <Physics/Collision/Shape/HeightFieldShape.h> #include <Physics/Collision/PhysicsMaterialSimple.h> TEST_SUITE("HeightFieldShapeTests") { static void sRandomizeMaterials(HeightFieldShapeSettings &ioSettings, uint inMaxMaterials) { for (uint i = 0; i < inMaxMaterials; ++i) ioSettings.mMaterials.push_back(new PhysicsMaterialSimple("Material " + ConvertToString(i), Color::sGetDistinctColor(i))); if (inMaxMaterials > 1) { UnitTestRandom random; uniform_int_distribution<uint> index_distribution(0, inMaxMaterials - 1); ioSettings.mMaterialIndices.resize(Square(ioSettings.mSampleCount - 1)); for (uint y = 0; y < ioSettings.mSampleCount - 1; ++y) for (uint x = 0; x < ioSettings.mSampleCount - 1; ++x) ioSettings.mMaterialIndices[y * (ioSettings.mSampleCount - 1) + x] = uint8(index_distribution(random)); } } static Ref<HeightFieldShape> sValidateGetPosition(const HeightFieldShapeSettings &inSettings, float inMaxError) { Ref<HeightFieldShape> shape = static_cast<HeightFieldShape *>(inSettings.Create().Get().GetPtr()); float max_diff = -1.0f; for (uint y = 0; y < inSettings.mSampleCount; ++y) for (uint x = 0; x < inSettings.mSampleCount; ++x) { RayCast ray { inSettings.mOffset + inSettings.mScale * Vec3((float)x, 100.0f, (float)y), inSettings.mScale.GetY() * Vec3(0, -200, 0) }; RayCastResult hit; shape->CastRay(ray, SubShapeIDCreator(), hit); float height = inSettings.mHeightSamples[y * inSettings.mSampleCount + x]; if (height != HeightFieldShapeConstants::cNoCollisionValue) { CHECK(!shape->IsNoCollision(x, y)); Vec3 original_pos = inSettings.mOffset + inSettings.mScale * Vec3((float)x, height, (float)y); Vec3 shape_pos = shape->GetPosition(x, y); float diff = (original_pos - shape_pos).Length(); max_diff = max(max_diff, diff); if (x < inSettings.mSampleCount - 1 && y < inSettings.mSampleCount - 1) { const PhysicsMaterial *m1 = PhysicsMaterial::sDefault; if (!inSettings.mMaterialIndices.empty()) m1 = inSettings.mMaterials[inSettings.mMaterialIndices[y * (inSettings.mSampleCount - 1) + x]];
TEST_CASE("TestPlane") { HeightFieldShapeSettings settings; settings.mOffset = Vec3(3, 5, 7); settings.mScale = Vec3(9, 13, 17); settings.mSampleCount = 32; settings.mBitsPerSample = 1; settings.mBlockSize = 4; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = 1.0f; UnitTestRandom random; uniform_int_distribution<uint> index_distribution(0, (uint)settings.mHeightSamples.size() - 1); for (int i = 0; i < 10; ++i) settings.mHeightSamples[index_distribution(random)] = HeightFieldShapeConstants::cNoCollisionValue; CHECK(settings.CalculateBitsPerSampleForError(0.0f) == 1); sRandomizeMaterials(settings, 256); sValidateGetPosition(settings, 0.0f); } TEST_CASE("TestPlaneCloseToOrigin") { HeightFieldShapeSettings settings; settings.mSampleCount = 32; settings.mBitsPerSample = 1; settings.mBlockSize = 4; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = 1.0e-6f; CHECK(settings.CalculateBitsPerSampleForError(0.0f) == 1); sRandomizeMaterials(settings, 50); sValidateGetPosition(settings, 0.0f); } TEST_CASE("TestRandomHeightField") { const float cMinHeight = -5.0f; const float cMaxHeight = 10.0f; UnitTestRandom random; uniform_real_distribution<float> height_distribution(cMinHeight, cMaxHeight); HeightFieldShapeSettings settings; settings.mOffset = Vec3(0.3f, 0.5f, 0.7f); settings.mScale = Vec3(1.1f, 1.2f, 1.3f); settings.mSampleCount = 32; settings.mBitsPerSample = 8; settings.mBlockSize = 4; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = height_distribution(random); for (uint32 bits_per_sample = 1; bits_per_sample <= 8; ++bits_per_sample) { float max_error = 0.5f * (cMaxHeight - cMinHeight) / ((1 << bits_per_sample) - 1); uint32 calculated_bits_per_sample = settings.CalculateBitsPerSampleForError(max_error); CHECK(calculated_bits_per_sample <= bits_per_sample); } sRandomizeMaterials(settings, 1); sValidateGetPosition(settings, settings.mScale.GetY() * (cMaxHeight - cMinHeight) / ((1 << settings.mBitsPerSample) - 1)); } TEST_CASE("TestEmptyHeightField") { HeightFieldShapeSettings settings; settings.mSampleCount = 32; settings.mHeightSamples.resize(Square(settings.mSampleCount)); for (float &h : settings.mHeightSamples) h = HeightFieldShapeConstants::cNoCollisionValue; CHECK(settings.CalculateBitsPerSampleForError(0.0f) == 1); sRandomizeMaterials(settings, 50); Ref<HeightFieldShape> shape = sValidateGetPosition(settings, 0.0f); Shape::Stats stats = shape->GetStats(); CHECK(stats.mNumTriangles == 0); CHECK(stats.mSizeBytes == sizeof(HeightFieldShape)); } }
else if (!inSettings.mMaterials.empty()) m1 = inSettings.mMaterials.front(); const PhysicsMaterial *m2 = shape->GetMaterial(x, y); CHECK(m1 == m2); } if (x > 0 && y > 0 && x < inSettings.mSampleCount - 1 && y < inSettings.mSampleCount - 1) { Vec3 hit_pos = ray.mOrigin + ray.mDirection * hit.mFraction; CHECK_APPROX_EQUAL(hit_pos, shape_pos, 1.0e-3f); } } else { CHECK(shape->IsNoCollision(x, y)); CHECK(hit.mFraction > 1.0f); } } CHECK(max_diff <= inMaxError); return shape; }
function_block-function_prefix_line
[ { "content": "/// A height field shape. Cannot be used as a dynamic object.\n\nclass HeightFieldShape final : public Shape\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t\t\t\t\t\t\t\t\tHeightFieldShape() : Shape(EShapeType::HeightField, EShapeSubType::HeightField) { }\n\n\t\t\t\t\t\t\t\t\tHeightFieldShape(const HeightFieldShapeSettings &inSettings, ShapeResult &outResult);\n\n\n\n\t// See Shape::MustBeStatic\n\n\tvirtual bool\t\t\t\t\tMustBeStatic() const override\t\t\t\t\t\t\t\t\t\t{ return true; }\n\n\n\n\t// See Shape::GetLocalBounds\n\n\tvirtual AABox\t\t\t\t\tGetLocalBounds() const override;\n\n\n\n\t// See Shape::GetSubShapeIDBitsRecursive\n\n\tvirtual uint\t\t\t\t\tGetSubShapeIDBitsRecursive() const override\t\t\t\t\t\t\t{ return GetSubShapeIDBits(); }\n\n\n\n\t// See Shape::GetInnerRadius\n\n\tvirtual float\t\t\t\t\tGetInnerRadius() const override\t\t\t\t\t\t\t\t\t\t{ return 0.0f; }\n\n\n\n\t// See Shape::GetMassProperties\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 0, "score": 154733.17245788907 }, { "content": "struct RayCast;\n", "file_path": "Jolt/Physics/Collision/Shape/Shape.h", "rank": 1, "score": 154289.84104420443 }, { "content": "class RayCastResult;\n", "file_path": "Jolt/Physics/Collision/Shape/Shape.h", "rank": 2, "score": 151533.85942643584 }, { "content": "struct RayCast;\n", "file_path": "Jolt/Physics/Collision/TransformedShape.h", "rank": 3, "score": 141128.41801112692 }, { "content": "class RayCastResult;\n\n\n", "file_path": "Jolt/Physics/Collision/TransformedShape.h", "rank": 4, "score": 138099.12036171422 }, { "content": "\t\t// A collector that just counts the number of hits\n\n\t\tclass HitCountCollector : public CastRayCollector\t\n\n\t\t{\n\n\t\tpublic:\n\n\t\t\tvirtual void\tAddHit(const RayCastResult &inResult) override\n\n\t\t\t{\n\n\t\t\t\t// Store the last sub shape ID so that we can provide something to our outer hit collector\n\n\t\t\t\tmSubShapeID = inResult.mSubShapeID2;\n\n\n\n\t\t\t\t++mHitCount;\n\n\t\t\t}\n\n\n\n\t\t\tint\t\t\t\tmHitCount = 0;\n\n\t\t\tSubShapeID\t\tmSubShapeID;\n\n\t\t};\n\n\t\tHitCountCollector collector;\n\n\n\n\t\t// Configure the raycast\n\n\t\tRayCastSettings settings;\n\n\t\tsettings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces;\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/MeshShape.cpp", "rank": 5, "score": 134980.19997187192 }, { "content": "/// A compound shape, sub shapes can be rotated and translated.\n\n/// Sub shapes cannot be modified once the shape is constructed.\n\n/// Shifts all child objects so that they're centered around the center of mass.\n\nclass StaticCompoundShape final : public CompoundShape\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t\t\t\t\t\t\t\t\tStaticCompoundShape() : CompoundShape(EShapeSubType::StaticCompound) { }\n\n\t\t\t\t\t\t\t\t\tStaticCompoundShape(const StaticCompoundShapeSettings &inSettings, TempAllocator &inTempAllocator, ShapeResult &outResult);\n\n\n\n\t// See Shape::CastRay\n\n\tvirtual bool\t\t\t\t\tCastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;\n\n\tvirtual void\t\t\t\t\tCastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const override;\n\n\n\n\t// See: Shape::CollidePoint\n\n\tvirtual void\t\t\t\t\tCollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const override;\n\n\n\n\t// See Shape::CollectTransformedShapes\n\n\tvirtual void\t\t\t\t\tCollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector) const override;\n\n\n\n\t// See: CompoundShape::GetIntersectingSubShapes\n\n\tvirtual int\t\t\t\t\t\tGetIntersectingSubShapes(const AABox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const override;\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 6, "score": 121047.48369150463 }, { "content": "/// Class that constructs a HeightFieldShape\n\nclass HeightFieldShapeSettings final : public ShapeSettings\n\n{\n\npublic:\n\n\tJPH_DECLARE_SERIALIZABLE_VIRTUAL(HeightFieldShapeSettings)\n\n\n\n\t/// Default constructor for deserialization\n\n\t\t\t\t\t\t\t\t\tHeightFieldShapeSettings() = default;\n\n\n\n\t/// Create a height field shape of inSampleCount * inSampleCount vertices.\n\n\t/// The height field is a surface defined by: inOffset + inScale * (x, inSamples[y * inSampleCount + x], y).\n\n\t/// where x and y are integers in the range x and y e [0, inSampleCount - 1].\n\n\t/// inSampleCount: inSampleCount / mBlockSize must be a power of 2 and minimally 2.\n\n\t/// inSamples: inSampleCount^2 vertices.\n\n\t/// inMaterialIndices: (inSampleCount - 1)^2 indices that index into inMaterialList.\n\n\t\t\t\t\t\t\t\t\tHeightFieldShapeSettings(const float *inSamples, Vec3Arg inOffset, Vec3Arg inScale, uint32 inSampleCount, const uint8 *inMaterialIndices = nullptr, const PhysicsMaterialList &inMaterialList = PhysicsMaterialList());\n\n\n\n\t// See: ShapeSettings\n\n\tvirtual ShapeResult\t\t\t\tCreate() const override;\n\n\n\n\t/// Determine the minimal and maximal value of mHeightSamples (will ignore cNoCollisionValue)\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 7, "score": 119301.00293122137 }, { "content": "class StaticCompoundShapeTest : public Test\n\n{\n\npublic:\n\n\tJPH_DECLARE_RTTI_VIRTUAL(StaticCompoundShapeTest)\n\n\n\n\t// See: Test\n\n\tvirtual void\tInitialize() override;\n\n};", "file_path": "Samples/Tests/Shapes/StaticCompoundShapeTest.h", "rank": 8, "score": 118351.96146518998 }, { "content": "class HeightFieldShapeTest : public Test\n\n{\n\npublic:\n\n\tJPH_DECLARE_RTTI_VIRTUAL(HeightFieldShapeTest)\n\n\n\n\t// Initialize the test\n\n\tvirtual void\t\tInitialize() override;\n\n\n\n\t// Update the test, called before the physics update\n\n\tvirtual void\t\tPrePhysicsUpdate(const PreUpdateParams &inParams) override;\n\n\n\n\t// Override to specify the initial camera state (local to GetCameraPivot)\n\n\tvirtual void\t\tGetInitialCamera(CameraState &ioState) const override;\n\n\n\n\t// Optional settings menu\n\n\tvirtual bool\t\tHasSettingsMenu() const\toverride\t\t\t\t\t\t\t{ return true; }\n\n\tvirtual void\t\tCreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu) override;\n\n\n\n\t// Original (uncompressed) terrain\n\n\tvector<float>\t\tmTerrain;\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.h", "rank": 9, "score": 118266.76385489863 }, { "content": "class HeightFieldShape::DecodingContext\n\n{\n\npublic:\n\n\tJPH_INLINE explicit\t\t\tDecodingContext(const HeightFieldShape *inShape) :\n\n\t\tmShape(inShape)\n\n\t{\n\n\t\tstatic_assert(sizeof(sGridOffsets) / sizeof(uint) == cNumBitsXY + 1, \"Offsets array is not long enough\");\n\n\t\n\n\t\t// Construct root stack entry\n\n\t\tmPropertiesStack[0] = 0; // level: 0, x: 0, y: 0\n\n\t}\n\n\n\n\ttemplate <class Visitor>\n\n\tJPH_INLINE void\t\t\t\tWalkHeightField(Visitor &ioVisitor)\n\n\t{\n\n\t\t// Early out if there's no collision\n\n\t\tif (mShape->mHeightSamples.empty())\n\n\t\t\treturn;\n\n\n\n\t\t// Precalculate values relating to sample count\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 10, "score": 118266.76385489863 }, { "content": "/// Class that constructs a StaticCompoundShape. Note that if you only want a compound of 1 shape, use a RotatedTranslatedShape instead.\n\nclass StaticCompoundShapeSettings final : public CompoundShapeSettings\n\n{\n\npublic:\n\n\tJPH_DECLARE_SERIALIZABLE_VIRTUAL(StaticCompoundShapeSettings)\n\n\n\n\t// See: ShapeSettings\n\n\tvirtual ShapeResult\t\t\t\tCreate() const override;\n\n\n\n\t/// Specialization of Create() function that allows specifying a temp allocator to avoid temporary memory allocations on the heap\n\n\tShapeResult\t\t\t\t\t\tCreate(TempAllocator &inTempAllocator) const;\n\n};\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 11, "score": 117762.51919873337 }, { "content": "struct HeightFieldShape::HSGetTrianglesContext\n\n{\n\n\t\t\tHSGetTrianglesContext(const HeightFieldShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) : \n\n\t\tmDecodeCtx(inShape),\n\n\t\tmShape(inShape),\n\n\t\tmLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),\n\n\t\tmHeightFieldScale(inScale),\n\n\t\tmLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),\n\n\t\tmIsInsideOut(ScaleHelpers::IsInsideOut(inScale))\n\n\t{\n\n\t}\n\n\n\n\tbool\tShouldAbort() const\n\n\t{\n\n\t\treturn mShouldAbort;\n\n\t}\n\n\n\n\tbool\tShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const\n\n\t{\n\n\t\treturn true;\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 12, "score": 114656.86230015199 }, { "content": "// Tests a lot of random rays against convex shapes\n\nclass RandomRayTest : public Test\n\n{\n\npublic:\n\n\tJPH_DECLARE_RTTI_VIRTUAL(RandomRayTest)\n\n\n\n\t// Update the test, called before the physics update\n\n\tvirtual void\tPrePhysicsUpdate(const PreUpdateParams &inParams) override;\n\n\n\nprivate:\n\n\ttemplate <typename A, typename Context>\n\n\tvoid\t\t\tTestRay(const char *inTestName, Vec3Arg inRenderOffset, const A &inA, const Context &inContext, float (*inCompareFunc)(const Context &inContext, Vec3Arg inRayOrigin, Vec3Arg inRayDirection));\n\n};", "file_path": "Samples/Tests/ConvexCollision/RandomRayTest.h", "rank": 13, "score": 114411.08751886727 }, { "content": "/// Base class for all shapes (collision volume of a body). Defines a virtual interface for collision detection.\n\nclass Shape : public RefTarget<Shape>\n\n{\n\npublic:\n\n\tusing ShapeResult = ShapeSettings::ShapeResult;\n\n\n\n\t/// Constructor\n\n\t\t\t\t\t\t\t\t\tShape(EShapeType inType, EShapeSubType inSubType) : mShapeType(inType), mShapeSubType(inSubType) { }\n\n\t\t\t\t\t\t\t\t\tShape(EShapeType inType, EShapeSubType inSubType, const ShapeSettings &inSettings, [[maybe_unused]] ShapeResult &outResult) : mUserData(inSettings.mUserData), mShapeType(inType), mShapeSubType(inSubType) { }\n\n\n\n\t/// Destructor\n\n\tvirtual\t\t\t\t\t\t\t~Shape() = default;\n\n\n\n\t/// Get type\n\n\tinline EShapeType\t\t\t\tGetType() const\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ return mShapeType; }\n\n\tinline EShapeSubType\t\t\tGetSubType() const\t\t\t\t\t\t\t\t\t\t\t\t\t{ return mShapeSubType; }\n\n\n\n\t/// User data (to be used freely by the application)\n\n\tuint64\t\t\t\t\t\t\tGetUserData() const\t\t\t\t\t\t\t\t\t\t\t\t\t{ return mUserData; }\n\n\tvoid\t\t\t\t\t\t\tSetUserData(uint64 inUserData)\t\t\t\t\t\t\t\t\t\t{ mUserData = inUserData; }\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/Shape.h", "rank": 14, "score": 113410.11042640018 }, { "content": "class ScaledStaticCompoundShapeTest : public Test\n\n{\n\npublic:\n\n\tJPH_DECLARE_RTTI_VIRTUAL(ScaledStaticCompoundShapeTest)\n\n\n\n\t// See: Test\n\n\tvirtual void\tInitialize() override;\n\n};", "file_path": "Samples/Tests/ScaledShapes/ScaledStaticCompoundShapeTest.h", "rank": 15, "score": 113015.5879773088 }, { "content": "class ScaledHeightFieldShapeTest : public Test\n\n{\n\npublic:\n\n\tJPH_DECLARE_RTTI_VIRTUAL(ScaledHeightFieldShapeTest)\n\n\n\n\t// See: Test\n\n\tvirtual void\tInitialize() override;\n\n};", "file_path": "Samples/Tests/ScaledShapes/ScaledHeightFieldShapeTest.h", "rank": 16, "score": 112934.77451971255 }, { "content": "class ConvexShape;\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 17, "score": 112288.8555352129 }, { "content": "class Shape;\n", "file_path": "Jolt/Physics/Collision/Shape/Shape.h", "rank": 18, "score": 111918.09116121448 }, { "content": "\t\tINVALID_NODE\t\t\t\t= 0x7fffffff,\t\t\t\t\t\t\t\t\t\t\t///< Signifies an invalid node\n\n\t};\n\n\n\n\t/// Node structure\n\n\tstruct Node\n\n\t{\n\n\t\tvoid\t\t\t\t\t\tSetChildBounds(uint inIndex, const AABox &inBounds);\t///< Set bounding box for child inIndex to inBounds\n\n\t\tvoid\t\t\t\t\t\tSetChildInvalid(uint inIndex);\t\t\t\t\t\t\t///< Mark the child inIndex as invalid and set its bounding box to invalid\n\n\n\n\t\tHalfFloat\t\t\t\t\tmBoundsMinX[4];\t\t\t\t\t\t\t\t\t\t\t///< 4 child bounding boxes\n\n\t\tHalfFloat\t\t\t\t\tmBoundsMinY[4];\n\n\t\tHalfFloat\t\t\t\t\tmBoundsMinZ[4];\n\n\t\tHalfFloat\t\t\t\t\tmBoundsMaxX[4];\n\n\t\tHalfFloat\t\t\t\t\tmBoundsMaxY[4];\n\n\t\tHalfFloat\t\t\t\t\tmBoundsMaxZ[4];\n\n\t\tuint32\t\t\t\t\t\tmNodeProperties[4];\t\t\t\t\t\t\t\t\t\t///< 4 child node properties\n\n\t};\n\n\t\n\n\tstatic_assert(sizeof(Node) == 64, \"Node should be 64 bytes\");\n\n\n\n\tusing Nodes = vector<Node>;\n\n\n\n\tNodes\t\t\t\t\t\t\tmNodes;\t\t\t\t\t\t\t\t\t\t\t\t\t///< Quad tree node structure\n\n};\n\n\n\n} // JPH", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 19, "score": 111178.70432124006 }, { "content": "\t/// Sorts ioBodyIdx from inBegin to (but excluding) inEnd spatially into 4 groups. \n\n\t/// outSplit needs to be 5 ints long, when the function returns each group runs from outSplit[i] to (but excluding) outSplit[i + 1]\n\n\t/// After the function returns ioBodyIdx and ioBounds will be shuffled\n\n\tstatic void\t\t\t\t\t\tsPartition4(uint *ioBodyIdx, AABox *ioBounds, int inBegin, int inEnd, int *outSplit);\n\n\n\n\t// Helper functions called by CollisionDispatch\n\n\tstatic void\t\t\t\t\t\tsCollideCompoundVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector);\n\n\tstatic void\t\t\t\t\t\tsCollideShapeVsCompound(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector);\n\n\tstatic void\t\t\t\t\t\tsCastShapeVsCompound(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);\n\n\n\n\t// Maximum size of the stack during tree walk\n\n\tstatic constexpr int\t\t\tcStackSize = 128;\n\n\n\n\ttemplate <class Visitor>\n\n\tJPH_INLINE void\t\t\t\t\tWalkTree(Visitor &ioVisitor) const;\t\t\t\t\t\t///< Walk the node tree calling the Visitor::VisitNodes for each node encountered and Visitor::VisitShape for each sub shape encountered\n\n\n\n\t/// Bits used in Node::mNodeProperties\n\n\tenum : uint32\n\n\t{\n\n\t\tIS_SUBSHAPE\t\t\t\t\t= 0x80000000,\t\t\t\t\t\t\t\t\t\t\t///< If this bit is set, the other bits index in mSubShape, otherwise in mNodes\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 20, "score": 111178.16836016592 }, { "content": "\t// See: CompoundShape::GetIntersectingSubShapes\n\n\tvirtual int\t\t\t\t\t\tGetIntersectingSubShapes(const OrientedBox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const override;\n\n\n\n\t// See Shape\n\n\tvirtual void\t\t\t\t\tSaveBinaryState(StreamOut &inStream) const override;\n\n\n\n\t// See Shape::GetStats\n\n\tvirtual Stats\t\t\t\t\tGetStats() const override\t\t\t\t\t\t\t\t{ return Stats(sizeof(*this) + mSubShapes.size() * sizeof(SubShape) + mNodes.size() * sizeof(Node), 0); }\n\n\n\n\t// Register shape functions with the registry\n\n\tstatic void\t\t\t\t\t\tsRegister();\n\n\n\nprotected:\n\n\t// See: Shape::RestoreBinaryState\n\n\tvirtual void\t\t\t\t\tRestoreBinaryState(StreamIn &inStream) override;\n\n\n\nprivate:\n\n\t// Visitor for GetIntersectingSubShapes\n\n\ttemplate <class BoxType>\n\n\tstruct GetIntersectingSubShapesVisitorSC : public GetIntersectingSubShapesVisitor<BoxType>\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 21, "score": 111173.51102115902 }, { "content": "\t{\n\n\t\tusing GetIntersectingSubShapesVisitor<BoxType>::GetIntersectingSubShapesVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\t\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn true;\n\n\t\t}\n\n\n\n\t\tJPH_INLINE int\t\t\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test if point overlaps with box\n\n\t\t\tUVec4 collides = GetIntersectingSubShapesVisitor<BoxType>::TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\t\treturn CountAndSortTrues(collides, ioProperties);\n\n\t\t}\n\n\t};\n\n\n\n\t/// Sorts ioBodyIdx spatially into 2 groups. Second groups starts at ioBodyIdx + outMidPoint.\n\n\t/// After the function returns ioBodyIdx and ioBounds will be shuffled\n\n\tstatic void\t\t\t\t\t\tsPartition(uint *ioBodyIdx, AABox *ioBounds, int inNumber, int &outMidPoint);\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 22, "score": 111172.82280417481 }, { "content": "// SPDX-FileCopyrightText: 2021 Jorrit Rouwe\n\n// SPDX-License-Identifier: MIT\n\n\n\n#pragma once\n\n\n\n#include <Physics/Collision/Shape/CompoundShape.h>\n\n#include <Physics/Collision/SortReverseAndStore.h>\n\n#include <Math/HalfFloat.h>\n\n\n\nnamespace JPH {\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 23, "score": 111171.74471369457 }, { "content": "// SPDX-FileCopyrightText: 2021 Jorrit Rouwe\n\n// SPDX-License-Identifier: MIT\n\n\n\n#pragma once\n\n\n\n#include <Tests/Test.h>\n\n\n", "file_path": "Samples/Tests/Shapes/StaticCompoundShapeTest.h", "rank": 24, "score": 111159.11117166236 }, { "content": "\tvirtual bool\t\t\t\t\tCastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;\n\n\tvirtual void\t\t\t\t\tCastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const override;\n\n\n\n\t// See: Shape::CollidePoint\n\n\tvirtual void\t\t\t\t\tCollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const override;\n\n\n\n\t// See Shape::GetTrianglesStart\n\n\tvirtual void\t\t\t\t\tGetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;\n\n\n\n\t// See Shape::GetTrianglesNext\n\n\tvirtual int\t\t\t\t\t\tGetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;\n\n\n\n\t/// Get height field position at sampled location (inX, inY).\n\n\t/// where inX and inY are integers in the range inX e [0, mSampleCount - 1] and inY e [0, mSampleCount - 1].\n\n\tVec3\t\t\t\t\t\t\tGetPosition(uint inX, uint inY) const;\n\n\n\n\t/// Check if height field at sampled location (inX, inY) has collision (has a hole or not)\n\n\tbool\t\t\t\t\t\t\tIsNoCollision(uint inX, uint inY) const;\n\n\n\n\t/// Projects inLocalPosition (a point in the space of the shape) along the Y axis onto the surface and returns it in outSurfacePosition.\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 25, "score": 111119.47679227329 }, { "content": "\n\n\t/// For block (inBlockX, inBlockY) get the offset and scale needed to decode a uint8 height sample to a uint16\n\n\tinline void\t\t\t\t\t\tGetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const;\n\n\n\n\t/// Get the height sample at position (inX, inY)\n\n\tinline uint8\t\t\t\t\tGetHeightSample(uint inX, uint inY) const;\n\n\n\n\t/// Faster version of GetPosition when block offset and scale are already known\n\n\tinline Vec3\t\t\t\t\t\tGetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const;\n\n\t\t\n\n\t/// Determine amount of bits needed to encode sub shape id\n\n\tuint\t\t\t\t\t\t\tGetSubShapeIDBits() const;\n\n\n\n\t/// En/decode a sub shape ID. inX and inY specify the coordinate of the triangle. inTriangle == 0 is the lower triangle, inTriangle == 1 is the upper triangle.\n\n\tinline SubShapeID\t\t\t\tEncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const;\n\n\tinline void\t\t\t\t\t\tDecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const;\n\n\n\n\t/// Get the edge flags for a triangle\n\n\tinline uint8\t\t\t\t\tGetEdgeFlags(uint inX, uint inY, uint inTriangle) const;\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 26, "score": 111116.3906726541 }, { "content": "\tPhysicsMaterialList mMaterials;\n\n\tvector<uint8>\t\tmMaterialIndices;\n\n\tuint\t\t\t\tmTerrainSize;\n\n\tVec3\t\t\t\tmTerrainOffset;\n\n\tVec3\t\t\t\tmTerrainScale;\n\n\n\n\t// Block size = 1 << sBlockSizeShift\n\n\tinline static int\tsBlockSizeShift = 2;\n\n\n\n\t// Bits per sample\n\n\tinline static int\tsBitsPerSample = 8;\n\n\n\n\t// Draw the terrain\n\n\tinline static bool\tsShowOriginalTerrain = false;\n\n\n\n\tRefConst<HeightFieldShape> mHeightField;\n\n\n\n\tVec3\t\t\t\tmHitPos = Vec3::sZero();\n\n};", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.h", "rank": 27, "score": 111114.2980293988 }, { "content": "\tvirtual MassProperties\t\t\tGetMassProperties() const override;\n\n\t\n\n\t// See Shape::GetMaterial\n\n\tvirtual const PhysicsMaterial *\tGetMaterial(const SubShapeID &inSubShapeID) const override;\n\n\n\n\t/// Overload to get the material at a particular location\n\n\tconst PhysicsMaterial *\t\t\tGetMaterial(uint inX, uint inY) const;\n\n\n\n\t// See Shape::GetSurfaceNormal\n\n\tvirtual Vec3\t\t\t\t\tGetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;\n\n\n\n\t// See Shape::GetSubmergedVolume\n\n\tvirtual void\t\t\t\t\tGetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy) const override { JPH_ASSERT(false, \"Not supported\"); }\n\n\n\n#ifdef JPH_DEBUG_RENDERER\n\n\t// See Shape::Draw\n\n\tvirtual void\t\t\t\t\tDraw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;\n\n#endif // JPH_DEBUG_RENDERER\n\n\n\n\t// See Shape::CastRay\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 28, "score": 111110.56537759176 }, { "content": "\t// Helper functions called by CollisionDispatch\n\n\tstatic void\t\t\t\t\t\tsCollideConvexVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector);\n\n\tstatic void\t\t\t\t\t\tsCollideSphereVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector);\n\n\tstatic void\t\t\t\t\t\tsCastConvexVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);\n\n\tstatic void\t\t\t\t\t\tsCastSphereVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);\n\n\n\n\t/// Visit the entire height field using a visitor pattern\n\n\ttemplate <class Visitor>\n\n\tJPH_INLINE void\t\t\t\t\tWalkHeightField(Visitor &ioVisitor) const;\n\n\n\n\t/// A block of 2x2 ranges used to form a hierarchical grid, ordered left top, right top, left bottom, right bottom\n\n\tstruct alignas(16) RangeBlock\n\n\t{\n\n\t\tuint16\t\t\t\t\t\tmMin[4];\n\n\t\tuint16\t\t\t\t\t\tmMax[4];\n\n\t};\n\n\n\n\t/// Offset of first RangedBlock in grid per level\n\n\tstatic const uint\t\t\t\tsGridOffsets[];\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 29, "score": 111108.63441200678 }, { "content": "\t/// When there is no surface position (because of a hole or because the point is outside the heightfield) the function will return false.\n\n\tbool\t\t\t\t\t\t\tProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const;\n\n\n\n\t// See Shape\n\n\tvirtual void\t\t\t\t\tSaveBinaryState(StreamOut &inStream) const override;\n\n\tvirtual void\t\t\t\t\tSaveMaterialState(PhysicsMaterialList &outMaterials) const override;\n\n\tvirtual void\t\t\t\t\tRestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials) override;\n\n\n\n\t// See Shape::GetStats\n\n\tvirtual Stats\t\t\t\t\tGetStats() const override;\n\n\n\n\t// See Shape::GetVolume\n\n\tvirtual float\t\t\t\t\tGetVolume() const override\t\t\t\t\t\t\t\t\t\t\t{ return 0; }\n\n\n\n#ifdef JPH_DEBUG_RENDERER\n\n\t// Settings\n\n\tstatic bool\t\t\t\t\t\tsDrawTriangleOutlines;\n\n#endif // JPH_DEBUG_RENDERER\n\n\n\n\t// Register shape functions with the registry\n\n\tstatic void\t\t\t\t\t\tsRegister();\n\n\n\nprotected:\n\n\t// See: Shape::RestoreBinaryState\n\n\tvirtual void\t\t\t\t\tRestoreBinaryState(StreamIn &inStream) override;\n\n\n\nprivate:\t\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 30, "score": 111107.22149466866 }, { "content": "\t/// @param outMinValue The minimal value fo mHeightSamples or FLT_MAX if no samples have collision\n\n\t/// @param outMaxValue The maximal value fo mHeightSamples or -FLT_MAX if no samples have collision\n\n\t/// @param outQuantizationScale (value - outMinValue) * outQuantizationScale quantizes a height sample to 16 bits\n\n\tvoid\t\t\t\t\t\t\tDetermineMinAndMaxSample(float &outMinValue, float &outMaxValue, float &outQuantizationScale) const;\n\n\n\n\t/// Given mBlockSize, mSampleCount and mHeightSamples, calculate the amount of bits needed to stay below absolute error inMaxError\n\n\t/// @param inMaxError Maximum allowed error in mHeightSamples after compression (note that this does not take mScale.Y into account)\n\n\t/// @return Needed bits per sample in the range [1, 8].\n\n\tuint32\t\t\t\t\t\t\tCalculateBitsPerSampleForError(float inMaxError) const;\n\n\n\n\t/// The height field is a surface defined by: mOffset + mScale * (x, mHeightSamples[y * mSampleCount + x], y).\n\n\t/// where x and y are integers in the range x and y e [0, mSampleCount - 1].\n\n\tVec3\t\t\t\t\t\t\tmOffset = Vec3::sZero();\n\n\tVec3\t\t\t\t\t\t\tmScale = Vec3::sReplicate(1.0f);\n\n\tuint32\t\t\t\t\t\t\tmSampleCount = 0;\n\n\n\n\t/// The heightfield is divided in blocks of mBlockSize * mBlockSize * 2 triangles and the acceleration structure culls blocks only, \n\n\t/// bigger block sizes reduce memory consumption but also reduce query performance. Sensible values are [2, 8], does not need to be\n\n\t/// a power of 2. Note that at run-time we'll perform one more grid subdivision, so the effective block size is half of what is provided here.\n\n\tuint32\t\t\t\t\t\t\tmBlockSize = 2;\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 31, "score": 111098.10744080409 }, { "content": "// SPDX-FileCopyrightText: 2021 Jorrit Rouwe\n\n// SPDX-License-Identifier: MIT\n\n\n\n#pragma once\n\n\n\n#include <Tests/Test.h>\n\n#include <Physics/Collision/Shape/HeightFieldShape.h>\n\n\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.h", "rank": 32, "score": 111096.89901669824 }, { "content": "\t/// The height field is a surface defined by: mOffset + mScale * (x, mHeightSamples[y * mSampleCount + x], y).\n\n\t/// where x and y are integers in the range x and y e [0, mSampleCount - 1].\n\n\tVec3\t\t\t\t\t\t\tmOffset = Vec3::sZero();\n\n\tVec3\t\t\t\t\t\t\tmScale = Vec3::sReplicate(1.0f);\n\n\n\n\t/// Height data\n\n\tuint32\t\t\t\t\t\t\tmSampleCount = 0;\t\t\t\t\t///< See HeightFieldShapeSettings::mSampleCount\n\n\tuint32\t\t\t\t\t\t\tmBlockSize = 2;\t\t\t\t\t\t///< See HeightFieldShapeSettings::mBlockSize\n\n\tuint8\t\t\t\t\t\t\tmBitsPerSample = 8;\t\t\t\t\t///< See HeightFieldShapeSettings::mBitsPerSample\n\n\tuint8\t\t\t\t\t\t\tmSampleMask = 0xff;\t\t\t\t\t///< All bits set for a sample: (1 << mBitsPerSample) - 1, used to indicate that there's no collision\n\n\tuint16\t\t\t\t\t\t\tmMinSample = HeightFieldShapeConstants::cNoCollisionValue16;\t///< Min and max value in mHeightSamples quantized to 16 bit, for calculating bounding box\n\n\tuint16\t\t\t\t\t\t\tmMaxSample = HeightFieldShapeConstants::cNoCollisionValue16;\n\n\tvector<RangeBlock>\t\t\t\tmRangeBlocks;\t\t\t\t\t\t///< Hierarchical grid of range data describing the height variations within 1 block. The grid for level <level> starts at offset sGridOffsets[<level>]\n\n\tvector<uint8>\t\t\t\t\tmHeightSamples;\t\t\t\t\t\t///< mBitsPerSample-bit height samples. Value [0, mMaxHeightValue] maps to highest detail grid in mRangeBlocks [mMin, mMax]. mNoCollisionValue is reserved to indicate no collision.\n\n\tvector<uint8>\t\t\t\t\tmActiveEdges;\t\t\t\t\t\t///< (mSampleCount - 1)^2 * 3-bit active edge flags. \n\n\n\n\t/// Materials\n\n\tPhysicsMaterialList\t\t\t\tmMaterials;\t\t\t\t\t\t\t///< The materials of square at (x, y) is: mMaterials[mMaterialIndices[x + y * (mSampleCount - 1)]]\n\n\tvector<uint8>\t\t\t\t\tmMaterialIndices;\t\t\t\t\t///< Compressed to the minimum amount of bits per material index (mSampleCount - 1) * (mSampleCount - 1) * mNumBitsPerMaterialIndex bits of data\n\n\tuint32\t\t\t\t\t\t\tmNumBitsPerMaterialIndex = 0;\t\t///< Number of bits per material index\n\n\n\n#ifdef JPH_DEBUG_RENDERER\n\n\t/// Temporary rendering data\n\n\tmutable vector<DebugRenderer::GeometryRef>\tmGeometry;\n\n\tmutable bool\t\t\t\t\tmCachedUseMaterialColors = false;\t///< This is used to regenerate the triangle batch if the drawing settings change\n\n#endif // JPH_DEBUG_RENDERER\n\n};\n\n\n\n} // JPH", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 33, "score": 111095.09913134854 }, { "content": "// SPDX-FileCopyrightText: 2021 Jorrit Rouwe\n\n// SPDX-License-Identifier: MIT\n\n\n\n#pragma once\n\n\n\n#include <Physics/Collision/Shape/Shape.h>\n\n#include <Physics/Collision/PhysicsMaterial.h>\n\n#ifdef JPH_DEBUG_RENDERER\n\n\t#include <Renderer/DebugRenderer.h>\n\n#endif // JPH_DEBUG_RENDERER\n\n\n\nnamespace JPH {\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 34, "score": 111091.22170916334 }, { "content": "\n\n\t/// How many bits per sample to use to compress the height field. Can be in the range [1, 8].\n\n\t/// Note that each sample is compressed relative to the min/max value of its block of mBlockSize * mBlockSize pixels so the effective precision is higher.\n\n\t/// Also note that increasing mBlockSize saves more memory than reducing the amount of bits per sample.\n\n\tuint32\t\t\t\t\t\t\tmBitsPerSample = 8;\n\n\n\n\tvector<float>\t\t\t\t\tmHeightSamples;\n\n\tvector<uint8>\t\t\t\t\tmMaterialIndices;\n\n\n\n\t/// The materials of square at (x, y) is: mMaterials[mMaterialIndices[x + y * (mSampleCount - 1)]]\n\n\tPhysicsMaterialList\t\t\t\tmMaterials;\n\n};\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 35, "score": 111088.05795907565 }, { "content": "class CollideShapeSettings;\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.h", "rank": 36, "score": 110067.31164693854 }, { "content": "class CollideShapeSettings;\n\n\n\n/// Constants for HeightFieldShape, this was moved out of the HeightFieldShape because of a linker bug\n\nnamespace HeightFieldShapeConstants\n\n{\n\n\t/// Value used to create gaps in the height field\n\n\tconstexpr float\t\t\tcNoCollisionValue = FLT_MAX;\n\n\n\n\t/// Stack size to use during WalkHeightField\n\n\tconstexpr int\t\t\tcStackSize = 128;\n\n\n\n\t/// A position in the hierarchical grid is defined by a level (which grid), x and y position. We encode this in a single uint32 as: level << 28 | y << 14 | x\n\n\tconstexpr uint\t\t\tcNumBitsXY = 14;\n\n\tconstexpr uint\t\t\tcMaskBitsXY = (1 << cNumBitsXY) - 1;\n\n\tconstexpr uint\t\t\tcLevelShift = 2 * cNumBitsXY;\n\n\n\n\t/// When height samples are converted to 16 bit:\n\n\tconstexpr uint16\t\tcNoCollisionValue16 = 0xffff;\t\t///< This is the magic value for 'no collision'\n\n\tconstexpr uint16\t\tcMaxHeightValue16 = 0xfffe;\t\t\t///< This is the maximum allowed height value\n\n};\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.h", "rank": 37, "score": 109998.71897121661 }, { "content": "\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test bounds of 4 children\n\n\t\t\tVec4 distance = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\n\n\t\t\t// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)\n\n\t\t\treturn SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);\n\n\t\t}\n\n\n\n\t\tfloat\t\t\t\tmDistanceStack[cStackSize];\n\n\t};\n\n\n\n\tVisitor visitor(inRay, this, inSubShapeIDCreator, ioHit);\n\n\tWalkTree(visitor);\n\n\treturn visitor.mReturnValue;\n\n}\n\n\n\nvoid StaticCompoundShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 38, "score": 108428.69570280617 }, { "content": "void StaticCompoundShapeTest::Initialize() \n\n{\n\n\t// Floor\n\n\tCreateFloor();\n\n\t\t\n\n\t// Simple compound\n\n\tRef<StaticCompoundShapeSettings> compound_shape1 = new StaticCompoundShapeSettings;\n\n\tcompound_shape1->AddShape(Vec3::sZero(), Quat::sIdentity(), new CapsuleShape(5, 1));\n\n\tcompound_shape1->AddShape(Vec3(0, -5, 0), Quat::sIdentity(), new SphereShape(2));\n\n\tcompound_shape1->AddShape(Vec3(0, 5, 0), Quat::sIdentity(), new SphereShape(2));\n\n\n\n\t// Compound with sub compound and rotation\n\n\tRef<StaticCompoundShapeSettings> sub_compound = new StaticCompoundShapeSettings;\n\n\tsub_compound->AddShape(Vec3(0, 1.5f, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), new BoxShape(Vec3(1.5f, 0.25f, 0.2f)));\n\n\tsub_compound->AddShape(Vec3(1.5f, 0, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), new CylinderShape(1.5f, 0.2f));\n\n\tsub_compound->AddShape(Vec3(0, 0, 1.5f), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), new TaperedCapsuleShapeSettings(1.5f, 0.25f, 0.2f));\n\n\n\n\tRef<StaticCompoundShapeSettings> compound_shape2 = new StaticCompoundShapeSettings;\n\n\tcompound_shape2->AddShape(Vec3(0, 0, 0), Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), 0.25f * JPH_PI), sub_compound);\n\n\tcompound_shape2->AddShape(Vec3(0, -0.1f, 0), Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), -0.75f * JPH_PI), sub_compound);\n", "file_path": "Samples/Tests/Shapes/StaticCompoundShapeTest.cpp", "rank": 39, "score": 108425.37867068152 }, { "content": "\t};\n\n\n\n\tVisitor visitor(inRay, inRayCastSettings, this, inSubShapeIDCreator, ioCollector);\n\n\tWalkTree(visitor);\n\n}\n\n\n\nvoid StaticCompoundShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor : public CollidePointVisitor\n\n\t{\n\n\t\tusing CollidePointVisitor::CollidePointVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn true;\n\n\t\t}\n\n\n\n\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 40, "score": 108422.97853669533 }, { "content": "\n\n\t// Compound with large amount of sub shapes\n\n\tRef<StaticCompoundShapeSettings> compound_shape3 = new StaticCompoundShapeSettings;\n\n\tfor (int y = -2; y <= 2; ++y)\n\n\t\tfor (int x = -2; x <= 2; ++x)\n\n\t\t\tfor (int z = -2; z <= 2; ++z)\n\n\t\t\t\tcompound_shape3->AddShape(Vec3(0.5f * x, 0.5f * y, 0.5f * z), Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), 0.25f * JPH_PI), new BoxShape(Vec3::sReplicate(0.5f)));\n\n\n\n\tRef<StaticCompoundShapeSettings> shapes[] = { compound_shape1, compound_shape2, compound_shape3 };\n\n\n\n\tfor (int i = 0; i < 10; ++i)\n\n\t\tfor (int j = 0; j < 3; ++j)\n\n\t\t{\n\n\t\t\tQuat rotation;\n\n\t\t\tif ((i & 1) == 0)\n\n\t\t\t\trotation = Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI);\n\n\t\t\telse\n\n\t\t\t\trotation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);\n\n\t\t\tBody &body = *mBodyInterface->CreateBody(BodyCreationSettings(shapes[j], Vec3(0, 10.0f + 4.0f * i, j * 20.0f), rotation, EMotionType::Dynamic, Layers::MOVING));\n\n\t\t\tmBodyInterface->AddBody(body.GetID(), EActivation::Activate);\n\n\t\t}\n\n}", "file_path": "Samples/Tests/Shapes/StaticCompoundShapeTest.cpp", "rank": 41, "score": 108421.22275961464 }, { "content": "\n\n\t// Make bounding box invalid\n\n\tmBoundsMinX[inIndex] = HALF_FLT_MAX;\n\n\tmBoundsMinY[inIndex] = HALF_FLT_MAX;\n\n\tmBoundsMinZ[inIndex] = HALF_FLT_MAX;\n\n\tmBoundsMaxX[inIndex] = HALF_FLT_MAX;\n\n\tmBoundsMaxY[inIndex] = HALF_FLT_MAX;\n\n\tmBoundsMaxZ[inIndex] = HALF_FLT_MAX;\n\n}\n\n\n\nvoid StaticCompoundShape::Node::SetChildBounds(uint inIndex, const AABox &inBounds)\n\n{\n\n\tmBoundsMinX[inIndex] = HalfFloatConversion::FromFloat<HalfFloatConversion::ROUND_TO_NEG_INF>(inBounds.mMin.GetX());\n\n\tmBoundsMinY[inIndex] = HalfFloatConversion::FromFloat<HalfFloatConversion::ROUND_TO_NEG_INF>(inBounds.mMin.GetY());\n\n\tmBoundsMinZ[inIndex] = HalfFloatConversion::FromFloat<HalfFloatConversion::ROUND_TO_NEG_INF>(inBounds.mMin.GetZ());\n\n\tmBoundsMaxX[inIndex] = HalfFloatConversion::FromFloat<HalfFloatConversion::ROUND_TO_POS_INF>(inBounds.mMax.GetX());\n\n\tmBoundsMaxY[inIndex] = HalfFloatConversion::FromFloat<HalfFloatConversion::ROUND_TO_POS_INF>(inBounds.mMax.GetY());\n\n\tmBoundsMaxZ[inIndex] = HalfFloatConversion::FromFloat<HalfFloatConversion::ROUND_TO_POS_INF>(inBounds.mMax.GetZ());\n\n}\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 42, "score": 108421.0398308562 }, { "content": "\n\nStaticCompoundShape::StaticCompoundShape(const StaticCompoundShapeSettings &inSettings, TempAllocator &inTempAllocator, ShapeResult &outResult) :\n\n\tCompoundShape(EShapeSubType::StaticCompound, inSettings, outResult)\n\n{\n\n\t// Check that there's at least 1 shape\n\n\tuint num_subshapes = (uint)inSettings.mSubShapes.size();\n\n\tif (num_subshapes < 2)\n\n\t{\n\n\t\toutResult.SetError(\"Compound needs at least 2 sub shapes, otherwise you should use a RotatedTranslatedShape!\");\n\n\t\treturn;\n\n\t}\n\n\n\n\t// Keep track of total mass to calculate center of mass\n\n\tfloat mass = 0.0f;\n\n\n\n\tmSubShapes.resize(num_subshapes);\n\n\tfor (uint i = 0; i < num_subshapes; ++i)\n\n\t{\n\n\t\tconst CompoundShapeSettings::SubShapeSettings &shape = inSettings.mSubShapes[i];\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 43, "score": 108420.84090981471 }, { "content": "\t\t{\n\n\t\t\treturn mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();\n\n\t\t}\n\n\n\n\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test bounds of 4 children\n\n\t\t\tVec4 distance = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\n\n\t\t\t// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)\n\n\t\t\treturn SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);\n\n\t\t}\n\n\n\n\t\tfloat\t\t\t\tmDistanceStack[cStackSize];\n\n\t};\n\n\n\n\tJPH_ASSERT(inShape->GetSubType() == EShapeSubType::StaticCompound);\n\n\tconst StaticCompoundShape *shape = static_cast<const StaticCompoundShape *>(inShape);\n\n\n\n\tVisitor visitor(inShapeCast, inShapeCastSettings, shape, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, ioCollector);\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 44, "score": 108420.76646505923 }, { "content": "\t\tdo \n\n\t\t\t--top;\n\n\t\twhile (top >= 0 && !ioVisitor.ShouldVisitNode(top));\n\n\t}\n\n\twhile (top >= 0);\n\n}\n\n\n\nbool StaticCompoundShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor : public CastRayVisitor\n\n\t{\n\n\t\tusing CastRayVisitor::CastRayVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn mDistanceStack[inStackTop] < mHit.mFraction;\n\n\t\t}\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 45, "score": 108420.74494302599 }, { "content": "\tshape->WalkTree(visitor);\n\n}\n\n\n\nvoid StaticCompoundShape::CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor : public CollectTransformedShapesVisitor\n\n\t{\n\n\t\tusing CollectTransformedShapesVisitor::CollectTransformedShapesVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn true;\n\n\t\t}\n\n\n\n\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test which nodes collide\n\n\t\t\tUVec4 collides = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 46, "score": 108420.03245934602 }, { "content": "\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\t// Build a regular compound shape\n\n\t\t\tRef<Shape> shape = new StaticCompoundShape(*this, inTempAllocator, mCachedResult); \n\n\t\t}\n\n\t}\n\n\treturn mCachedResult;\n\n}\n\n\n\nShapeSettings::ShapeResult StaticCompoundShapeSettings::Create() const\n\n{\n\n\tTempAllocatorMalloc allocator;\n\n\treturn Create(allocator);\n\n}\n\n\n\nvoid StaticCompoundShape::Node::SetChildInvalid(uint inIndex)\n\n{\n\n\t// Make this an invalid node\n\n\tmNodeProperties[inIndex] = INVALID_NODE;\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 47, "score": 108419.8885175681 }, { "content": "void StaticCompoundShape::sPartition(uint *ioBodyIdx, AABox *ioBounds, int inNumber, int &outMidPoint)\n\n{\n\n\t// Handle trivial case\n\n\tif (inNumber <= 4)\n\n\t{\n\n\t\toutMidPoint = inNumber / 2;\n\n\t\treturn;\n\n\t}\n\n\n\n\t// Calculate bounding box of box centers\n\n\tVec3 center_min = Vec3::sReplicate(FLT_MAX);\n\n\tVec3 center_max = Vec3::sReplicate(-FLT_MAX);\n\n\tfor (AABox *b = ioBounds, *b_end = ioBounds + inNumber; b < b_end; ++b)\n\n\t{\n\n\t\tVec3 center = b->GetCenter();\n\n\t\tcenter_min = Vec3::sMin(center_min, center);\n\n\t\tcenter_max = Vec3::sMax(center_max, center);\n\n\t}\n\n\n\n\t// Calculate split plane\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 48, "score": 108419.63428147406 }, { "content": "\t\t}\n\n\n\n\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test which nodes collide\n\n\t\t\tUVec4 collides = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\t\treturn CountAndSortTrues(collides, ioProperties);\n\n\t\t}\n\n\t};\n\n\n\n\tVisitor visitor(shape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, ioCollector);\n\n\tshape1->WalkTree(visitor);\n\n}\n\n\n\nvoid StaticCompoundShape::sCollideShapeVsCompound(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor : public CollideShapeVsCompoundVisitor\n\n\t{\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 49, "score": 108418.77231983165 }, { "content": "\t\t{\n\n\t\t\t// Test if point overlaps with box\n\n\t\t\tUVec4 collides = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\t\treturn CountAndSortTrues(collides, ioProperties);\n\n\t\t}\n\n\t};\n\n\n\n\tVisitor visitor(inPoint, this, inSubShapeIDCreator, ioCollector);\n\n\tWalkTree(visitor);\n\n}\n\n\n\nvoid StaticCompoundShape::sCastShapeVsCompound(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor : public CastShapeVisitor\n\n\t{\n\n\t\tusing CastShapeVisitor::CastShapeVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 50, "score": 108418.53156109058 }, { "content": "// SPDX-FileCopyrightText: 2021 Jorrit Rouwe\n\n// SPDX-License-Identifier: MIT\n\n\n\n#include <TestFramework.h>\n\n\n\n#include <Tests/Shapes/StaticCompoundShapeTest.h>\n\n#include <Physics/Collision/Shape/StaticCompoundShape.h>\n\n#include <Physics/Collision/Shape/SphereShape.h>\n\n#include <Physics/Collision/Shape/BoxShape.h>\n\n#include <Physics/Collision/Shape/CapsuleShape.h>\n\n#include <Physics/Collision/Shape/TaperedCapsuleShape.h>\n\n#include <Physics/Collision/Shape/CylinderShape.h>\n\n#include <Physics/Body/BodyCreationSettings.h>\n\n#include <Layers.h>\n\n\n\nJPH_IMPLEMENT_RTTI_VIRTUAL(StaticCompoundShapeTest) \n\n{ \n\n\tJPH_ADD_BASE_CLASS(StaticCompoundShapeTest, Test) \n\n}\n\n\n", "file_path": "Samples/Tests/Shapes/StaticCompoundShapeTest.cpp", "rank": 51, "score": 108418.52677373457 }, { "content": "\n\n\tGetIntersectingSubShapesVisitorSC<OrientedBox> visitor(inBox, outSubShapeIndices, inMaxSubShapeIndices);\n\n\tWalkTree(visitor);\n\n\treturn visitor.GetNumResults();\n\n}\n\n\n\nvoid StaticCompoundShape::sCollideCompoundVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)\n\n{\t\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tJPH_ASSERT(inShape1->GetSubType() == EShapeSubType::StaticCompound);\n\n\tconst StaticCompoundShape *shape1 = static_cast<const StaticCompoundShape *>(inShape1);\n\n\n\n\tstruct Visitor : public CollideCompoundVsShapeVisitor\n\n\t{\n\n\t\tusing CollideCompoundVsShapeVisitor::CollideCompoundVsShapeVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn true;\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 52, "score": 108418.07552255676 }, { "content": "// SPDX-FileCopyrightText: 2021 Jorrit Rouwe\n\n// SPDX-License-Identifier: MIT\n\n\n\n#include <Jolt.h>\n\n\n\n#include <Physics/Collision/Shape/StaticCompoundShape.h>\n\n#include <Physics/Collision/Shape/RotatedTranslatedShape.h>\n\n#include <Physics/Collision/Shape/CompoundShapeVisitors.h>\n\n#include <Core/Profiler.h>\n\n#include <Core/StreamIn.h>\n\n#include <Core/StreamOut.h>\n\n#include <Core/TempAllocator.h>\n\n#include <ObjectStream/TypeDeclarations.h>\n\n\n\nnamespace JPH {\n\n\n\nJPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(StaticCompoundShapeSettings)\n\n{\n\n\tJPH_ADD_BASE_CLASS(StaticCompoundShapeSettings, CompoundShapeSettings)\n\n}\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 53, "score": 108417.91966160572 }, { "content": "}\n\n\n\nvoid StaticCompoundShape::SaveBinaryState(StreamOut &inStream) const\n\n{\n\n\tCompoundShape::SaveBinaryState(inStream);\n\n\n\n\tinStream.Write(mNodes);\n\n}\n\n\n\nvoid StaticCompoundShape::RestoreBinaryState(StreamIn &inStream)\n\n{\n\n\tCompoundShape::RestoreBinaryState(inStream);\n\n\n\n\tinStream.Read(mNodes);\n\n}\n\n\n\nvoid StaticCompoundShape::sRegister()\n\n{\n\n\tShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::StaticCompound);\n\n\tf.mConstruct = []() -> Shape * { return new StaticCompoundShape; };\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 54, "score": 108417.77671222363 }, { "content": "\t\t\t++start;\n\n\t\t\t--end;\n\n\t\t}\n\n\t}\n\n\tJPH_ASSERT(start == end);\n\n\n\n\tif (start > 0 && start < inNumber)\n\n\t{\n\n\t\t// Success!\n\n\t\toutMidPoint = start;\n\n\t}\n\n\telse\n\n\t{\n\n\t\t// Failed to divide bodies\n\n\t\toutMidPoint = inNumber / 2; \n\n\t}\n\n}\n\n\n\nvoid StaticCompoundShape::sPartition4(uint *ioBodyIdx, AABox *ioBounds, int inBegin, int inEnd, int *outSplit)\n\n{\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 55, "score": 108416.48948187707 }, { "content": "\t\tusing CollideShapeVsCompoundVisitor::CollideShapeVsCompoundVisitor;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn true;\n\n\t\t}\n\n\n\n\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test which nodes collide\n\n\t\t\tUVec4 collides = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\t\treturn CountAndSortTrues(collides, ioProperties);\n\n\t\t}\n\n\t};\n\n\n\n\tJPH_ASSERT(inShape2->GetSubType() == EShapeSubType::StaticCompound);\n\n\tconst StaticCompoundShape *shape2 = static_cast<const StaticCompoundShape *>(inShape2);\n\n\n\n\tVisitor visitor(inShape1, shape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, ioCollector);\n\n\tshape2->WalkTree(visitor);\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 56, "score": 108414.95319980249 }, { "content": "\t\t\treturn CountAndSortTrues(collides, ioProperties);\n\n\t\t}\n\n\t};\n\n\n\n\tVisitor visitor(inBox, this, inPositionCOM, inRotation, inScale, inSubShapeIDCreator, ioCollector);\n\n\tWalkTree(visitor);\n\n}\n\n\n\nint StaticCompoundShape::GetIntersectingSubShapes(const AABox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tGetIntersectingSubShapesVisitorSC<AABox> visitor(inBox, outSubShapeIndices, inMaxSubShapeIndices);\n\n\tWalkTree(visitor);\n\n\treturn visitor.GetNumResults();\n\n}\n\n\n\nint StaticCompoundShape::GetIntersectingSubShapes(const OrientedBox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 57, "score": 108414.48661286227 }, { "content": "\tuint bounds_size = num_subshapes * sizeof(AABox);\n\n\tAABox *bounds = (AABox *)inTempAllocator.Allocate(bounds_size);\n\n\n\n\t// Temporary storage for body indexes (we're shuffling them)\n\n\tuint body_idx_size = num_subshapes * sizeof(uint);\n\n\tuint *body_idx = (uint *)inTempAllocator.Allocate(body_idx_size);\n\n\n\n\t// Shift all shapes so that the center of mass is now at the origin and calculate bounds\n\n\tfor (uint i = 0; i < num_subshapes; ++i)\n\n\t{\n\n\t\tSubShape &shape = mSubShapes[i];\n\n\n\n\t\t// Shift the shape so it's centered around our center of mass\n\n\t\tshape.SetPositionCOM(shape.GetPositionCOM() - mCenterOfMass);\n\n\n\n\t\t// Transform the shape's bounds into our local space\n\n\t\tMat44 transform = Mat44::sRotationTranslation(shape.GetRotation(), shape.GetPositionCOM());\n\n\t\tAABox shape_bounds = shape.mShape->GetWorldSpaceBounds(transform, Vec3::sReplicate(1.0f));\n\n\n\n\t\t// Store bounds and body index for tree construction\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 58, "score": 108414.2992298553 }, { "content": "\n\n\tstruct Visitor : public CastRayVisitorCollector\n\n\t{\n\n\t\tusing CastRayVisitorCollector::CastRayVisitorCollector;\n\n\n\n\t\tJPH_INLINE bool\t\tShouldVisitNode(int inStackTop) const\n\n\t\t{\n\n\t\t\treturn mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();\n\n\t\t}\n\n\n\n\t\tJPH_INLINE int\t\tVisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test bounds of 4 children\n\n\t\t\tVec4 distance = TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\n\n\t\t\t// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)\n\n\t\t\treturn SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);\n\n\t\t}\n\n\n\n\t\tfloat\t\t\t\tmDistanceStack[cStackSize];\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 59, "score": 108414.2610892973 }, { "content": "\tf.mColor = Color::sOrange;\n\n\n\n\tfor (EShapeSubType s : sAllSubShapeTypes)\n\n\t{\n\n\t\tCollisionDispatch::sRegisterCollideShape(EShapeSubType::StaticCompound, s, sCollideCompoundVsShape);\n\n\t\tCollisionDispatch::sRegisterCollideShape(s, EShapeSubType::StaticCompound, sCollideShapeVsCompound);\n\n\t\tCollisionDispatch::sRegisterCastShape(s, EShapeSubType::StaticCompound, sCastShapeVsCompound);\n\n\t}\n\n}\n\n\n\n} // JPH", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 60, "score": 108410.95747871911 }, { "content": "}\n\n\n\ntemplate <class Visitor>\n\ninline void StaticCompoundShape::WalkTree(Visitor &ioVisitor) const\n\n{\n\n\tuint32 node_stack[cStackSize];\n\n\tnode_stack[0] = 0;\n\n\tint top = 0;\n\n\tdo\n\n\t{\n\n\t\t// Test if the node is valid, the node should rarely be invalid but it is possible when testing\n\n\t\t// a really large box against the tree that the invalid nodes will intersect with the box\n\n\t\tuint32 node_properties = node_stack[top];\n\n\t\tif (node_properties != INVALID_NODE)\n\n\t\t{\n\n\t\t\t// Test if node contains triangles\n\n\t\t\tbool is_node = (node_properties & IS_SUBSHAPE) == 0;\n\n\t\t\tif (is_node)\n\n\t\t\t{\n\n\t\t\t\tconst Node &node = mNodes[node_properties];\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 61, "score": 108409.28728085596 }, { "content": "\n\nShapeSettings::ShapeResult StaticCompoundShapeSettings::Create(TempAllocator &inTempAllocator) const\n\n{ \n\n\tif (mCachedResult.IsEmpty())\n\n\t{\n\n\t\tif (mSubShapes.size() == 0)\n\n\t\t{\n\n\t\t\t// It's an error to create a compound with no subshapes (the compound cannot encode this)\n\n\t\t\tmCachedResult.SetError(\"Compound needs a sub shape!\");\n\n\t\t}\n\n\t\telse if (mSubShapes.size() == 1)\n\n\t\t{\n\n\t\t\t// If there's only 1 part, we can use a RotatedTranslatedShape instead\n\n\t\t\tRotatedTranslatedShapeSettings settings;\n\n\t\t\tconst SubShapeSettings &s = mSubShapes[0];\n\n\t\t\tsettings.mPosition = s.mPosition;\n\n\t\t\tsettings.mRotation = s.mRotation;\n\n\t\t\tsettings.mInnerShape = s.mShape;\n\n\t\t\tsettings.mInnerShapePtr = s.mShapePtr;\n\n\t\t\tRef<Shape> shape = new RotatedTranslatedShape(settings, mCachedResult);\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 62, "score": 108408.47582005018 }, { "content": "\n\n\t\t\t\t// Unpack bounds\n\n\t\t\t\tUVec4 bounds_minxy = UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(&node.mBoundsMinX[0]));\n\n\t\t\t\tVec4 bounds_minx = HalfFloatConversion::ToFloat(bounds_minxy);\n\n\t\t\t\tVec4 bounds_miny = HalfFloatConversion::ToFloat(bounds_minxy.Swizzle<SWIZZLE_Z, SWIZZLE_W, SWIZZLE_UNUSED, SWIZZLE_UNUSED>());\n\n\t\t\t\t\t\n\n\t\t\t\tUVec4 bounds_minzmaxx = UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(&node.mBoundsMinZ[0]));\n\n\t\t\t\tVec4 bounds_minz = HalfFloatConversion::ToFloat(bounds_minzmaxx);\n\n\t\t\t\tVec4 bounds_maxx = HalfFloatConversion::ToFloat(bounds_minzmaxx.Swizzle<SWIZZLE_Z, SWIZZLE_W, SWIZZLE_UNUSED, SWIZZLE_UNUSED>());\n\n\n\n\t\t\t\tUVec4 bounds_maxyz = UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(&node.mBoundsMaxY[0]));\n\n\t\t\t\tVec4 bounds_maxy = HalfFloatConversion::ToFloat(bounds_maxyz);\n\n\t\t\t\tVec4 bounds_maxz = HalfFloatConversion::ToFloat(bounds_maxyz.Swizzle<SWIZZLE_Z, SWIZZLE_W, SWIZZLE_UNUSED, SWIZZLE_UNUSED>());\n\n\n\n\t\t\t\t// Load properties for 4 children\n\n\t\t\t\tUVec4 properties = UVec4::sLoadInt4(&node.mNodeProperties[0]);\n\n\n\n\t\t\t\t// Check which sub nodes to visit\n\n\t\t\t\tint num_results = ioVisitor.VisitNodes(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, properties, top);\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 63, "score": 108406.60847207396 }, { "content": "\t\tbounds[i] = shape_bounds;\n\n\t\tbody_idx[i] = i;\n\n\n\n\t\t// Update our local bounds\n\n\t\tmLocalBounds.Encapsulate(shape_bounds);\n\n\t}\n\n\n\n\t// The algorithm is a recursive tree build, but to avoid the call overhead we keep track of a stack here\n\n\tstruct StackEntry\n\n\t{\n\n\t\tuint32\t\t\tmNodeIdx;\t\t\t\t\t// Node index of node that is generated\n\n\t\tint\t\t\t\tmChildIdx;\t\t\t\t\t// Index of child that we're currently processing\n\n\t\tint\t\t\t\tmSplit[5];\t\t\t\t\t// Indices where the node ID's have been split to form 4 partitions\n\n\t\tAABox\t\t\tmBounds;\t\t\t\t\t// Bounding box of this node\n\n\t};\n\n\tuint stack_size = num_subshapes * sizeof(StackEntry);\n\n\tStackEntry *stack = (StackEntry *)inTempAllocator.Allocate(stack_size);\n\n\tint top = 0;\n\n\n\n\t// Reserve enough space so that every sub shape gets its own leaf node\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 64, "score": 108406.586844244 }, { "content": "\t\t// Start constructing the runtime sub shape\n\n\t\tSubShape &out_shape = mSubShapes[i];\n\n\t\tif (!out_shape.FromSettings(shape, outResult))\n\n\t\t\treturn;\n\n\n\n\t\t// Calculate mass properties of child\n\n\t\tMassProperties child = out_shape.mShape->GetMassProperties();\n\n\t\n\n\t\t// Accumulate center of mass\n\n\t\tmass += child.mMass;\n\n\t\tmCenterOfMass += out_shape.GetPositionCOM() * child.mMass;\n\n\t}\n\n\n\n\tif (mass > 0.0f)\n\n\t\tmCenterOfMass /= mass;\n\n\n\n\t// Cache the inner radius as it can take a while to recursively iterate over all sub shapes\n\n\tCalculateInnerRadius();\n\n\n\n\t// Temporary storage for the bounding boxes of all shapes\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 65, "score": 108404.48787587178 }, { "content": "\t\t\t\t// Push them onto the stack\n\n\t\t\t\tJPH_ASSERT(top + 4 < cStackSize);\n\n\t\t\t\tproperties.StoreInt4(&node_stack[top]);\n\n\t\t\t\ttop += num_results;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\t\n\n\t\t\t\t// Points to a sub shape\n\n\t\t\t\tuint32 sub_shape_idx = node_properties ^ IS_SUBSHAPE;\n\n\t\t\t\tconst SubShape &sub_shape = mSubShapes[sub_shape_idx];\n\n\n\n\t\t\t\tioVisitor.VisitShape(sub_shape, sub_shape_idx);\n\n\t\t\t}\n\n\n\n\t\t\t// Check if we're done\n\n\t\t\tif (ioVisitor.ShouldAbort())\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\n\n\t\t// Fetch next node until we find one that the visitor wants to see\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 66, "score": 108404.35931180207 }, { "content": "\t// Free temporary memory\n\n\tinTempAllocator.Free(stack, stack_size);\n\n\tinTempAllocator.Free(body_idx, body_idx_size);\n\n\tinTempAllocator.Free(bounds, bounds_size);\n\n\n\n\t// Check if we ran out of bits for addressing a node\n\n\tif (next_node_idx > IS_SUBSHAPE)\n\n\t{\n\n\t\toutResult.SetError(\"Compound hierarchy has too many nodes\");\n\n\t\treturn;\n\n\t}\n\n\n\n\t// Check if we're not exceeding the amount of sub shape id bits\n\n\tif (GetSubShapeIDBitsRecursive() > SubShapeID::MaxBits)\n\n\t{\n\n\t\toutResult.SetError(\"Compound hierarchy is too deep and exceeds the amount of available sub shape ID bits\");\n\n\t\treturn;\n\n\t}\n\n\n\n\toutResult.Set(this);\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 67, "score": 108403.35169552793 }, { "content": "\tuint next_node_idx = 0;\n\n\tmNodes.resize(num_subshapes + (num_subshapes + 2) / 3); // = Sum(num_subshapes * 4^-i) with i = [0, Inf].\n\n\n\n\t// Create root node\n\n\tstack[0].mNodeIdx = next_node_idx++;\n\n\tstack[0].mChildIdx = -1;\n\n\tstack[0].mBounds = AABox();\n\n\tsPartition4(body_idx, bounds, 0, num_subshapes, stack[0].mSplit);\n\n\n\n\tfor (;;)\n\n\t{\n\n\t\tStackEntry &cur_stack = stack[top];\n\n\n\n\t\t// Next child\n\n\t\tcur_stack.mChildIdx++;\n\n\n\n\t\t// Check if all children processed\n\n\t\tif (cur_stack.mChildIdx >= 4)\n\n\t\t{\n\n\t\t\t// Terminate if there's nothing left to pop\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 68, "score": 108401.15101523967 }, { "content": "\tuint *body_idx = ioBodyIdx + inBegin;\n\n\tAABox *node_bounds = ioBounds + inBegin;\n\n\tint number = inEnd - inBegin;\n\n\n\n\t// Partition entire range\n\n\tsPartition(body_idx, node_bounds, number, outSplit[2]); \n\n\t\n\n\t// Partition lower half\n\n\tsPartition(body_idx, node_bounds, outSplit[2], outSplit[1]); \n\n\n\n\t// Partition upper half\n\n\tsPartition(body_idx + outSplit[2], node_bounds + outSplit[2], number - outSplit[2], outSplit[3]); \n\n\n\n\t// Convert to proper range \n\n\toutSplit[0] = inBegin;\n\n\toutSplit[1] += inBegin;\n\n\toutSplit[2] += inBegin;\n\n\toutSplit[3] += outSplit[2];\n\n\toutSplit[4] = inEnd;\n\n}\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 69, "score": 108401.07938904181 }, { "content": "\t\t\tint num_bodies = high - low;\n\n\n\n\t\t\tif (num_bodies == 0)\n\n\t\t\t{\n\n\t\t\t\t// Mark invalid\n\n\t\t\t\tNode &node = mNodes[cur_stack.mNodeIdx];\n\n\t\t\t\tnode.SetChildInvalid(cur_stack.mChildIdx);\n\n\t\t\t}\n\n\t\t\telse if (num_bodies == 1)\n\n\t\t\t{\n\n\t\t\t\t// Get body info\n\n\t\t\t\tuint child_node_idx = body_idx[low];\n\n\t\t\t\tconst AABox &child_bounds = bounds[low];\n\n\n\n\t\t\t\t// Update node\n\n\t\t\t\tNode &node = mNodes[cur_stack.mNodeIdx];\n\n\t\t\t\tnode.mNodeProperties[cur_stack.mChildIdx] = child_node_idx | IS_SUBSHAPE;\n\n\t\t\t\tnode.SetChildBounds(cur_stack.mChildIdx, child_bounds);\n\n\n\n\t\t\t\t// Encapsulate bounding box in parent\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 70, "score": 108400.81536669329 }, { "content": "\tint dimension = (center_max - center_min).GetHighestComponentIndex();\n\n\tfloat split = 0.5f * (center_min + center_max)[dimension];\n\n\n\n\t// Divide bodies\n\n\tint start = 0, end = inNumber;\n\n\twhile (start < end)\n\n\t{\n\n\t\t// Search for first element that is on the right hand side of the split plane\n\n\t\twhile (start < end && ioBounds[start].GetCenter()[dimension] < split)\n\n\t\t\t++start;\n\n\n\n\t\t// Search for the first element that is on the left hand side of the split plane\n\n\t\twhile (start < end && ioBounds[end - 1].GetCenter()[dimension] >= split)\n\n\t\t\t--end;\n\n\n\n\t\tif (start < end)\n\n\t\t{\n\n\t\t\t// Swap the two elements\n\n\t\t\tswap(ioBodyIdx[start], ioBodyIdx[end - 1]);\n\n\t\t\tswap(ioBounds[start], ioBounds[end - 1]);\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 71, "score": 108400.80032987935 }, { "content": "\t\t\tif (top <= 0)\n\n\t\t\t\tbreak;\n\n\n\n\t\t\t// Add our bounds to our parents bounds\n\n\t\t\tStackEntry &prev_stack = stack[top - 1];\n\n\t\t\tprev_stack.mBounds.Encapsulate(cur_stack.mBounds);\n\n\n\n\t\t\t// Store this node's properties in the parent node\n\n\t\t\tNode &parent_node = mNodes[prev_stack.mNodeIdx];\n\n\t\t\tparent_node.mNodeProperties[prev_stack.mChildIdx] = cur_stack.mNodeIdx;\n\n\t\t\tparent_node.SetChildBounds(prev_stack.mChildIdx, cur_stack.mBounds);\n\n\n\n\t\t\t// Pop entry from stack\n\n\t\t\t--top;\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\t// Get low and high index to bodies to process\n\n\t\t\tint low = cur_stack.mSplit[cur_stack.mChildIdx];\n\n\t\t\tint high = cur_stack.mSplit[cur_stack.mChildIdx + 1];\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 72, "score": 108396.87368126915 }, { "content": "\t\t\t\tcur_stack.mBounds.Encapsulate(child_bounds);\n\n\t\t\t}\n\n\t\t\telse \n\n\t\t\t{\n\n\t\t\t\t// Allocate new node\n\n\t\t\t\tStackEntry &new_stack = stack[++top];\n\n\t\t\t\tJPH_ASSERT(top < (int)num_subshapes);\n\n\t\t\t\tnew_stack.mNodeIdx = next_node_idx++;\n\n\t\t\t\tnew_stack.mChildIdx = -1;\n\n\t\t\t\tnew_stack.mBounds = AABox();\n\n\t\t\t\tsPartition4(body_idx, bounds, low, high, new_stack.mSplit);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\t// Resize nodes to actual size\n\n\tJPH_ASSERT(next_node_idx <= mNodes.size());\n\n\tmNodes.resize(next_node_idx);\n\n\tmNodes.shrink_to_fit();\n\n\n", "file_path": "Jolt/Physics/Collision/Shape/StaticCompoundShape.cpp", "rank": 73, "score": 108396.87368126915 }, { "content": "class RayCastSettings;\n", "file_path": "Jolt/Physics/Collision/Shape/Shape.h", "rank": 74, "score": 108382.1865124542 }, { "content": "\n\n\t\t\t// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)\n\n\t\t\treturn SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);\n\n\t\t}\n\n\n\n\t\tJPH_INLINE void\t\t\tVisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) \n\n\t\t{\t\t\t\n\n\t\t\tfloat fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);\n\n\t\t\tif (fraction < mHit.mFraction)\n\n\t\t\t{\n\n\t\t\t\t// It's a closer hit\n\n\t\t\t\tmHit.mFraction = fraction;\n\n\t\t\t\tmHit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);\n\n\t\t\t\tmReturnValue = true;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tRayCastResult &\t\t\tmHit;\n\n\t\tVec3\t\t\t\t\tmRayOrigin;\n\n\t\tVec3\t\t\t\t\tmRayDirection;\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 75, "score": 108368.8081986479 }, { "content": "\t\tJPH_INLINE void\t\t\t\tVisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)\n\n\t\t{\t\t\t\n\n\t\t\t// Create sub shape id for this part\n\n\t\t\tSubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);\n\n\n\n\t\t\t// Determine active edges\n\n\t\t\tuint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);\n\n\n\n\t\t\tCast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);\n\n\t\t}\n\n\n\n\t\tconst HeightFieldShape *\tmShape2;\n\n\t\tRayInvDirection\t\t\t\tmInvDirection;\n\n\t\tVec3\t\t\t\t\t\tmBoxCenter;\n\n\t\tVec3\t\t\t\t\t\tmBoxExtent;\n\n\t\tSubShapeIDCreator\t\t\tmSubShapeIDCreator2;\n\n\t\tfloat\t\t\t\t\t\tmDistanceStack[cStackSize];\n\n\t};\n\n\n\n\tJPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 76, "score": 108363.83555649094 }, { "content": "\t\n\n\t\t\t// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)\n\n\t\t\treturn SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);\n\n\t\t}\n\n\n\n\t\tJPH_INLINE void\t\t\t\tVisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)\n\n\t\t{\t\t\t\n\n\t\t\t// Create sub shape id for this part\n\n\t\t\tSubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);\n\n\n\n\t\t\t// Determine active edges\n\n\t\t\tuint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);\n\n\n\n\t\t\tCast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);\n\n\t\t}\n\n\n\n\t\tconst HeightFieldShape *\tmShape2;\n\n\t\tRayInvDirection\t\t\t\tmInvDirection;\n\n\t\tSubShapeIDCreator\t\t\tmSubShapeIDCreator2;\n\n\t\tfloat\t\t\t\t\t\tmDistanceStack[cStackSize];\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 77, "score": 108363.63969211439 }, { "content": "\t\t\t\thit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());\n\n\t\t\t\thit.mFraction = fraction;\n\n\t\t\t\thit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);\n\n\t\t\t\tmCollector.AddHit(hit);\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\tCastRayCollector &\t\tmCollector;\n\n\t\tVec3\t\t\t\t\tmRayOrigin;\n\n\t\tVec3\t\t\t\t\tmRayDirection;\n\n\t\tRayInvDirection\t\t\tmRayInvDirection;\n\n\t\tEBackFaceMode\t\t\tmBackFaceMode;\n\n\t\tconst HeightFieldShape *mShape;\n\n\t\tSubShapeIDCreator\t\tmSubShapeIDCreator;\n\n\t\tfloat\t\t\t\t\tmDistanceStack[cStackSize];\n\n\t};\n\n\n\n\tVisitor visitor(this, inRay, inRayCastSettings, inSubShapeIDCreator, ioCollector);\n\n\tWalkHeightField(visitor);\n\n}\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 78, "score": 108362.65282022684 }, { "content": "{ \n\n\t// Get quantized value\n\n\tuint8 height_sample = GetHeightSample(inX, inY);\n\n\toutNoCollision = height_sample == mSampleMask;\n\n\n\n\t// Add 0.5 to the quantized value to minimize the error (see constructor)\n\n\treturn mOffset + mScale * Vec3(float(inX), inBlockOffset + (0.5f + height_sample) * inBlockScale, float(inY)); \n\n}\n\n\n\nVec3 HeightFieldShape::GetPosition(uint inX, uint inY) const\n\n{\n\n\t// Test if there are any samples\n\n\tif (mHeightSamples.empty())\n\n\t\treturn mOffset + mScale * Vec3(float(inX), 0.0f, float(inY));\n\n\n\n\t// Get block location\n\n\tuint bx = inX / mBlockSize;\n\n\tuint by = inY / mBlockSize;\n\n\n\n\t// Calculate offset and stride\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 79, "score": 108361.18644834006 }, { "content": "}\n\n\n\ninline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const\n\n{\n\n\tJPH_ASSERT(inX < mSampleCount); \n\n\tJPH_ASSERT(inY < mSampleCount); \n\n\t\n\n\t// Determine bit position of sample\n\n\tuint sample = (inY * mSampleCount + inX) * uint(mBitsPerSample);\n\n\tuint byte_pos = sample >> 3;\n\n\tuint bit_pos = sample & 0b111;\n\n\n\n\t// Fetch the height sample value\n\n\tJPH_ASSERT(byte_pos + 1 < mHeightSamples.size());\n\n\tconst uint8 *height_samples = mHeightSamples.data() + byte_pos;\n\n\tuint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);\n\n\treturn uint8(height_sample >> bit_pos) & mSampleMask; \n\n}\n\n\n\ninline Vec3 HeightFieldShape::GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 80, "score": 108358.13968268623 }, { "content": "\n\ninline void HeightFieldShape::sGetRangeBlockOffsetAndStride(uint inNumBlocks, uint inMaxLevel, uint &outRangeBlockOffset, uint &outRangeBlockStride)\n\n{\n\n\toutRangeBlockOffset = sGridOffsets[inMaxLevel - 1];\n\n\toutRangeBlockStride = inNumBlocks >> 1;\n\n}\n\n\n\ninline void HeightFieldShape::GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const\n\n{\n\n\tJPH_ASSERT(inBlockX < GetNumBlocks() && inBlockY < GetNumBlocks());\n\n\n\n\t// Convert to location of range block\n\n\tuint rbx = inBlockX >> 1;\n\n\tuint rby = inBlockY >> 1;\n\n\tuint n = ((inBlockY & 1) << 1) + (inBlockX & 1);\n\n\n\n\t// Calculate offset and scale\n\n\tconst RangeBlock &block = mRangeBlocks[inRangeBlockOffset + rby * inRangeBlockStride + rbx];\n\n\toutBlockOffset = float(block.mMin[n]);\n\n\toutBlockScale = float(block.mMax[n] - block.mMin[n]) / float(mSampleMask);\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 81, "score": 108357.05655234962 }, { "content": "\tuint num_blocks = GetNumBlocks();\n\n\tuint range_block_offset, range_block_stride;\n\n\tsGetRangeBlockOffsetAndStride(num_blocks, sGetMaxLevel(num_blocks), range_block_offset, range_block_stride);\n\n\n\n\tfloat offset, scale;\n\n\tGetBlockOffsetAndScale(bx, by, range_block_offset, range_block_stride, offset, scale);\n\n\n\n\tbool no_collision;\n\n\treturn GetPosition(inX, inY, offset, scale, no_collision);\n\n}\n\n\n\nbool HeightFieldShape::IsNoCollision(uint inX, uint inY) const\n\n{ \n\n\treturn mHeightSamples.empty() || GetHeightSample(inX, inY) == mSampleMask;\n\n}\n\n\n\nbool HeightFieldShape::ProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const\n\n{\n\n\t// Check if we have collision\n\n\tif (mHeightSamples.empty())\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 82, "score": 108357.02784852013 }, { "content": "\t// Calculate amount of memory used\n\n\tShape::Stats stats = mHeightField->GetStats();\n\n\n\n\t// Trace stats\n\n\tTrace(\"Block size: %d, bits per sample: %d, min height: %g, max height: %g, avg diff: %g, max diff: %g at (%d, %d), relative error: %g%%, size: %u bytes\", 1 << sBlockSizeShift, sBitsPerSample, (double)min_height, (double)max_height, (double)avg_diff, (double)max_diff, max_diff_x, max_diff_y, (double)rel_error, stats.mSizeBytes);\n\n\tif (rel_error > max_error)\n\n\t\tFatalError(\"Error too big!\");\n\n\n\n\t// Determine terrain height\n\n\tRayCastResult result;\n\n\tVec3 start(0, 1000, 0);\n\n\tVec3 direction(0, -2000, 0);\n\n\tRayCast ray { start, direction };\n\n\tif (mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, result, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::NON_MOVING), SpecifiedObjectLayerFilter(Layers::NON_MOVING)))\n\n\t\tmHitPos = start + result.mFraction * direction;\n\n\n\n\t// Dynamic body\n\n\tBody &body1 = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 1.0f, 2.0f)), mHitPos + Vec3(0, 10, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING));\n\n\tmBodyInterface->AddBody(body1.GetID(), EActivation::Activate);\n\n}\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.cpp", "rank": 83, "score": 108356.75077274762 }, { "content": "\t\t\t\tif (h == HeightFieldShapeConstants::cNoCollisionValue)\n\n\t\t\t\t\tcontinue;\n\n\n\n\t\t\t\t// Get original position\n\n\t\t\t\tVec3 original = mTerrainOffset + mTerrainScale * Vec3(float(x), h, float(y));\n\n\n\n\t\t\t\t// Get compressed position\n\n\t\t\t\tVec3 compressed = mHeightField->GetPosition(x, y);\n\n\n\n\t\t\t\t// Draw marker that is red when error is too big and green when not\n\n\t\t\t\tconst float cMaxError = 0.1f;\n\n\t\t\t\tfloat error = (original - compressed).Length();\n\n\t\t\t\tuint8 c = uint8(round(255.0f * min(error / cMaxError, 1.0f)));\n\n\t\t\t\tmDebugRenderer->DrawMarker(original, Color(c, 255 - c, 0, 255), 0.1f);\n\n\t\t\t}\n\n}\n\n\n\nvoid HeightFieldShapeTest::GetInitialCamera(CameraState &ioState) const\n\n{\n\n\t// Correct camera pos for hit position\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.cpp", "rank": 84, "score": 108356.03882892412 }, { "content": "\t\tJPH_INLINE int\t\t\tVisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop) \n\n\t\t{\n\n\t\t\t// Test bounds of 4 children\n\n\t\t\tVec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);\n\n\t\n\n\t\t\t// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)\n\n\t\t\treturn SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);\n\n\t\t}\n\n\n\n\t\tJPH_INLINE void\t\t\tVisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const\n\n\t\t{\t\t\t\n\n\t\t\t// Back facing check\n\n\t\t\tif (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)\n\n\t\t\t\treturn;\n\n\n\n\t\t\t// Check the triangle\n\n\t\t\tfloat fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);\n\n\t\t\tif (fraction < mCollector.GetEarlyOutFraction())\n\n\t\t\t{\n\n\t\t\t\tRayCastResult hit;\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 85, "score": 108355.79972495987 }, { "content": "\t\tJPH_INLINE void\t\t\t\tVisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)\n\n\t\t{\t\t\t\n\n\t\t\t// Create ID for triangle\n\n\t\t\tSubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);\n\n\n\n\t\t\t// Determine active edges\n\n\t\t\tuint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);\n\n\n\n\t\t\tCollide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);\n\n\t\t}\n\n\n\n\t\tconst HeightFieldShape *\tmShape2;\n\n\t\tSubShapeIDCreator\t\t\tmSubShapeIDCreator2;\n\n\t};\n\n\n\n\tVisitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);\n\n\tvisitor.mShape2 = shape2;\n\n\tvisitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;\n\n\tshape2->WalkHeightField(visitor);\n\n}\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 86, "score": 108355.64803024755 }, { "content": "\tuint32\t\t\t\t\t\tmPropertiesStack[cStackSize];\n\n};\n\n\n\ntemplate <class Visitor>\n\nJPH_INLINE void HeightFieldShape::WalkHeightField(Visitor &ioVisitor) const\n\n{\n\n\tDecodingContext ctx(this);\n\n\tctx.WalkHeightField(ioVisitor);\n\n}\n\n\n\nbool HeightFieldShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor\n\n\t{\n\n\t\tJPH_INLINE explicit\t\tVisitor(const HeightFieldShape *inShape, const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) : \n\n\t\t\tmHit(ioHit),\n\n\t\t\tmRayOrigin(inRay.mOrigin),\n\n\t\t\tmRayDirection(inRay.mDirection),\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 87, "score": 108355.53824931107 }, { "content": "\tfloat max_diff = -1.0f;\n\n\tuint max_diff_x = 0, max_diff_y = 0;\n\n\tfloat min_height = FLT_MAX, max_height = -FLT_MAX, avg_diff = 0.0f;\n\n\tfor (uint y = 0; y < mTerrainSize; ++y)\n\n\t\tfor (uint x = 0; x < mTerrainSize; ++x)\n\n\t\t{\n\n\t\t\tfloat h1 = mTerrain[y * mTerrainSize + x];\n\n\t\t\tif (h1 != HeightFieldShapeConstants::cNoCollisionValue)\n\n\t\t\t{\n\n\t\t\t\th1 = mTerrainOffset.GetY() + mTerrainScale.GetY() * h1;\n\n\t\t\t\tif (mHeightField->IsNoCollision(x, y))\n\n\t\t\t\t\tFatalError(\"No collision where there should be\");\n\n\t\t\t\tfloat h2 = mHeightField->GetPosition(x, y).GetY();\n\n\t\t\t\tfloat diff = abs(h2 - h1);\n\n\t\t\t\tif (diff > max_diff)\n\n\t\t\t\t{\n\n\t\t\t\t\tmax_diff = diff;\n\n\t\t\t\t\tmax_diff_x = x;\n\n\t\t\t\t\tmax_diff_y = y;\n\n\t\t\t\t}\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.cpp", "rank": 88, "score": 108355.46342261702 }, { "content": "\t\tRayInvDirection\t\t\tmRayInvDirection;\n\n\t\tconst HeightFieldShape *mShape;\n\n\t\tSubShapeIDCreator\t\tmSubShapeIDCreator;\n\n\t\tbool\t\t\t\t\tmReturnValue = false;\n\n\t\tfloat\t\t\t\t\tmDistanceStack[cStackSize];\n\n\t};\n\n\n\n\tVisitor visitor(this, inRay, inSubShapeIDCreator, ioHit);\n\n\tWalkHeightField(visitor);\n\n\n\n\treturn visitor.mReturnValue;\n\n}\n\n\n\nvoid HeightFieldShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\tstruct Visitor\n\n\t{\n\n\t\tJPH_INLINE explicit\t\tVisitor(const HeightFieldShape *inShape, const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) : \n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 89, "score": 108355.43434601183 }, { "content": "\tJPH_ADD_BASE_CLASS(HeightFieldShapeTest, Test) \n\n}\n\n\n\nstatic int sTerrainType = 0;\n\n\n\nstatic const char *sTerrainTypes[] = {\n\n\t\"Procedural Terrain\",\n\n\t\"Heightfield 1\",\n\n\t\"Flat\",\n\n\t\"No Collision\"\n\n};\n\n\n\nvoid HeightFieldShapeTest::Initialize()\n\n{\n\n\tif (sTerrainType == 0)\n\n\t{\n\n\t\tconst int n = 128;\n\n\t\tconst float cell_size = 1.0f;\n\n\t\tconst float max_height = 5.0f;\n\n\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.cpp", "rank": 90, "score": 108354.15547969351 }, { "content": "\tuint16 material_index = uint16(material_indices[0]) + uint16(uint16(material_indices[1]) << 8);\n\n\tmaterial_index >>= bit_pos;\n\n\tmaterial_index &= (1 << mNumBitsPerMaterialIndex) - 1;\n\n\n\n\t// Return the material\n\n\treturn mMaterials[material_index];\n\n}\n\n\n\nuint HeightFieldShape::GetSubShapeIDBits() const\n\n{\n\n\t// Need to store X, Y and 1 extra bit to specify the triangle number in the quad\n\n\treturn 2 * (32 - CountLeadingZeros(mSampleCount - 1)) + 1;\n\n}\n\n\n\nSubShapeID HeightFieldShape::EncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const\n\n{\n\n\treturn inCreator.PushID((inX + inY * mSampleCount) * 2 + inTriangle, GetSubShapeIDBits()).GetID();\n\n}\n\n\n\nvoid HeightFieldShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 91, "score": 108353.50600731463 }, { "content": "\n\nvoid HeightFieldShapeTest::PrePhysicsUpdate(const PreUpdateParams &inParams)\n\n{\n\n\t// Test the 'GetHeight' function and draw a marker on the surface\n\n\tVec3 test_pos = inParams.mCameraState.mPos + 10.0f * inParams.mCameraState.mForward, surface_pos;\n\n\tSubShapeID sub_shape_id;\n\n\tif (mHeightField->ProjectOntoSurface(test_pos, surface_pos, sub_shape_id))\n\n\t{\n\n\t\tVec3 surface_normal = mHeightField->GetSurfaceNormal(sub_shape_id, surface_pos);\n\n\t\tmDebugRenderer->DrawMarker(surface_pos, Color::sWhite, 1.0f);\n\n\t\tmDebugRenderer->DrawArrow(surface_pos, surface_pos + surface_normal, Color::sRed, 0.1f);\n\n\t}\n\n\n\n\t// Draw the original uncompressed terrain\n\n\tif (sShowOriginalTerrain)\n\n\t\tfor (uint y = 0; y < mTerrainSize; ++y)\n\n\t\t\tfor (uint x = 0; x < mTerrainSize; ++x)\n\n\t\t\t{\n\n\t\t\t\t// Get original height\n\n\t\t\t\tfloat h = mTerrain[y * mTerrainSize + x];\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.cpp", "rank": 92, "score": 108353.44660591616 }, { "content": "\t\t\tUVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);\n\n\t\t\treturn CountAndSortTrues(collides, ioProperties);\n\n\t\t}\n\n\n\n\t\tJPH_INLINE void\t\t\t\tVisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)\n\n\t\t{\t\t\t\n\n\t\t\t// Create ID for triangle\n\n\t\t\tSubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);\n\n\n\n\t\t\t// Determine active edges\n\n\t\t\tuint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);\n\n\n\n\t\t\tCollide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);\n\n\t\t}\n\n\n\n\t\tconst HeightFieldShape *\tmShape2;\n\n\t\tSubShapeIDCreator\t\t\tmSubShapeIDCreator2;\n\n\t};\n\n\n\n\tVisitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 93, "score": 108353.15604323454 }, { "content": "\treturn mCachedResult;\n\n}\n\n\n\nvoid HeightFieldShapeSettings::DetermineMinAndMaxSample(float &outMinValue, float &outMaxValue, float &outQuantizationScale) const\n\n{\n\n\t// Determine min and max value\n\n\toutMinValue = FLT_MAX;\n\n\toutMaxValue = -FLT_MAX;\n\n\tfor (float h : mHeightSamples)\n\n\t\tif (h != cNoCollisionValue)\n\n\t\t{\n\n\t\t\toutMinValue = min(outMinValue, h);\n\n\t\t\toutMaxValue = max(outMaxValue, h);\n\n\t\t}\n\n\n\n\t// Prevent dividing by zero by setting a minimal height difference\n\n\tfloat height_diff = max(outMaxValue - outMinValue, 1.0e-6f);\n\n\n\n\t// Calculate the scale factor to quantize to 16 bits\n\n\toutQuantizationScale = float(cMaxHeightValue16) / height_diff;\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 94, "score": 108351.34052571692 }, { "content": "\t\t\t*mMaterials++ = mShape->GetMaterial(inX, inY);\n\n\n\n\t\t// Accumulate triangles found\n\n\t\tmNumTrianglesFound++;\n\n\t}\n\n\n\n\tDecodingContext\t\t\t\tmDecodeCtx;\n\n\tconst HeightFieldShape *\tmShape;\n\n\tOrientedBox\t\t\t\t\tmLocalBox;\n\n\tVec3\t\t\t\t\t\tmHeightFieldScale;\n\n\tMat44\t\t\t\t\t\tmLocalToWorld;\n\n\tint\t\t\t\t\t\t\tmMaxTrianglesRequested;\n\n\tFloat3 *\t\t\t\t\tmTriangleVertices;\n\n\tint\t\t\t\t\t\t\tmNumTrianglesFound;\n\n\tconst PhysicsMaterial **\tmMaterials;\n\n\tbool\t\t\t\t\t\tmShouldAbort;\n\n\tbool\t\t\t\t\t\tmIsInsideOut;\n\n};\n\n\n\nvoid HeightFieldShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 95, "score": 108350.48418782894 }, { "content": "\t\treturn AABox(center, center);\n\n\t}\n\n\telse\n\n\t{\n\n\t\t// Bounding box based on min and max sample height\n\n\t\tVec3 bmin = mOffset + mScale * Vec3(0.0f, float(mMinSample), 0.0f);\n\n\t\tVec3 bmax = mOffset + mScale * Vec3(float(mSampleCount - 1), float(mMaxSample), float(mSampleCount - 1));\n\n\t\treturn AABox(bmin, bmax);\n\n\t}\n\n}\n\n\n\n#ifdef JPH_DEBUG_RENDERER\n\nvoid HeightFieldShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const\n\n{\n\n\t// Don't draw anything if we don't have any collision\n\n\tif (mHeightSamples.empty())\n\n\t\treturn;\n\n\n\n\t// Reset the batch if we switch coloring mode\n\n\tif (mCachedUseMaterialColors != inUseMaterialColors)\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 96, "score": 108350.19670162618 }, { "content": "\tcontext.mMaterials = outMaterials;\n\n\tcontext.mShouldAbort = false; // Reset the abort flag\n\n\tcontext.mNumTrianglesFound = 0;\n\n\t\n\n\t// Continue (or start) walking the height field\n\n\tcontext.mDecodeCtx.WalkHeightField(context);\n\n\treturn context.mNumTrianglesFound;\n\n}\n\n\n\nvoid HeightFieldShape::sCollideConvexVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\t// Get the shapes\n\n\tJPH_ASSERT(inShape1->GetType() == EShapeType::Convex);\n\n\tJPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);\n\n\tconst ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);\n\n\tconst HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);\n\n\n\n\tstruct Visitor : public CollideConvexVsTriangles\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 97, "score": 108350.07447916297 }, { "content": "\tvisitor.mShape2 = shape2;\n\n\tvisitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;\n\n\tshape2->WalkHeightField(visitor);\n\n}\n\n\n\nvoid HeightFieldShape::sCollideSphereVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)\n\n{\n\n\tJPH_PROFILE_FUNCTION();\n\n\n\n\t// Get the shapes\n\n\tJPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);\n\n\tJPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);\n\n\tconst SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);\n\n\tconst HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);\n\n\n\n\tstruct Visitor : public CollideSphereVsTriangles\n\n\t{\n\n\t\tusing CollideSphereVsTriangles::CollideSphereVsTriangles;\n\n\n\n\t\tJPH_INLINE bool\t\t\t\tShouldAbort() const\n", "file_path": "Jolt/Physics/Collision/Shape/HeightFieldShape.cpp", "rank": 98, "score": 108349.77392748058 }, { "content": "\t\t// Determine scale and offset\n\n\t\tmTerrainOffset = Vec3(-0.5f * cell_size * n, 0.0f, -0.5f * cell_size * n);\n\n\t\tmTerrainScale = Vec3(cell_size, 1.0f, cell_size);\n\n\n\n\t\t// Mark the entire terrain as no collision\n\n\t\tmTerrainSize = n;\n\n\t\tmTerrain.resize(n * n);\n\n\t\tfor (float &v : mTerrain)\n\n\t\t\tv = HeightFieldShapeConstants::cNoCollisionValue;\n\n\t}\n\n\n\n\t// Create height field\n\n\tHeightFieldShapeSettings settings(mTerrain.data(), mTerrainOffset, mTerrainScale, mTerrainSize, mMaterialIndices.data(), mMaterials);\n\n\tsettings.mBlockSize = 1 << sBlockSizeShift;\n\n\tsettings.mBitsPerSample = sBitsPerSample;\n\n\tmHeightField = static_cast<const HeightFieldShape *>(settings.Create().Get().GetPtr());\n\n\tBody &terrain = *mBodyInterface->CreateBody(BodyCreationSettings(mHeightField, Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));\n\n\tmBodyInterface->AddBody(terrain.GetID(), EActivation::DontActivate);\n\n\n\n\t// Validate it\n", "file_path": "Samples/Tests/Shapes/HeightFieldShapeTest.cpp", "rank": 99, "score": 108349.64390883422 } ]
C++
include/sharpen/MemoryTable.hpp
TalexDreamSoul/Sharpen
9167c4080438a1f150232d733c4da878639d6f66
#pragma once #ifndef _SHARPEN_MEMORYTABLE_HPP #define _SHARPEN_MEMORYTABLE_HPP #include <stdexcept> #include <map> #include <cassert> #include "ByteBuffer.hpp" #include "CompressedPair.hpp" #include "MemoryTableConcepts.hpp" #include "Noncopyable.hpp" #include "Optional.hpp" namespace sharpen { class MemoryTableItem { private: using Self = sharpen::MemoryTableItem; sharpen::Optional<sharpen::ByteBuffer> value_; public: MemoryTableItem() = default; explicit MemoryTableItem(sharpen::ByteBuffer value) :value_(std::move(value)) {} MemoryTableItem(const Self &other) = default; MemoryTableItem(Self &&other) noexcept = default; inline Self &operator=(const Self &other) { Self tmp{other}; std::swap(tmp,*this); return *this; } Self &operator=(Self &&other) noexcept = default; ~MemoryTableItem() noexcept = default; inline sharpen::ByteBuffer &Value() noexcept { assert(this->value_.Exist()); return this->value_.Get(); } inline const sharpen::ByteBuffer &Value() const noexcept { assert(this->value_.Exist()); return this->value_.Get(); } inline bool IsDeleted() const noexcept { return !this->value_.Exist(); } void Delete() noexcept { this->value_.Reset(); } }; template<typename _Logger,typename _Check = void> class InternalMemoryTable; template<typename _Logger> class InternalMemoryTable<_Logger,sharpen::EnableIf<sharpen::IsMemoryTableLogger<_Logger>::Value>>:public sharpen::Noncopyable { private: using Self = sharpen::InternalMemoryTable<_Logger,sharpen::EnableIf<sharpen::IsMemoryTableLogger<_Logger>::Value>>; using StoreItem = sharpen::MemoryTableItem; using MapType = std::map<sharpen::ByteBuffer,StoreItem>; using ConstIterator = typename MapType::const_iterator; sharpen::CompressedPair<_Logger,MapType> pair_; _Logger &Logger() noexcept { return this->pair_.First(); } const _Logger &Logger() const noexcept { return this->pair_.First(); } MapType &Map() noexcept { return this->pair_.Second(); } const MapType &Map() const noexcept { return this->pair_.Second(); } void InternalPut(sharpen::ByteBuffer key,sharpen::ByteBuffer value) { this->Map()[std::move(key)] = StoreItem{std::move(value)}; } void InternalDelete(sharpen::ByteBuffer key) { auto ite = this->Map().find(key); if(ite != this->Map().end()) { ite->second.Delete(); } else { this->Map().emplace(std::move(key),StoreItem{}); } } void InternalAction(sharpen::WriteBatch &batch) { for (auto begin = batch.Begin(),end = batch.End(); begin != end; ++begin) { if (begin->type_ == sharpen::WriteBatch::ActionType::Put) { this->InternalPut(std::move(begin->key_),std::move(begin->value_)); } else { this->InternalDelete(std::move(begin->key_)); } } batch.Clear(); } void InternalAction(const sharpen::WriteBatch &batch) { for (auto begin = batch.Begin(),end = batch.End(); begin != end; ++begin) { if (begin->type_ == sharpen::WriteBatch::ActionType::Put) { this->InternalPut(begin->key_,begin->value_); } else { this->InternalDelete(begin->key_); } } } public: enum class ExistStatus { Exist, Deleted, NotFound }; template<typename ..._Args,typename _Check = decltype(_Logger{std::declval<_Args>()...})> explicit InternalMemoryTable(_Args &&...args) :pair_(_Logger{std::forward<_Args>(args)...},MapType{}) {} InternalMemoryTable(Self &&other) noexcept = default; Self &operator=(Self &&other) noexcept { if(this != std::addressof(other)) { this->pair_ = std::move(other.pair_); } return *this; } ~InternalMemoryTable() noexcept = default; inline void Restore() { auto batchs = this->Logger().GetWriteBatchs(); for (auto begin = batchs.begin(),end = batchs.end(); begin != end; ++begin) { sharpen::WriteBatch &batch = *begin; this->InternalAction(batch); } } inline void Action(sharpen::WriteBatch &batch) { this->Logger().Log(batch); this->InternalAction(batch); } inline void Action(sharpen::WriteBatch &&batch) { this->Action(batch); } inline void Action(const sharpen::WriteBatch &batch) { this->Logger().Log(batch); this->InternalAction(batch); } inline void Put(sharpen::ByteBuffer key,sharpen::ByteBuffer value) { sharpen::WriteBatch batch; batch.Put(std::move(key),std::move(value)); this->Action(std::move(batch)); } inline void Delete(sharpen::ByteBuffer key) { sharpen::WriteBatch batch; batch.Delete(std::move(key)); this->Action(std::move(batch)); } void ClearLogs() { this->Logger().Clear(); } void RemoveLogs() { this->Logger().Remove(); } Self::ExistStatus Exist(const sharpen::ByteBuffer &key) const noexcept { auto ite = this->Map().find(key); if(ite == this->Map().end()) { return Self::ExistStatus::NotFound; } else if(ite->second.IsDeleted()) { return Self::ExistStatus::Deleted; } return Self::ExistStatus::Exist; } sharpen::ByteBuffer &Get(const sharpen::ByteBuffer &key) { auto &item = this->Map().at(key); if(item.IsDeleted()) { throw std::out_of_range("key doesn't exists"); } return item.Value(); } const sharpen::ByteBuffer &Get(const sharpen::ByteBuffer &key) const { auto &item = this->Map().at(key); if(item.deleteTag_) { throw std::out_of_range("key doesn't exists"); } return item.value_; } sharpen::ByteBuffer &operator[](const sharpen::ByteBuffer &key) { return this->Get(key); } const sharpen::ByteBuffer &operator[](const sharpen::ByteBuffer &key) const { return this->Get(key); } inline ConstIterator Begin() const noexcept { return this->Map().begin(); } inline ConstIterator End() const noexcept { return this->Map().end(); } }; template<typename _Logger> using MemoryTable = sharpen::InternalMemoryTable<_Logger>; } #endif
#pragma once #ifndef _SHARPEN_MEMORYTABLE_HPP #define _SHARPEN_MEMORYTABLE_HPP #include <stdexcept> #include <map> #include <cassert> #include "ByteBuffer.hpp" #include "CompressedPair.hpp" #include "MemoryTableConcepts.hpp" #include "Noncopyable.hpp" #include "Optional.hpp" namespace sharpen { class MemoryTableItem { private: using Self = sharpen::MemoryTableItem; sharpen::Optional<sharpen::ByteBuffer> value_; public: MemoryTableItem() = default; explicit MemoryTableItem(sharpen::ByteBuffer value) :value_(std::move(value)) {} MemoryTableItem(const Self &other) = default; MemoryTableItem(Self &&other) noexcept = default; inline Self &operator=(const Self &other) { Self tmp{other}; std::swap(tmp,*this); return *this; } Self &operator=(Self &&other) noexcept = default; ~MemoryTableItem() noexcept = default; inline sharpen::ByteBuffer &Value() noexcept { assert(this->value_.Exist()); return this->value_.Get(); } inline const sharpen::ByteBuffer &Value() const noexcept { assert(this->value_.Exist()); return this->value_.Get(); } inline bool IsDeleted() const noexcept { return !this->value_.Exist(); } void Delete() noexcept { this->value_.Reset(); } }; template<typename _Logger,typename _Check = void> class InternalMemoryTable; template<typename _Logger> class InternalMemoryTable<_Logger,sharpen::EnableIf<sharpen::IsMemoryTableLogger<_Logger>::Value>>:public sharpen::Noncopyable { private: using Self = sharpen::InternalMemoryTable<_Logger,sharpen::EnableIf<sharpen::IsMemoryTableLogger<_Logger>::Value>>; using StoreItem = sharpen::MemoryTableItem; using MapType = std::map<sharpen::ByteBuffer,StoreItem>; using ConstIterator = typename MapType::const_iterator; sharpen::CompressedPair<_Logger,MapType> pair_; _Logger &Logger() noexcept { return this->pair_.First(); } const _Logger &Logger() const noexcept { return this->pair_.First(); } MapType &Map() noexcept { return this->pair_.Second(); } const MapType &Map() const noexcept { return this->pair_.Second(); } void InternalPut(sharpen::ByteBuffer key,sharpen::ByteBuffer value) { this->Map()[std::move(key)] = StoreItem{std::move(value)}; } void InternalDelete(sharpen::ByteBuffer key) { auto ite = this->Map().find(key); if(ite != this->Map().end()) { ite->second.Delete(); } else { this->Map().emplace(std::move(key),StoreItem{}); } } void InternalAction(sharpen::WriteBatch &batch) { for (auto begin = batch.Begin(),end = batch.End(); begin != end; ++begin) { if (begin->type_ == sharpen::WriteBatch::ActionType::Put) { this->InternalPut(std::move(begin->key_),std::move(begin->value_)); } else { this->InternalDelete(std::move(begin->key_)); } } batch.Clear(); } void InternalAction(const sharpen::WriteBatch &batch) { for (auto begin = batch.Begin(),end = batch.End(); begin != end;
key_,begin->value_); } else { this->InternalDelete(begin->key_); } } } public: enum class ExistStatus { Exist, Deleted, NotFound }; template<typename ..._Args,typename _Check = decltype(_Logger{std::declval<_Args>()...})> explicit InternalMemoryTable(_Args &&...args) :pair_(_Logger{std::forward<_Args>(args)...},MapType{}) {} InternalMemoryTable(Self &&other) noexcept = default; Self &operator=(Self &&other) noexcept { if(this != std::addressof(other)) { this->pair_ = std::move(other.pair_); } return *this; } ~InternalMemoryTable() noexcept = default; inline void Restore() { auto batchs = this->Logger().GetWriteBatchs(); for (auto begin = batchs.begin(),end = batchs.end(); begin != end; ++begin) { sharpen::WriteBatch &batch = *begin; this->InternalAction(batch); } } inline void Action(sharpen::WriteBatch &batch) { this->Logger().Log(batch); this->InternalAction(batch); } inline void Action(sharpen::WriteBatch &&batch) { this->Action(batch); } inline void Action(const sharpen::WriteBatch &batch) { this->Logger().Log(batch); this->InternalAction(batch); } inline void Put(sharpen::ByteBuffer key,sharpen::ByteBuffer value) { sharpen::WriteBatch batch; batch.Put(std::move(key),std::move(value)); this->Action(std::move(batch)); } inline void Delete(sharpen::ByteBuffer key) { sharpen::WriteBatch batch; batch.Delete(std::move(key)); this->Action(std::move(batch)); } void ClearLogs() { this->Logger().Clear(); } void RemoveLogs() { this->Logger().Remove(); } Self::ExistStatus Exist(const sharpen::ByteBuffer &key) const noexcept { auto ite = this->Map().find(key); if(ite == this->Map().end()) { return Self::ExistStatus::NotFound; } else if(ite->second.IsDeleted()) { return Self::ExistStatus::Deleted; } return Self::ExistStatus::Exist; } sharpen::ByteBuffer &Get(const sharpen::ByteBuffer &key) { auto &item = this->Map().at(key); if(item.IsDeleted()) { throw std::out_of_range("key doesn't exists"); } return item.Value(); } const sharpen::ByteBuffer &Get(const sharpen::ByteBuffer &key) const { auto &item = this->Map().at(key); if(item.deleteTag_) { throw std::out_of_range("key doesn't exists"); } return item.value_; } sharpen::ByteBuffer &operator[](const sharpen::ByteBuffer &key) { return this->Get(key); } const sharpen::ByteBuffer &operator[](const sharpen::ByteBuffer &key) const { return this->Get(key); } inline ConstIterator Begin() const noexcept { return this->Map().begin(); } inline ConstIterator End() const noexcept { return this->Map().end(); } }; template<typename _Logger> using MemoryTable = sharpen::InternalMemoryTable<_Logger>; } #endif
++begin) { if (begin->type_ == sharpen::WriteBatch::ActionType::Put) { this->InternalPut(begin->
function_block-random_span
[]
C++
Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
#include <askap_swcorrelator.h> #include <swcorrelator/BasicMonitor.h> #include <askap/AskapLogging.h> #include <askap/AskapError.h> #include <askap/AskapUtil.h> #include <utils/DelayEstimator.h> #include <fstream> ASKAP_LOGGER(logger, ".basicmonitor"); namespace askap { namespace swcorrelator { BasicMonitor::BasicMonitor() : itsLastHistPosition(-1), itsWrapped(false) {} boost::shared_ptr<IMonitor> BasicMonitor::setup(const LOFAR::ParameterSet &) { ASKAPLOG_INFO_STR(logger, "Setting up Basic Data Monitor"); boost::shared_ptr<BasicMonitor> result(new BasicMonitor); return result; } void BasicMonitor::initialise(const int nAnt, const int nBeam, const int nChan) { if (itsHistory.nelements() == 0) { const int nHistory = 620; ASKAPDEBUGASSERT(nAnt > 1); ASKAPDEBUGASSERT(nBeam > 0); ASKAPDEBUGASSERT(nChan > 0); const int nBaselines = nAnt * (nAnt - 1) / 2; itsLastHistPosition = -1; itsWrapped = false; itsHistory.resize(nHistory,nBeam,nBaselines); itsHistory.set(casa::Complex(0.,0.)); itsDelayHistory.resize(nHistory, nBeam, nBaselines); itsDelayHistory.set(0.); itsControlHistory.resize(nHistory, nBeam, nBaselines); itsControlHistory.set(0u); itsBATs.resize(nHistory); itsBATs.set(0); } ASKAPDEBUGASSERT(itsHistory.shape() == itsDelayHistory.shape()); ASKAPDEBUGASSERT(itsHistory.nrow() == itsBATs.nelements()); } void BasicMonitor::advanceHistoryCursor(const uint64_t bat) { if (itsLastHistPosition >= 0) { if (bat == itsBATs[itsLastHistPosition]) { return; } else if (bat < itsBATs[itsLastHistPosition]) { ASKAPLOG_DEBUG_STR(logger, "New BAT = "<<bat<<" is earlier than the last history item BAT="<< itsBATs[itsLastHistPosition]); } } ++itsLastHistPosition; if (itsLastHistPosition >= int(itsHistory.nrow())) { itsLastHistPosition = 0; itsWrapped = true; } ASKAPDEBUGASSERT(itsLastHistPosition >= 0); ASKAPDEBUGASSERT(itsLastHistPosition < int(itsBATs.nelements())); itsBATs[itsLastHistPosition] = bat; } void BasicMonitor::publish(const CorrProducts &buf) { advanceHistoryCursor(buf.itsBAT); { const std::string fname = "spc_beam" + utility::toString<int>(buf.itsBeam) + ".dat"; std::ofstream os(fname.c_str()); for (casa::uInt chan=0; chan < buf.itsVisibility.ncolumn(); ++chan) { os<<chan<<" "; for (casa::uInt baseline = 0; baseline < buf.itsVisibility.nrow(); ++baseline) { os<<abs(buf.itsVisibility(baseline,chan))<<" "<<arg(buf.itsVisibility(baseline,chan))/casa::C::pi*180.<<" "; } os<<std::endl; } } const casa::Vector<casa::Float> delays = estimateDelays(buf.itsVisibility); ASKAPLOG_DEBUG_STR(logger, "Beam "<<buf.itsBeam<<": delays (s) = "<<delays); ASKAPDEBUGASSERT(delays.nelements() == buf.itsVisibility.nrow()); if (buf.itsBeam >= int(itsHistory.ncolumn())) { ASKAPLOG_DEBUG_STR(logger, "Receive buffer corresponding to beam "<<buf.itsBeam<< " which exceeds the maximum number of beams "<<itsHistory.ncolumn()); return; } for (casa::uInt baseline = 0; baseline < buf.itsVisibility.nrow(); ++baseline) { itsDelayHistory(itsLastHistPosition, buf.itsBeam, baseline) = delays[baseline]; itsControlHistory(itsLastHistPosition, buf.itsBeam, baseline) = buf.itsControl[baseline]; casa::Complex temp(0.,0.); for (casa::uInt chan=0; chan < buf.itsVisibility.ncolumn(); ++chan) { temp += buf.itsVisibility(baseline,chan); } itsHistory(itsLastHistPosition,buf.itsBeam,baseline) = temp / float(buf.itsVisibility.ncolumn()); } } void BasicMonitor::finalise() { std::ofstream os("visplot.dat"); const int nHistory = int(itsBATs.nelements()); for (int i=0, curPos = itsWrapped ? itsLastHistPosition + 1 : 0; i<nHistory; ++i,++curPos) { if (curPos >= nHistory) { curPos = 0; if (!itsWrapped) { break; } } os<<itsBATs[curPos]<<" "; for (int beam=0; beam < int(itsHistory.ncolumn()); ++beam) { for (casa::uInt baseline = 0; baseline < itsHistory.nplane(); ++baseline) { os<<abs(itsHistory(curPos,beam,baseline))<<" "<<arg(itsHistory(curPos,beam,baseline))/casa::C::pi*180.<<" " <<itsDelayHistory(curPos,beam,baseline)*1e9<<" "; } } for (casa::uInt baseline = 0; baseline < itsHistory.nplane(); ++baseline) { os<<itsControlHistory(curPos,0,baseline)<<" "; } os<<std::endl; if (curPos == itsLastHistPosition) { break; } } } casa::Vector<casa::Float> BasicMonitor::estimateDelays(const casa::Matrix<casa::Complex> &vis) { casa::Vector<casa::Float> result(vis.nrow(),0.); if (vis.ncolumn() >= 2) { scimath::DelayEstimator de(1e6); for (casa::uInt row = 0; row < vis.nrow(); ++row) { result[row] = float(de.getDelay(vis.row(row))); } } return result; } } }
#include <askap_swcorrelator.h> #include <swcorrelator/BasicMonitor.h> #include <askap/AskapLogging.h> #include <askap/AskapError.h> #include <askap/AskapUtil.h> #include <utils/DelayEstimator.h> #include <fstream> ASKAP_LOGGER(logger, ".basicmonitor"); namespace askap { namespace swcorrelator { BasicMonitor::BasicMonitor() : itsLastHistPosition(-1), itsWrapped(false) {} boost::shared_ptr<IMonitor> BasicMonitor::setup(const LOFAR::ParameterSet &) { ASKAPLOG_INFO_STR(logger, "Setting up Basic Data Monitor"); boost::shared_ptr<BasicMonitor> result(new BasicMonitor); return result; } void BasicMonitor::initialise(const int nAnt, const int nBeam, const int nChan) { if (itsHistory.nelements() == 0) { const int nHistory = 620; ASKAPDEBUGASSERT(nAnt > 1); ASKAPDEBUGASSERT(nBeam > 0); ASKAPDEBUGASSERT(nChan > 0); const int nBaselines = nAnt * (nAnt - 1) / 2; itsLastHistPosition = -1; itsWrapped = false; itsHistory.resize(nHistory,nBeam,nBaselines); itsHistory.set(casa::Complex(0.,0.)); itsDelayHistory.resize(nHistory, nBeam, nBaselines); itsDelayHistory.set(0.); itsControlHistory.resize(nHistory, nBeam, nBaselines); itsControlHistory.set(0u); itsBATs.resize(nHistory); itsBATs.set(0); } ASKAPDEBUGASSERT(itsHistory.shape() == itsDelayHistory.shape()); ASKAPDEBUGASSERT(itsHistory.nrow() == itsBATs.nelements()); } void BasicMonitor::advanceHistoryCursor(const uint64_t bat) { if (itsLastHistPosition >= 0) { if (bat == itsBATs[itsLastHistPosition]) { return; } else if (bat < itsBATs[itsLastHistPosition]) { ASKAPLOG_DEBUG_STR(logger, "New BAT = "<<bat<<" is earlier than the last history item BAT="<< itsBATs[itsLastHistPosition]); } } ++itsLastHistPosition; if (itsLastHistPosition >= int(itsHistory.nrow())) { itsLastHistPosition = 0; itsWrapped = true; } ASKAPDEBUGASSERT(itsLastHistPosition >= 0); ASKAPDEBUGASSERT(itsLastHistPosition < int(itsBATs.nelements())); itsBATs[itsLastHistPosition] = bat; } void BasicMonitor::publish(const CorrProducts &buf) { advanceHistoryCursor(buf.itsBAT); { const std::string fname = "spc_beam" + utility::toString<int>(buf.itsBeam) + ".dat"; std::ofstream os(fname.c_str()); for (casa::uInt chan=0; chan < buf.itsVisibility.ncolumn(); ++chan) { os<<chan<<" "; for (casa::uInt baseline = 0; baseline < buf.itsVisibility.nrow(); ++baseline) { os<<abs(buf.itsVisibility(baseline,chan))<<" "<<arg(buf.itsVisibility(baseline,chan))/casa::C::pi*180.<<" "; } os<<std::endl; } } const casa::Vector<casa::Float> delays = estimateDelays(buf.itsVisibility); ASKAPLOG_DEBUG_STR(logger, "Beam "<<buf.itsBeam<<": delays (s) = "<<delays); ASKAPDEBUGASSERT(delays.nelements() == buf.itsVisibility.nrow()); if (buf.itsBeam >= int(itsHistory.ncolumn())) { ASKAPLOG_DEBUG_STR(logger, "Receive buffer corresponding to beam "<<buf.itsBeam<< " which exceeds the maximum number of beams "<<itsHistory.ncolumn()); return; } for (casa::uInt baseline = 0; baseline < buf.itsVisibility.nrow(); ++baseline) { itsDelayHistory(itsLastHistPosition, buf.itsBeam, baseline) = delays[baseline]; itsControlHistory(itsLastHistPosition, buf.itsBeam, baseline) = buf.itsControl[baseline]; casa::Complex temp(0.,0.); for (casa::uInt chan=0; chan < buf.itsVisibility.ncolumn(); ++chan) { temp += buf.itsVisibility(baseline,chan); } itsHistory(itsLastHistPosition,buf.itsBeam,baseline) = temp / float(buf.itsVisibility.ncolumn()); } } void BasicMonitor::finalise() { std::ofstream os("visplot.dat"); const int nHistory = int(itsBATs.nelements()); for (int i=0, curPos = itsWrapped ? itsLastHistPosition + 1 : 0; i<nHistory; ++i,++curPos) { if (curPos >= nHistory) { curPos = 0; if (!itsWrapped) { break; } } os<<itsBATs[curPos]<<" "; for (int beam=0; beam < int(itsHistory.ncolumn()); ++beam) { for (casa::uInt baseline = 0; baseline < itsHistory.nplane(); ++baseline) { os<<abs(itsHistory(curPos,beam,baseline))<<" "<<arg(itsHistory(curPos,beam,baseline))/casa::C::pi*180.<<" " <<itsDelayHistory(curPos,beam,baseline)*1e9<<" "; } } for (casa::uInt baseline = 0; baseline < itsHistory.nplane(); ++baseline) { os<<itsControlHistory(curPos,0,baseline)<<" "; } os<<std::endl; if (curPos == itsLastHistPosition) { break; } } }
} }
casa::Vector<casa::Float> BasicMonitor::estimateDelays(const casa::Matrix<casa::Complex> &vis) { casa::Vector<casa::Float> result(vis.nrow(),0.); if (vis.ncolumn() >= 2) { scimath::DelayEstimator de(1e6); for (casa::uInt row = 0; row < vis.nrow(); ++row) { result[row] = float(de.getDelay(vis.row(row))); } } return result; }
function_block-full_function
[ { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief a collection of data monitors\n\n/// @details This class is just a container of data monitors. It implements basic calls\n\n/// of the IMonitor interface and translates them to each monitor held in the container.\n\n/// @ingroup swcorrelator\n\nstruct DataMonitors : public IMonitor {\n\n /// @brief constructor, creates monitors using the factory and adds them to the container\n\n /// @param[in] parset parset file used (without the swcorrelator prefix)\n\n /// @note The list of monitors to create is specified by the \"monitors\" keyword.\n\n explicit DataMonitors(const LOFAR::ParameterSet &parset);\n\n \n\n /// @brief destructor, added to assist synchronisation\n\n ~DataMonitors();\n\n\n\n /// @brief initialise publishing\n\n /// @details Technically, this step is not required. But given the\n\n /// current design of the code it seems better to give a hint on the maximum\n\n /// possible number of antennas, beams and channels, e.g. to initialise caches.\n\n /// @param[in] nAnt maximum number of antennas\n\n /// @param[in] nBeam maximum number of beams\n\n /// @param[in] nChan maximum number of channels\n\n /// @note At the moment we envisage that this method would only be called once.\n\n /// Technically all this information could be extracted from the parset supplied\n\n /// in the setup method, but it seems handy to have each parameter extracted from\n\n /// the parset at a single place only. \n\n virtual void initialise(const int nAnt, const int nBeam, const int nChan);\n\n \n\n /// @brief Publish one buffer of data\n\n /// @details This method is called as soon as the new chunk of data is written out\n\n /// @param[in] buf products buffer\n\n /// @note the buffer is locked for the duration of execution of this method, different\n\n /// beams are published separately\n\n virtual void publish(const CorrProducts &buf);\n\n \n\n /// @brief finilaise publishing for the current integration\n\n /// @details This method is called when data corresponding to all beams are published.\n\n /// It is the place for operations which do not require the lock on the buffers\n\n /// (i.e. dumping the accumulated history to the file, etc).\n\n virtual void finalise();\n\n \n\nprivate:\n\n /// @brief name of the monitor\n\n /// @return the name of the monitor\n\n static std::string name() { return \"not_supposed_to_be_called\"; }\n\n \n\n /// @brief container of actual monitors\n\n /// @details We use vector because the most time-critical operation is the iteration over all\n\n /// elements. In addition, it seems unlikely that we have many monitors co-existing at the same time.\n\n std::vector<boost::shared_ptr<IMonitor> > itsMonitors;\n\n\n\n /// @brief mutex to synchronise access to data monitors\n\n mutable boost::mutex itsMonitorsMutex;\n\n};\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.h", "rank": 0, "score": 305549.81501957594 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief data monitored externally\n\n/// @details This is a basic structure containing a number of monitoring points\n\n/// such as amplitudes, delays or phases. A structure of this type is passed to \n\n/// a registered call back method at every new correlation cycle. Although we \n\n/// could've passed the CorrProducts structure which is used in the generic monitoring\n\n/// interface, an adapter seems worth while to avoid a tight coupling between epics part\n\n/// and the rest of the software correlator. In addition, we can latter add other information\n\n/// to the type which is not present in the CorrProducts structure.\n\n/// @ingroup corrinterfaces\n\nstruct MonitoringData : private boost::noncopyable {\n\n /// @brief individual baselines\n\n enum Baseline {\n\n BASELINE_12 = 0,\n\n BASELINE_23,\n\n BASELINE_13\n\n };\n\n\n\n /// @brief constructor, initialises the beam number and resizes the vectors\n\n /// @param[in] beam beam index [0..nBeam-1]\n\n explicit MonitoringData(const int beam);\n\n \n\n /// @brief obtain UT date/time string\n\n /// @return the date/time corresponding to itsTime as a string (to simplify reporting)\n\n std::string timeString() const;\n\n \n\n /// @brief the beam number related to this structure\n\n /// @return the beam number\n\n int beam() const; \n\n \n\n /// @brief obtain amplitude for a given baseline \n\n /// @param[in] baseline baseline index\n\n /// @return amplitude in raw counts\n\n float amplitude(const Baseline baseline) const;\n\n\n\n /// @brief obtain phase for a given baseline \n\n /// @param[in] baseline baseline index\n\n /// @return phase in degrees\n\n float phase(const Baseline baseline) const;\n\n\n\n /// @brief obtain fitted delay for a given baseline \n\n /// @param[in] baseline baseline index\n\n /// @return delay in nanoseconds\n\n double delay(const Baseline baseline) const;\n\n\n\n /// @brief check whether a particular baseline has valid data\n\n /// @param[in] baseline baseline index\n\n /// @return true, if the data corresponding to the given baseline are valid\n\n bool isValid(const Baseline baseline) const;\n\n\n\n /// @brief obtain time\n\n /// @return UT epoch in days since 0 MJD\n\n double time() const;\n\n \n\n // monitoring information for the last correlated data\n\n \n\n /// @brief the beam this structure corresponds to [0..nBeam-1]\n\n int itsBeam;\n\n\n\n /// @brief averaged amplitudes for all 3 baselines in raw counts\n\n /// @details This vector is supposed to have 3 elements at all times. The order\n\n /// of baselines is 1-2,2-3,1-3 (1-based indices).\n\n std::vector<float> itsAmplitudes;\n\n \n\n /// @brief averaged phases for all 3 baselines in degrees\n\n /// @details This vector is supposed to have 3 elements at all times. The order\n\n /// of baselines is 1-2,2-3,1-3 (1-based indices).\n\n std::vector<float> itsPhases;\n\n \n\n /// @brief delays for all 3 baselines in nanoseconds\n\n /// @details This vector is supposed to have 3 elements at all times. The order\n\n /// of baselines is 1-2,2-3,1-3 (1-based indices).\n\n std::vector<double> itsDelays;\n\n \n\n /// @brief flagging information\n\n /// @details This vector is supposed to have 3 elements at all times. True for a \n\n /// particular baseline means that the corresponding amplitudes, phases and delays\n\n /// are not valid. The order of baselines is 1-2,2-3,1-3 (1-based indices).\n\n std::vector<bool> itsFlags;\n\n \n\n /// @brief UT time in days since 0 MJD\n\n double itsTime; \n\n};\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.h", "rank": 1, "score": 291214.9235100251 }, { "content": "/// @brief basic on-the-fly monitor dumping data into an ascii file\n\n/// @details This implementation of the data monitor dumps delay and\n\n/// visibility history into ascii files for on-the-fly monitoring along\n\n/// with the latest spectra for each beam\n\n/// @ingroup swcorrelator\n\nclass BasicMonitor : public IMonitor {\n\npublic:\n\n /// @brief constructor\n\n BasicMonitor();\n\n\n\n /// @brief create and configure the monitor \n\n /// @details\n\n /// @param[in] parset parset with parameters (without the swcorrelator prefix)\n\n /// @return shared pointer to the monitor\n\n static boost::shared_ptr<IMonitor> setup(const LOFAR::ParameterSet &parset);\n\n \n\n /// @brief name of the monitor\n\n /// @return the name of the monitor\n\n static std::string name() { return \"basic\"; }\n\n \n\n /// @brief initialise publishing\n\n /// @details Technically, this step is not required. But given the\n\n /// current design of the code it seems better to give a hint on the maximum\n\n /// possible number of antennas, beams and channels, e.g. to initialise caches.\n\n /// @param[in] nAnt maximum number of antennas\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 2, "score": 267982.62338736525 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief generic interface for an on-the-fly monitor\n\n/// @details Possible implementations could include dumping some history\n\n/// into ascii files or providing monitoring via epics.\n\n/// @ingroup swcorrelator\n\nstruct IMonitor : private boost::noncopyable {\n\n \n\n /// @brief shared pointer type\n\n typedef boost::shared_ptr<IMonitor> ShPtr;\n\n \n\n /// @brief virtual destructor to keep the compiler happy\n\n virtual ~IMonitor() {};\n\n \n\n /// @brief name of the monitor\n\n /// @return the name of the monitor\n\n static std::string name() { return \"undefined\"; }\n\n \n\n /// @brief initialise publishing\n\n /// @details Technically, this step is not required. But given the\n\n /// current design of the code it seems better to give a hint on the maximum\n\n /// possible number of antennas, beams and channels, e.g. to initialise caches.\n\n /// @param[in] nAnt maximum number of antennas\n\n /// @param[in] nBeam maximum number of beams\n\n /// @param[in] nChan maximum number of channels\n\n /// @note At the moment we envisage that this method would only be called once.\n\n /// Technically all this information could be extracted from the parset supplied\n\n /// in the setup method, but it seems handy to have each parameter extracted from\n\n /// the parset at a single place only. \n\n virtual void initialise(const int nAnt, const int nBeam, const int nChan) = 0;\n\n \n\n /// @brief Publish one buffer of data\n\n /// @details This method is called as soon as the new chunk of data is written out\n\n /// @param[in] buf products buffer\n\n /// @note the buffer is locked for the duration of execution of this method, different\n\n /// beams are published separately\n\n virtual void publish(const CorrProducts &buf) = 0;\n\n \n\n /// @brief finilaise publishing for the current integration\n\n /// @details This method is called when data corresponding to all beams are published.\n\n /// It is the place for operations which do not require the lock on the buffers\n\n /// (i.e. dumping the accumulated history to the file, etc).\n\n virtual void finalise() = 0;\n\n};\n\n \n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/IMonitor.h", "rank": 3, "score": 249246.8077438395 }, { "content": " uint64_t bat; // BAT of first sample\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BufferHeader.h", "rank": 4, "score": 247907.26075640976 }, { "content": " uint32_t beam; // beam number 1-18\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BufferHeader.h", "rank": 5, "score": 247863.44428795762 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief header preceding each data chunk for all buffers\n\n/// @details This header preceds any actual data in the stream.\n\n/// @ingroup swcorrelator\n\nstruct BufferHeader {\n\n uint64_t bat; // BAT of first sample\n\n uint32_t antenna; // antenna number\n\n uint32_t freqId; // currently card number 1-16. If we go to more DSPs will be 1-64 (same as FreqId field is FITs acm capture)\n\n uint32_t beam; // beam number 1-18\n\n uint32_t frame; // frame number of first sample (from digitiser packet, see below)\n\n uint32_t control; // user defined value, can be hooked up thru epics to send control via OSL script or gui to software correlator if necessary\n\n uint32_t length; // length of data (should always be 4194304 (num ddr pages * bytes per beam) for 16MHz\n\n};\n\n\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BufferHeader.h", "rank": 6, "score": 246400.306509534 }, { "content": " /// @param[in] nBeam maximum number of beams\n\n /// @param[in] nChan maximum number of channels\n\n /// @note At the moment we envisage that this method would only be called once.\n\n /// Technically all this information could be extracted from the parset supplied\n\n /// in the setup method, but it seems handy to have each parameter extracted from\n\n /// the parset at a single place only. \n\n virtual void initialise(const int nAnt, const int nBeam, const int nChan);\n\n \n\n /// @brief Publish one buffer of data\n\n /// @details This method is called as soon as the new chunk of data is written out\n\n /// @param[in] buf products buffer\n\n /// @note the buffer is locked for the duration of execution of this method, different\n\n /// beams are published separately\n\n virtual void publish(const CorrProducts &buf);\n\n \n\n /// @brief finilaise publishing for the current integration\n\n /// @details This method is called when data corresponding to all beams are published.\n\n /// It is the place for operations which do not require the lock on the buffers\n\n /// (i.e. dumping the accumulated history to the file, etc).\n\n virtual void finalise();\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 7, "score": 204867.445135815 }, { "content": "#include <casacore/casa/Arrays/Vector.h>\n\n\n\n// other 3rd party\n\n#include <Common/ParameterSet.h>\n\n#include <inttypes.h>\n\n\n\nnamespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief basic on-the-fly monitor dumping data into an ascii file\n\n/// @details This implementation of the data monitor dumps delay and\n\n/// visibility history into ascii files for on-the-fly monitoring along\n\n/// with the latest spectra for each beam\n\n/// @ingroup swcorrelator\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 8, "score": 204864.0248015621 }, { "content": "\n\n /// @brief history of user defined control keywords\n\n casa::Cube<uint32_t> itsControlHistory;\n\n \n\n /// @brief BATs for the history items\n\n casa::Vector<uint64_t> itsBATs;\n\n \n\n /// @brief last position in the history (circular buffers)\n\n /// @details negative value for an uninitialised history\n\n int itsLastHistPosition;\n\n \n\n /// @brief true if the history buffers were wrapped\n\n bool itsWrapped;\n\n};\n\n\n\n} // namespace swcorrelator\n\n\n\n} // namespace askap\n\n\n\n#endif // #ifndef ASKAP_SWCORRELATOR_BASIC_MONITOR_H\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 9, "score": 204863.29141174912 }, { "content": "\n\n /// @brief helper method to get delays\n\n /// @details\n\n /// @param[in] vis visibility matrix (rows are baselines, columns are channels)\n\n /// @return delays in seconds for each baseline\n\n /// @note the routine assumes 1 MHz channel spacing and will not work for a very quick wrap\n\n static casa::Vector<casa::Float> estimateDelays(const casa::Matrix<casa::Complex> &vis);\n\n\n\nprotected:\n\n /// @brief advance history if necessary\n\n /// @details Advances the cursor in the history list if the new bat is different from the one \n\n /// stored during the previous step (unless it is a first step)\n\n /// @param[in] bat new BAT \n\n void advanceHistoryCursor(const uint64_t bat);\n\nprivate:\n\n /// @brief history of visibilities\n\n casa::Cube<casa::Complex> itsHistory;\n\n \n\n /// @brief history of delays\n\n casa::Cube<casa::Float> itsDelayHistory;\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 10, "score": 204833.70864316673 }, { "content": "/// This program is distributed in the hope that it will be useful,\n\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\n/// GNU General Public License for more details.\n\n///\n\n/// You should have received a copy of the GNU General Public License\n\n/// along with this program; if not, write to the Free Software\n\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n///\n\n/// @author Max Voronkov <[email protected]>\n\n\n\n#ifndef ASKAP_SWCORRELATOR_BASIC_MONITOR_H\n\n#define ASKAP_SWCORRELATOR_BASIC_MONITOR_H\n\n\n\n// own includes\n\n#include <swcorrelator/IMonitor.h>\n\n\n\n// casa includes\n\n#include <casacore/casa/Arrays/Matrix.h>\n\n#include <casacore/casa/Arrays/Cube.h>\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 11, "score": 204832.74873002138 }, { "content": "/// @file \n\n///\n\n/// @brief basic on-the-fly monitor dumping data into an ascii file\n\n/// @details This implementation of the data monitor dumps delay and\n\n/// visibility history into ascii files for on-the-fly monitoring along\n\n/// with the latest spectra for each beam\n\n///\n\n/// @copyright (c) 2007 CSIRO\n\n/// Australia Telescope National Facility (ATNF)\n\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n\n/// PO Box 76, Epping NSW 1710, Australia\n\n/// [email protected]\n\n///\n\n/// This file is part of the ASKAP software distribution.\n\n///\n\n/// The ASKAP software distribution is free software: you can redistribute it\n\n/// and/or modify it under the terms of the GNU General Public License as\n\n/// published by the Free Software Foundation; either version 2 of the License,\n\n/// or (at your option) any later version.\n\n///\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BasicMonitor.h", "rank": 12, "score": 204832.5316110967 }, { "content": "/// @param[in] nBeam maximum number of beams\n\n/// @param[in] nChan maximum number of channels\n\n/// @note At the moment we envisage that this method would only be called once.\n\n/// Technically all this information could be extracted from the parset supplied\n\n/// in the setup method, but it seems handy to have each parameter extracted from\n\n/// the parset at a single place only. \n\nvoid DataMonitors::initialise(const int nAnt, const int nBeam, const int nChan)\n\n{\n\n boost::lock_guard<boost::mutex> lock(itsMonitorsMutex);\n\n for (std::vector<boost::shared_ptr<IMonitor> >::const_iterator ci = itsMonitors.begin();\n\n ci != itsMonitors.end(); ++ci) {\n\n ASKAPDEBUGASSERT(*ci);\n\n (*ci)->initialise(nAnt,nBeam,nChan);\n\n }\n\n}\n\n \n\n/// @brief Publish one buffer of data\n\n/// @details This method is called as soon as the new chunk of data is written out\n\n/// @param[in] buf products buffer\n\n/// @note the buffer is locked for the duration of execution of this method, different\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 25, "score": 201310.01312149307 }, { "content": "/// beams are published separately\n\nvoid DataMonitors::publish(const CorrProducts &buf)\n\n{\n\n boost::lock_guard<boost::mutex> lock(itsMonitorsMutex);\n\n for (std::vector<boost::shared_ptr<IMonitor> >::const_iterator ci = itsMonitors.begin();\n\n ci != itsMonitors.end(); ++ci) {\n\n ASKAPDEBUGASSERT(*ci);\n\n (*ci)->publish(buf);\n\n }\n\n}\n\n \n\n/// @brief finilaise publishing for the current integration\n\n/// @details This method is called when data corresponding to all beams are published.\n\n/// It is the place for operations which do not require the lock on the buffers\n\n/// (i.e. dumping the accumulated history to the file, etc).\n\nvoid DataMonitors::finalise()\n\n{\n\n boost::lock_guard<boost::mutex> lock(itsMonitorsMutex);\n\n for (std::vector<boost::shared_ptr<IMonitor> >::const_iterator ci = itsMonitors.begin();\n\n ci != itsMonitors.end(); ++ci) {\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 26, "score": 201289.15958581647 }, { "content": "/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\n/// GNU General Public License for more details.\n\n///\n\n/// You should have received a copy of the GNU General Public License\n\n/// along with this program; if not, write to the Free Software\n\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n///\n\n/// @author Max Voronkov <[email protected]>\n\n\n\n#include <askap_swcorrelator.h>\n\n#include <askap/AskapError.h>\n\n#include <askap/AskapLogging.h>\n\n\n\n#include <swcorrelator/DataMonitors.h>\n\n#include <swcorrelator/MonitorFactory.h>\n\n\n\nASKAP_LOGGER(logger, \".datamonitors\");\n\n\n\nnamespace askap {\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 27, "score": 201285.3053264966 }, { "content": "\n\nnamespace swcorrelator {\n\n\n\n/// @brief constructor, creates monitors using the factory and adds them to the container\n\n/// @param[in] parset parset file used (without the swcorrelator prefix)\n\n/// @note The list of monitors to create is specified by the \"monitors\" keyword.\n\nDataMonitors::DataMonitors(const LOFAR::ParameterSet &parset)\n\n{\n\n const std::vector<std::string> monitors = parset.getStringVector(\"monitors\",std::vector<std::string>(1,\"basic\"));\n\n if (monitors.size() == 0) {\n\n ASKAPLOG_INFO_STR(logger, \"No on-the-fly data monitors will be created\");\n\n } else {\n\n itsMonitors.reserve(monitors.size());\n\n ASKAPLOG_INFO_STR(logger, \"Setting up data monitors from the list: \"<<monitors);\n\n for (std::vector<std::string>::const_iterator ci = monitors.begin(); ci != monitors.end(); ++ci) {\n\n const boost::shared_ptr<IMonitor> curMonitor = MonitorFactory::make(*ci, parset);\n\n ASKAPCHECK(curMonitor, \"Failed to create data monitor name = `\"<<*ci<<\"`\");\n\n itsMonitors.push_back(curMonitor);\n\n }\n\n }\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 28, "score": 201276.92211566388 }, { "content": "}\n\n\n\n// @brief destructor, added to assist synchronisation\n\nDataMonitors::~DataMonitors()\n\n{\n\n boost::lock_guard<boost::mutex> lock(itsMonitorsMutex);\n\n for (std::vector<boost::shared_ptr<IMonitor> >::iterator it = itsMonitors.begin();\n\n it != itsMonitors.end(); ++it) {\n\n ASKAPDEBUGASSERT(*it);\n\n it->reset();\n\n }\n\n itsMonitors.resize(0);\n\n}\n\n\n\n \n\n/// @brief initialise publishing\n\n/// @details Technically, this step is not required. But given the\n\n/// current design of the code it seems better to give a hint on the maximum\n\n/// possible number of antennas, beams and channels, e.g. to initialise caches.\n\n/// @param[in] nAnt maximum number of antennas\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 29, "score": 201273.78919691162 }, { "content": "/// @file \n\n///\n\n/// @brief a collection of data monitors\n\n/// @details This class is just a container of data monitors. It implements basic calls\n\n/// of the IMonitor interface and translates them to each monitor held in the container.\n\n///\n\n/// @copyright (c) 2007 CSIRO\n\n/// Australia Telescope National Facility (ATNF)\n\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n\n/// PO Box 76, Epping NSW 1710, Australia\n\n/// [email protected]\n\n///\n\n/// This file is part of the ASKAP software distribution.\n\n///\n\n/// The ASKAP software distribution is free software: you can redistribute it\n\n/// and/or modify it under the terms of the GNU General Public License as\n\n/// published by the Free Software Foundation; either version 2 of the License,\n\n/// or (at your option) any later version.\n\n///\n\n/// This program is distributed in the hope that it will be useful,\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 30, "score": 201264.99690795044 }, { "content": " ASKAPDEBUGASSERT(*ci);\n\n (*ci)->finalise();\n\n }\n\n}\n\n\n\n} // namespace swcorrelator\n\n\n\n} // namespace askap\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/DataMonitors.cc", "rank": 31, "score": 201260.77138981773 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief generic interface for sink of the correlation products\n\n/// @details One of the possible implementations is the MS writer\n\n/// @ingroup swcorrelator\n\nstruct ISink : private boost::noncopyable {\n\n /// @brief virtual destructor to keep the compiler happy\n\n virtual ~ISink() {};\n\n \n\n /// @brief calculate uvw for the given buffer\n\n /// @param[in] buf products buffer\n\n /// @note The calculation is bypassed if itsUVWValid flag is already set in the buffer\n\n /// @return time epoch corresponding to the BAT of the buffer\n\n virtual casa::MEpoch calculateUVW(CorrProducts &buf) const = 0;\n\n \n\n /// @brief write one buffer to the measurement set\n\n /// @details Current fieldID and dataDescID are assumed\n\n /// @param[in] buf products buffer\n\n /// @note This method could've received a const reference to the buffer. However, more\n\n /// workarounds would be required with casa arrays, so we don't bother doing this at the moment.\n\n /// In addition, we could call calculateUVW inside this method (but we still need an option to\n\n /// calculate uvw's ahead of writing the buffer if we implement some form of delay tracking).\n\n virtual void write(CorrProducts &buf) = 0;\n\n};\n\n \n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/ISink.h", "rank": 32, "score": 188726.42404934886 }, { "content": "\n\nnamespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief constructor, initialises the beam number and resizes the vectors\n\n/// @param[in] beam beam index [0..nBeam-1]\n\nMonitoringData::MonitoringData(const int beam) : itsBeam(beam), itsAmplitudes(3,0.),\n\n itsPhases(3,0.), itsDelays(3,0.), itsFlags(3,true), itsTime(0.) {}\n\n\n\n/// @brief obtain UT date/time string\n\n/// @return the date/time corresponding to itsTime as a string (to simplify reporting)\n\nstd::string MonitoringData::timeString() const\n\n{\n\n const casa::MVEpoch epoch(itsTime);\n\n std::ostringstream os;\n\n epoch.print(os);\n\n return os.str();\n\n}\n\n\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.cc", "rank": 33, "score": 187760.1569016535 }, { "content": "/// @brief check whether a particular baseline has valid data\n\n/// @param[in] baseline baseline index\n\n/// @return true, if the data corresponding to the given baseline are valid\n\nbool MonitoringData::isValid(const Baseline baseline) const\n\n{\n\n const int bl = int(baseline);\n\n ASKAPDEBUGASSERT(bl >= 0);\n\n ASKAPDEBUGASSERT(bl < int(itsFlags.size()));\n\n return !itsFlags[bl];\n\n}\n\n\n\n/// @brief obtain time\n\n/// @return UT epoch in days since 0 MJD\n\ndouble MonitoringData::time() const\n\n{\n\n return itsTime;\n\n}\n\n\n\n} // namespace swcorrelator\n\n\n\n} // namespace askap\n\n\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.cc", "rank": 34, "score": 187752.82591506373 }, { "content": "/// @brief the beam number related to this structure\n\n/// @return the beam number\n\nint MonitoringData::beam() const\n\n{\n\n return itsBeam;\n\n}\n\n\n\n/// @brief obtain amplitude for a given baseline \n\n/// @param[in] baseline baseline index\n\n/// @return amplitude in raw counts\n\nfloat MonitoringData::amplitude(const Baseline baseline) const\n\n{\n\n const int bl = int(baseline);\n\n ASKAPDEBUGASSERT(bl >= 0);\n\n ASKAPDEBUGASSERT(bl < int(itsAmplitudes.size()));\n\n return itsAmplitudes[bl];\n\n}\n\n\n\n/// @brief obtain phase for a given baseline \n\n/// @param[in] baseline baseline\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.cc", "rank": 35, "score": 187738.46084817822 }, { "content": "/// @return phase in degrees \n\nfloat MonitoringData::phase(const Baseline baseline) const\n\n{\n\n const int bl = int(baseline);\n\n ASKAPDEBUGASSERT(bl >= 0);\n\n ASKAPDEBUGASSERT(bl < int(itsPhases.size()));\n\n return itsPhases[bl];\n\n}\n\n\n\n/// @brief obtain fitted delay for a given baseline \n\n/// @param[in] baseline baseline index \n\n/// @return delay in nanoseconds\n\ndouble MonitoringData::delay(const Baseline baseline) const\n\n{\n\n const int bl = int(baseline);\n\n ASKAPDEBUGASSERT(bl >= 0);\n\n ASKAPDEBUGASSERT(bl < int(itsDelays.size()));\n\n return itsDelays[bl];\n\n}\n\n\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.cc", "rank": 36, "score": 187732.022651667 }, { "content": "/// @file \n\n///\n\n/// @brief data monitored externally\n\n/// @details This is a basic structure containing a number of monitoring points\n\n/// such as amplitudes, delays or phases. A structure of this type is passed to \n\n/// a registered call back method at every new correlation cycle. Although we \n\n/// could've passed the CorrProducts structure which is used in the generic monitoring\n\n/// interface, an adapter seems worth while to avoid a tight coupling between epics part\n\n/// and the rest of the software correlator. In addition, we can latter add other information\n\n/// to the type which is not present in the CorrProducts structure.\n\n///\n\n/// @copyright (c) 2007 CSIRO\n\n/// Australia Telescope National Facility (ATNF)\n\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n\n/// PO Box 76, Epping NSW 1710, Australia\n\n/// [email protected]\n\n///\n\n/// This file is part of the ASKAP software distribution.\n\n///\n\n/// The ASKAP software distribution is free software: you can redistribute it\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.cc", "rank": 37, "score": 187729.82266914644 }, { "content": "/// and/or modify it under the terms of the GNU General Public License as\n\n/// published by the Free Software Foundation; either version 2 of the License,\n\n/// or (at your option) any later version.\n\n///\n\n/// This program is distributed in the hope that it will be useful,\n\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\n/// GNU General Public License for more details.\n\n///\n\n/// You should have received a copy of the GNU General Public License\n\n/// along with this program; if not, write to the Free Software\n\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n///\n\n/// @author Max Voronkov <[email protected]>\n\n\n\n#include <corrinterfaces/MonitoringData.h>\n\n#include <askap/AskapError.h>\n\n#include <casacore/casa/Quanta/MVEpoch.h>\n\n\n\n#include <sstream>\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/MonitoringData.cc", "rank": 38, "score": 187721.2420092597 }, { "content": "#!/usr/bin/env python\n\n\n\nimport math\n\nfrom numpy import *\n\n\n\ndef getInputParams(infilename, prefix):\n\n paramlist = {}\n\n infile = file(infilename,'rU')\n\n lines = infile.readlines()\n\n for line in lines:\n\n if(line[:line.find('.')+1]==prefix):\n\n key = line.split('=')[0][line.find('.')+1:]\n\n val = line.split('=')[1]\n\n paramlist[key.strip()] = val.strip()\n\n return paramlist\n\n\n\ndef getParamValue(dict, param, default):\n\n if(not dict.has_key(param)):\n\n return default\n\n val = dict[param]\n\n return val \n\n\n\ndef getParamArray(dict, param, default):\n\n if(not dict.has_key(param)):\n\n return default\n\n val = dict[param]\n\n if(val[0]!='['):\n\n return default\n\n if(val[-1]!=']'):\n\n return default\n\n return array(val.replace('[','').replace(']','').split(','))\n\n\n", "file_path": "Code/Components/Analysis/data/current/askap/analysis/data/parsets.py", "rank": 39, "score": 187547.72504613595 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief Writing thread of the MS filler\n\n/// @details This class holds a shared pointer to the main filler and can call\n\n/// its methods to get data and to synchronise.\n\n/// @ingroup swcorrelator\n\nstruct FillerWorker {\n\n\n\n /// @brief constructor, pass the shared pointer to the filler\n\n FillerWorker(const boost::shared_ptr<CorrFiller> &filler);\n\n\n\n /// @brief entry point for the parallel thread\n\n void operator()();\n\n\n\nprivate:\n\n boost::shared_ptr<CorrFiller> itsFiller; \n\n};\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/FillerWorker.h", "rank": 40, "score": 186912.22638827033 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief Thread which manages a single data stream connection\n\n/// @details This class is initialised with two shared pointers, one to the socket \n\n/// corresponding to one input data stream and another corresponding to the buffer\n\n/// manager. Each instance (executed as a separate thread), obtains a buffer from \n\n/// the manager, fills it with new data and de-allocates it. The correlator thread\n\n/// is responsible for further processing when sufficient data are accumulated.\n\n/// @ingroup swcorrelator\n\nstruct StreamConnection {\n\n\n\n /// @brief constructor\n\n /// @details\n\n /// @param[in] socket shared pointer to the socket corresponding to this connection\n\n /// @param[in] bm shared pointer to the buffer manager\n\n StreamConnection(const boost::shared_ptr<boost::asio::ip::tcp::socket> &socket,\n\n const boost::shared_ptr<BufferManager> &bm);\n\n \n\n /// @brief parallel thread\n\n /// @details This is the main entry point to the code executed in a parallel thread\n\n void operator()();\n\n \n\nprivate:\n\n /// @details shared pointer to the socket corresponding connection managed by this instance\n\n boost::shared_ptr<boost::asio::ip::tcp::socket> itsSocket;\n\n \n\n /// @brief buffer manager\n\n boost::shared_ptr<BufferManager> itsBufferManager;\n\n};\n\n\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/StreamConnection.h", "rank": 41, "score": 186912.22638827033 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief Thread which does correlation\n\n/// @details This class holds shared pointers to the filler and the buffer\n\n/// manager. The parallel thread extracts data corresponding to all three \n\n/// baselines, some spectral channel and beam, correlates them and passes\n\n/// to the filler for writing. The filler and buffer manager manage \n\n/// synchronisation.\n\n/// @ingroup swcorrelator\n\nstruct CorrWorker {\n\n\n\n /// @brief constructor\n\n /// @details \n\n /// @param[in] filler shared pointer to a filler\n\n /// @param[in] bm shared pointer to a buffer manager\n\n CorrWorker(const boost::shared_ptr<CorrFiller> &filler,\n\n const boost::shared_ptr<BufferManager> &bm);\n\n\n\n /// @brief entry point for the parallel thread\n\n void operator()();\n\n \n\nprivate:\n\n /// @brief filler\n\n boost::shared_ptr<CorrFiller> itsFiller;\n\n /// @brief buffer manager\n\n boost::shared_ptr<BufferManager> itsBufferManager; \n\n};\n\n\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/CorrWorker.h", "rank": 42, "score": 186912.22638827033 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief Thread which just dumps the data into binary file\n\n/// @details This class holds shared pointer to the buffer\n\n/// manager. The parallel thread extracts data when a new buffer is ready\n\n/// and then dumps the content into a file. This is an anternative to the\n\n/// correlation thread and they shouldn't be launched together (or there \n\n/// will be a data race).\n\n/// @ingroup swcorrelator\n\nstruct CaptureWorker {\n\n\n\n /// @brief constructor\n\n /// @details \n\n /// @param[in] bm shared pointer to a buffer manager\n\n /// @param[in] statsOnly if true, only statistics will be stored, not the\n\n /// actual data (and the same output file will be reused for different integrations)\n\n CaptureWorker(const boost::shared_ptr<BufferManager> &bm, const bool statsOnly = false);\n\n\n\n /// @brief entry point for the parallel thread\n\n void operator()();\n\n \n\n /// @brief method to simplify reading the file\n\n /// @details It allows to encapsulate all low-level file \n\n /// operations in the same file.\n\n /// @param[in] fname file name\n\n /// @return a vector with data\n\n static std::vector<std::complex<float> > read(const std::string &fname);\n\n \n\nprivate:\n\n /// @brief buffer manager\n\n boost::shared_ptr<BufferManager> itsBufferManager; \n\n \n\n /// @brief if true, only distribution function is to be written\n\n bool itsStatsOnly;\n\n \n\n /// @brief output stream to store time series for statistics\n\n /// @details Full flexibility is not supported, antenna/channel/beam selection is hard coded\n\n static std::ofstream theirOStream;\n\n \n\n /// @brief BAT time of the start, used in conjunction with the stream defined above\n\n static uint64_t theirStartBAT;\n\n};\n\n\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/CaptureWorker.h", "rank": 43, "score": 186912.22638827033 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief Final products of correlation\n\n/// @details This class encapsulates the data, which is the final product of correlation, i.e\n\n/// visibilities for all spectral channels and baselines, flagging information and, BAT and uvw.\n\n/// @ingroup swcorrelator\n\nstruct CorrProducts : private boost::noncopyable {\n\n // baselines are hardcoded at the moment in the order 1-2, 2-3 and 1-3\n\n \n\n /// @brief constructor \n\n /// @param[in] nchan number of channels (cards)\n\n /// @param[in] beam beam number corresponding to this buffer\n\n /// @param[in] nant number of antennas\n\n CorrProducts(const int nchan, const int beam, const int nant = 3);\n\n \n\n /// @brief initialise the buffer for a given beam and bat\n\n /// @details\n\n /// @param[in] bat time\n\n void init(const uint64_t bat);\n\n \n\n /// @brief obtain the number of antennas\n\n /// @return number of antennas handled by this buffer\n\n casa::uInt nAnt() const;\n\n \n\n /// @brief obtain the number of baselines\n\n /// @return number of baselines handled by this buffer\n\n casa::uInt nBaseline() const;\n\n \n\n /// @brief baseline index for a pair of antennas\n\n /// @details For more than 3 antennas mapping between antennas and baselines \n\n /// is handy to implement inside this method\n\n /// @param[in] first index of the first antenna (0..nant-1)\n\n /// @param[in] second index of the second antenna (0..nant-1)\n\n /// @return baseline index (0..(nant*(nant-1)/2)-1)\n\n /// @note an exception is thrown if there is no matching baseline (i.e. if first >= second)\n\n static int baseline(const int first, const int second);\n\n \n\n /// @brief index of the first antenna for a given baseline\n\n /// @details It is handy to encapsulate mapping between baseline and antenna\n\n /// indices.\n\n /// @param[in] baseline baseline index (0..(nant*(nant-1)/2-1))\n\n /// @return index of the first antenna\n\n static int first(const int baseline);\n\n\n\n /// @brief index of the second antenna for a given baseline\n\n /// @details It is handy to encapsulate mapping between baseline and antenna\n\n /// indices.\n\n /// @param[in] baseline baseline index (0..(nant*(nant-1)/2-1))\n\n /// @return index of the second antenna\n\n static int second(const int baseline);\n\n \n\n \n\n /// @brief visibility buffer (dimensions are baseline and channel)\n\n casa::Matrix<casa::Complex> itsVisibility; \n\n \n\n /// @brief flagging information (dimensions are baseline and channel)\n\n casa::Matrix<casa::Bool> itsFlag;\n\n \n\n /// @brief beam index (negative value means that this buffer is not valid)\n\n int itsBeam;\n\n \n\n /// @brief time\n\n uint64_t itsBAT;\n\n \n\n /// @brief baseline spacings for all 3 baselines (rows are baselines)\n\n casa::Matrix<double> itsUVW;\n\n \n\n /// @brief delay vector for all 3 baselines\n\n /// @details We can't use W from itsUVW because it is in J2000 rather than JTRUE\n\n casa::Vector<double> itsDelays;\n\n \n\n /// @brief flag that uvw matrix and delay vector are filled with valid info\n\n bool itsUVWValid;\n\n\n\n /// @brief user defined control words for antennas 1,2 and 3\n\n casa::Vector<uint32_t> itsControl;\n\n};\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/CorrProducts.h", "rank": 44, "score": 186912.22638827033 }, { "content": "namespace askap {\n\n\n\n/// @details The profile package is used to accumulate statistics\n\n/// (e.g. to produce a pie chart to investigate where processing time goes)\n\n/// This class represent a data structure which is accumulated for every\n\n/// selected method.\n\n/// @ingroup profile\n\nstruct ProfileData {\n\n /// @brief default constructor\n\n /// @details Initialises the node with default values of zero execution time and\n\n /// zero number of calls\n\n ProfileData();\n\n \n\n /// @brief constructor corresponding to the first call\n\n /// @details This version initialises the number of calls to one and the times to\n\n /// the given execution times of the first call\n\n /// @param[in] time execution time for the first call\n\n explicit ProfileData(const double time);\n\n\n\n // access to the stats\n\n /// @return number of calls\n\n inline long count() const { return itsCount; }\n\n\n\n /// @param[in] cnt counter to set\n\n inline void setCount(const long cnt) { itsCount = cnt;}\n\n\n\n /// @return total execution time\n\n inline double totalTime() const { return itsTotalTime; }\n\n\n\n /// @return longest execution time\n\n inline double maxTime() const { return itsMaxTime; }\n\n\n\n /// @return shortest execution time\n\n inline double minTime() const { return itsMinTime; }\n\n \n\n /// @brief process another execution\n\n /// @details This method increments total time and count and\n\n /// adjusts min/max statistics as required. It is called after each run of the \n\n /// traced method.\n\n /// @param[in] time execution time for this call\n\n void add(const double time);\n\n\n\n /// @brief process another execution\n\n /// @details This method merges in an additional object of the same type\n\n /// @param[in] other another ProfileData object\n\n void add(const ProfileData &other);\n\n \n\nprivate:\n\n /// @brief number of calls\n\n long itsCount;\n\n /// @brief total execution time\n\n double itsTotalTime;\n\n /// @brief longest execution time\n\n /// @note it is undefined if itsCount == 0\n\n double itsMaxTime;\n\n /// @brief shortest execution time\n\n /// @note it is undefined if itsCount == 0\n\n double itsMinTime;\n", "file_path": "Code/Base/askap/current/profile/ProfileData.h", "rank": 45, "score": 186480.37898911524 }, { "content": " def set(self):\n\n self.__cond.acquire()\n\n try:\n\n self.__flag = True\n\n self.__message = \"\"\n\n self.__cond.notify_all()\n\n finally:\n", "file_path": "Code/Base/py-askap/current/askap/event.py", "rank": 46, "score": 185726.4210312904 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief Thread which manages a single data stream connection\n\n/// @details This class is initialised with two shared pointers, one to the socket \n\n/// corresponding to one input data stream and another corresponding to the buffer\n\n/// manager. Each instance (executed as a separate thread), obtains a buffer from \n\n/// the manager, fills it with new data and de-allocates it. The correlator thread\n\n/// is responsible for further processing when sufficient data are accumulated.\n\n/// This version of the class supports data stream in floats as opposed to 16 bit integers\n\n/// @ingroup swcorrelator\n\nstruct FloatStreamConnection {\n\n\n\n /// @brief constructor\n\n /// @details\n\n /// @param[in] socket shared pointer to the socket corresponding to this connection\n\n /// @param[in] bm shared pointer to the buffer manager\n\n FloatStreamConnection(const boost::shared_ptr<boost::asio::ip::tcp::socket> &socket,\n\n const boost::shared_ptr<BufferManager> &bm);\n\n \n\n /// @brief parallel thread\n\n /// @details This is the main entry point to the code executed in a parallel thread\n\n void operator()();\n\n \n\nprivate:\n\n /// @details shared pointer to the socket corresponding connection managed by this instance\n\n boost::shared_ptr<boost::asio::ip::tcp::socket> itsSocket;\n\n \n\n /// @brief buffer manager\n\n boost::shared_ptr<BufferManager> itsBufferManager;\n\n};\n\n\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/FloatStreamConnection.h", "rank": 47, "score": 185149.07113780576 }, { "content": "from askap import logging\n\nlogger = logging.getLogger(__name__)\n", "file_path": "Code/Components/Analysis/data/current/askap/analysis/data/__init__.py", "rank": 48, "score": 184979.18263131875 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief An interface to generic buffer (for writing visibilities)\n\n/// @details Read-write iterator (see IDataIterator) uses the concept\n\n/// of buffers to store scratch data. This is an abstract interface\n\n/// to operations with such buffers.\n\n/// @ingroup dataaccess_hlp\n\nstruct IBufferManager : virtual public IHolder\n\n{\n\n /// @brief populate the cube with the data stored in the given buffer\n\n /// @details The method throws an exception if the requested buffer\n\n /// does not exist (prevents a shape mismatch)\n\n /// @param[in] vis a reference to the nRow x nChannel x nPol buffer\n\n /// cube to fill with the complex visibility data\n\n /// @param[in] name a name of the buffer to work with\n\n /// @param[in] index a sequential index in the buffer\n\n virtual void readBuffer(casa::Cube<casa::Complex> &vis,\n\n const std::string &name,\n\n\t\t\t casa::uInt index) const = 0;\n\n \n\n /// @brief write the cube back to the given buffer\n\n /// @details This buffer is created on the first write operation\n\n /// @param[in] vis a reference to the nRow x nChannel x nPol buffer\n\n /// cube to fill with the complex visibility data\n\n /// @param[in] name a name of the buffer to work with\n\n /// @param[in] index a sequential index in the buffer\n\n virtual void writeBuffer(const casa::Cube<casa::Complex> &vis,\n\n const std::string &name,\n\n\t\t\t casa::uInt index) const = 0;\n\n\n\n /// @brief check whether the particular buffer exists\n\n /// @param[in] name a name of the buffer to query\n\n /// @param[in] index a sequential index in the buffer\n\n /// @return true, if the buffer with the given name is present\n\n virtual bool bufferExists(const std::string &name,\n\n\t\t\t casa::uInt index) const = 0;\n\n};\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/IBufferManager.h", "rank": 49, "score": 172645.5825159102 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief Helper class representing a scratch buffer\n\n/// @details Read-write access idiom is to work with so-called\n\n/// buffers, a chunk of visibility data sharing the same metadada\n\n/// with the main accessor (see IDataAccessor for more info).\n\n/// This is a helper class used between ITableDataIterator and\n\n/// ITableDataAccessor, which represents one scratch buffer used to\n\n/// cache disk information for each current iteration.\n\n/// @note an std::pair can be used instead, but this class gives\n\n/// a better looking code\n\n/// @ingroup dataaccess_hlp\n\nstruct ScratchBuffer {\n\n ScratchBuffer() : needsRead(true), needsFlush(false) {}\n\n \n\n /// visibility cube\n\n casa::Cube<casa::Complex> vis;\n\n /// True if the cube has to be initialized (reading is required)\n\n mutable bool needsRead;\n\n /// True if there was a write operation and the cube has to be\n\n /// flushed back to disk (or whatever is used for storage of buffers)\n\n mutable bool needsFlush;\n\n};\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/ScratchBuffer.h", "rank": 50, "score": 172645.5825159102 }, { "content": "namespace askap {\n\n\n\nnamespace scimath {\n\n\n\n/// @brief helper class to monitor updates of parameters\n\n/// @details It is often needed to monitor a change of some parameters. This class \n\n/// has comparison operators defined (equal and not equal). Two instances are not\n\n/// equal if they correspond to a different version of tracked parameters. This class\n\n/// can be used in various caching-related implementations where some hierarchy exists\n\n/// (and so different parts of the code can be concerned about changes made at a different time) \n\n/// It essentially wraps over an integer number which is incremented every time a\n\n/// tracked parameter changes. \n\n/// @ingroup utils\n\nstruct ChangeMonitor {\n\n /// @brief constructor\n\n inline ChangeMonitor() : itsTag(0) {}\n\n \n\n /// @brief check whether two monitors are equal\n\n /// @details\n\n /// @param[in] in another change monitor object\n\n /// @return true if this class and in are equal\n\n inline bool operator==(const ChangeMonitor &in) const { return in.itsTag == itsTag; }\n\n \n\n /// @brief check whether two monitors are not equal\n\n /// @details\n\n /// @param[in] in another change monitor object\n\n /// @return true if this class and in are not equal\n\n inline bool operator!=(const ChangeMonitor &in) const { return in.itsTag != itsTag; }\n\n \n\n /// @brief notify that a change has been made\n\n /// @details This method is supposed to be called every time a corresponding \n\n /// parameter has been updated.\n\n inline void notifyOfChanges() { ++itsTag; ASKAPCHECK(itsTag!=0, \"Overflow detected!\");}\n\n \n\nprivate: \n\n /// @brief integer tag\n\n /// @details it is incremented every time there is a change in a tracked parameter \n\n unsigned long itsTag;\n", "file_path": "Code/Base/scimath/current/utils/ChangeMonitor.h", "rank": 51, "score": 172642.31525703857 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n/// @brief class which can run the correlator\n\n/// @details This class is analogous to the main method of the stand alone correlator \n\n/// application. It can run the correlator, get monitoring data and stop when necessary.\n\n/// The primary goal for this interface is to run the software correlator from the epics\n\n/// CA server.\n\n/// @ingroup corrinterfaces\n\nstruct CorrRunner : private boost::noncopyable {\n\n \n\n /// @brief call back function type\n\n typedef void (*CallBackType)(const MonitoringData&, void* optionalData); \n\n \n\n /// @brief default constructor\n\n CorrRunner(); // doesn't throw\n\n\n\n /// @brief default destructor\n\n ~CorrRunner(); // doesn't throw\n\n \n\n /// @brief setup call back function\n\n /// @details If not NULL, the given function will be called every time the new data arrive.\n\n /// @param[in] callBackPtr pointer to the call back function\n\n /// @param[in[ optionalData optional pointer which is then passed to call back function\n\n /// @note the meaning of optionalData is user interpreted. It doesn't need to be a valid pointer\n\n void setCallBack(CallBackType callBackPtr = NULL, void* optionalData = NULL);\n\n \n\n /// @brief start the correlator\n\n /// @details This method starts all required threads and intialises the correlator using\n\n /// the parset.\n\n /// @param[in] parset parset with input parameters\n\n void start(const LOFAR::ParameterSet &parset); // doesn't throw\n\n \n\n /// @brief start the correlator\n\n /// @details This version reads the parset from the given file.\n\n /// @param[in] fname parset file name\n\n void start(const std::string &fname); // doesn't throw\n\n \n\n /// @brief stop the correlator\n\n /// @details This method can be called at any time to request a stop. The correlator\n\n /// finishes processing of the current cycle and gracefully shuts down closing the MS.\n\n /// @note This method must be called at the end to avoid corruption of the MS. \n\n static void stop(); // doesn't throw\n\n \n\n // check the status\n\n \n\n /// @brief check whether the correlator is running\n\n /// @details If it is not, the data in the data fields are not valid and all flags are set\n\n /// to true. Note, this method is thread safe and can be called asynchronously\n\n /// @return true if the correlator is running, false otherwise\n\n bool isRunning() const; // doesn't throw\n\n \n\n /// @brief obtain the status of error message\n\n /// @details When the correlator stops due to exception, the error message is available via\n\n /// this method. Note, this method is thread safe and can be called asynchronously\n\n std::string statusMsg() const; // doesn't throw\n\n \n\n /// @brief set status message\n\n /// @param[in] running true, if the correlator is running\n\n /// @param[in] msg status/error message\n\n void setStatus(const bool running, const std::string &msg = \"OK\"); // doesn't throw\n\n\n\nprivate: \n\n // current execution status\n\n\n\n /// @brief true if the correlator is running, false otherwise\n\n bool itsIsRunning;\n\n\n\n /// @brief error or status message\n\n std::string itsStatus;\n\n\n\n /// @brief mutex to protect status message and the running state\n\n mutable boost::mutex itsStatusMutex;\n\n \n\n /// @brief main correlator thread \n\n /// @details This class is executed in the main epics thread. The methods like start and stop\n\n /// return the control without waiting. The correlator is executed in a separate thread (where\n\n /// it spawns its own child threads)\n\n boost::thread itsCorrelatorThread; \n\n \n\n};\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/CorrRunner.h", "rank": 52, "score": 172577.33487871944 }, { "content": "namespace askap {\n\n\n\nnamespace synthesis {\n\n\n\n/// @brief Interface to a basic illumination pattern\n\n/// @details This class is an abstract base (i.e. an interface) to \n\n/// an hierarchy of classes representing illumination patterns.\n\n/// It provides a method to obtain illumination pattern by populating a \n\n/// pre-defined grid supplied as a UVPattern object. \n\n/// @ingroup gridding\n\nstruct IBasicIllumination {\n\n \n\n /// @brief obtain illumination pattern\n\n /// @details This is the main method which populates the \n\n /// supplied uv-pattern with the values corresponding to the model\n\n /// represented by this object. It has to be overridden in the \n\n /// derived classes. An optional phase slope can be applied to\n\n /// simulate offset pointing.\n\n /// @param[in] freq frequency in Hz for which an illumination pattern is required\n\n /// @param[in] pattern a UVPattern object to fill\n\n /// @param[in] l angular offset in the u-direction (in radians)\n\n /// @param[in] m angular offset in the v-direction (in radians)\n\n /// @param[in] pa parallactic angle, or strictly speaking the angle between \n\n /// uv-coordinate system and the system where the pattern is defined\n\n virtual void getPattern(double freq, UVPattern &pattern, double l = 0., \n\n double m = 0., double pa = 0.) const = 0;\n\n \n\n /// @brief check whether the pattern is symmetric\n\n /// @details Some illumination patterns are trivial and it may be known a priori that\n\n /// the pattern does not depend on the parallactic angle. This method allows to check\n\n /// whether such trivial case exists. If true is returned, getPattern ignores pa\n\n /// parameter.\n\n /// @return true if the pattern is symmetric, false otherwise\n\n virtual bool isSymmetric() const = 0;\n\n \n\n /// @brief empty virtual destructor to keep the compiler happy\n\n virtual ~IBasicIllumination();\n\n};\n\n\n\n} // namespace synthesis\n\n\n", "file_path": "Code/Components/Synthesis/synthesis/current/gridding/IBasicIllumination.h", "rank": 53, "score": 170703.22094502096 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief A class to manage buffers stored in subtable\n\n/// @details Read-write iterator (see IDataIterator) uses the concept\n\n/// of buffers to store scratch data. This class stores buffers in the\n\n/// BUFFERS subtable \n\n/// @ingroup dataaccess_tab\n\nstruct TableBufferManager : virtual public IBufferManager,\n\n virtual protected TableHolder\n\n{\n\n /// construct the object and link it to the given buffers subtable\n\n /// @param[in] tab subtable to use\n\n TableBufferManager(const casa::Table &tab);\n\n \n\n /// @brief populate the cube with the data stored in the given buffer\n\n /// @details The method throws an exception if the requested buffer\n\n /// does not exist (prevents a shape mismatch)\n\n /// @param[in] vis a reference to the nRow x nChannel x nPol buffer\n\n /// cube to fill with the complex visibility data\n\n /// @param[in] name a name of the buffer to work with\n\n /// @param[in] index a sequential index in the buffer\n\n virtual void readBuffer(casa::Cube<casa::Complex> &vis,\n\n const std::string &name,\n\n\t\t\t casa::uInt index) const;\n\n \n\n /// @brief write the cube back to the given buffer\n\n /// @details This buffer is created on the first write operation\n\n /// @param[in] vis a reference to the nRow x nChannel x nPol buffer\n\n /// cube to fill with the complex visibility data\n\n /// @param[in] name a name of the buffer to work with\n\n /// @param[in] index a sequential index in the buffer\n\n virtual void writeBuffer(const casa::Cube<casa::Complex> &vis,\n\n const std::string &name,\n\n\t\t\t casa::uInt index) const;\n\n\n\n /// @brief check whether the particular buffer exists\n\n /// @param[in] name a name of the buffer to query\n\n /// @return true, if the buffer with the given name is present\n\n /// @param[in] index a sequential index in the buffer\n\n virtual bool bufferExists(const std::string &name,\n\n\t\t\t casa::uInt index) const;\n\nprotected:\n\n // templated methods to handle cubes of different types\n\n\n\n /// @brief populate the cube with the data stored in the given table cell\n\n /// @details The method throws an exception if the requested table cell\n\n /// does not exist\n\n /// @param[in] cube a reference to a cube of some type\n\n /// @param[in] name a name of the column to work with\n\n /// @param[in] index row number\n\n template<typename T>\n\n void readCube(casa::Cube<T> &cube, const std::string &name,\n\n\t\t\t casa::uInt index) const;\n\n \n\n /// @brief write the cube back to the table\n\n /// @details The table cell is populated with values on the first write \n\n /// operation\n\n /// @param[in] cube to take the data from \n\n /// @param[in] name a name of the column to work with\n\n /// @param[in] index row number\n\n template<typename T>\n\n void writeCube(const casa::Cube<T> &cube, const std::string &name,\n\n\t\t\t casa::uInt index) const;\n\n\n\n /// @brief check whether a particular table cell exists\n\n /// @param[in] name a name of the table column to query\n\n /// @param[in] index row number \n\n /// @return true, if the given cell exists and has an array\n\n /// @note template type defined the type of the data\n\n template<typename T>\n\n bool cellDefined(const std::string &name,\n\n\t\t\t casa::uInt index) const; \t\t\t \n\n};\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/TableBufferManager.h", "rank": 54, "score": 170656.65728011035 }, { "content": "namespace askap {\n\n\n\n namespace synthesis {\n\n\n\n /// @brief Base class for monitor of Deconvolver\n\n /// @details All the monitoring is delegated to this class so that\n\n /// more control is possible.\n\n /// @ingroup Deconvolver\n\n template<class T> class DeconvolverMonitor {\n\n\n\n public:\n\n typedef boost::shared_ptr<DeconvolverMonitor<T> > ShPtr;\n\n\n\n DeconvolverMonitor();\n\n\n\n virtual ~DeconvolverMonitor() {};\n\n\n\n /// Monitor the current state\n\n virtual void monitor(const DeconvolverState<T>& ds);\n\n\n\n /// @brief configure basic parameters\n\n /// @details This method encapsulates extraction of basic parameters from the parset.\n\n /// @param[in] parset parset\n\n virtual void configure(const LOFAR::ParameterSet &parset);\n\n\n\n private:\n\n\n\n casa::Bool itsVerbose;\n\n casa::uInt itsLogEvery;\n\n };\n\n\n\n } // namespace synthesis\n\n\n", "file_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverMonitor.h", "rank": 55, "score": 170653.44498713134 }, { "content": "namespace askap {\n\n\n\nnamespace swcorrelator {\n\n\n\n// forward declaration to allow passing a pointer\n\nstruct CorrRunner;\n\n\n\n/// @brief parallel thread which runs the correlator\n\n/// @details This class is analogous to the main method of the stand alone correlator \n\n/// application. It can run the correlator, get monitoring data and stop when necessary.\n\n/// The primary goal for this interface is to run the software correlator from the epics\n\n/// CA server. We use parallel thread to get the asynchronous behavior. This class represents\n\n/// the child thread and CorrRunner the main thread.\n\n/// @ingroup corrinterfaces\n\nstruct CorrRunnerThread {\n\n \n\n /// @brief constructor\n\n /// @details\n\n /// @param[in] parent shared pointer to an instance of the main thread class\n\n /// @param[in] parset shared pointer to the parset\n\n CorrRunnerThread(const boost::shared_ptr<CorrRunner> &parent, const boost::shared_ptr<LOFAR::ParameterSet> &parset);\n\n \n\n /// @brief the entry point for the parallel thread\n\n void operator()();\n\n \n\n /// @brief stop the correlator\n\n /// @details This method can be called at any time to request a stop. The correlator\n\n /// finishes processing of the current cycle and gracefully shuts down closing the MS.\n\n /// @note This method must be called at the end to avoid corruption of the MS. \n\n static void stop(); // doesn't throw\n\n \n\nprivate:\n\n /// @brief shared pointer to an instance of the main thread class (to allow status update) \n\n boost::shared_ptr<CorrRunner> itsParent;\n\n \n\n /// @brief shared pointer to the parset with parameters\n\n boost::shared_ptr<LOFAR::ParameterSet> itsParset;\n\n};\n\n\n\n} // namespace swcorrelator\n\n\n", "file_path": "Code/Components/swcorrelator/current/corrinterfaces/CorrRunnerThread.h", "rank": 56, "score": 170589.55778956076 }, { "content": "namespace askap {\n\nnamespace cp {\n\nnamespace sms {\n\nnamespace datamodel {\n\n\n\n// Map C++ bool to an INT NOT NULL database type\n\n#pragma db value(bool) type(\"INT\")\n\n\n\n/// @brief Datamodel class for ancillary data source information.\n\n/// This is primarily intended to identify the source of seed data\n\n/// that did not come from ASKAP observations.\n\n\n\n// Do not edit the version of this file in the `datamodel` directory, as it is\n\n// a copy of the files in the `schema` directory.\n\n\n\n#pragma db object optimistic\n\nstruct DataSource {\n\n DataSource() {}\n\n\n\n // @brief Optimistic concurrency lock version\n\n // @units none\n\n #pragma db version\n\n version_type version;\n\n\n\n // @brief Primary key unique identifier\n\n // @units none\n\n #pragma db index\n\n #pragma db id auto\n\n id_type data_source_id;\n\n\n\n // Include the fields generated from the design spreadsheet\n\n #include \"DataSource.i\"\n\n};\n\n\n\n};\n\n};\n\n};\n", "file_path": "Code/Components/Services/skymodel/current/schema/DataSource.h", "rank": 57, "score": 170326.99383463658 }, { "content": "namespace askap {\n\nnamespace cp {\n\nnamespace sms {\n\nnamespace datamodel {\n\n\n\n// Map C++ bool to an INT NOT NULL database type\n\n#pragma db value(bool) type(\"INT\")\n\n\n\n/// @brief Datamodel class for ancillary data source information.\n\n/// This is primarily intended to identify the source of seed data\n\n/// that did not come from ASKAP observations.\n\n\n\n// Do not edit the version of this file in the `datamodel` directory, as it is\n\n// a copy of the files in the `schema` directory.\n\n\n\n#pragma db object optimistic\n\nstruct DataSource {\n\n DataSource() {}\n\n\n\n // @brief Optimistic concurrency lock version\n\n // @units none\n\n #pragma db version\n\n version_type version;\n\n\n\n // @brief Primary key unique identifier\n\n // @units none\n\n #pragma db index\n\n #pragma db id auto\n\n id_type data_source_id;\n\n\n\n // Include the fields generated from the design spreadsheet\n\n #include \"DataSource.i\"\n\n};\n\n\n\n};\n\n};\n\n};\n", "file_path": "Code/Components/Services/skymodel/current/datamodel/DataSource.h", "rank": 58, "score": 170326.99383463658 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief general exception class used in the data access layer\n\n/// @ingroup dataaccess_i\n\nstruct DataAccessError : public AskapError\n\n{\n\n /// constructor - pass the message to the base class\n\n ///\n\n /// @param message a string message explaining what happens\n\n ///\n\n explicit DataAccessError(const std::string& message);\n\n};\n\n\n\n/// @brief exception class indicating a logic error in the data access layer\n\nstruct DataAccessLogicError : public DataAccessError\n\n{\n\n /// constructor - pass the message to the base class\n\n ///\n\n /// @param message a string message explaining what happens\n\n ///\n\n explicit DataAccessLogicError(const std::string& message);\n\n};\n\n\n\n} // namespace askap\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/DataAccessError.h", "rank": 59, "score": 170326.99383463658 }, { "content": "namespace askap {\n\nnamespace cp {\n\nnamespace sms {\n\n\n\n// Alias for the Ice type namespace\n\nnamespace ice_interfaces = askap::interfaces::skymodelservice;\n\n\n\n/// @brief Transfers data from the datamodel::ContinuumComponent class to the\n\n/// Ice DTO class. If present, polarisation data will be added to the optional\n\n/// polarisation member of ContinuumComponent.\n\n///\n\n/// @param[in] components Pointer to a vector of components for transfer.\n\n/// @throw AskapError Thrown if there are errors.\n\n/// @return askap::interfaces::skymodelservice::ComponentSeq\n\nice_interfaces::ComponentSeq marshallComponentsToDTO(\n\n boost::shared_ptr< std::vector<datamodel::ContinuumComponent> > components)\n\n{\n\n // This might be nice if I can define a conversion operator from\n\n // datamodel::ContinuumComponent to ice_interfaces::ContinuumComponent\n\n // But unfortunately, both source and destination classes are produced by\n\n // the corresponding systems (Ice slice compiler, ODB class generation),\n\n // so I have no easy way to define the conversion. Doing it manually isn't\n\n // too bad though due to the code generation.\n\n //return ice_interfaces::ComponentSeq(components->begin(), components->end());\n\n\n\n // preallocate space for more efficient allocation\n\n ice_interfaces::ComponentSeq dst(components->size());\n\n\n\n int i = 0;\n\n for (std::vector<datamodel::ContinuumComponent>::const_iterator it = components->begin();\n\n it != components->end();\n\n it++, i++) {\n\n\n\n // Copy the component data\n\n dst[i].componentId = it->component_id;\n\n dst[i].ra = it->ra;\n\n dst[i].dec = it->dec;\n\n dst[i].raErr = it->ra_err;\n\n dst[i].decErr = it->dec_err;\n\n dst[i].freq = it->freq;\n\n dst[i].fluxPeak = it->flux_peak;\n\n dst[i].fluxPeakErr = it->flux_peak_err;\n\n dst[i].fluxInt = it->flux_int;\n\n dst[i].fluxIntErr = it->flux_int_err;\n\n dst[i].spectralIndex = it->spectral_index;\n\n dst[i].spectralCurvature = it->spectral_curvature;\n\n\n\n // polarisation may not be present\n\n if (it->polarisation.get()) {\n\n const datamodel::Polarisation* src_pol = it->polarisation.get();\n\n\n\n // I need to profile how the performance of stack instance followed\n\n // by assignment to the vector compares to the resize and assign\n\n // members in place. On the surface, it is comparing a default ctor, field assignment, and copy ctor\n\n // to default ctor and field assignment. I hope to avoid the additional\n\n // copy when pushing the stack instance into the vectory.\n\n // Of course, the compiler could be doing all sorts of optimisations, so\n\n // sticking to the clearer code is probably best.\n\n ice_interfaces::ContinuumComponentPolarisation dst_pol;\n\n\n\n // Or:\n\n //dst[i].polarisation.resize(1);\n\n // And then:\n\n //dst[i].polarisation[0].polPeakFit = src_pol->pol_peak_fit;\n\n\n\n dst_pol.lambdaRefSq = src_pol->lambda_ref_sq;\n\n dst_pol.polPeakFit = src_pol->pol_peak_fit;\n\n dst_pol.polPeakFitDebias = src_pol->pol_peak_fit_debias;\n\n dst_pol.polPeakFitErr = src_pol->pol_peak_fit_err;\n\n dst_pol.polPeakFitSnr = src_pol->pol_peak_fit_snr;\n\n dst_pol.polPeakFitSnrErr = src_pol->pol_peak_fit_snr_err;\n\n dst_pol.fdPeakFit = src_pol->fd_peak_fit;\n\n dst_pol.fdPeakFitErr = src_pol->fd_peak_fit_err;\n\n\n\n // Assign our stack variable to the vector. Hopefully the additional\n\n // copy constructor gets optimised away.\n\n dst[i].polarisation.push_back(dst_pol);\n\n } // end of polarisation branch\n\n } // end of component loop\n\n\n\n\n\n return dst;\n\n}\n\n\n\n\n\n}\n\n}\n", "file_path": "Code/Components/Services/skymodel/current/service/DataMarshalling.h", "rank": 60, "score": 170326.99383463658 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief A stubbed implementation of the data accessor\n\n/// @ingroup dataaccess_hlp\n\nstruct DataAccessorStub : virtual public IFlagDataAccessor\n\n{\n\n /// Default version can fill with MIRANdA data\n\n DataAccessorStub(const bool fill=false);\n\n\t\n\n /// The number of rows in this chunk\n\n /// @return the number of rows in this chunk\n\n virtual casa::uInt nRow() const throw();\n\n\n\n // The following methods implement metadata access\n\n\t\t\n\n /// The number of spectral channels (equal for all rows)\n\n /// @return the number of spectral channels\n\n virtual casa::uInt nChannel() const throw();\n\n\n\n /// The number of polarization products (equal for all rows)\n\n /// @return the number of polarization products (can be 1,2 or 4)\n\n virtual casa::uInt nPol() const throw();\n\n\n\n\n\n /// First antenna IDs for all rows\n\n /// @return a vector with IDs of the first antenna corresponding\n\n /// to each visibility (one for each row)\n\n virtual const casa::Vector<casa::uInt>& antenna1() const;\n\n\n\n /// Second antenna IDs for all rows\n\n /// @return a vector with IDs of the second antenna corresponding\n\n /// to each visibility (one for each row)\n\n virtual const casa::Vector<casa::uInt>& antenna2() const;\n\n\t\n\n /// First feed IDs for all rows\n\n /// @return a vector with IDs of the first feed corresponding\n\n /// to each visibility (one for each row)\n\n virtual const casa::Vector<casa::uInt>& feed1() const;\n\n \n\n /// Second feed IDs for all rows\n\n /// @return a vector with IDs of the second feed corresponding\n\n /// to each visibility (one for each row)\n\n virtual const casa::Vector<casa::uInt>& feed2() const;\n\n \n\n /// Position angles of the first feed for all rows\n\n /// @return a vector with position angles (in radians) of the\n\n /// first feed corresponding to each visibility\n\n virtual const casa::Vector<casa::Float>& feed1PA() const;\n\n \n\n /// Position angles of the second feed for all rows\n\n /// @return a vector with position angles (in radians) of the\n\n /// second feed corresponding to each visibility\n\n virtual const casa::Vector<casa::Float>& feed2PA() const;\n\n \n\n /// Return pointing centre directions of the first antenna/feed\n\n /// @return a vector with direction measures (coordinate system\n\n /// is determined by the data accessor), one direction for each\n\n /// visibility/row\n\n virtual const casa::Vector<casa::MVDirection>& pointingDir1() const;\n\n \n\n /// Pointing centre directions of the second antenna/feed\n\n /// @return a vector with direction measures (coordinate system\n\n /// is determined by the data accessor), one direction for each\n\n /// visibility/row\n\n virtual const casa::Vector<casa::MVDirection>& pointingDir2() const;\n\n\n\n /// pointing direction for the centre of the first antenna \n\n /// @details The same as pointingDir1, if the feed offsets are zero\n\n /// @return a vector with direction measures (coordinate system\n\n /// is is set via IDataConverter), one direction for each\n\n /// visibility/row\n\n virtual const casa::Vector<casa::MVDirection>& dishPointing1() const;\n\n\n\n /// pointing direction for the centre of the first antenna \n\n /// @details The same as pointingDir2, if the feed offsets are zero\n\n /// @return a vector with direction measures (coordinate system\n\n /// is is set via IDataConverter), one direction for each\n\n /// visibility/row\n\n virtual const casa::Vector<casa::MVDirection>& dishPointing2() const;\n\n \n\n /// Visibilities (a cube is nRow x nChannel x nPol; each element is\n\n /// a complex visibility)\n\n /// @return a reference to nRow x nChannel x nPol cube, containing\n\n /// all visibility data\n\n /// TODO:\n\n /// a non-const version to be able to subtract the model\n\n virtual const casa::Cube<casa::Complex>& visibility() const;\n\n\n\n /// Read-write visibilities (a cube is nRow x nChannel x nPol; \n\n /// each element is a complex visibility)\n\n /// \n\n /// @return a reference to nRow x nChannel x nPol cube, containing\n\n /// all visibility data\n\n ///\n\n virtual casa::Cube<casa::Complex>& rwVisibility();\n\n\n\n\n\n /// Cube of flags corresponding to the output of visibility() \n\n /// @return a reference to nRow x nChannel x nPol cube with flag \n\n /// information. If True, the corresponding element is flagged.\n\n virtual const casa::Cube<casa::Bool>& flag() const;\n\n\n\n /// Non-const access to the cube of flags.\n\n /// @return a reference to nRow x nChannel x nPol cube with the flag\n\n /// information. If True, the corresponding element is flagged.\n\n virtual casa::Cube<casa::Bool>& rwFlag();\n\n\n\n \n\n /// Noise level required for a proper weighting\n\n /// @return a reference to nRow x nChannel x nPol cube with\n\n /// complex noise estimates\n\n virtual const casa::Cube<casa::Complex>& noise() const;\n\n\n\n /// UVW\n\n /// @return a reference to vector containing uvw-coordinates\n\n /// packed into a 3-D rigid vector\n\n virtual const casa::Vector<casa::RigidVector<casa::Double, 3> >&\n\n uvw() const;\n\n \n\n /// @brief uvw after rotation\n\n /// @details This method calls UVWMachine to rotate baseline coordinates \n\n /// for a new tangent point. Delays corresponding to this correction are\n\n /// returned by a separate method.\n\n /// @param[in] tangentPoint tangent point to rotate the coordinates to\n\n /// @return uvw after rotation to the new coordinate system for each row\n\n virtual const casa::Vector<casa::RigidVector<casa::Double, 3> >&\n\n\t rotatedUVW(const casa::MDirection &tangentPoint) const;\n\n\t \n\n /// @brief delay associated with uvw rotation\n\n /// @details This is a companion method to rotatedUVW. It returns delays corresponding\n\n /// to the baseline coordinate rotation. An additional delay corresponding to the \n\n /// translation in the tangent plane can also be applied using the image \n\n /// centre parameter. Set it to tangent point to apply no extra translation.\n\n /// @param[in] tangentPoint tangent point to rotate the coordinates to\n\n /// @param[in] imageCentre image centre (additional translation is done if imageCentre!=tangentPoint)\n\n /// @return delays corresponding to the uvw rotation for each row\n\n virtual const casa::Vector<casa::Double>& uvwRotationDelay(\n\n\t const casa::MDirection &tangentPoint, const casa::MDirection &imageCentre) const;\n\n \n\n \n\n /// Timestamp for each row\n\n /// @return a timestamp for this buffer (it is always the same\n\n /// for all rows. The timestamp is returned as \n\n /// Double w.r.t. the origin specified by the \n\n /// DataSource object and in that reference frame\n\n virtual casa::Double time() const;\n\n \n\n \n\n /// Frequency for each channel\n\n /// @return a reference to vector containing frequencies for each\n\n /// spectral channel (vector size is nChannel). Frequencies\n\n /// are given as Doubles, the frame/units are specified by\n\n /// the DataSource object\n\n virtual const casa::Vector<casa::Double>& frequency() const;\n\n\n\n /// Velocity for each channel\n\n /// @return a reference to vector containing velocities for each\n\n /// spectral channel (vector size is nChannel). Velocities\n\n /// are given as Doubles, the frame/units are specified by\n\n /// the DataSource object (via IDataConverter).\n\n virtual const casa::Vector<casa::Double>& velocity() const;\n\n\n\n /// @brief polarisation type for each product\n\n /// @return a reference to vector containing polarisation types for\n\n /// each product in the visibility cube (nPol() elements).\n\n /// @note All rows of the accessor have the same structure of the visibility\n\n /// cube, i.e. polarisation types returned by this method are valid for all rows.\n\n virtual const casa::Vector<casa::Stokes::StokesTypes>& stokes() const;\n\n \n\n//private: // to be able to change stubbed data directly, if necessary\n\n // cached results which are filled from an appropriate table\n\n // when necessary (they probably have to be moved to DataSource)\n\n /// cached antenna1\n\n mutable casa::Vector<casa::uInt> itsAntenna1;\n\n /// cached antenna2\n\n mutable casa::Vector<casa::uInt> itsAntenna2;\n\n /// cached feed1\n\n mutable casa::Vector<casa::uInt> itsFeed1;\n\n /// cached feed2\n\n mutable casa::Vector<casa::uInt> itsFeed2;\n\n /// cached feed1 position angle\n\n mutable casa::Vector<casa::Float> itsFeed1PA;\n\n /// cached feed2 position angle\n\n mutable casa::Vector<casa::Float> itsFeed2PA;\n\n /// cached pointing direction of the first antenna/feed\n\n mutable casa::Vector<casa::MVDirection> itsPointingDir1;\n\n /// cached pointing direction of the second antenna/feed\n\n mutable casa::Vector<casa::MVDirection> itsPointingDir2;\n\n /// cached pointing direction of the centre of the first antenna\n\n mutable casa::Vector<casa::MVDirection> itsDishPointing1;\n\n /// cached pointing direction of the centre of the second antenna\n\n mutable casa::Vector<casa::MVDirection> itsDishPointing2;\n\n /// cached visibility\n\n mutable casa::Cube<casa::Complex> itsVisibility;\n\n /// cached flag\n\n mutable casa::Cube<casa::Bool> itsFlag;\n\n /// cached uvw\n\n mutable casa::Vector<casa::RigidVector<casa::Double, 3> > itsUVW;\n\n /// cached noise\n\n mutable casa::Cube<casa::Complex> itsNoise;\n\n /// cached time\n\n mutable casa::Double itsTime;\n\n /// cached frequency\n\n mutable casa::Vector<casa::Double> itsFrequency;\n\n /// cached velocity\n\n mutable casa::Vector<casa::Double> itsVelocity;\n\n /// cached uvw-rotation delay \n\n mutable casa::Vector<casa::Double> itsUVWRotationDelay;\n\n /// cached polarisation types\n\n mutable casa::Vector<casa::Stokes::StokesTypes> itsStokes;\n\n};\n\n\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/DataAccessorStub.h", "rank": 61, "score": 170326.99383463658 }, { "content": "class MonitoringBuffer(object):\n\n def __init__(self):\n\n \"\"\"Thread safe buffer of monitoring points\"\"\"\n\n self._mutex = ReadWriteMutex()\n\n self._buffer = {}\n\n\n\n def add_points(self, points, timetag=None):\n\n \"\"\"Add a :class:`dict` of point(s) to the buffer. This is to support points\n\n without metadata (old-style monitoring points)\"\"\"\n\n try:\n\n timestamp = timetag or bat_now()\n\n self._mutex.acquire_write_lock()\n\n for k, v in points.items():\n\n self._buffer[k] = {'value': v, 'name': k,\n\n 'timestamp': timestamp}\n\n finally:\n\n self._mutex.release_write_lock()\n\n\n\n def add_full_points(self, points):\n\n \"\"\" points is a list of dict, each is a monitor point \"\"\"\n\n try:\n\n self._mutex.acquire_write_lock()\n\n for point in points:\n\n name = point['name']\n\n mon_point = {'name': name,\n\n 'timestamp': point.get('timestamp', bat_now()),\n\n 'unit': point.get('unit', ''),\n\n 'status': point.get('status', 'OK'),\n\n 'value': point['value']}\n\n self._buffer[name] = mon_point\n\n finally:\n\n self._mutex.release_write_lock()\n\n\n\n def add(self, name, value, timestamp=None, status=\"OK\", unit=\"\"):\n\n \"\"\"Add a monitor point with metadata\"\"\"\n\n try:\n\n timestamp = timestamp or bat_now()\n\n point = {'name': name, 'timestamp': timestamp,\n\n 'unit': unit,\n\n 'status': status,\n\n 'value': value}\n\n self._mutex.acquire_write_lock()\n\n self._buffer[name] = point\n\n finally:\n\n self._mutex.release_write_lock()\n\n\n\n def remove(self, keys):\n\n points = keys\n\n if isinstance(keys, basestring):\n\n points = (keys,)\n\n try:\n\n self._mutex.acquire_write_lock()\n\n for k in points:\n\n if k in self._buffer:\n\n self._buffer.pop(k)\n\n finally:\n\n self._mutex.release_write_lock()\n\n\n\n def clear(self):\n\n \"\"\"\n\n Clear the buffer\n\n \"\"\"\n\n try:\n\n self._mutex.acquire_write_lock()\n\n self._buffer.clear()\n\n finally:\n\n self._mutex.release_write_lock()\n\n\n\n def get(self, keys):\n\n \"\"\"Get given point names `keys` from buffer\n\n\n\n :param list keys: a list of point names.\n\n\n\n \"\"\"\n\n if isinstance(keys, basestring):\n\n keys = (keys,)\n\n try:\n\n self._mutex.acquire_read_lock()\n\n return [self._buffer[k] for k in keys if k in self._buffer]\n\n finally:\n", "file_path": "Code/Base/py-iceutils/current/askap/iceutils/monitoringprovider.py", "rank": 62, "score": 169032.64104016824 }, { "content": "namespace askap {\n\n\n\nnamespace synthesis {\n\n\n\n/// @brief A measurement equation, which does nothing.\n\n/// @details The current calibration class requires a perfect measurement\n\n/// equation. This class has been written to be able to use the same code \n\n/// for both applying a calibration and solving for parameters. It is \n\n/// a void measurement equation in the sense that it does nothing to the \n\n/// data or normal equations given to it.\n\n/// @ingroup measurementequation\n\nstruct VoidMeasurementEquation : public IMeasurementEquation\n\n{\n\n /// @brief Predict model visibilities for one accessor (chunk).\n\n /// @details This prediction is done for single chunk of data only. \n\n /// It seems that all measurement equations should work with accessors \n\n /// rather than iterators (i.e. the iteration over chunks should be \n\n /// moved to the higher level, outside this class). \n\n /// @param[in] chunk a read-write accessor to work with\n\n virtual void predict(accessors::IDataAccessor &chunk) const;\n\n\n\n /// @brief Calculate the normal equation for one accessor (chunk).\n\n /// @details This calculation is done for a single chunk of\n\n /// data only (one iteration).It seems that all measurement\n\n /// equations should work with accessors rather than iterators\n\n /// (i.e. the iteration over chunks should be moved to the higher\n\n /// level, outside this class). \n\n /// @param[in] chunk a read-write accessor to work with\n\n /// @param[in] ne Normal equations\n\n virtual void calcEquations(const accessors::IConstDataAccessor &chunk,\n\n askap::scimath::INormalEquations& ne) const;\n\n};\n\n\n\n} // namespace synthesis\n\n\n", "file_path": "Code/Components/Synthesis/synthesis/current/measurementequation/VoidMeasurementEquation.h", "rank": 63, "score": 168826.5319338146 }, { "content": "namespace askap {\n\n\n\nnamespace synthesis {\n\n\n\n/// @brief Basic composite illumination pattern\n\n/// @details This class is implements an basic composite illumination pattern corresponding\n\n/// to a given weights and offsets of physical feeds. It can be used for simulation and/or\n\n/// imaging with a synthetic beam. As an implementation of IBasicIllumination interface, \n\n/// this class provides a method to obtain illumination pattern by populating a pre-defined \n\n/// grid supplied as a UVPattern object. \n\n/// @note It looks like handling of illumination patterns\n\n/// inside gridders has to be generalised (i.e. main method should receive a full accessor\n\n/// with all the metadata instead of just the pointing offsets, frequency, etc). Such \n\n/// transition would definitely require an interface change in this class.\n\n/// @ingroup gridding\n\nstruct BasicCompositeIllumination : public IBasicIllumination {\n\n /// @brief construct the pattern using given weights and offsets\n\n /// @param[in] pattern single-feed illumination pattern (assumed the same for all feeds)\n\n /// @param[in] feedOffsets offsets of physical feeds in radians\n\n /// @param[in] weights complex weights for each feed\n\n /// @note The size of two vectors should be the same\n\n BasicCompositeIllumination(const boost::shared_ptr<IBasicIllumination> &pattern,\n\n const casa::Vector<casa::RigidVector<casa::Double, 2> > &feedOffsets,\n\n const casa::Vector<casa::Complex> &weights); \n\n \n\n /// @brief obtain illumination pattern\n\n /// @details This is the main method which populates the \n\n /// supplied uv-pattern with the values corresponding to the model\n\n /// represented by this object. It has to be overridden in the \n\n /// derived classes. An optional phase slope can be applied to\n\n /// simulate offset pointing.\n\n /// @param[in] freq frequency in Hz for which an illumination pattern is required\n\n /// @param[in] pattern a UVPattern object to fill\n\n /// @param[in] l angular offset in the u-direction (in radians)\n\n /// @param[in] m angular offset in the v-direction (in radians)\n\n /// @param[in] pa parallactic angle (in radians), or strictly speaking the angle between \n\n /// uv-coordinate system and the system where the pattern is defined\n\n virtual void getPattern(double freq, UVPattern &pattern, double l = 0., \n\n double m = 0., double pa = 0.) const;\n\n \n\n /// @brief check whether the pattern is symmetric\n\n /// @details Some illumination patterns are trivial and it may be known a priori that\n\n /// the pattern does not depend on the parallactic angle. This method allows to check\n\n /// whether such trivial case exists. If true is returned, getPattern ignores pa\n\n /// parameter.\n\n /// @return true if the pattern is symmetric, false otherwise\n\n virtual bool isSymmetric() const;\n\n \n\nprivate:\n\n /// @brief single-feed illumination pattern (assumed the same for all feeds)\n\n boost::shared_ptr<IBasicIllumination> itsPattern;\n\n \n\n /// @brief offsets of physical feeds in radians\n\n casa::Vector<casa::RigidVector<casa::Double, 2> > itsFeedOffsets;\n\n \n\n /// @brief complex weights for each physical feed\n\n casa::Vector<casa::Complex> itsWeights;\n\n \n\n /// @brief flag showing that this pattern is symmetric\n\n /// @details Whether or not it is the case depends on the assigned offsets\n\n /// (i.e. any non-zero offset means automatically that this pattern is asymmetric,\n\n /// it is checked in the constructor)\n\n bool itsSymmetricFlag;\n\n};\n\n\n\n} // namespace synthesis\n\n\n", "file_path": "Code/Components/Synthesis/synthesis/current/gridding/BasicCompositeIllumination.h", "rank": 64, "score": 168779.3384754149 }, { "content": "namespace askap {\n\nnamespace accessors {\n\n\n\n/// @brief An interface for accessing calibration solutions for reading.\n\n/// @details This interface is used to access calibration parameters\n\n/// read-only. A writable version of the interface is derived from this\n\n/// class. Various implementations are possible, i.e. parset-based, \n\n/// table-based and working via database ice service.\n\n/// @ingroup calibaccess\n\nstruct ICalSolutionConstAccessor {\n\n /// @brief virtual destructor to keep the compiler happy\n\n virtual ~ICalSolutionConstAccessor();\n\n \n\n // virtual methods which need to be overridden in concrete \n\n // implementation classes\n\n \n\n /// @brief obtain gains (J-Jones)\n\n /// @details This method retrieves parallel-hand gains for both \n\n /// polarisations (corresponding to XX and YY). If no gains are defined\n\n /// for a particular index, gains of 1. with invalid flags set are\n\n /// returned.\n\n /// @param[in] index ant/beam index \n\n /// @return JonesJTerm object with gains and validity flags\n\n virtual JonesJTerm gain(const JonesIndex &index) const = 0;\n\n \n\n /// @brief obtain leakage (D-Jones)\n\n /// @details This method retrieves cross-hand elements of the \n\n /// Jones matrix (polarisation leakages). There are two values\n\n /// (corresponding to XY and YX) returned (as members of JonesDTerm \n\n /// class). If no leakages are defined for a particular index,\n\n /// zero leakages are returned with invalid flags set. \n\n /// @param[in] index ant/beam index\n\n /// @return JonesDTerm object with leakages and validity flags\n\n virtual JonesDTerm leakage(const JonesIndex &index) const = 0;\n\n \n\n /// @brief obtain bandpass (frequency dependent J-Jones)\n\n /// @details This method retrieves parallel-hand spectral\n\n /// channel-dependent gain (also known as bandpass) for a\n\n /// given channel and antenna/beam. The actual implementation\n\n /// does not necessarily store these channel-dependent gains\n\n /// in an array. It could also implement interpolation or \n\n /// sample a polynomial fit at the given channel (and \n\n /// parameters of the polynomial could be in the database). If\n\n /// no bandpass is defined (at all or for this particular channel),\n\n /// gains of 1.0 are returned (with invalid flag is set).\n\n /// @param[in] index ant/beam index\n\n /// @param[in] chan spectral channel of interest\n\n /// @return JonesJTerm object with gains and validity flags\n\n virtual JonesJTerm bandpass(const JonesIndex &index, const casa::uInt chan) const = 0;\n\n \n\n // helper methods to simplify access to the calibration parameters\n\n \n\n /// @brief obtain full 2x2 Jones Matrix taking all effects into account\n\n /// @details This method returns resulting 2x2 matrix taking gain, leakage and\n\n /// bandpass effects (for a given channel) into account. Invalid gains (and bandpass\n\n /// values) are replaced by 1., invalid leakages are replaced by zeros. This method\n\n /// calls gain, bandpass and leakage virtual methods\n\n /// @param[in] index ant/beam index\n\n /// @param[in] chan spectral channel of interest\n\n /// @return 2x2 Jones matrix\n\n /// @note The relation between leakage terms and Jones matrices matches \n\n /// the definition of Hamaker, Bregman & Sault. See their equation \n\n /// (14) for details. Our parameters d12 (corresponding to Stokes:XY) and\n\n /// d21 (corresponding to Stokes::YX) correspond to d_{Ap} and d_{Aq} from\n\n /// Hamaker, Bregman & Sault, respectively. It is assumed that the gain errors\n\n /// are applied after leakages (i.e. R=GD). \n\n casa::SquareMatrix<casa::Complex, 2> jones(const JonesIndex &index, const casa::uInt chan) const;\n\n \n\n /// @brief obtain full 2x2 Jones Matrix taking all effects into account\n\n /// @details This version of the method accepts antenna and beam indices explicitly and\n\n /// does extra checks before calling the main method expressed via JonesIndex.\n\n /// @param[in] ant antenna index\n\n /// @param[in] beam beam index\n\n /// @param[in] chan spectral channel of interest\n\n /// @return 2x2 Jones matrix\n\n casa::SquareMatrix<casa::Complex, 2> jones(const casa::uInt ant, const casa::uInt beam, const casa::uInt chan) const;\n\n \n\n /// @brief obtain validity flag for the full 2x2 Jones Matrix\n\n /// @details This method combines all validity flags for parameters used to compose Jones\n\n /// matrix and returns true if all elements are valid and false if at least one constituent\n\n /// is not valid\n\n /// @param[in] index ant/beam index\n\n /// @param[in] chan spectral channel of interest\n\n /// @return true, if the matrix returned by jones(...) method called with the same parameters is\n\n /// valid, false otherwise\n\n bool jonesValid(const JonesIndex &index, const casa::uInt chan) const;\n\n \n\n /// @brief obtain validity flag for the full 2x2 Jones Matrix\n\n /// @details This version of the method accepts antenna and beam indices explicitly and\n\n /// does extra checks before calling the main method expressed via JonesIndex.\n\n /// @param[in] ant antenna index\n\n /// @param[in] beam beam index\n\n /// @param[in] chan spectral channel of interest\n\n /// @return true, if the matrix returned by jones(...) method called with the same parameters is\n\n /// valid, false otherwise\n\n bool jonesValid(const casa::uInt ant, const casa::uInt beam, const casa::uInt chan) const;\n\n\n\n /// @brief shared pointer definition\n\n typedef boost::shared_ptr<ICalSolutionConstAccessor> ShPtr;\n\n};\n\n\n\n} // namespace accessors\n", "file_path": "Code/Base/accessors/current/calibaccess/ICalSolutionConstAccessor.h", "rank": 65, "score": 168742.31176564324 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief A high-level interface to access calibration solutions\n\n/// @details This interface hides the database look up of the appropriate\n\n/// calibration solution. It manages solution IDs and provides access\n\n/// to the actual solution via ICalSolutionConstAccessor. A single\n\n/// solution ID refers to some gain, leakage and bandpass, although \n\n/// individual solutions may be obtained at different times. The read\n\n/// operation always delivers the \"active\" (i.e. most recent) solution \n\n/// at the given time.\n\n/// @ingroup calibaccess\n\nstruct ICalSolutionConstSource {\n\n\n\n /// @brief virtual destructor to keep the compiler happy\n\n virtual ~ICalSolutionConstSource();\n\n \n\n // virtual methods to be overridden in implementations\n\n \n\n /// @brief obtain ID for the most recent solution\n\n /// @return ID for the most recent solution\n\n virtual long mostRecentSolution() const = 0;\n\n \n\n /// @brief obtain solution ID for a given time\n\n /// @details This method looks for a solution valid at the given time\n\n /// and returns its ID. It is equivalent to mostRecentSolution() if\n\n /// called with a time sufficiently into the future.\n\n /// @param[in] time time stamp in seconds since MJD of 0.\n\n /// @return solution ID\n\n virtual long solutionID(const double time) const = 0;\n\n \n\n /// @brief obtain read-only accessor for a given solution ID\n\n /// @details This method returns a shared pointer to the solution accessor, which\n\n /// can be used to read the parameters. If a solution with the given ID doesn't \n\n /// exist, an exception is thrown. Existing solutions with undefined parameters \n\n /// are managed via validity flags of gains, leakages and bandpasses\n\n /// @param[in] id solution ID to read\n\n /// @return shared pointer to an accessor object\n\n virtual boost::shared_ptr<ICalSolutionConstAccessor> roSolution(const long id) const = 0;\n\n \n\n /// @brief shared pointer definition\n\n typedef boost::shared_ptr<ICalSolutionConstSource> ShPtr;\n\n};\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/calibaccess/ICalSolutionConstSource.h", "rank": 66, "score": 168742.31176564324 }, { "content": "class MonitorData(dict):\n\n \"\"\" :class:`dict` class adding :meth:`send` to send the dictionary\n\n to :class:`Monitoring` singleton.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n dict.__init__(self, *args, **kwargs)\n\n\n\n def publish(self):\n\n mon = get_monitor()\n", "file_path": "Code/Base/py-iceutils/current/askap/iceutils/monitorpublisher.py", "rank": 67, "score": 168720.63669109676 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief An interface to DATA_DESCRIPTION subtable\n\n/// @details A class derived from this interface provides access to\n\n/// the content of the DATA_DESCRIPTION table (which connects data\n\n/// description id with spectral window id and polarization id\n\n/// @ingroup dataaccess_tab\n\nstruct ITableDataDescHolder : virtual public IHolder {\n\n\n\n /// obtain spectral window ID via data description ID\n\n /// @param dataDescriptionID an index into data description table for\n\n /// which to return an associated spectral window ID\n\n /// @return spectral window id for a given dataDescriptionID\n\n /// @note return type has sign. User is responsible for interpreting\n\n /// the negative values\n\n virtual int getSpectralWindowID(size_t dataDescriptionID) const = 0;\n\n\n\n /// obtain polaraziation ID via data description ID\n\n /// @param dataDescriptionID an index into data description table for\n\n /// which to return an associated polarization ID\n\n /// @return polarization id for a given dataDescriptionID\n\n /// @note return type has sign. User is responsible for interpreting\n\n /// the negative values\n\n virtual int getPolarizationID(size_t dataDescriptionID) const = 0;\n\n\n\n /// obtain all data description IDs which correspond to the given\n\n /// spectral window ID (requires for selection on the spectral window)\n\n /// @param spWindowID a spectral window ID to search for\n\n /// @return a vector containing data description IDs\n\n /// @note a signed type is used for spWindowID. User is responsible for\n\n /// interpreting the negative values\n\n virtual std::vector<size_t> getDescIDsForSpWinID(int spWindowID) const = 0; \n\n};\n\n\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/ITableDataDescHolder.h", "rank": 68, "score": 168409.33600677756 }, { "content": "/// This class implements the \"MonitoringProvider\" Ice interface.\n\n/// Remote clients invoke methods on this class to fetch monitoring data.\n\nclass MonitoringProviderImpl : public askap::interfaces::monitoring::MonitoringProvider {\n\n public:\n\n /// @brief Constructor.\n\n MonitoringProviderImpl(DataManager& datasource);\n\n\n\n /// @brief Destructor.\n\n virtual ~MonitoringProviderImpl();\n\n\n\n /// The caller provides zero or more point names and the\n\n /// return value will contain at most the same number of\n\n /// monitoring points in the returned sequence.\n\n ///\n\n /// Where a point name is not available it will simply not\n\n /// be included in the result sequence.\n\n ///\n\n /// If an empty sequence is passed, the returned sequence will\n\n /// be empty.\n\n ///\n\n /// @param[in] pointnames a sequence of point names for\n\n /// which data will be fetched\n", "file_path": "Code/Components/Services/ingest/current/monitoring/MonitoringProviderImpl.h", "rank": 69, "score": 166914.7332916763 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief Parset file-based implementation of the calibration solution source\n\n/// @details This implementation is to be used with pre-existing code writing/reading\n\n/// the parset directly and with a number of tests. It is just to convert the legacy code.\n\n/// There is only one implementation of this class which is used for both reading and writing.\n\n/// Main functionality is implemented in the corresponding ParsetCalSolutionAccessor class.\n\n/// This class just creates an instance of the accessor and manages it.\n\n/// @ingroup calibaccess\n\nstruct ParsetCalSolutionConstSource : public CalSolutionConstSourceStub {\n\n /// @brief constructor\n\n /// @details Creates solution source object for a given parset file\n\n /// (whether it is for writing or reading depends on the actual methods\n\n /// used).\n\n /// @param[in] parset parset file name\n\n explicit ParsetCalSolutionConstSource(const std::string &parset);\n\n \n\n /// @brief shared pointer definition\n\n typedef boost::shared_ptr<ParsetCalSolutionConstSource> ShPtr;\n\n\n\n};\n\n\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/calibaccess/ParsetCalSolutionConstSource.h", "rank": 70, "score": 166881.6567126775 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\nstruct DataAccessTestImpl {\n\n /// demonstration of flagging from the given iterator position until the\n\n /// end of the block pointed by the iterator\n\n static void flaggingRoutine(const IDataSharedIter &di);\n\n\n\n /// demonstration of the read-only access\n\n static void readOnlyRoutine(const IConstDataSharedIter &cdi);\n\n\n\n /// obtaining iterators, invoke other methods\n\n static void doTheJob(const boost::shared_ptr<IDataSource> &ds);\n\n};\n\n\n\n} // namespace accessors\n", "file_path": "Code/Base/accessors/current/tests/dataaccess/DataAccessTestImpl.h", "rank": 71, "score": 166554.10034278792 }, { "content": "namespace askap {\n\n\n\nnamespace accessors {\n\n\n\n/// @brief Implementation of ITableDataDescHolder holding everything in memory\n\n/// @details This file contains a class implementing the ITableDataDescHolder\n\n/// interface by reading the appropriate subtable into memory in the constructor.\n\n/// @ingroup dataaccess_tab\n\nstruct MemTableDataDescHolder : public ITableDataDescHolder {\n\n\n\n /// read all required information from the DATA_DESCRIPTION subtable\n\n /// @param ms an input measurement set (a table which has a\n\n /// DATA_DESCRIPTION subtable defined)\n\n explicit MemTableDataDescHolder(const casa::Table &ms);\n\n \n\n /// obtain spectral window ID via data description ID\n\n /// @param dataDescriptionID an index into data description table for\n\n /// which to return an associated spectral window ID\n\n /// @return spectral window id for a given dataDescriptionID\n\n /// @note return type has sign. User is responsible for interpreting\n\n /// the negative values\n\n virtual int getSpectralWindowID(size_t dataDescriptionID) const;\n\n\n\n /// obtain polaraziation ID via data description ID\n\n /// @param dataDescriptionID an index into data description table for\n\n /// which to return an associated polarization ID\n\n /// @return polarization id for a given dataDescriptionID\n\n /// @note return type has sign. User is responsible for interpreting\n\n /// the negative values\n\n virtual int getPolarizationID(size_t dataDescriptionID) const;\n\n\n\n /// obtain all data description IDs which correspond to the given\n\n /// spectral window ID (requires for selection on the spectral window)\n\n /// @param spWindowID a spectral window ID to search for\n\n /// @return a vector containing data description IDs\n\n /// @note a signed type is used for spWindowID. User is responsible for\n\n /// interpreting the negative values\n\n virtual std::vector<size_t> getDescIDsForSpWinID(int spWindowID) const;\n\nprivate:\n\n std::vector<std::pair<int, int> > itsDataDescription;\n\n};\n\n\n\n\n\n} // namespace accessors\n\n\n", "file_path": "Code/Base/accessors/current/dataaccess/MemTableDataDescHolder.h", "rank": 72, "score": 166554.10034278792 }, { "content": "# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages\n\ntry:\n\n __import__('pkg_resources').declare_namespace(__name__)\n\nexcept ImportError:\n\n from pkgutil import extend_path\n\n __path__ = extend_path(__path__, __name__)\n", "file_path": "Code/Components/Analysis/data/current/askap/__init__.py", "rank": 73, "score": 166375.35406146443 }, { "content": " private long lastSBID = -10;\n", "file_path": "Code/Components/Services/manager/current/src/askap/cp/manager/ingest/IngestMonitorThread.java", "rank": 74, "score": 165699.14026493052 }, { "content": "namespace askap {\n\n\n\nnamespace synthesis {\n\n\n\n/// @brief Calibration effect: antenna gains without cross-pol, one value for all beams\n\n/// @details This is a simple effect which can be used in conjunction\n\n/// with the CalibrationME template (as its template argument)\n\n/// @ingroup measurementequation\n\nstruct NoXPolBeamIndependentGain : public ParameterizedMEComponent<false> {\n\n \n\n /// @brief constructor, store reference to paramters\n\n /// @param[in] par shared pointer to parameters\n\n inline explicit NoXPolBeamIndependentGain(const scimath::Params::ShPtr &par) : \n\n ParameterizedMEComponent<false>(par) {}\n\n \n\n /// @brief main method returning Mueller matrix and derivatives\n\n /// @details This method has to be overloaded (in the template sense) for\n\n /// all classes representing various calibration effects. CalibrationME\n\n /// template will call it when necessary. It returns \n\n /// @param[in] chunk accessor to work with\n\n /// @param[in] row row of the chunk to work with\n\n /// @return ComplexDiffMatrix filled with Mueller matrix corresponding to\n\n /// this effect\n\n inline scimath::ComplexDiffMatrix get(const accessors::IConstDataAccessor &chunk, \n\n casa::uInt row) const; \n\n};\n\n\n\n} // namespace synthesis\n\n\n", "file_path": "Code/Components/Synthesis/synthesis/current/measurementequation/NoXPolBeamIndependentGain.h", "rank": 75, "score": 165117.78719468563 }, { "content": " private void updateDataService(long sbid, List<MonitorPoint> pointValues) {\n\n\n\n // don't need to update Dataservice if we have already. Assume the obs detail\n\n // does not change during observation.\n\n if (this.lastSBID == sbid)\n\n return;\n\n\n\n MonitorPoint startFreqPoint = null;\n\n MonitorPoint nChanPoint = null;\n\n MonitorPoint chanWidthPoint = null;\n\n\n\n for (MonitorPoint point : pointValues) {\n\n\n\n if (point.name.equals(\"cp.ingest.obs.StartFreq\"))\n\n startFreqPoint = point;\n\n else if (point.name.equals(\"cp.ingest.obs.nChan\"))\n\n nChanPoint = point;\n\n else if (point.name.equals(\"cp.ingest.obs.ChanWidth\"))\n\n chanWidthPoint = point;\n\n }\n\n\n\n /*\n\n * write observation details as a json string:\n\n *\n\n * {\n\n * \"nChan\": {\"value\": 10368},\n\n * \"ChanWidth\": {\"value\": 1344.49, \"unit\": \"MHz\"},\n\n * \"StartFreq\": {\"value\": 1344.49, \"unit\": \"MHz\"},\n\n * \"CentreFreq\": {\"value\": 2344.49, \"unit\": \"MHz\"},\n\n * \"BandWidth\": {\"value\": 192.00, \"unit\": \"MHz\"}\n\n * }\n\n *\n\n */\n\n if (startFreqPoint != null && nChanPoint != null && chanWidthPoint != null) {\n\n\n\n double startFreq = ((TypedValueDouble) startFreqPoint.value).value;\n\n double chanWidth = ((TypedValueDouble) chanWidthPoint.value).value;\n\n long nChan = ((TypedValueLong) nChanPoint.value).value;\n\n\n\n double bandWidth = 0;\n\n if (chanWidthPoint.unit.equalsIgnoreCase(\"khz\"))\n\n bandWidth = chanWidth * nChan / 1000;\n\n else // assume mhz\n\n bandWidth = chanWidth * nChan;\n\n\n\n double centreFreq = startFreq + bandWidth / 2;\n\n\n\n JsonObject obsInfo = new JsonObject();\n\n\n\n JsonObject obj = new JsonObject();\n\n obj.addProperty(\"value\", nChan);\n\n obsInfo.add(\"nChan\", obj);\n\n\n\n obj = new JsonObject();\n\n obj.addProperty(\"value\", chanWidth);\n\n obj.addProperty(\"unit\", chanWidthPoint.unit);\n\n obsInfo.add(\"ChanWidth\", obj);\n\n\n\n obj = new JsonObject();\n\n obj.addProperty(\"value\", startFreq);\n\n obj.addProperty(\"unit\", startFreqPoint.unit);\n\n obsInfo.add(\"StartFreq\", obj);\n\n\n\n obj = new JsonObject();\n\n obj.addProperty(\"value\", centreFreq);\n\n obj.addProperty(\"unit\", startFreqPoint.unit);\n\n obsInfo.add(\"CentreFreq\", obj);\n\n\n\n obj = new JsonObject();\n\n obj.addProperty(\"value\", bandWidth);\n\n obj.addProperty(\"unit\", startFreqPoint.unit);\n\n obsInfo.add(\"BandWidth\", obj);\n\n\n\n\n\n Map<String, String> obsVar = new HashMap<String, String>();\n\n obsVar.put(\"obs.info\", theirGson.toJson(obsInfo));\n\n\n\n try {\n\n ClientServiceFactory.getDataServiceClient().setObsVariables(sbid, obsVar);\n\n this.lastSBID = sbid;\n\n } catch (Exception e) {\n\n logger.error(\"Could not update Dataservice with observation details\", e);\n\n }\n\n }\n", "file_path": "Code/Components/Services/manager/current/src/askap/cp/manager/ingest/IngestMonitorThread.java", "rank": 76, "score": 163296.2993353305 }, { "content": " public void setObsVariables(long sbid, Map<String, String> obsVars)\n", "file_path": "Code/Components/Services/manager/current/src/askap/cp/manager/svcclients/IDataServiceClient.java", "rank": 77, "score": 163226.96174812582 }, { "content": "# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages\n\ntry:\n\n __import__('pkg_resources').declare_namespace(__name__)\n\nexcept ImportError:\n\n from pkgutil import extend_path\n\n __path__ = extend_path(__path__, __name__)\n", "file_path": "Code/Components/Analysis/data/current/askap/analysis/__init__.py", "rank": 78, "score": 161833.5372301237 }, { "content": " @Override\n\n public void setObsVariables(long sbid, Map<String, String> obsVars) throws NoSuchSchedulingBlockException, ParameterException {\n\n // only need to check the obsVar string is correct\n\n String obsVar = obsVars.get(\"obs.info\");\n\n FuncTestReporterClient.getFuncTestReporterClient().methodCalled(obsVar);\n", "file_path": "Code/Components/Services/manager/current/src/askap/cp/manager/svcclients/MockDataServiceClient.java", "rank": 79, "score": 159314.34088777882 }, { "content": " @Override\n\n public void setObsVariables(long sbid, Map<String, String> obsVars) throws NoSuchSchedulingBlockException, ParameterException {\n\n getProxy();\n\n itsProxy.setObsVariables(sbid, obsVars);\n", "file_path": "Code/Components/Services/manager/current/src/askap/cp/manager/svcclients/IceDataServiceClient.java", "rank": 80, "score": 159314.34088777882 }, { "content": "// Enumerated constants for data status.\n\n// UNKNOWN: the data status is unknown\n\n// EMPTY : no data inside\n\n// FULL : data inside\n\nenum CorrBufferUnitStatus { UNKNOWN = 0, EMPTY = 1, FULL = 2 };\n\n\n\n#endif\n\n\n\n\n\n\n", "file_path": "Code/Components/Services/correlatorsim/current/simplayback/CorrBufferUnit.h", "rank": 81, "score": 157995.7916803237 }, { "content": "/// @brief task for running another task in a parallel thread\n\n/// @details This task is a wrapper around any other task known to the ingest pipeline.\n\n/// Except for the first chunk of data which is just passed to the child task as is\n\n/// (to allow adjustment to the actual configuration of the parallel streams within the\n\n/// ingest pipeline), this task makes the copy of the data, buffers them and executes the\n\n/// child task in a parallel thread. Provided the execution time plus copy overheads \n\n/// do not exceed the cycle time, this allows better utilisation of resources and more\n\n/// distributed computing. The child task should obey the following conditions (otherwise,\n\n/// ingesting will not work correctly and may even lock up):\n\n/// * it should not modify the data\n\n/// * it should not alter the distribution of data streams (except on the first cycle)\n\n/// For example, MSSink or TCPSink are suitable while ChannelAvgTask or BeamScatterTask are not.\n\n/// The code has limited ability to detect misuse, so it is largely up to an expert user to \n\n/// configure ingest pipeline correctly to avoid problems. This task supports a couple of\n\n/// different strategies deailg with the processing not keeping up: throw an exception, \n\n/// skip the data.\n\n///\n\n/// Parameters (example):\n\n/// child = MSSink (child task, same name as understood in tasklist)\n\n/// lossless = true (if not allowed to skip data in the not-keeping up case)\n\n/// size = 1 (circular buffer size)\n\n/// maxwait = 20 (maximum waiting time in seconds for the child task to complete)\n\n///\n\nclass BufferedTask : public askap::cp::ingest::ITask {\n\n public:\n\n\n\n /// @brief Constructor\n\n /// @param[in] parset the configuration parameter set.\n\n /// @param[in] config configuration\n\n BufferedTask(const LOFAR::ParameterSet& parset,\n\n const Configuration& config);\n\n\n\n /// @brief destructor\n\n ~BufferedTask();\n\n\n\n /// @brief Process single visibility chunk\n\n /// @details There is no modification of the data, just internal buffers are updated.\n\n /// If the child task updates the chunk this change is lost, except on the first \n\n /// iteration where the task is allowed to change data distribution by resetting\n\n /// the shared pointer where appropriate.\n\n ///\n\n /// @param[in,out] chunk the instance of VisChunk for which the\n\n /// phase factors will be applied.\n", "file_path": "Code/Components/Services/ingest/current/ingestpipeline/bufferedtask/BufferedTask.h", "rank": 82, "score": 155264.04373298964 }, { "content": "/// @brief Task to scatter beams\n\n/// @details This task increases the number of parallel streams handling data \n\n/// by scattering beams to different streams. For simplicity, only one stream\n\n/// is allowed to be active prior to this task and this rank will continue to\n\n/// be active past this task (if this approach is proven to be worthwhile, \n\n/// we would need to rework the whole visibility corner turn and merge gather in\n\n/// frequency with scatter in beams.\n\n///\n\n/// This task requires a configuration entry in the parset passed to the\n\n/// constructor. This configuration entry specifies how many streams will exist\n\n/// after this task. For example:\n\n/// @verbatim\n\n/// nstreams = 6\n\n/// @endverbatim\n\n/// The above results in 6 parallel streams handling roughly 1/6 of the beam space\n\n/// each. Obviously, total number of ranks should be equal or more than the\n\n/// value of this parameter.\n\nclass BeamScatterTask : public askap::cp::ingest::ITask {\n\n public:\n\n /// @brief Constructor.\n\n /// @param[in] parset the parameter set used to configure this task.\n\n /// @param[in] config configuration\n\n BeamScatterTask(const LOFAR::ParameterSet& parset, const Configuration& config);\n\n\n\n /// @brief Destructor.\n\n virtual ~BeamScatterTask();\n\n\n\n /// @brief Splits chunks.\n\n ///\n\n /// @param[in,out] chunk the instance of VisChunk to work with\n\n /// This method manipulates the VisChunk\n\n /// instance which is passed in, hence the value of the\n\n /// pointer may be changed \n\n virtual void process(askap::cp::common::VisChunk::ShPtr& chunk);\n\n\n\n /// @brief should this task be executed for inactive ranks?\n\n /// @details If a particular rank is inactive, process method is\n", "file_path": "Code/Components/Services/ingest/current/ingestpipeline/beamscattertask/BeamScatterTask.h", "rank": 83, "score": 152280.0998818906 }, { "content": "/// @brief task for monitoring average data properties\n\n/// @details This task is intended to be used in early commissioning experiments.\n\n/// It is an alternative diagnostics to check the average amplitude, phase and\n\n/// delay for the subset of data managed by this particular rank (in the way\n\n/// similar to software correlator). This class is not intended to survive\n\n/// in its current form in the long term.\n\nclass SimpleMonitorTask : public askap::cp::ingest::ITask {\n\n public:\n\n\n\n /// @brief Constructor\n\n /// @param[in] parset the configuration parameter set.\n\n /// @param[in] config configuration\n\n SimpleMonitorTask(const LOFAR::ParameterSet& parset,\n\n const Configuration& config);\n\n\n\n /// @brief destructor\n\n ~SimpleMonitorTask();\n\n\n\n /// @brief Extract required information from visibilities in the specified VisChunk.\n\n /// @details There is no modification of the data, just internal buffers are updated.\n\n ///\n\n /// @param[in,out] chunk the instance of VisChunk for which the\n\n /// phase factors will be applied.\n\n virtual void process(askap::cp::common::VisChunk::ShPtr& chunk);\n\n\n\n protected:\n", "file_path": "Code/Components/Services/ingest/current/ingestpipeline/simplemonitortask/SimpleMonitorTask.h", "rank": 84, "score": 152214.9161832399 }, { "content": "/// @brief Implementation of IConstDataSource in the table-based case\n\n/// @details\n\n/// TableConstDataSource: Allow read-only access to the data stored in the\n\n/// measurement set. This class implements IConstDataSource interface.\n\n/// @ingroup dataaccess_tab\n\nclass TableConstDataSource : virtual public IConstDataSource,\n\n virtual protected TableInfoAccessor\n\n{\n\npublic:\n\n /// @brief construct a read-only data source object\n\n /// @details All iterators obtained from this object will be read-only\n\n /// iterators.\n\n /// @param[in] fname file name of the measurement set to use\n\n /// @param[in] dataColumn a name of the data column used by default\n\n /// (default is DATA)\n\n explicit TableConstDataSource(const std::string &fname, \n\n const std::string &dataColumn = \"DATA\");\n\n \n\n /// create a converter object corresponding to this type of the\n\n /// DataSource. The user can change converting policies (units,\n\n /// reference frames) by appropriate calls to this converter object\n\n /// and pass it back to createConstIterator(...). The data returned by\n\n /// the iteratsr will automatically be in the requested frame/units\n\n ///\n\n /// @return a shared pointer to a new DataConverter object\n", "file_path": "Code/Base/accessors/current/dataaccess/TableConstDataSource.h", "rank": 85, "score": 151985.81337726206 }, { "content": "/// @brief an implementation of IConstDataAccessor in the table-based case\n\n///\n\n/// @details TableConstDataAccessor is an implementation of the\n\n/// DataAccessor working with TableConstDataIterator.\n\n/// It is currently\n\n/// derived from DataAccessorStub as most of the\n\n/// methods are stubbed. However, in the future\n\n/// it should become a separate class derived\n\n/// directly from its interface\n\n/// @ingroup dataaccess_tab\n\nclass TableConstDataAccessor : virtual public IConstDataAccessor\n\n{\n\npublic:\n\n /// construct an object linked with the given iterator\n\n /// @param iter a reference to associated iterator\n\n explicit TableConstDataAccessor(const TableConstDataIterator &iter);\n\n\n\n /// The number of rows in this chunk\n\n /// @return the number of rows in this chunk\n\n virtual casa::uInt nRow() const throw();\n\n\n\n /// The number of spectral channels (equal for all rows)\n\n /// @return the number of spectral channels\n\n virtual casa::uInt nChannel() const throw();\n\n\n\n /// The number of polarization products (equal for all rows)\n\n /// @return the number of polarization products (can be 1,2 or 4)\n\n virtual casa::uInt nPol() const throw();\n\n \n\n /// Return pointing centre directions of the first antenna/feed\n", "file_path": "Code/Base/accessors/current/dataaccess/TableConstDataAccessor.h", "rank": 86, "score": 151979.573310659 }, { "content": "/// @brief Implementation of IConstDataIterator in the table-based case\n\n/// @details\n\n/// TableConstDataIterator: Allow read-only iteration across preselected data. Each \n\n/// iteration step is represented by the IConstDataAccessor interface.\n\n/// This is an implementation in the table-based case.\n\n/// @ingroup dataaccess_tab\n\nclass TableConstDataIterator : virtual public IConstDataIterator,\n\n virtual public TableInfoAccessor\n\n{\n\npublic:\n\n /// @brief constructor of the const iterator\n\n /// @param[in] msManager a manager of the measurement set to use\n\n /// @param[in] sel shared pointer to selector\n\n /// @param[in] conv shared pointer to converter\n\n /// @param[in] cacheSize a number of uvw machines in the cache (default is 1)\n\n /// @param[in] tolerance pointing direction tolerance in radians, exceeding which leads \n\n /// to initialisation of a new UVW Machine\n\n /// @param[in] maxChunkSize maximum number of rows per accessor\n\n TableConstDataIterator(const boost::shared_ptr<ITableManager const>\n\n &msManager,\n\n const boost::shared_ptr<ITableDataSelectorImpl const> &sel,\n\n\t const boost::shared_ptr<IDataConverterImpl const> &conv,\n\n\t size_t cacheSize = 1, double tolerance = 1e-6,\n\n\t casa::uInt maxChunkSize = INT_MAX);\n\n\n\n /// Restart the iteration from the beginning\n", "file_path": "Code/Base/accessors/current/dataaccess/TableConstDataIterator.h", "rank": 87, "score": 151979.54061020407 }, { "content": "/// @brief basic on-the-fly monitor dumping data into an ascii file\n\n/// @details This implementation of the data monitor dumps delay and\n\n/// visibility history into ascii files for on-the-fly monitoring along\n\n/// with the latest spectra for each beam. Unlike BasicMonitor, this\n\n/// one opens an ascii file in the constructor and appends the data\n\n/// indefinitely.\n\n/// @ingroup swcorrelator\n\nclass SimpleVisMonitor : public IMonitor {\n\npublic:\n\n /// @brief constructor\n\n SimpleVisMonitor();\n\n\n\n /// @brief create and configure the monitor \n\n /// @details\n\n /// @param[in] parset parset with parameters (without the swcorrelator prefix)\n\n /// @return shared pointer to the monitor\n\n static boost::shared_ptr<IMonitor> setup(const LOFAR::ParameterSet &parset);\n\n \n\n /// @brief name of the monitor\n\n /// @return the name of the monitor\n\n static std::string name() { return \"simple\"; }\n\n \n\n /// @brief initialise publishing\n\n /// @details Technically, this step is not required. But given the\n\n /// current design of the code it seems better to give a hint on the maximum\n\n /// possible number of antennas, beams and channels, e.g. to initialise caches.\n\n /// @param[in] nAnt maximum number of antennas\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/SimpleVisMonitor.h", "rank": 88, "score": 151343.2720684634 }, { "content": "/// @brief manages buffers for raw data\n\n/// @details This class manages buffers for raw data. \n\n/// It keeps track of the current status (i.e. free, filled, \n\n/// being reduced) providing the required syncronisation between\n\n/// parallel threads accessing the buffers. The number of buffers should be\n\n/// at least twice the number of beams * antennas * cards.\n\n/// @ingroup swcorrelator\n\nclass BufferManager {\n\npublic:\n\n /// @brief 3 buffers corresponding to the same channel and beam\n\n struct BufferSet {\n\n BufferSet() : itsAnt1(-1), itsAnt2(-1), itsAnt3(-1) {}\n\n int itsAnt1;\n\n int itsAnt2;\n\n int itsAnt3;\n\n };\n\n \n\n enum BufferStatus {\n\n BUF_FREE = 0,\n\n BUF_BEING_FILLED,\n\n BUF_READY,\n\n BUF_BEING_PROCESSED\n\n };\n\n \n\n /// @brief constructor\n\n /// @details\n\n /// @param[in] nBeam number of beams\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/BufferManager.h", "rank": 89, "score": 150832.23688571565 }, { "content": "class DelaySolverApp : public askap::Application {\n\npublic:\n\n /// @brief process a single file\n\n /// @param[in] ds data source\n\n /// @param[in] currentDelays a vector with fixed delays (per antenna) used for observations\n\n void process(const IConstDataSource &ds, const std::vector<double>& currentDelays);\n\n \n\n /// @brief run application\n\n /// @param[in] argc number of parameters\n\n /// @param[in] argv parameter vector\n\n /// @return exit code\n\n virtual int run(int argc, char *argv[]);\n\nprotected:\n\n /// @brief helper method to fill antenna names\n\n /// @details This method extracts antenna names from the supplied parset of ingest pipeline\n\n /// (obtained via the SB number) and populates itsAntennaNames in the order of ingest indices.\n\n /// @param[in] parset parset used with ingest pipeline\n\n void fillAntennaNames(const LOFAR::ParameterSet &parset);\n\n\n\n /// @brief helper method to extract current delays from the ingest's parset\n", "file_path": "Code/Components/Utilities/current/apps/delaysolver.cc", "rank": 90, "score": 150585.36486178997 }, { "content": "/// @brief manages buffers for raw data\n\n/// @details This class provides support for more than 3 baselines. Although\n\n/// the original BufferManager accepts the number of antennas as its parameter,\n\n/// it is only used to resize the storage accordingly. The logic to split \n\n/// the set of baselines into 3-antenna triangles is implemented here.\n\n/// @ingroup swcorrelator\n\nclass ExtendedBufferManager : public BufferManager {\n\npublic:\n\n\n\n /// @brief constructor\n\n /// @details\n\n /// @param[in] nBeam number of beams\n\n /// @param[in] nChan number of channels (cards)\n\n /// @param[in] nAnt number of antennas\n\n /// @param[in[ hdrProc optional shared pointer to the header preprocessor\n\n ExtendedBufferManager(const size_t nBeam, const size_t nChan, const size_t nAnt = 3, \n\n const boost::shared_ptr<HeaderPreprocessor> &hdrProc = boost::shared_ptr<HeaderPreprocessor>());\n\n \n\n /// @brief get filled buffers for a matching channel + beam\n\n /// @details This method returns the first available set of\n\n /// completely filled buffers corresponding to the same channel\n\n /// and beam. The calling thread is blocked until a suitable set\n\n /// is available for correlation.\n\n /// @return a set of buffers ready for correlation\n\n virtual BufferSet getFilledBuffers() const;\n\n \n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/ExtendedBufferManager.h", "rank": 91, "score": 150001.10153118343 }, { "content": " class access::object_traits< ::askap::cp::sms::datamodel::DataSource >\n\n {\n\n public:\n\n typedef ::askap::cp::sms::datamodel::DataSource object_type;\n\n typedef ::boost::shared_ptr< ::askap::cp::sms::datamodel::DataSource > pointer_type;\n\n typedef odb::pointer_traits<pointer_type> pointer_traits;\n\n\n\n static const bool polymorphic = false;\n\n\n\n typedef ::askap::cp::sms::datamodel::id_type id_type;\n\n typedef ::askap::cp::sms::datamodel::version_type version_type;\n\n\n\n static const bool auto_id = true;\n\n\n\n static const bool abstract = false;\n\n\n\n static id_type\n\n id (const object_type&);\n\n\n\n typedef\n", "file_path": "Code/Components/Services/skymodel/current/datamodel/DataSource-odb.h", "rank": 92, "score": 149737.33154631557 }, { "content": "/// @brief Interface class for read-only access to visibility data\n\n/// @details IConstDataAccessor is an interface class for read-only \n\n/// access to buffered visibility data. Working instances include \n\n/// a chunk of streamed data or a portion of the disk-based table. \n\n/// A reference to this type is returned by a derivative from\n\n/// IConstDataIterator\n\n/// @ingroup dataaccess_i\n\nclass IConstDataAccessor\n\n{\n\npublic:\n\n\t\n\n\t/// Destruct\n\n\tvirtual ~IConstDataAccessor();\n\n\t\t\n\n\t/// The number of rows in this chunk\n\n\t/// @return the number of rows in this chunk\n\n\tvirtual casa::uInt nRow() const throw() = 0;\n\n\n\n // The following methods implement metadata access\n\n\t\t\n\n\t/// The number of spectral channels (equal for all rows)\n\n\t/// @return the number of spectral channels\n\n\tvirtual casa::uInt nChannel() const throw() = 0;\n\n\n\n\t/// The number of polarization products (equal for all rows)\n\n\t/// @return the number of polarization products (can be 1,2 or 4)\n\n\tvirtual casa::uInt nPol() const throw() = 0;\n", "file_path": "Code/Base/accessors/current/dataaccess/IConstDataAccessor.h", "rank": 93, "score": 147307.8014075735 }, { "content": "/// @brief Read-only iterator across preselected data\n\n/// @details Each \n\n/// iteration step is represented by the IConstDataAccessor interface.\n\n/// The idea is that an iterator object will be obtained via IDataSource\n\n/// which will take care of the actual method to access the data and the\n\n/// source (a MeasurementSet or a stream). Any class controlling data selection\n\n/// is likely to be held by a real implementation of the iterator. However,\n\n/// it will be set up via the IDataSource object and IS NOT a part of this\n\n/// interface.\n\n/// \n\n/// Additional read/write buffers can be used via the IDataIterator, which\n\n/// implements a read/write interface\n\n/// @ingroup dataaccess_i\n\nclass IConstDataIterator\n\n{\n\npublic:\n\n\t/// the type of the value pointed by this iterator\n\n\ttypedef const IConstDataAccessor& value_type;\n\n\n\n\t/// the type of the pointer returned by operator->\n\n\t/// We can't generally just use value_type * because \n\n\ttypedef const IConstDataAccessor* pointer_type;\n\n\n\n\t/// an empty virtual destructor to make the compiler happy\n\n\tvirtual ~IConstDataIterator();\n\n\t\n\n\t/// Restart the iteration from the beginning\n\n\tvirtual void init() = 0;\n\n\t\n\n\t/// Return the data accessor (current chunk) in various ways\n\n\t\n\n\t/// operator* delivers a reference to data accessor (current chunk)\n\n\t/// @return a reference to the current chunk\n", "file_path": "Code/Base/accessors/current/dataaccess/IConstDataIterator.h", "rank": 94, "score": 147299.6159504557 }, { "content": "/// @brief Read-only access to a source of visibility data\n\n/// @details IConstDataSource allows access to a source of visibility data,\n\n/// probably either a MeasurementSet or a stream.\n\n/// @ingroup dataaccess_i\n\nclass IConstDataSource\n\n{\n\npublic:\n\n\t\n\n\t/// an empty virtual destructor to make the compiler happy\n\n\tvirtual ~IConstDataSource();\n\n\n\n\t/// create a converter object corresponding to this type of the\n\n\t/// DataSource. The user can change converting policies (units,\n\n\t/// reference frames) by appropriate calls to this converter object\n\n\t/// and pass it back to createConstIterator(...). The data returned by\n\n\t/// the iteratsr will automatically be in the requested frame/units\n\n\t///\n\n\t/// @return a shared pointer to a new DataConverter object\n\n\t///\n\n\t/// The method acts as a factory by creating a new DataConverter.\n\n\t/// The lifetime of this converter is the same as the lifetime of the\n\n\t/// DataSource object. Therefore, it can be reused multiple times,\n\n\t/// if necessary. However, the behavior of iterators created\n\n\t/// with a particular DataConverter is undefined, if you change\n", "file_path": "Code/Base/accessors/current/dataaccess/IConstDataSource.h", "rank": 95, "score": 147294.9498177687 }, { "content": "class DataSet\n\n{\n\n public:\n\n DataSet(const std::string& filename, const LOFAR::ParameterSet& parset);\n\n ~DataSet();\n\n\n\n void add(void);\n\n\n\n private:\n\n void create(const std::string& filename);\n\n void initAnt(void);\n\n void initFields(void);\n\n void initSpWindows(void);\n\n void initFeeds(void);\n\n void initObs(void);\n\n\n\n casa::MeasurementSet* itsMs;\n\n LOFAR::ParameterSet itsParset;\n\n};\n\n\n\n#endif\n", "file_path": "Code/Components/CP/benchmarks/current/msperf/writers/DataSet.h", "rank": 96, "score": 147289.65801521053 }, { "content": "/// @brief\n\n/// An implementation of the data converter (IDataConverter interface).\n\n/// @details\n\n/// The intention is to use this class in conjunction\n\n/// with the table based implementation of the data accessor. However,\n\n/// it looks at this stage that this class is relatively general and can be\n\n/// used with any implementation of the data accessor layer. One may want to\n\n/// write a different implementation to achieve a better optimization, which\n\n/// may be specific to a particular DataSource.\n\n///\n\n/// The main idea is to supply a DataConverter and DataSelector when\n\n/// an iterator is requested from the DataSource object. The iterator will\n\n/// return the data in the requested frame/units. The end user interacts\n\n/// with the IDataConverter interface only.\n\n/// @ingroup dataaccess_conv\n\nclass BasicDataConverter : virtual public IDataConverterImpl\n\n{\n\npublic:\n\n /// default constructor sets up the default conversion options,\n\n /// which are:\n\n /// for Epoch, origin/frame are MJD 0 UTC, units are seconds\n\n /// (defined in the default arguments for the\n\n /// constructor of EpochConverter)\n\n /// for Directions, frame is J2000, units are not used\n\n BasicDataConverter();\n\n\n\n /// implementation of the interface methods\n\n\n\n /// set the reference frame for any time epochs \n\n /// (e.g. time-based selection, visibility timestamp)\n\n /// The value of the specified measure is the origin epoch. \n\n /// All visibility timestamps will be given as offsets from\n\n /// it. The units of these offsets are given by the second\n\n /// parameter\n\n /// @param[in] origin a zero-point for the visibility timestamps \n", "file_path": "Code/Base/accessors/current/dataaccess/BasicDataConverter.h", "rank": 97, "score": 147070.45819436706 }, { "content": "/// @brief a factory class creating data monitors \n\n/// @details We support both built-in and dynamically loadable\n\n/// data monitors (i.e. something which is called for every chunk of the\n\n/// data written to the MS). The latter can be used for example to implement\n\n/// monitoring via epics.\n\n/// @ingroup swcorrelator\n\nclass MonitorFactory : private boost::noncopyable {\n\n\n\n /// @brief default constructor\n\n /// @details It is declared private, so this type cannot be explicitly created.\n\n /// All work is done via static methods\n\n MonitorFactory();\n\n\n\npublic: \n\n /// @brief signature of the factory method\n\n /// @details All functions creating an IMonitor objects must have this\n\n /// signature. Preferably, such a function should be a static method of the \n\n /// appropriate monitor class.\n\n typedef IMonitor::ShPtr MonitorCreator(const LOFAR::ParameterSet &);\n\n \n\n /// @brief helper method to register a monitor\n\n /// @param[in] name name of the monitor (key into the map)\n\n /// @param[in] creatorFunc factory function able to create the monitor\n\n static void registerMonitor(const std::string &name, MonitorCreator *creatorFunc);\n\n\n\n /// @brief factory method\n", "file_path": "Code/Components/swcorrelator/current/swcorrelator/MonitorFactory.h", "rank": 98, "score": 146061.64268471245 }, { "content": "/// @brief an adapter to most methods of IConstDataAccessor with buffering\n\n///\n\n/// @details This class is somewhat similar to MemBufferDataAccessor, however it is\n\n/// not as basic. The latter doesn't manage the cube at all and only ensures that it has\n\n/// a conforming size. In contrast, this class returns the existing read-only visibility cube \n\n/// until a non-const reference is requested (rwVisibility). Then the read-only visibilities are\n\n/// copied to the internal buffer and the reference to this buffer is passed for all later calls\n\n/// to read-write and read-only methods until either the shape changes or discardCache method is\n\n/// called. The intention is to provide a similar functionality for the flagging methos\n\n/// @ingroup dataaccess_hlp\n\nclass OnDemandBufferDataAccessor : virtual public MetaDataAccessor,\n\n virtual public IDataAccessor,\n\n public boost::noncopyable\n\n{\n\npublic:\n\n /// construct an object linked with the given const accessor\n\n /// @param[in] acc a reference to the associated accessor\n\n explicit OnDemandBufferDataAccessor(const IConstDataAccessor &acc);\n\n \n\n /// Read-only visibilities (a cube is nRow x nChannel x nPol; \n\n /// each element is a complex visibility)\n\n ///\n\n /// @return a reference to nRow x nChannel x nPol cube, containing\n\n /// all visibility data\n\n ///\n\n virtual const casa::Cube<casa::Complex>& visibility() const;\n\n\n\n\t\n\n /// Read-write access to visibilities (a cube is nRow x nChannel x nPol;\n\n /// each element is a complex visibility)\n", "file_path": "Code/Base/accessors/current/dataaccess/OnDemandBufferDataAccessor.h", "rank": 99, "score": 144523.30532490328 } ]
C++
src/core/net/netif.cpp
jjzhang166/openthread
e68e38b8e85fe4eeb3810727cd3583b5f87a4e70
#include <common/code_utils.hpp> #include <common/debug.hpp> #include <common/message.hpp> #include <net/netif.hpp> namespace Thread { namespace Ip6 { Netif *Netif::sNetifListHead = NULL; int Netif::sNextInterfaceId = 1; Netif::Netif() : mUnicastChangedTask(&HandleUnicastChangedTask, this) { mHandlers = NULL; mUnicastAddresses = NULL; mMulticastAddresses = NULL; mInterfaceId = -1; mAllRoutersSubscribed = false; mNext = NULL; } ThreadError Netif::RegisterHandler(NetifHandler &aHandler) { ThreadError error = kThreadError_None; for (NetifHandler *cur = mHandlers; cur; cur = cur->mNext) { if (cur == &aHandler) { ExitNow(error = kThreadError_Busy); } } aHandler.mNext = mHandlers; mHandlers = &aHandler; exit: return error; } ThreadError Netif::AddNetif() { ThreadError error = kThreadError_None; Netif *netif; if (sNetifListHead == NULL) { sNetifListHead = this; } else { netif = sNetifListHead; do { if (netif == this) { ExitNow(error = kThreadError_Busy); } } while (netif->mNext); netif->mNext = this; } mNext = NULL; if (mInterfaceId < 0) { mInterfaceId = sNextInterfaceId++; } exit: return error; } ThreadError Netif::RemoveNetif() { ThreadError error = kThreadError_None; VerifyOrExit(sNetifListHead != NULL, error = kThreadError_Busy); if (sNetifListHead == this) { sNetifListHead = mNext; } else { for (Netif *netif = sNetifListHead; netif->mNext; netif = netif->mNext) { if (netif->mNext != this) { continue; } netif->mNext = mNext; break; } } mNext = NULL; exit: return error; } Netif *Netif::GetNext() const { return mNext; } Netif *Netif::GetNetifById(uint8_t aInterfaceId) { Netif *netif; for (netif = sNetifListHead; netif; netif = netif->mNext) { if (netif->mInterfaceId == aInterfaceId) { ExitNow(); } } exit: return netif; } Netif *Netif::GetNetifByName(char *aName) { Netif *netif; for (netif = sNetifListHead; netif; netif = netif->mNext) { if (strcmp(netif->GetName(), aName) == 0) { ExitNow(); } } exit: return netif; } int Netif::GetInterfaceId() const { return mInterfaceId; } bool Netif::IsMulticastSubscribed(const Address &aAddress) const { bool rval = false; if (aAddress.IsLinkLocalAllNodesMulticast() || aAddress.IsRealmLocalAllNodesMulticast()) { ExitNow(rval = true); } else if (aAddress.IsLinkLocalAllRoutersMulticast() || aAddress.IsRealmLocalAllRoutersMulticast()) { ExitNow(rval = mAllRoutersSubscribed); } for (NetifMulticastAddress *cur = mMulticastAddresses; cur; cur = cur->mNext) { if (memcmp(&cur->mAddress, &aAddress, sizeof(cur->mAddress)) == 0) { ExitNow(rval = true); } } exit: return rval; } void Netif::SubscribeAllRoutersMulticast() { mAllRoutersSubscribed = true; } void Netif::UnsubscribeAllRoutersMulticast() { mAllRoutersSubscribed = false; } ThreadError Netif::SubscribeMulticast(NetifMulticastAddress &aAddress) { ThreadError error = kThreadError_None; for (NetifMulticastAddress *cur = mMulticastAddresses; cur; cur = cur->mNext) { if (cur == &aAddress) { ExitNow(error = kThreadError_Busy); } } aAddress.mNext = mMulticastAddresses; mMulticastAddresses = &aAddress; exit: return error; } ThreadError Netif::UnsubscribeMulticast(const NetifMulticastAddress &aAddress) { ThreadError error = kThreadError_None; if (mMulticastAddresses == &aAddress) { mMulticastAddresses = mMulticastAddresses->mNext; ExitNow(); } else if (mMulticastAddresses != NULL) { for (NetifMulticastAddress *cur = mMulticastAddresses; cur->mNext; cur = cur->mNext) { if (cur->mNext == &aAddress) { cur->mNext = aAddress.mNext; ExitNow(); } } } ExitNow(error = kThreadError_Error); exit: return error; } const NetifUnicastAddress *Netif::GetUnicastAddresses() const { return mUnicastAddresses; } ThreadError Netif::AddUnicastAddress(NetifUnicastAddress &aAddress) { ThreadError error = kThreadError_None; for (NetifUnicastAddress *cur = mUnicastAddresses; cur; cur = cur->GetNext()) { if (cur == &aAddress) { ExitNow(error = kThreadError_Busy); } } aAddress.mNext = mUnicastAddresses; mUnicastAddresses = &aAddress; mUnicastChangedTask.Post(); exit: return error; } ThreadError Netif::RemoveUnicastAddress(const NetifUnicastAddress &aAddress) { ThreadError error = kThreadError_None; if (mUnicastAddresses == &aAddress) { mUnicastAddresses = mUnicastAddresses->GetNext(); ExitNow(); } else if (mUnicastAddresses != NULL) { for (NetifUnicastAddress *cur = mUnicastAddresses; cur->GetNext(); cur = cur->GetNext()) { if (cur->mNext == &aAddress) { cur->mNext = aAddress.mNext; ExitNow(); } } } ExitNow(error = kThreadError_Error); exit: mUnicastChangedTask.Post(); return error; } Netif *Netif::GetNetifList() { return sNetifListHead; } bool Netif::IsUnicastAddress(const Address &aAddress) { bool rval = false; for (Netif *netif = sNetifListHead; netif; netif = netif->mNext) { for (NetifUnicastAddress *cur = netif->mUnicastAddresses; cur; cur = cur->GetNext()) { if (cur->GetAddress() == aAddress) { ExitNow(rval = true); } } } exit: return rval; } const NetifUnicastAddress *Netif::SelectSourceAddress(MessageInfo &aMessageInfo) { Address *destination = &aMessageInfo.GetPeerAddr(); int interfaceId = aMessageInfo.mInterfaceId; const NetifUnicastAddress *rvalAddr = NULL; const Address *candidateAddr; uint8_t candidateId; uint8_t rvalIface = 0; for (Netif *netif = GetNetifList(); netif; netif = netif->mNext) { candidateId = netif->GetInterfaceId(); for (const NetifUnicastAddress *addr = netif->GetUnicastAddresses(); addr; addr = addr->GetNext()) { candidateAddr = &addr->GetAddress(); if (destination->IsLinkLocal() || destination->IsMulticast()) { if (interfaceId != candidateId) { continue; } } if (rvalAddr == NULL) { rvalAddr = addr; rvalIface = candidateId; } else if (*candidateAddr == *destination) { rvalAddr = addr; rvalIface = candidateId; goto exit; } else if (candidateAddr->GetScope() < rvalAddr->GetAddress().GetScope()) { if (candidateAddr->GetScope() >= destination->GetScope()) { rvalAddr = addr; rvalIface = candidateId; } } else if (candidateAddr->GetScope() > rvalAddr->GetAddress().GetScope()) { if (rvalAddr->GetAddress().GetScope() < destination->GetScope()) { rvalAddr = addr; rvalIface = candidateId; } } else if (addr->mPreferredLifetime != 0 && rvalAddr->mPreferredLifetime == 0) { rvalAddr = addr; rvalIface = candidateId; } else if (aMessageInfo.mInterfaceId != 0 && aMessageInfo.mInterfaceId == candidateId && rvalIface != candidateId) { rvalAddr = addr; rvalIface = candidateId; } else if (destination->PrefixMatch(*candidateAddr) > destination->PrefixMatch(rvalAddr->GetAddress())) { rvalAddr = addr; rvalIface = candidateId; } } } exit: aMessageInfo.mInterfaceId = rvalIface; return rvalAddr; } int Netif::GetOnLinkNetif(const Address &aAddress) { int rval = -1; for (Netif *netif = sNetifListHead; netif; netif = netif->mNext) { for (NetifUnicastAddress *cur = netif->mUnicastAddresses; cur; cur = cur->GetNext()) { if (cur->GetAddress().PrefixMatch(aAddress) >= cur->mPrefixLength) { ExitNow(rval = netif->mInterfaceId); } } } exit: return rval; } void Netif::HandleUnicastChangedTask(void *aContext) { Netif *obj = reinterpret_cast<Netif *>(aContext); obj->HandleUnicastChangedTask(); } void Netif::HandleUnicastChangedTask() { for (NetifHandler *handler = mHandlers; handler; handler = handler->mNext) { handler->HandleUnicastAddressesChanged(); } } } }
#include <common/code_utils.hpp> #include <common/debug.hpp> #include <common/message.hpp> #include <net/netif.hpp> namespace Thread { namespace Ip6 { Netif *Netif::sNetifListHead = NULL; int Netif::sNextInterfaceId = 1; Netif::Netif() : mUnicastChangedTask(&HandleUnicastChangedTask, this) { mHandlers = NULL; mUnicastAddresses = NULL; mMulticastAddresses = NULL; mInterfaceId = -1; mAllRoutersSubscribed = false; mNext = NULL; } ThreadError Netif::RegisterHandler(NetifHandler &aHandler) { ThreadError error = kThreadError_None; for (NetifHandler *cur = mHandlers; cur; cur = cur->mNext) { if (cur == &aHandler) { ExitNow(error = kThreadError_Busy); } } aHandler.mNext = mHandlers; mHandlers = &aHandler; exit: return error; } ThreadError Netif::AddNetif() { ThreadError error = kThreadError_None; Netif *netif; if (sNetifListHead == NULL) { sNetifListHead = this; } else { netif = sNetifListHead; do { if (netif == this) { ExitNow(error = kThreadError_Busy); } } while (netif->mNext); netif->mNext = this; } mNext = NULL; if (mInterfaceId < 0) { mInterfaceId = sNextInterfaceId++; } exit: return error; } ThreadError Netif::RemoveNetif() { ThreadError error = kThreadError_None; VerifyOrExit(sNetifListHead != NULL, error = kThreadError_Busy); if (sNetifListHead == this) { sNetifListHead = mNext; } else { for (Netif *netif = sNetifListHead; netif->mNext; netif = netif->mNext) { if (netif->mNext != this) { continue; } netif->mNext = mNext; break; } } mNext = NULL; exit: return error; } Netif *Netif::GetNext() const { return mNext; } Netif *Netif::GetNetifById(uint8_t aInterfaceId) { Netif *netif; for (netif = sNetifListHead; netif; netif = netif->mNext) { if (netif->mInterfaceId == aInterfaceId) { ExitNow(); } } exit: return netif; } Netif *Netif::GetNetifByName(char *aName) { Netif *netif; for (netif = sNetifListHead; netif; netif = netif->mNext) { if (strcmp(netif->GetName(), aName) == 0) { ExitNow(); } } exit: return netif; } int Netif::GetInterfaceId() const { return mInterfaceId; } bool Netif::IsMulticastSubscribed(const Address &aAddress) const { bool rval = false; if (aAddress.IsLinkLocalAllNodesMulticast() || aAddress.IsRealmLocalAllNodesMulticast()) { ExitNow(rval = true); } else if (aAddress.IsLinkLocalAllRoutersMulticast() || aAddress.IsRealmLocalAllRoutersMulticast()) { ExitNow(rval = mAllRoutersSubscribed); } for (NetifMulticastAddress *cur = mMulticastAddresses; cur; cur = cur->mNext) { if (memcmp(&cur->mAddress, &aAddress, sizeof(cur->mAddress)) == 0) { ExitNow(rval = true); } } exit: return rval; } void Netif::SubscribeAllRoutersMulticast() { mAllRoutersSubscribed = true; } void Netif::UnsubscribeAllRoutersMulticast() { mAllRoutersSubscribed = false; } ThreadError Netif::SubscribeMulticast(NetifMulticastAddress &aAddress) { ThreadError error = kThreadError_None; for (NetifMulticastAddress *cur = mMulticastAddresses; cur; cur = cur->mNext) { if (cur == &aAddress) { ExitNow(error = kThreadError_Busy); } } aAddress.mNext = mMulticastAddresses; mMulticastAddresses = &aAddress; exit: return error; } ThreadError Netif::UnsubscribeMulticast(const NetifMulticastAddress &aAddress) { ThreadError error = kThreadError_None; if (mMulticastAddresses == &aAddress) { mMulticastAddresses = mMulticastAddresses->mNext; ExitNow(); } else if (mMulticastAddresses != NULL) { for (NetifMulticastAddress *cur = mMulticastAddresses; cur->mNext; cur = cur->mNext) { if (cur->mNext == &aAddress) { cur->mNext = aAddress.mNext; ExitNow(); } } } ExitNow(error = kThreadError_Error); exit: return error; } const NetifUnicastAddress *Netif::GetUnicastAddresses() const { return mUnicastAddresses; } ThreadError Netif::AddUnicastAddress(NetifUnicastAddress &aAddress) { ThreadError error = kThreadError_None; for (NetifUnicastAddress *cur = mUnicastAddresses; cur; cur = cur->GetNext()) { if (cur == &aAddress) { ExitNow(error = kThreadError_Busy); } } aAddress.mNext = mUnicastAddresses; mUnicastAddresses = &aAddress; mUnicastChangedTask.Post(); exit: return error; } ThreadError Netif::RemoveUnicastAddress(const NetifUnicastAddress &aAddress) { ThreadError error = kThreadError_None; if (mUnicastAddresses == &aAddress) { mUnicastAddresses = mUnicastAddresses->GetNext(); ExitNow(); } else if (mUnicastAddresses != NULL) { for (NetifUnicastAddress *cur = mUnicastAddresses; cur->GetNext(); cur = cur->GetNext()) { if (cur->mNext == &aAddress) { cur->mNext = aAddress.mNext; ExitNow(); } } } ExitNow(error = kThreadError_Error); exit: mUnicastChangedTask.Post(); return error; } Netif *Netif::GetNetifList() { return sNetifListHead; } bool Netif::IsUnicastAddress(const Address &aAddress) { bool rval = false; for (Netif *netif = sNetifListHead; netif; netif = netif->mNext) { for (NetifUnicastAddress *cur = netif->mUnicastAddresses; cur; cur = cur->GetNext()) { if (cur->GetAddress() == aAddress) { ExitNow(rval = true); } } } exit: return rval; } const NetifUnicastAddress *Netif::SelectSourceAddress(MessageInfo &aMessageInfo) { Address *destination = &aMessageInfo.GetPeerAddr(); int interfaceId = aMessageInfo.mInterfaceId; const NetifUnicastAddress *rvalAddr = NULL; const Address *candidateAddr; uint8_t candidateId; uint8_t rvalIface = 0; for (Netif *netif = GetNetifList(); netif; netif = netif->mNext) { candidateId = netif->GetInterfaceId(); for (const NetifUnicastAddress *addr = netif->GetUnicastAddresses(); addr; addr = addr->GetNext()) { candidateAddr = &addr->GetAddress(); if (destination->IsLinkLocal() || destination->IsMulticast()) { if (interfaceId != candidateId) { continue; } } if (rvalAddr == NULL) { rvalAddr = addr; rvalIface = candidateId; } else if (*candidateAddr == *destination) { rvalAddr = addr; rvalIface = candidateId; goto exit; } else if (candidateAddr->GetScope() < rvalAddr->GetAddress().GetScope()) { if (candidateAddr->GetScope() >= destination->GetScope()) { rvalAddr = addr; rvalIface = candidateId; } } else if (candidateAddr->GetScope() > rvalAddr->GetAddress().GetScope()) { if (rvalAddr->
int Netif::GetOnLinkNetif(const Address &aAddress) { int rval = -1; for (Netif *netif = sNetifListHead; netif; netif = netif->mNext) { for (NetifUnicastAddress *cur = netif->mUnicastAddresses; cur; cur = cur->GetNext()) { if (cur->GetAddress().PrefixMatch(aAddress) >= cur->mPrefixLength) { ExitNow(rval = netif->mInterfaceId); } } } exit: return rval; } void Netif::HandleUnicastChangedTask(void *aContext) { Netif *obj = reinterpret_cast<Netif *>(aContext); obj->HandleUnicastChangedTask(); } void Netif::HandleUnicastChangedTask() { for (NetifHandler *handler = mHandlers; handler; handler = handler->mNext) { handler->HandleUnicastAddressesChanged(); } } } }
GetAddress().GetScope() < destination->GetScope()) { rvalAddr = addr; rvalIface = candidateId; } } else if (addr->mPreferredLifetime != 0 && rvalAddr->mPreferredLifetime == 0) { rvalAddr = addr; rvalIface = candidateId; } else if (aMessageInfo.mInterfaceId != 0 && aMessageInfo.mInterfaceId == candidateId && rvalIface != candidateId) { rvalAddr = addr; rvalIface = candidateId; } else if (destination->PrefixMatch(*candidateAddr) > destination->PrefixMatch(rvalAddr->GetAddress())) { rvalAddr = addr; rvalIface = candidateId; } } } exit: aMessageInfo.mInterfaceId = rvalIface; return rvalAddr; }
function_block-function_prefixed
[ { "content": "class ThreadNetif: public Ip6::Netif\n\n{\n\npublic:\n\n /**\n\n * This constructor initializes the Thread network interface.\n\n *\n\n */\n\n ThreadNetif(void);\n\n\n\n /**\n\n * This method enables the Thread network interface.\n\n *\n\n */\n\n ThreadError Up(void);\n\n\n\n /**\n\n * This method disables the Thread network interface.\n\n *\n\n */\n\n ThreadError Down(void);\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 0, "score": 229476.2600924089 }, { "content": " class Buffer *GetNextBuffer(void) const { return mHeader.mNext; }\n\n\n\n /**\n\n * This method sets the pointer to the next message buffer.\n\n *\n\n */\n\n void SetNextBuffer(class Buffer *buf) { mHeader.mNext = buf; }\n\n\n\nprivate:\n\n /**\n\n * This method returns a pointer to the first byte of data in the first message buffer.\n\n *\n\n * @returns A pointer to the first data byte.\n\n *\n\n */\n\n uint8_t *GetFirstData(void) { return mHeadData; }\n\n\n\n /**\n\n * This method returns a pointer to the first byte of data in the first message buffer.\n\n *\n", "file_path": "src/core/common/message.hpp", "rank": 1, "score": 200601.5930662636 }, { "content": "class ThreadNetif;\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 2, "score": 161911.49890523514 }, { "content": "class Address: public otIp6Address\n\n{\n\npublic:\n\n /**\n\n * Constants\n\n *\n\n */\n\n enum\n\n {\n\n kInterfaceIdentifierSize = 8, ///< Interface Identifier size in bytes.\n\n };\n\n\n\n /**\n\n * IPv6 Address Scopes\n\n */\n\n enum\n\n {\n\n kNodeLocalScope = 0, ///< Node-Local scope\n\n kInterfaceLocalScope = 1, ///< Interface-Local scope\n\n kLinkLocalScope = 2, ///< Link-Local scope\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 3, "score": 155845.0499763362 }, { "content": "class NetifUnicastAddress: public otNetifAddress\n\n{\n\n friend class Netif;\n\n\n\npublic:\n\n /**\n\n * This method returns the unicast address.\n\n *\n\n * @returns The unicast address.\n\n *\n\n */\n\n const Address &GetAddress(void) const { return *static_cast<const Address *>(&mAddress); }\n\n\n\n /**\n\n * This method returns the unicast address.\n\n *\n\n * @returns The unicast address.\n\n *\n\n */\n\n Address &GetAddress(void) { return *static_cast<Address *>(&mAddress); }\n", "file_path": "src/core/net/netif.hpp", "rank": 4, "score": 154618.25790192393 }, { "content": "class NetifMulticastAddress\n\n{\n\n friend class Netif;\n\n\n\npublic:\n\n /**\n\n * This method returns the multicast address.\n\n *\n\n * @returns The multicast address.\n\n *\n\n */\n\n const Address &GetAddress(void) const { return *static_cast<const Address *>(&mAddress); }\n\n\n\n /**\n\n * This method returns the multicast address.\n\n *\n\n * @returns The multicast address.\n\n *\n\n */\n\n Address &GetAddress(void) { return *static_cast<Address *>(&mAddress); }\n", "file_path": "src/core/net/netif.hpp", "rank": 5, "score": 152626.59057236684 }, { "content": " void *address;\n", "file_path": "third_party/nlbuild-autotools/repo/tools/host/include/ltdl.h", "rank": 6, "score": 137945.55823489535 }, { "content": " mIsUp = true;\n\n return kThreadError_None;\n\n}\n\n\n\nThreadError ThreadNetif::Down(void)\n\n{\n\n mCoapServer.Stop();\n\n mMleRouter.Stop();\n\n mMeshForwarder.Stop();\n\n Netif::RemoveNetif();\n\n mIsUp = false;\n\n return kThreadError_None;\n\n}\n\n\n\nbool ThreadNetif::IsUp(void) const\n\n{\n\n return mIsUp;\n\n}\n\n\n\nThreadError ThreadNetif::GetLinkAddress(Ip6::LinkAddress &address) const\n", "file_path": "src/core/thread/thread_netif.cpp", "rank": 7, "score": 114798.49630142128 }, { "content": "{\n\n address.mType = Ip6::LinkAddress::kEui64;\n\n address.mLength = sizeof(address.mExtAddress);\n\n memcpy(&address.mExtAddress, mMac.GetExtAddress(), address.mLength);\n\n return kThreadError_None;\n\n}\n\n\n\nThreadError ThreadNetif::RouteLookup(const Ip6::Address &source, const Ip6::Address &destination, uint8_t *prefixMatch)\n\n{\n\n return mNetworkDataLeader.RouteLookup(source, destination, prefixMatch, NULL);\n\n}\n\n\n\nThreadError ThreadNetif::SendMessage(Message &message)\n\n{\n\n return mMeshForwarder.SendMessage(message);\n\n}\n\n\n\n} // namespace Thread\n", "file_path": "src/core/thread/thread_netif.cpp", "rank": 8, "score": 114796.3174057129 }, { "content": " * @param[in] aDestination A reference to the IPv6 destination address.\n\n * @param[out] aPrefixMatch A pointer where the number of prefix match bits for the chosen route is stored.\n\n *\n\n * @retval kThreadError_None Successfully found a route.\n\n * @retval kThreadError_NoRoute Could not find a valid route.\n\n *\n\n */\n\n ThreadError RouteLookup(const Ip6::Address &aSource, const Ip6::Address &aDestination, uint8_t *aPrefixMatch);\n\n\n\n /**\n\n * This method returns a pointer to the address resolver object.\n\n *\n\n * @returns A pointer to the address resolver object.\n\n *\n\n */\n\n AddressResolver &GetAddressResolver(void) { return mAddressResolver; }\n\n\n\n /**\n\n * This method returns a pointer to the coap server object.\n\n *\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 9, "score": 114786.40263151436 }, { "content": "\n\n /**\n\n * This method indicates whether or not the Thread network interface is enabled.\n\n *\n\n * @retval TRUE If the Thread network interface is enabled.\n\n * @retval FALSE If the Thread network interface is not enabled.\n\n *\n\n */\n\n bool IsUp(void) const;\n\n\n\n /**\n\n * This method returns a pointer to a NULL-terminated string that names the interface.\n\n *\n\n * @returns A pointer to a NULL-terminated string that names the interface.\n\n *\n\n */\n\n const char *GetName(void) const;\n\n\n\n /**\n\n * This method retrieves the link address.\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 10, "score": 114784.48580565417 }, { "content": "#include <thread/thread_netif.hpp>\n\n#include <thread/thread_tlvs.hpp>\n\n\n\nusing Thread::Encoding::BigEndian::HostSwap16;\n\n\n\nnamespace Thread {\n\n\n\nstatic const uint8_t kThreadMasterKey[] =\n\n{\n\n 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n\n 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,\n\n};\n\n\n\nstatic const char name[] = \"thread\";\n\n\n\nThreadNetif::ThreadNetif(void):\n\n mCoapServer(kCoapUdpPort),\n\n mAddressResolver(*this),\n\n mKeyManager(*this),\n\n mLowpan(*this),\n", "file_path": "src/core/thread/thread_netif.cpp", "rank": 11, "score": 114783.3138399322 }, { "content": "#include <thread/key_manager.hpp>\n\n#include <thread/mesh_forwarder.hpp>\n\n#include <thread/mle.hpp>\n\n#include <thread/mle_router.hpp>\n\n#include <thread/network_data_local.hpp>\n\n\n\nnamespace Thread {\n\n\n\n/**\n\n * @addtogroup core-netif\n\n *\n\n * @brief\n\n * This module includes definitions for the Thread network interface.\n\n *\n\n * @{\n\n */\n\n\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 12, "score": 114776.5519470204 }, { "content": " *\n\n * @param[out] aAddress A reference to the link address.\n\n *\n\n */\n\n ThreadError GetLinkAddress(Ip6::LinkAddress &aAddress) const;\n\n\n\n /**\n\n * This method submits a message to the network interface.\n\n *\n\n * @param[in] aMessage A reference to the message.\n\n *\n\n * @retval kThreadError_None Successfully submitted the message to the interface.\n\n *\n\n */\n\n ThreadError SendMessage(Message &aMessage);\n\n\n\n /**\n\n * This method performs a route lookup.\n\n *\n\n * @param[in] aSource A reference to the IPv6 source address.\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 13, "score": 114776.43672335584 }, { "content": " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n/**\n\n * @file\n\n * This file includes definitions for the Thread network interface.\n\n */\n\n\n\n#ifndef THREAD_NETIF_HPP_\n\n#define THREAD_NETIF_HPP_\n\n\n\n#include <openthread-types.h>\n\n#include <mac/mac.hpp>\n\n#include <net/netif.hpp>\n\n#include <thread/address_resolver.hpp>\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 14, "score": 114775.98904557679 }, { "content": " mMac(*this),\n\n mMeshForwarder(*this),\n\n mMleRouter(*this),\n\n mNetworkDataLocal(*this),\n\n mNetworkDataLeader(*this)\n\n{\n\n mKeyManager.SetMasterKey(kThreadMasterKey, sizeof(kThreadMasterKey));\n\n}\n\n\n\nconst char *ThreadNetif::GetName(void) const\n\n{\n\n return name;\n\n}\n\n\n\nThreadError ThreadNetif::Up(void)\n\n{\n\n Netif::AddNetif();\n\n mMeshForwarder.Start();\n\n mMleRouter.Start();\n\n mCoapServer.Start();\n", "file_path": "src/core/thread/thread_netif.cpp", "rank": 15, "score": 114775.96569012286 }, { "content": " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n/**\n\n * @file\n\n * This file implements the Thread network interface.\n\n */\n\n\n\n#include <common/code_utils.hpp>\n\n#include <common/encoding.hpp>\n\n#include <common/message.hpp>\n\n#include <net/ip6.hpp>\n\n#include <net/netif.hpp>\n\n#include <net/udp6.hpp>\n\n#include <thread/mle.hpp>\n", "file_path": "src/core/thread/thread_netif.cpp", "rank": 16, "score": 114772.95012253907 }, { "content": "\n\nprivate:\n\n Coap::Server mCoapServer;\n\n AddressResolver mAddressResolver;\n\n KeyManager mKeyManager;\n\n Lowpan::Lowpan mLowpan;\n\n Mac::Mac mMac;\n\n MeshForwarder mMeshForwarder;\n\n Mle::MleRouter mMleRouter;\n\n NetworkData::Local mNetworkDataLocal;\n\n NetworkData::Leader mNetworkDataLeader;\n\n bool mIsUp;\n\n};\n\n\n\n/**\n\n * This structure represents Thread-specific link information.\n\n *\n\n */\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 17, "score": 114767.42469298828 }, { "content": " * @returns A pointer to the coap server object.\n\n *\n\n */\n\n Coap::Server &GetCoapServer(void) { return mCoapServer; }\n\n\n\n /**\n\n * This method returns a pointer to the key manager object.\n\n *\n\n * @returns A pointer to the key manager object.\n\n *\n\n */\n\n KeyManager &GetKeyManager(void) { return mKeyManager; }\n\n\n\n /**\n\n * This method returns a pointer to the lowpan object.\n\n *\n\n * @returns A pointer to the lowpan object.\n\n *\n\n */\n\n Lowpan::Lowpan &GetLowpan(void) { return mLowpan; }\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 18, "score": 114759.69835033688 }, { "content": " * @returns A pointer to the mesh forwarder object.\n\n *\n\n */\n\n MeshForwarder &GetMeshForwarder(void) { return mMeshForwarder; }\n\n\n\n /**\n\n * This method returns a pointer to the network data local object.\n\n *\n\n * @returns A pointer to the network data local object.\n\n *\n\n */\n\n NetworkData::Local &GetNetworkDataLocal(void) { return mNetworkDataLocal; }\n\n\n\n /**\n\n * This method returns a pointer to the network data leader object.\n\n *\n\n * @returns A pointer to the network data leader object.\n\n *\n\n */\n\n NetworkData::Leader &GetNetworkDataLeader(void) { return mNetworkDataLeader; }\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 19, "score": 114759.45141070873 }, { "content": "\n\n /**\n\n * This method returns a pointer to the mac object.\n\n *\n\n * @returns A pointer to the mac object.\n\n *\n\n */\n\n Mac::Mac &GetMac(void) { return mMac; }\n\n\n\n /**\n\n * This method returns a pointer to the mle object.\n\n *\n\n * @returns A pointer to the mle object.\n\n *\n\n */\n\n Mle::MleRouter &GetMle(void) { return mMleRouter; }\n\n\n\n /**\n\n * This method returns a pointer to the mesh forwarder object.\n\n *\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 20, "score": 114759.37623629822 }, { "content": "/*\n\n * Copyright (c) 2016, Nest Labs, Inc.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n * 1. Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * 2. Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in the\n\n * documentation and/or other materials provided with the distribution.\n\n * 3. Neither the name of the copyright holder nor the\n\n * names of its contributors may be used to endorse or promote products\n\n * derived from this software without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n", "file_path": "src/core/thread/thread_netif.cpp", "rank": 21, "score": 114756.9481988199 }, { "content": "/*\n\n * Copyright (c) 2016, Nest Labs, Inc.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n * 1. Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * 2. Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in the\n\n * documentation and/or other materials provided with the distribution.\n\n * 3. Neither the name of the copyright holder nor the\n\n * names of its contributors may be used to endorse or promote products\n\n * derived from this software without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 22, "score": 114756.9481988199 }, { "content": "struct ThreadMessageInfo\n\n{\n\n uint8_t mLinkMargin; ///< The Link Margin for a received message in dBm.\n\n};\n\n\n\n/**\n\n * @}\n\n */\n\n\n\n} // namespace Thread\n\n\n\n#endif // THREAD_NETIF_HPP_\n", "file_path": "src/core/thread/thread_netif.hpp", "rank": 23, "score": 114297.83099104001 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nBR = 2\n\nROUTER2 = 3\n\nROUTER3 = 4\n\nSED2 = 5\n\n\n\nclass Cert_5_3_9_AddressQuery(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,6):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[BR].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER3].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[BR].set_panid(0xface)\n\n self.nodes[BR].set_mode('rsdn')\n\n self.nodes[BR].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[BR].enable_whitelist()\n\n\n\n self.nodes[ROUTER2].set_panid(0xface)\n\n self.nodes[ROUTER2].set_mode('rsdn')\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[SED2].get_addr64())\n\n self.nodes[ROUTER2].enable_whitelist()\n\n\n\n self.nodes[ROUTER3].set_panid(0xface)\n\n self.nodes[ROUTER3].set_mode('rsdn')\n\n self.nodes[ROUTER3].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER3].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ROUTER3].enable_whitelist()\n\n\n\n self.nodes[SED2].set_panid(0xface)\n\n self.nodes[SED2].set_mode('sn')\n\n self.nodes[SED2].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[SED2].set_timeout(3)\n\n self.nodes[SED2].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[BR].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[BR].get_state(), 'router')\n\n\n\n self.nodes[BR].add_prefix('2003::/64', 'pvcrs')\n\n self.nodes[BR].add_prefix('2004::/64', 'pvcrs')\n\n self.nodes[BR].register_netdata()\n\n\n\n self.nodes[ROUTER2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n\n\n self.nodes[ROUTER3].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER3].get_state(), 'router')\n\n\n\n self.nodes[SED2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[SED2].get_state(), 'child')\n\n\n\n addrs = self.nodes[ROUTER3].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[SED2].ping(addr)\n\n\n\n addrs = self.nodes[SED2].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[BR].ping(addr)\n\n\n\n addrs = self.nodes[ROUTER3].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[SED2].ping(addr)\n\n\n\n self.nodes[ROUTER3].stop()\n\n time.sleep(300)\n\n \n\n addrs = self.nodes[ROUTER3].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n try:\n\n self.nodes[SED2].ping(addr)\n\n self.assertFalse()\n\n except pexpect.TIMEOUT:\n\n pass\n\n\n\n self.nodes[SED2].stop()\n\n time.sleep(10)\n\n\n\n addrs = self.nodes[SED2].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n try:\n\n self.nodes[BR].ping(addr)\n\n self.assertFalse()\n\n except pexpect.TIMEOUT:\n\n pass\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_3_10_AddressQuery.py", "rank": 24, "score": 113207.01380080033 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nBR = 1\n\nLEADER = 2\n\nROUTER2 = 3\n\nROUTER3 = 4\n\nED2 = 5\n\n\n\nclass Cert_5_3_3_AddressQuery(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,6):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[BR].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER3].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[BR].set_panid(0xface)\n\n self.nodes[BR].set_mode('rsdn')\n\n self.nodes[BR].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[BR].enable_whitelist()\n\n\n\n self.nodes[ROUTER2].set_panid(0xface)\n\n self.nodes[ROUTER2].set_mode('rsdn')\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER3].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ED2].get_addr64())\n\n self.nodes[ROUTER2].enable_whitelist()\n\n\n\n self.nodes[ROUTER3].set_panid(0xface)\n\n self.nodes[ROUTER3].set_mode('rsdn')\n\n self.nodes[ROUTER3].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER3].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ROUTER3].enable_whitelist()\n\n\n\n self.nodes[ED2].set_panid(0xface)\n\n self.nodes[ED2].set_mode('rsn')\n\n self.nodes[ED2].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ED2].set_timeout(3)\n\n self.nodes[ED2].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[BR].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[BR].get_state(), 'router')\n\n\n\n self.nodes[BR].add_prefix('2003::/64', 'pvcrs')\n\n self.nodes[BR].add_prefix('2004::/64', 'pvcrs')\n\n self.nodes[BR].register_netdata()\n\n\n\n self.nodes[ROUTER2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n\n\n self.nodes[ROUTER3].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER3].get_state(), 'router')\n\n\n\n self.nodes[ED2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED2].get_state(), 'child')\n\n\n\n addrs = self.nodes[ROUTER3].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[ED2].ping(addr)\n\n time.sleep(1)\n\n\n\n addrs = self.nodes[ED2].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[LEADER].ping(addr)\n\n time.sleep(1)\n\n\n\n addrs = self.nodes[BR].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[ED2].ping(addr)\n\n time.sleep(1)\n\n\n\n addrs = self.nodes[ROUTER3].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[ED2].ping(addr)\n\n time.sleep(1)\n\n\n\n addrs = self.nodes[ROUTER3].get_addrs()\n\n self.nodes[ROUTER3].stop()\n\n time.sleep(130)\n\n\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n try:\n\n self.nodes[ED2].ping(addr)\n\n self.assertFalse()\n\n except pexpect.TIMEOUT:\n\n pass\n\n\n\n addrs = self.nodes[ED2].get_addrs()\n\n self.nodes[ED2].stop()\n\n time.sleep(10)\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n try:\n\n self.nodes[BR].ping(addr) \n\n self.assertFalse()\n\n except pexpect.TIMEOUT:\n\n pass\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_3_03_AddressQuery.py", "rank": 25, "score": 113207.01380080033 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nROUTER1 = 2\n\nROUTER2 = 3\n\nED1 = 4\n\nED2 = 5\n\nED3 = 6\n\n\n\nclass Cert_5_3_7_DuplicateAddress(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,7):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED3].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ROUTER1].set_panid(0xface)\n\n self.nodes[ROUTER1].set_mode('rsdn')\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[ED1].get_addr64())\n\n self.nodes[ROUTER1].enable_whitelist()\n\n\n\n self.nodes[ROUTER2].set_panid(0xface)\n\n self.nodes[ROUTER2].set_mode('rsdn')\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ED2].get_addr64())\n\n self.nodes[ROUTER2].enable_whitelist()\n\n\n\n self.nodes[ED1].set_panid(0xface)\n\n self.nodes[ED1].set_mode('rsn')\n\n self.nodes[ED1].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[ED1].enable_whitelist()\n\n\n\n self.nodes[ED2].set_panid(0xface)\n\n self.nodes[ED2].set_mode('rsn')\n\n self.nodes[ED2].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ED2].enable_whitelist()\n\n\n\n self.nodes[ED3].set_panid(0xface)\n\n self.nodes[ED3].set_mode('rsn')\n\n self.nodes[ED3].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED3].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ROUTER1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n\n\n self.nodes[ROUTER2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n\n\n self.nodes[ED1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED1].get_state(), 'child')\n\n\n\n self.nodes[ED2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED2].get_state(), 'child')\n\n\n\n self.nodes[ED3].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED3].get_state(), 'child')\n\n\n\n self.nodes[ROUTER2].add_prefix('2001::/64', 'pvcrs')\n\n self.nodes[ROUTER2].register_netdata()\n\n\n\n self.nodes[ED1].add_ipaddr('2001::1')\n\n self.nodes[ED2].add_ipaddr('2001::1')\n\n time.sleep(3)\n\n\n\n self.nodes[ED3].ping('2001::1')\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_3_07_DuplicateAddress.py", "rank": 26, "score": 113207.01380080033 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nED1 = 1\n\nBR1 = 2\n\nLEADER = 3\n\nROUTER2 = 4\n\nREED = 5\n\nED2 = 6\n\nED3 = 7\n\n\n\nclass Cert_5_2_5_AddressQuery(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,8):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[BR1].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[REED].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[BR1].set_panid(0xface)\n\n self.nodes[BR1].set_mode('rsdn')\n\n self.nodes[BR1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[BR1].add_whitelist(self.nodes[ED1].get_addr64())\n\n self.nodes[BR1].enable_whitelist()\n\n\n\n self.nodes[ED1].set_panid(0xface)\n\n self.nodes[ED1].set_mode('rsn')\n\n self.nodes[ED1].add_whitelist(self.nodes[BR1].get_addr64())\n\n self.nodes[ED1].enable_whitelist()\n\n\n\n self.nodes[REED].set_panid(0xface)\n\n self.nodes[REED].set_mode('rsdn')\n\n self.nodes[REED].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[REED].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[REED].set_router_upgrade_threshold(0)\n\n self.nodes[REED].enable_whitelist()\n\n\n\n self.nodes[ROUTER2].set_panid(0xface)\n\n self.nodes[ROUTER2].set_mode('rsdn')\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[REED].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ED2].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ED3].get_addr64())\n\n self.nodes[ROUTER2].enable_whitelist()\n\n\n\n self.nodes[ED2].set_panid(0xface)\n\n self.nodes[ED2].set_mode('rsn')\n\n self.nodes[ED2].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ED2].enable_whitelist()\n\n\n\n self.nodes[ED3].set_panid(0xface)\n\n self.nodes[ED3].set_mode('rsn')\n\n self.nodes[ED3].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ED3].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[BR1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[BR1].get_state(), 'router')\n\n\n\n self.nodes[BR1].add_prefix('2003::/64', 'pvcrs')\n\n self.nodes[BR1].add_prefix('2004::/64', 'pvcrs')\n\n self.nodes[BR1].register_netdata()\n\n\n\n self.nodes[ED1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED1].get_state(), 'child')\n\n\n\n self.nodes[REED].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[REED].get_state(), 'child')\n\n\n\n self.nodes[ROUTER2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n\n\n self.nodes[ED2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED2].get_state(), 'child')\n\n\n\n self.nodes[ED3].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED3].get_state(), 'child')\n\n\n\n addrs = self.nodes[REED].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[ED2].ping(addr)\n\n time.sleep(1)\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_2_05_AddressQuery.py", "rank": 27, "score": 113207.01380080033 }, { "content": "class ThreadNetif;\n", "file_path": "src/core/thread/mle.hpp", "rank": 28, "score": 112814.99743628965 }, { "content": "class ThreadNetif;\n\n\n\nnamespace NetworkData { class Leader; }\n\n\n\n/**\n\n * @addtogroup core-6lowpan\n\n *\n\n * @brief\n\n * This module includes definitions for 6LoWPAN header compression.\n\n *\n\n * @{\n\n */\n\n\n\n/**\n\n * @namespace Thread::Lowpan\n\n *\n\n * @brief\n\n * This namespace includes definitions for 6LoWPAN message processing.\n\n *\n\n */\n\nnamespace Lowpan {\n\n\n\n/**\n\n * This structure represents a LOWPAN_IPHC Context.\n\n *\n\n */\n", "file_path": "src/core/thread/lowpan.hpp", "rank": 29, "score": 112814.99743628965 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nED1 = 2\n\nED2 = 3\n\nED3 = 4\n\nED4 = 5\n\n\n\nclass Cert_5_3_8_ChildAddressSet(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,6):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED1].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED2].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED3].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED4].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ED1].set_panid(0xface)\n\n self.nodes[ED1].set_mode('rsn')\n\n self.nodes[ED1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED1].enable_whitelist()\n\n\n\n self.nodes[ED2].set_panid(0xface)\n\n self.nodes[ED2].set_mode('rsn')\n\n self.nodes[ED2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED2].enable_whitelist()\n\n\n\n self.nodes[ED3].set_panid(0xface)\n\n self.nodes[ED3].set_mode('rsn')\n\n self.nodes[ED3].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED3].enable_whitelist()\n\n\n\n self.nodes[ED4].set_panid(0xface)\n\n self.nodes[ED4].set_mode('rsn')\n\n self.nodes[ED4].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED4].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ED1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED1].get_state(), 'child')\n\n\n\n self.nodes[ED2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED2].get_state(), 'child')\n\n\n\n self.nodes[ED3].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED3].get_state(), 'child')\n\n\n\n self.nodes[ED4].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED4].get_state(), 'child')\n\n\n\n for i in range(2,6):\n\n addrs = self.nodes[i].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[LEADER].ping(addr)\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_3_08_ChildAddressSet.py", "rank": 30, "score": 111399.71214581616 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nROUTER1 = 2\n\n\n\nclass Cert_5_1_05_RouterAddressTimeout(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,3):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ROUTER1].set_panid(0xface)\n\n self.nodes[ROUTER1].set_mode('rsdn')\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER1].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ROUTER1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n\n\n rloc16 = self.nodes[ROUTER1].get_addr16()\n\n\n\n self.nodes[ROUTER1].stop()\n\n time.sleep(200)\n\n self.nodes[ROUTER1].start()\n\n time.sleep(5)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n self.assertNotEqual(self.nodes[ROUTER1].get_addr16(), rloc16)\n\n\n\n rloc16 = self.nodes[ROUTER1].get_addr16()\n\n\n\n self.nodes[ROUTER1].stop()\n\n time.sleep(300)\n\n self.nodes[ROUTER1].start()\n\n time.sleep(5)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n self.assertEqual(self.nodes[ROUTER1].get_addr16(), rloc16)\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_1_05_RouterAddressTimeout.py", "rank": 31, "score": 111399.71214581616 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nROUTER1 = 2\n\nROUTER2 = 3\n\n\n\nclass Cert_5_1_03_RouterAddressReallocation(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,4):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ROUTER1].set_panid(0xface)\n\n self.nodes[ROUTER1].set_mode('rsdn')\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ROUTER1].enable_whitelist()\n\n\n\n self.nodes[ROUTER2].set_panid(0xface)\n\n self.nodes[ROUTER2].set_mode('rsdn')\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[ROUTER2].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ROUTER1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n\n\n self.nodes[ROUTER2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n\n\n rloc16 = self.nodes[ROUTER1].get_addr16()\n\n\n\n self.nodes[ROUTER2].set_network_id_timeout(110)\n\n self.nodes[LEADER].stop()\n\n time.sleep(130)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'leader')\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n self.assertEqual(self.nodes[ROUTER1].get_addr16(), rloc16)\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_1_03_RouterAddressReallocation.py", "rank": 32, "score": 111399.71214581616 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nROUTER = 2\n\nED = 3\n\nSED = 4\n\n\n\nclass Cert_5_1_02_ChildAddressTimeout(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,5):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ROUTER].set_panid(0xface)\n\n self.nodes[ROUTER].set_mode('rsdn')\n\n self.nodes[ROUTER].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER].add_whitelist(self.nodes[ED].get_addr64())\n\n self.nodes[ROUTER].add_whitelist(self.nodes[SED].get_addr64())\n\n self.nodes[ROUTER].enable_whitelist()\n\n\n\n self.nodes[ED].set_panid(0xface)\n\n self.nodes[ED].set_mode('rsn')\n\n self.nodes[ED].set_timeout(3)\n\n self.nodes[ED].add_whitelist(self.nodes[ROUTER].get_addr64())\n\n self.nodes[ED].enable_whitelist()\n\n\n\n self.nodes[SED].set_panid(0xface)\n\n self.nodes[SED].set_mode('sn')\n\n self.nodes[SED].set_timeout(3)\n\n self.nodes[SED].add_whitelist(self.nodes[ROUTER].get_addr64())\n\n self.nodes[SED].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ROUTER].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER].get_state(), 'router')\n\n\n\n self.nodes[ED].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED].get_state(), 'child')\n\n\n\n self.nodes[SED].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[SED].get_state(), 'child')\n\n\n\n ed_addrs = self.nodes[ED].get_addrs()\n\n sed_addrs = self.nodes[SED].get_addrs()\n\n\n\n self.nodes[ED].stop()\n\n time.sleep(5)\n\n for addr in ed_addrs:\n\n if addr[0:4] != 'fe80':\n\n try:\n\n self.nodes[LEADER].ping(addr)\n\n self.assertFalse()\n\n except pexpect.TIMEOUT:\n\n pass\n\n\n\n self.nodes[SED].stop()\n\n time.sleep(5)\n\n for addr in sed_addrs:\n\n if addr[0:4] != 'fe80':\n\n try:\n\n self.nodes[LEADER].ping(addr)\n\n self.assertFalse()\n\n except pexpect.TIMEOUT:\n\n pass\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_1_02_ChildAddressTimeout.py", "rank": 33, "score": 111399.71214581616 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nROUTER1 = 2\n\nSED1 = 3\n\nED2 = 4\n\nED3 = 5\n\nED4 = 6\n\nED5 = 7\n\n\n\nclass Cert_5_3_4_AddressMapCache(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,8):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED2].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED3].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED4].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ED5].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ROUTER1].set_panid(0xface)\n\n self.nodes[ROUTER1].set_mode('rsdn')\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[SED1].get_addr64())\n\n self.nodes[ROUTER1].enable_whitelist()\n\n\n\n self.nodes[SED1].set_panid(0xface)\n\n self.nodes[SED1].set_mode('rsn')\n\n self.nodes[SED1].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[SED1].enable_whitelist()\n\n\n\n self.nodes[ED2].set_panid(0xface)\n\n self.nodes[ED2].set_mode('rsn')\n\n self.nodes[ED2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED2].enable_whitelist()\n\n\n\n self.nodes[ED3].set_panid(0xface)\n\n self.nodes[ED3].set_mode('rsn')\n\n self.nodes[ED3].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED3].enable_whitelist()\n\n\n\n self.nodes[ED4].set_panid(0xface)\n\n self.nodes[ED4].set_mode('rsn')\n\n self.nodes[ED4].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED4].enable_whitelist()\n\n\n\n self.nodes[ED5].set_panid(0xface)\n\n self.nodes[ED5].set_mode('rsn')\n\n self.nodes[ED5].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ED5].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ROUTER1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n\n\n self.nodes[SED1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[SED1].get_state(), 'child')\n\n\n\n self.nodes[ED2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED2].get_state(), 'child')\n\n\n\n self.nodes[ED3].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED3].get_state(), 'child')\n\n\n\n self.nodes[ED4].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED4].get_state(), 'child')\n\n\n\n self.nodes[ED5].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ED5].get_state(), 'child')\n\n\n\n for i in range(4, 8):\n\n addrs = self.nodes[i].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[SED1].ping(addr)\n\n\n\n for i in range(4, 8):\n\n addrs = self.nodes[i].get_addrs()\n\n for addr in addrs:\n\n if addr[0:4] != 'fe80':\n\n self.nodes[SED1].ping(addr)\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_3_04_AddressMapCache.py", "rank": 34, "score": 111399.71214581616 }, { "content": "#!/usr/bin/python\n\n#\n\n# Copyright (c) 2016, Nest Labs, Inc.\n\n# All rights reserved.\n\n#\n\n# Redistribution and use in source and binary forms, with or without\n\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright\n\n# notice, this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright\n\n# notice, this list of conditions and the following disclaimer in the\n\n# documentation and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the\n\n# names of its contributors may be used to endorse or promote products\n\n# derived from this software without specific prior written permission.\n\n#\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n# POSSIBILITY OF SUCH DAMAGE.\n\n#\n\n\n\nimport pexpect\n\nimport time\n\nimport unittest\n\n\n\nimport node\n\n\n\nLEADER = 1\n\nROUTER1 = 2\n\nROUTER2 = 3\n\n\n\nclass Cert_5_1_04_RouterAddressReallocation(unittest.TestCase):\n\n def setUp(self):\n\n self.nodes = {}\n\n for i in range(1,4):\n\n self.nodes[i] = node.Node(i)\n\n\n\n self.nodes[LEADER].set_panid(0xface)\n\n self.nodes[LEADER].set_mode('rsdn')\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[LEADER].enable_whitelist()\n\n\n\n self.nodes[ROUTER1].set_panid(0xface)\n\n self.nodes[ROUTER1].set_mode('rsdn')\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER1].add_whitelist(self.nodes[ROUTER2].get_addr64())\n\n self.nodes[ROUTER1].enable_whitelist()\n\n\n\n self.nodes[ROUTER2].set_panid(0xface)\n\n self.nodes[ROUTER2].set_mode('rsdn')\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[LEADER].get_addr64())\n\n self.nodes[ROUTER2].add_whitelist(self.nodes[ROUTER1].get_addr64())\n\n self.nodes[ROUTER2].enable_whitelist()\n\n\n\n def tearDown(self):\n\n for node in self.nodes.itervalues():\n\n node.stop()\n\n del self.nodes\n\n\n\n def test(self):\n\n self.nodes[LEADER].start()\n\n self.nodes[LEADER].set_state('leader')\n\n self.assertEqual(self.nodes[LEADER].get_state(), 'leader')\n\n\n\n self.nodes[ROUTER1].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')\n\n\n\n self.nodes[ROUTER2].start()\n\n time.sleep(3)\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n\n\n rloc16 = self.nodes[ROUTER1].get_addr16()\n\n\n\n self.nodes[ROUTER2].set_network_id_timeout(200)\n\n self.nodes[LEADER].stop()\n\n time.sleep(210)\n\n self.assertEqual(self.nodes[ROUTER1].get_state(), 'leader')\n\n self.assertEqual(self.nodes[ROUTER2].get_state(), 'router')\n\n self.assertEqual(self.nodes[ROUTER1].get_addr16(), rloc16)\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n", "file_path": "tests/scripts/thread-cert/Cert_5_1_04_RouterAddressReallocation.py", "rank": 35, "score": 111399.71214581616 }, { "content": "class AddressResolver\n\n{\n\npublic:\n\n /**\n\n * This constructor initializes the object.\n\n *\n\n */\n\n explicit AddressResolver(ThreadNetif &aThreadNetif);\n\n\n\n /**\n\n * This method clears the EID-to-RLOC cache.\n\n *\n\n */\n\n void Clear(void);\n\n\n\n /**\n\n * This method removes a Router ID from the EID-to-RLOC cache.\n\n *\n\n * @param[in] aRouterId The Router ID.\n\n *\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 36, "score": 111366.58737722444 }, { "content": "class ThreadNetif;\n\n\n\n/**\n\n * @addtogroup core-security\n\n *\n\n * @brief\n\n * This module includes definitions for Thread security material generation.\n\n *\n\n * @{\n\n */\n\n\n", "file_path": "src/core/thread/key_manager.hpp", "rank": 37, "score": 110944.59247700083 }, { "content": "class ThreadExtMacAddressTlv: public ThreadTlv\n\n{\n\npublic:\n\n /**\n\n * This method initializes the TLV.\n\n *\n\n */\n\n void Init() { SetType(kExtMacAddress); SetLength(sizeof(*this) - sizeof(ThreadTlv)); }\n\n\n\n /**\n\n * This method indicates whether or not the TLV appears to be well-formed.\n\n *\n\n * @retval TRUE If the TLV appears to be well-formed.\n\n * @retval FALSE If the TLV does not appear to be well-formed.\n\n *\n\n */\n\n bool IsValid() const { return GetLength() == sizeof(*this) - sizeof(ThreadTlv); }\n\n\n\n /**\n\n * This method returns a pointer to the Extended MAC Address.\n", "file_path": "src/core/thread/thread_tlvs.hpp", "rank": 38, "score": 110136.77265292345 }, { "content": "class ThreadNetif;\n\n\n\n/**\n\n * @addtogroup core-netdata-local\n\n *\n\n * @brief\n\n * This module includes definitions for manipulating local Thread Network Data.\n\n *\n\n * @{\n\n */\n\n\n\nnamespace NetworkData {\n\n\n\n/**\n\n * This class implements the Thread Network Data contributed by the local device.\n\n *\n\n */\n", "file_path": "src/core/thread/network_data_local.hpp", "rank": 39, "score": 109138.64054876044 }, { "content": "class ThreadNetif;\n\n\n\nnamespace NetworkData {\n\n\n\n/**\n\n * @addtogroup core-netdata-leader\n\n *\n\n * @brief\n\n * This module includes definitions for manipulating Thread Network Data maanged by the Thread Leader.\n\n *\n\n * @{\n\n *\n\n */\n\n\n\n/**\n\n * This class implements the Thread Network Data maintained by the Leader.\n\n *\n\n */\n", "file_path": "src/core/thread/network_data_leader.hpp", "rank": 40, "score": 109138.64054876044 }, { "content": "class ThreadTargetTlv;\n\n\n\n/**\n\n * @addtogroup core-arp\n\n *\n\n * @brief\n\n * This module includes definitions for Thread EID-to-RLOC mapping and caching.\n\n *\n\n * @{\n\n */\n\n\n\n/**\n\n * This class implements the EID-to-RLOC mapping and caching.\n\n *\n\n */\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 41, "score": 109020.91638284735 }, { "content": "\n\nusing Thread::Encoding::BigEndian::HostSwap16;\n\nusing Thread::Encoding::BigEndian::HostSwap32;\n\n\n\nnamespace Thread {\n\nnamespace Ip6 {\n\n\n\nbool Address::IsUnspecified(void) const\n\n{\n\n return (m32[0] == 0 && m32[1] == 0 && m32[2] == 0 && m32[3] == 0);\n\n}\n\n\n\nbool Address::IsLoopback(void) const\n\n{\n\n return (m32[0] == 0 && m32[1] == 0 && m32[2] == 0 && m32[3] == HostSwap32(1));\n\n}\n\n\n\nbool Address::IsLinkLocal(void) const\n\n{\n\n return (m8[0] == 0xfe) && ((m8[1] & 0xc0) == 0x80);\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 42, "score": 106463.91362158509 }, { "content": "\n\n break;\n\n }\n\n }\n\n\n\n return rval;\n\n}\n\n\n\nbool Address::operator==(const Address &aOther) const\n\n{\n\n return memcmp(m8, aOther.m8, sizeof(m8)) == 0;\n\n}\n\n\n\nbool Address::operator!=(const Address &aOther) const\n\n{\n\n return memcmp(m8, aOther.m8, sizeof(m8)) != 0;\n\n}\n\n\n\nThreadError Address::FromString(const char *aBuf)\n\n{\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 43, "score": 106462.21781361669 }, { "content": " if (ch == '\\0' || ch == ' ')\n\n {\n\n break;\n\n }\n\n\n\n continue;\n\n }\n\n else\n\n {\n\n VerifyOrExit('0' <= ch && ch <= '9', error = kThreadError_Parse);\n\n }\n\n\n\n first = false;\n\n val = (val << 4) | d;\n\n VerifyOrExit(++count <= 4, error = kThreadError_Parse);\n\n }\n\n\n\n while (colonp && dst > colonp)\n\n {\n\n *endp-- = *dst--;\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 44, "score": 106458.0339054554 }, { "content": " }\n\n\n\n while (endp > dst)\n\n {\n\n *endp-- = 0;\n\n }\n\n\n\nexit:\n\n return error;\n\n}\n\n\n\nconst char *Address::ToString(char *aBuf, uint16_t aSize) const\n\n{\n\n snprintf(aBuf, aSize, \"%x:%x:%x:%x:%x:%x:%x:%x\",\n\n HostSwap16(m16[0]), HostSwap16(m16[1]),\n\n HostSwap16(m16[2]), HostSwap16(m16[3]),\n\n HostSwap16(m16[4]), HostSwap16(m16[5]),\n\n HostSwap16(m16[6]), HostSwap16(m16[7]));\n\n return aBuf;\n\n}\n\n\n\n} // namespace Ip6\n\n} // namespace Thread\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 45, "score": 106457.2436781186 }, { "content": " ThreadError error = kThreadError_None;\n\n uint8_t *dst = reinterpret_cast<uint8_t *>(m8);\n\n uint8_t *endp = reinterpret_cast<uint8_t *>(m8 + 15);\n\n uint8_t *colonp = NULL;\n\n uint16_t val = 0;\n\n uint8_t count = 0;\n\n bool first = true;\n\n uint8_t ch;\n\n uint8_t d;\n\n\n\n memset(m8, 0, 16);\n\n\n\n dst--;\n\n\n\n for (;;)\n\n {\n\n ch = *aBuf++;\n\n d = ch & 0xf;\n\n\n\n if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'))\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 46, "score": 106454.70405725768 }, { "content": " */\n\n bool IsLinkLocal(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is multicast address.\n\n *\n\n * @retval TRUE If the IPv6 address is a multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a multicast address.\n\n *\n\n */\n\n bool IsMulticast(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is a link-local multicast address.\n\n *\n\n * @retval TRUE If the IPv6 address is a link-local multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a link-local multicast address.\n\n *\n\n */\n\n bool IsLinkLocalMulticast(void) const;\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 47, "score": 106454.18232279213 }, { "content": "namespace Thread {\n\nnamespace Ip6 {\n\n\n\n/**\n\n * @addtogroup core-ip6-ip6\n\n *\n\n * @{\n\n *\n\n */\n\n\n\n/**\n\n * This class implements an IPv6 address object.\n\n *\n\n */\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 48, "score": 106453.92147669538 }, { "content": " * @retval FALSE If the IPv6 address is not the Loopback Address.\n\n *\n\n */\n\n bool IsLoopback(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address scope is Interafce-Local.\n\n *\n\n * @retval TRUE If the IPv6 address scope is Interface-Local.\n\n * @retval FALSE If the IPv6 address scope is not Interface-Local.\n\n *\n\n */\n\n bool IsInterfaceLocal(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address scope is Link-Local.\n\n *\n\n * @retval TRUE If the IPv6 address scope is Link-Local.\n\n * @retval FALSE If the IPv6 address scope is not Link-Local.\n\n *\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 49, "score": 106452.74901331998 }, { "content": "private:\n\n enum\n\n {\n\n kInterfaceIdentifierOffset = 8, ///< Interface Identifier offset in bytes.\n\n };\n\n} __attribute__((packed));\n\n\n\n/**\n\n * @}\n\n *\n\n */\n\n\n\n} // namespace Ip6\n\n} // namespace Thread\n\n\n\n#endif // NET_IP6_ADDRESS_HPP_\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 50, "score": 106452.70843862837 }, { "content": " {\n\n d += 9;\n\n }\n\n else if (ch == ':' || ch == '\\0' || ch == ' ')\n\n {\n\n if (count)\n\n {\n\n VerifyOrExit(dst + 2 <= endp, error = kThreadError_Parse);\n\n *(dst + 1) = static_cast<uint8_t>(val >> 8);\n\n *(dst + 2) = static_cast<uint8_t>(val);\n\n dst += 2;\n\n count = 0;\n\n val = 0;\n\n }\n\n else if (ch == ':')\n\n {\n\n VerifyOrExit(colonp == NULL || first, error = kThreadError_Parse);\n\n colonp = dst;\n\n }\n\n\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 51, "score": 106452.24470221254 }, { "content": " *\n\n * @param[in] aBuf A pointer to the NULL-terminated string.\n\n *\n\n * @retval kThreadError_None Successfully parsed the IPv6 address string.\n\n * @retval kTheradError_InvalidArgs Failed to parse the IPv6 address string.\n\n *\n\n */\n\n ThreadError FromString(const char *aBuf);\n\n\n\n /**\n\n * This method converts an IPv6 address object to a NULL-terminated string.\n\n *\n\n * @param[out] aBuf A pointer to the buffer.\n\n * @param[in] aSize The maximum size of the buffer.\n\n *\n\n * @returns A pointer to the buffer.\n\n *\n\n */\n\n const char *ToString(char *aBuf, uint16_t aSize) const;\n\n\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 52, "score": 106452.23065638776 }, { "content": "\n\n /**\n\n * This method indicates whether or not the IPv6 address is a link-local all nodes multicast address.\n\n *\n\n * @retval TRUE If the IPv6 address is a link-local all nodes multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a link-local all nodes multicast address.\n\n *\n\n */\n\n bool IsLinkLocalAllNodesMulticast(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is a link-local all routers multicast address.\n\n *\n\n * @retval TRUE If the IPv6 address is a link-local all routers multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a link-local all routers multicast address.\n\n *\n\n */\n\n bool IsLinkLocalAllRoutersMulticast(void) const;\n\n\n\n /**\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 53, "score": 106452.17441599857 }, { "content": " * This method indicates whether or not the IPv6 address is a realm-local multicast address.\n\n *\n\n * @retval TRUE If the IPv6 address is a realm-local multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a realm-local multicast address.\n\n *\n\n */\n\n bool IsRealmLocalMulticast(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is a realm-local all nodes multicast address.\n\n *\n\n * @retval TRUE If the IPv6 address is a realm-local all nodes multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a realm-local all nodes multicast address.\n\n *\n\n */\n\n bool IsRealmLocalAllNodesMulticast(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is a realm-local all routers multicast address.\n\n *\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 54, "score": 106451.90676218623 }, { "content": " * @retval TRUE If the IPv6 address is a realm-local all routers multicast address.\n\n * @retval FALSE If the IPv6 address scope is not a realm-local all routers multicast address.\n\n *\n\n */\n\n bool IsRealmLocalAllRoutersMulticast(void) const;\n\n\n\n /**\n\n * This method returns a pointer to the Interface Identifier.\n\n *\n\n * @returns A pointer to the Interface Identifier.\n\n *\n\n */\n\n const uint8_t *GetIid(void) const;\n\n\n\n /**\n\n * This method returns a pointer to the Interface Identifier.\n\n *\n\n * @returns A pointer to the Interface Identifier.\n\n *\n\n */\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 55, "score": 106450.72977783885 }, { "content": " kRealmLocalScope = 3, ///< Realm-Local scope\n\n kAdminLocalScope = 4, ///< Admin-Local scope\n\n kSiteLocalScope = 5, ///< Site-Local scope\n\n kOrgLocalScope = 8, ///< Organization-Local scope\n\n kGlobalScope = 14, ///< Global scope\n\n };\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is the Unspecified Address.\n\n *\n\n * @retval TRUE If the IPv6 address is the Unspecified Address.\n\n * @retval FALSE If the IPv6 address is not the Unspecified Address.\n\n *\n\n */\n\n bool IsUnspecified(void) const;\n\n\n\n /**\n\n * This method indicates whether or not the IPv6 address is the Loopback Address.\n\n *\n\n * @retval TRUE If the IPv6 address is the Loopback Address.\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 56, "score": 106449.9335854148 }, { "content": "}\n\n\n\nbool Address::IsMulticast(void) const\n\n{\n\n return m8[0] == 0xff;\n\n}\n\n\n\nbool Address::IsLinkLocalMulticast(void) const\n\n{\n\n return IsMulticast() && (GetScope() == kLinkLocalScope);\n\n}\n\n\n\nbool Address::IsLinkLocalAllNodesMulticast(void) const\n\n{\n\n return (m32[0] == HostSwap32(0xff020000) && m32[1] == 0 &&\n\n m32[2] == 0 && m32[3] == HostSwap32(0x01));\n\n}\n\n\n\nbool Address::IsLinkLocalAllRoutersMulticast(void) const\n\n{\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 57, "score": 106449.41535476582 }, { "content": " *\n\n * @retval TRUE If the IPv6 addresses match.\n\n * @retval FALSE If the IPv6 addresses do not match.\n\n *\n\n */\n\n bool operator==(const Address &aOther) const;\n\n\n\n /**\n\n * This method evaluates whether or not the IPv6 addresses differ.\n\n *\n\n * @param[in] aOther The IPv6 address to compare.\n\n *\n\n * @retval TRUE If the IPv6 addresses differ.\n\n * @retval FALSE If the IPv6 addresses do not differ.\n\n *\n\n */\n\n bool operator!=(const Address &aOther) const;\n\n\n\n /**\n\n * This method converts an IPv6 address string to binary.\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 58, "score": 106448.41258194325 }, { "content": " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n/**\n\n * @file\n\n * This file includes definitions for IPv6 addresses.\n\n */\n\n\n\n#ifndef IP6_ADDRESS_HPP_\n\n#define IP6_ADDRESS_HPP_\n\n\n\n#include <stdint.h>\n\n\n\n#include <openthread-types.h>\n\n\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 59, "score": 106447.96289278283 }, { "content": " return (m32[0] == HostSwap32(0xff020000) && m32[1] == 0 &&\n\n m32[2] == 0 && m32[3] == HostSwap32(0x02));\n\n}\n\n\n\nbool Address::IsRealmLocalMulticast(void) const\n\n{\n\n return IsMulticast() && (GetScope() == kRealmLocalScope);\n\n}\n\n\n\nbool Address::IsRealmLocalAllNodesMulticast(void) const\n\n{\n\n return (m32[0] == HostSwap32(0xff030000) && m32[1] == 0 &&\n\n m32[2] == 0 && m32[3] == HostSwap32(0x01));\n\n}\n\n\n\nbool Address::IsRealmLocalAllRoutersMulticast(void) const\n\n{\n\n return (m32[0] == HostSwap32(0xff030000) && m32[1] == 0 &&\n\n m32[2] == 0 && m32[3] == HostSwap32(0x02));\n\n}\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 60, "score": 106447.70419753097 }, { "content": " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\n * POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n/**\n\n * @file\n\n * This file implements IPv6 addresses.\n\n */\n\n\n\n#include <stdio.h>\n\n#include <string.h>\n\n\n\n#include <common/code_utils.hpp>\n\n#include <common/encoding.hpp>\n\n#include <mac/mac_frame.hpp>\n\n#include <net/ip6_address.hpp>\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 61, "score": 106445.98352173381 }, { "content": "uint8_t Address::PrefixMatch(const Address &aOther) const\n\n{\n\n uint8_t rval = 0;\n\n uint8_t diff;\n\n\n\n for (uint8_t i = 0; i < sizeof(Address); i++)\n\n {\n\n diff = m8[i] ^ aOther.m8[i];\n\n\n\n if (diff == 0)\n\n {\n\n rval += 8;\n\n }\n\n else\n\n {\n\n while ((diff & 0x80) == 0)\n\n {\n\n rval++;\n\n diff <<= 1;\n\n }\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 62, "score": 106443.21950482506 }, { "content": "\n\nconst uint8_t *Address::GetIid(void) const\n\n{\n\n return m8 + kInterfaceIdentifierOffset;\n\n}\n\n\n\nuint8_t *Address::GetIid(void)\n\n{\n\n return m8 + kInterfaceIdentifierOffset;\n\n}\n\n\n\nvoid Address::SetIid(const uint8_t *aIid)\n\n{\n\n memcpy(m8 + kInterfaceIdentifierOffset, aIid, kInterfaceIdentifierSize);\n\n}\n\n\n\nvoid Address::SetIid(const Mac::ExtAddress &aEui64)\n\n{\n\n memcpy(m8 + kInterfaceIdentifierOffset, aEui64.m8, kInterfaceIdentifierSize);\n\n m8[kInterfaceIdentifierOffset] ^= 0x02;\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 63, "score": 106442.6989666933 }, { "content": " uint8_t *GetIid(void);\n\n\n\n /**\n\n * This method sets the Interface Identifier.\n\n *\n\n * @param[in] aIid A reference to the Interface Identifier.\n\n *\n\n */\n\n void SetIid(const uint8_t *aIid);\n\n\n\n /**\n\n * This method sets the Interface Identifier.\n\n *\n\n * @param[in] aEui64 A reference to the IEEE EUI-64 address.\n\n *\n\n */\n\n void SetIid(const Mac::ExtAddress &aEui64);\n\n\n\n /**\n\n * This method returns the IPv6 address scope.\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 64, "score": 106442.3195440893 }, { "content": " *\n\n * @returns The IPv6 address scope.\n\n *\n\n */\n\n uint8_t GetScope(void) const;\n\n\n\n /**\n\n * This method returns the number of IPv6 prefix bits that match.\n\n *\n\n * @param[in] aOther The IPv6 address to match against.\n\n *\n\n * @returns The number of IPv6 prefix bits that match.\n\n *\n\n */\n\n uint8_t PrefixMatch(const Address &aOther) const;\n\n\n\n /**\n\n * This method evaluates whether or not the IPv6 addresses match.\n\n *\n\n * @param[in] aOther The IPv6 address to compare.\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 65, "score": 106441.24631331959 }, { "content": "}\n\n\n\nuint8_t Address::GetScope(void) const\n\n{\n\n if (IsMulticast())\n\n {\n\n return m8[1] & 0xf;\n\n }\n\n else if (IsLinkLocal())\n\n {\n\n return kLinkLocalScope;\n\n }\n\n else if (IsLoopback())\n\n {\n\n return kNodeLocalScope;\n\n }\n\n\n\n return kGlobalScope;\n\n}\n\n\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 66, "score": 106440.16098428724 }, { "content": "/*\n\n * Copyright (c) 2016, Nest Labs, Inc.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n * 1. Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * 2. Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in the\n\n * documentation and/or other materials provided with the distribution.\n\n * 3. Neither the name of the copyright holder nor the\n\n * names of its contributors may be used to endorse or promote products\n\n * derived from this software without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n", "file_path": "src/core/net/ip6_address.hpp", "rank": 67, "score": 106433.47519413303 }, { "content": "/*\n\n * Copyright (c) 2016, Nest Labs, Inc.\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are met:\n\n * 1. Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * 2. Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in the\n\n * documentation and/or other materials provided with the distribution.\n\n * 3. Neither the name of the copyright holder nor the\n\n * names of its contributors may be used to endorse or promote products\n\n * derived from this software without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n", "file_path": "src/core/net/ip6_address.cpp", "rank": 68, "score": 106433.47519413303 }, { "content": "class ThreadMeshLocalEidTlv;\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 69, "score": 105593.52283816083 }, { "content": "class ThreadLastTransactionTimeTlv;\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 70, "score": 105593.52283816083 }, { "content": "class LinkAddress\n\n{\n\npublic :\n\n /**\n\n * Hardware types.\n\n *\n\n */\n\n enum HardwareType\n\n {\n\n kEui64 = 27,\n\n };\n\n HardwareType mType; ///< Link address type.\n\n uint8_t mLength; ///< Length of link address.\n\n Mac::ExtAddress mExtAddress; ///< Link address.\n\n};\n\n\n\n/**\n\n * This class implements an IPv6 network interface unicast address.\n\n *\n\n */\n", "file_path": "src/core/net/netif.hpp", "rank": 71, "score": 104232.2058515706 }, { "content": " }\n\n\n\nexit:\n\n {}\n\n}\n\n\n\nvoid AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv,\n\n const ThreadMeshLocalEidTlv &aMlIidTlv,\n\n const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv,\n\n const Ip6::Address &aDestination)\n\n{\n\n ThreadError error;\n\n Message *message;\n\n Coap::Header header;\n\n ThreadRloc16Tlv rloc16Tlv;\n\n Ip6::MessageInfo messageInfo;\n\n\n\n VerifyOrExit((message = Ip6::Udp::NewMessage(0)) != NULL, error = kThreadError_NoBufs);\n\n\n\n header.Init();\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 72, "score": 103971.99509999841 }, { "content": " ThreadTargetTlv targetTlv;\n\n ThreadMeshLocalEidTlv mlIidTlv;\n\n Child *children;\n\n uint8_t numChildren;\n\n Mac::ExtAddress macAddr;\n\n Ip6::Address destination;\n\n\n\n VerifyOrExit(aHeader.GetCode() == Coap::Header::kCodePost, error = kThreadError_Drop);\n\n\n\n otLogInfoArp(\"Received address error notification\\n\");\n\n\n\n SuccessOrExit(error = ThreadTlv::GetTlv(aMessage, ThreadTlv::kTarget, sizeof(targetTlv), targetTlv));\n\n VerifyOrExit(targetTlv.IsValid(), error = kThreadError_Parse);\n\n\n\n SuccessOrExit(error = ThreadTlv::GetTlv(aMessage, ThreadTlv::kMeshLocalEid, sizeof(mlIidTlv), mlIidTlv));\n\n VerifyOrExit(mlIidTlv.IsValid(), error = kThreadError_Parse);\n\n\n\n for (const Ip6::NetifUnicastAddress *address = mNetif.GetUnicastAddresses(); address; address = address->GetNext())\n\n {\n\n if (memcmp(&address->mAddress, targetTlv.GetTarget(), sizeof(address->mAddress)) == 0 &&\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 73, "score": 103970.90226299173 }, { "content": " break;\n\n\n\n case Cache::kStateCached:\n\n aRloc16 = entry->mRloc16;\n\n break;\n\n }\n\n\n\nexit:\n\n return error;\n\n}\n\n\n\nThreadError AddressResolver::SendAddressQuery(const Ip6::Address &aEid)\n\n{\n\n ThreadError error;\n\n Ip6::SockAddr sockaddr;\n\n Message *message;\n\n Coap::Header header;\n\n ThreadTargetTlv targetTlv;\n\n Ip6::MessageInfo messageInfo;\n\n\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 74, "score": 103970.37314704972 }, { "content": " for (int j = 0; j < Child::kMaxIp6AddressPerChild; j++)\n\n {\n\n if (memcmp(&children[i].mIp6Address[j], targetTlv.GetTarget(), sizeof(children[i].mIp6Address[j])) == 0 &&\n\n memcmp(&children[i].mMacAddr, &macAddr, sizeof(children[i].mMacAddr)))\n\n {\n\n // Target EID matches child address and Mesh Local EID differs on child\n\n memset(&children[i].mIp6Address[j], 0, sizeof(children[i].mIp6Address[j]));\n\n\n\n memset(&destination, 0, sizeof(destination));\n\n destination.m16[0] = HostSwap16(0xfe80);\n\n destination.SetIid(children[i].mMacAddr);\n\n\n\n SendAddressError(targetTlv, mlIidTlv, &destination);\n\n ExitNow();\n\n }\n\n }\n\n }\n\n\n\nexit:\n\n {}\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 75, "score": 103969.10304161055 }, { "content": " }\n\n\n\n memset(&messageInfo, 0, sizeof(messageInfo));\n\n memcpy(&messageInfo.GetPeerAddr(), &aDestination, sizeof(messageInfo.GetPeerAddr()));\n\n messageInfo.mInterfaceId = messageInfo.mInterfaceId;\n\n messageInfo.mPeerPort = kCoapUdpPort;\n\n\n\n SuccessOrExit(error = mSocket.SendTo(*message, messageInfo));\n\n\n\n otLogInfoArp(\"Sent address notification\\n\");\n\n\n\nexit:\n\n\n\n if (error != kThreadError_None && message != NULL)\n\n {\n\n Message::Free(*message);\n\n }\n\n}\n\n\n\nvoid AddressResolver::HandleTimer(void *aContext)\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 76, "score": 103968.77394261141 }, { "content": "\n\n if (error != kThreadError_None && message != NULL)\n\n {\n\n Message::Free(*message);\n\n }\n\n}\n\n\n\nThreadError AddressResolver::SendAddressError(const ThreadTargetTlv &aTarget, const ThreadMeshLocalEidTlv &aEid,\n\n const Ip6::Address *aDestination)\n\n{\n\n ThreadError error;\n\n Message *message;\n\n Coap::Header header;\n\n Ip6::MessageInfo messageInfo;\n\n Ip6::SockAddr sockaddr;\n\n\n\n sockaddr.mPort = kCoapUdpPort;\n\n mSocket.Open(&HandleUdpReceive, this);\n\n mSocket.Bind(sockaddr);\n\n\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 77, "score": 103967.99379329135 }, { "content": " {\n\n SendAddressError(targetTlv, mlIidTlv, NULL);\n\n }\n\n\n\n ExitNow();\n\n }\n\n }\n\n\n\n ExitNow();\n\n\n\nexit:\n\n {}\n\n}\n\n\n\nvoid AddressResolver::SendAddressNotificationResponse(const Coap::Header &aRequestHeader,\n\n const Ip6::MessageInfo &aRequestInfo)\n\n{\n\n ThreadError error;\n\n Message *message;\n\n Coap::Header responseHeader;\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 78, "score": 103967.59804571696 }, { "content": "#include <thread/address_resolver.hpp>\n\n#include <thread/mesh_forwarder.hpp>\n\n#include <thread/mle_router.hpp>\n\n#include <thread/thread_netif.hpp>\n\n#include <thread/thread_tlvs.hpp>\n\n#include <thread/thread_uris.hpp>\n\n\n\nusing Thread::Encoding::BigEndian::HostSwap16;\n\n\n\nnamespace Thread {\n\n\n\nAddressResolver::AddressResolver(ThreadNetif &aThreadNetif) :\n\n mAddressError(OPENTHREAD_URI_ADDRESS_ERROR, &HandleAddressError, this),\n\n mAddressQuery(OPENTHREAD_URI_ADDRESS_QUERY, &HandleAddressQuery, this),\n\n mAddressNotification(OPENTHREAD_URI_ADDRESS_NOTIFY, &HandleAddressNotification, this),\n\n mIcmpHandler(&HandleDstUnreach, this),\n\n mTimer(&HandleTimer, this),\n\n mMeshForwarder(aThreadNetif.GetMeshForwarder()),\n\n mCoapServer(aThreadNetif.GetCoapServer()),\n\n mMle(aThreadNetif.GetMle()),\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 79, "score": 103966.24268356853 }, { "content": " uint8_t mFailures;\n\n\n\n enum State\n\n {\n\n kStateInvalid,\n\n kStateQuery,\n\n kStateCached,\n\n };\n\n State mState;\n\n };\n\n\n\n ThreadError SendAddressQuery(const Ip6::Address &aEid);\n\n ThreadError SendAddressError(const ThreadTargetTlv &aTarget, const ThreadMeshLocalEidTlv &aEid,\n\n const Ip6::Address *aDestination);\n\n void SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv, const ThreadMeshLocalEidTlv &aMlEidTlv,\n\n const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv,\n\n const Ip6::Address &aDestination);\n\n void SendAddressNotificationResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo);\n\n\n\n static void HandleUdpReceive(void *aContext, otMessage aMessage, const otMessageInfo *aMessageInfo);\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 80, "score": 103965.52510042177 }, { "content": "\n\n if (error != kThreadError_None && message != NULL)\n\n {\n\n Message::Free(*message);\n\n }\n\n\n\n return error;\n\n}\n\n\n\nvoid AddressResolver::HandleAddressError(void *aContext, Coap::Header &aHeader,\n\n Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n\n{\n\n AddressResolver *obj = reinterpret_cast<AddressResolver *>(aContext);\n\n obj->HandleAddressError(aHeader, aMessage, aMessageInfo);\n\n}\n\n\n\nvoid AddressResolver::HandleAddressError(Coap::Header &aHeader, Message &aMessage,\n\n const Ip6::MessageInfo &aMessageInfo)\n\n{\n\n ThreadError error = kThreadError_None;\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 81, "score": 103965.16459794847 }, { "content": " mNetif(aThreadNetif)\n\n{\n\n memset(&mCache, 0, sizeof(mCache));\n\n\n\n mCoapServer.AddResource(mAddressError);\n\n mCoapServer.AddResource(mAddressQuery);\n\n mCoapServer.AddResource(mAddressNotification);\n\n mCoapMessageId = otPlatRandomGet();\n\n\n\n Ip6::Icmp::RegisterCallbacks(mIcmpHandler);\n\n}\n\n\n\nvoid AddressResolver::Clear()\n\n{\n\n memset(&mCache, 0, sizeof(mCache));\n\n}\n\n\n\nvoid AddressResolver::Remove(uint8_t routerId)\n\n{\n\n for (int i = 0; i < kCacheEntries; i++)\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 82, "score": 103964.50627574127 }, { "content": " break;\n\n }\n\n }\n\n else if (entry == NULL)\n\n {\n\n entry = &mCache[i];\n\n }\n\n }\n\n\n\n VerifyOrExit(entry != NULL, error = kThreadError_NoBufs);\n\n\n\n switch (entry->mState)\n\n {\n\n case Cache::kStateInvalid:\n\n entry->mTarget = aEid;\n\n entry->mRloc16 = Mac::kShortAddrInvalid;\n\n entry->mTimeout = kAddressQueryTimeout;\n\n entry->mFailures = 0;\n\n entry->mRetryTimeout = kAddressQueryInitialRetryDelay;\n\n entry->mState = Cache::kStateQuery;\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 83, "score": 103964.37608314399 }, { "content": " memset(&messageInfo, 0, sizeof(messageInfo));\n\n\n\n if (aDestination == NULL)\n\n {\n\n messageInfo.GetPeerAddr().m16[0] = HostSwap16(0xff03);\n\n messageInfo.GetPeerAddr().m16[7] = HostSwap16(0x0002);\n\n }\n\n else\n\n {\n\n memcpy(&messageInfo.GetPeerAddr(), aDestination, sizeof(messageInfo.GetPeerAddr()));\n\n }\n\n\n\n messageInfo.mPeerPort = kCoapUdpPort;\n\n messageInfo.mInterfaceId = mNetif.GetInterfaceId();\n\n\n\n SuccessOrExit(error = mSocket.SendTo(*message, messageInfo));\n\n\n\n otLogInfoArp(\"Sent address error\\n\");\n\n\n\nexit:\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 84, "score": 103963.86231067083 }, { "content": " VerifyOrExit(aIcmpHeader.GetCode() == Ip6::IcmpHeader::kCodeDstUnreachNoRoute, ;);\n\n VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(ip6Header), &ip6Header) == sizeof(ip6Header), ;);\n\n\n\n for (int i = 0; i < kCacheEntries; i++)\n\n {\n\n if (mCache[i].mState != Cache::kStateInvalid &&\n\n memcmp(&mCache[i].mTarget, &ip6Header.GetDestination(), sizeof(mCache[i].mTarget)) == 0)\n\n {\n\n mCache[i].mState = Cache::kStateInvalid;\n\n otLogInfoArp(\"cache entry removed!\\n\");\n\n break;\n\n }\n\n }\n\n\n\nexit:\n\n {}\n\n}\n\n\n\n} // namespace Thread\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 85, "score": 103963.28196065738 }, { "content": "{\n\n AddressResolver *obj = reinterpret_cast<AddressResolver *>(aContext);\n\n obj->HandleTimer();\n\n}\n\n\n\nvoid AddressResolver::HandleTimer()\n\n{\n\n bool continueTimer = false;\n\n\n\n for (int i = 0; i < kCacheEntries; i++)\n\n {\n\n if (mCache[i].mState != Cache::kStateQuery)\n\n {\n\n continue;\n\n }\n\n\n\n continueTimer = true;\n\n\n\n if (mCache[i].mTimeout > 0)\n\n {\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 86, "score": 103962.74124781726 }, { "content": " {\n\n if ((mCache[i].mRloc16 >> 10) == routerId)\n\n {\n\n mCache[i].mState = Cache::kStateInvalid;\n\n }\n\n }\n\n}\n\n\n\nThreadError AddressResolver::Resolve(const Ip6::Address &aEid, uint16_t &aRloc16)\n\n{\n\n ThreadError error = kThreadError_None;\n\n Cache *entry = NULL;\n\n\n\n for (int i = 0; i < kCacheEntries; i++)\n\n {\n\n if (mCache[i].mState != Cache::kStateInvalid)\n\n {\n\n if (memcmp(&mCache[i].mTarget, &aEid, sizeof(mCache[i].mTarget)) == 0)\n\n {\n\n entry = &mCache[i];\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 87, "score": 103962.18486395813 }, { "content": "\n\n otLogInfoArp(\"Received address query from %04x\\n\", HostSwap16(aMessageInfo.GetPeerAddr().m16[7]));\n\n\n\n SuccessOrExit(ThreadTlv::GetTlv(aMessage, ThreadTlv::kTarget, sizeof(targetTlv), targetTlv));\n\n VerifyOrExit(targetTlv.IsValid(), ;);\n\n\n\n mlIidTlv.Init();\n\n\n\n lastTransactionTimeTlv.Init();\n\n\n\n if (mNetif.IsUnicastAddress(*targetTlv.GetTarget()))\n\n {\n\n mlIidTlv.SetIid(mMle.GetMeshLocal64()->GetIid());\n\n SendAddressQueryResponse(targetTlv, mlIidTlv, NULL, aMessageInfo.GetPeerAddr());\n\n ExitNow();\n\n }\n\n\n\n children = mMle.GetChildren(&numChildren);\n\n\n\n for (int i = 0; i < Mle::kMaxChildren; i++)\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 88, "score": 103961.78845560494 }, { "content": " Coap::Resource mAddressError;\n\n Coap::Resource mAddressQuery;\n\n Coap::Resource mAddressNotification;\n\n Cache mCache[kCacheEntries];\n\n uint16_t mCoapMessageId;\n\n uint8_t mCoapToken[2];\n\n Ip6::IcmpHandler mIcmpHandler;\n\n Ip6::UdpSocket mSocket;\n\n Timer mTimer;\n\n\n\n MeshForwarder &mMeshForwarder;\n\n Coap::Server &mCoapServer;\n\n Mle::MleRouter &mMle;\n\n Ip6::Netif &mNetif;\n\n};\n\n\n\n/**\n\n * @}\n\n */\n\n\n\n} // namespace Thread\n\n\n\n#endif // ADDRESS_RESOLVER_HPP_\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 89, "score": 103961.21684873708 }, { "content": " mTimer.Start(kStateUpdatePeriod);\n\n }\n\n\n\n if (error != kThreadError_None && message != NULL)\n\n {\n\n Message::Free(*message);\n\n }\n\n\n\n return error;\n\n}\n\n\n\nvoid AddressResolver::HandleUdpReceive(void *aContext, otMessage aMessage, const otMessageInfo *aMessageInfo)\n\n{\n\n}\n\n\n\nvoid AddressResolver::HandleAddressNotification(void *aContext, Coap::Header &aHeader, Message &aMessage,\n\n const Ip6::MessageInfo &aMessageInfo)\n\n{\n\n AddressResolver *obj = reinterpret_cast<AddressResolver *>(aContext);\n\n obj->HandleAddressNotification(aHeader, aMessage, aMessageInfo);\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 90, "score": 103961.17952986823 }, { "content": " {\n\n if (children[i].mState != Neighbor::kStateValid || (children[i].mMode & Mle::ModeTlv::kModeFFD) != 0)\n\n {\n\n continue;\n\n }\n\n\n\n for (int j = 0; j < Child::kMaxIp6AddressPerChild; j++)\n\n {\n\n if (memcmp(&children[i].mIp6Address[j], targetTlv.GetTarget(), sizeof(children[i].mIp6Address[j])))\n\n {\n\n continue;\n\n }\n\n\n\n children[i].mMacAddr.m8[0] ^= 0x2;\n\n mlIidTlv.SetIid(children[i].mMacAddr.m8);\n\n children[i].mMacAddr.m8[0] ^= 0x2;\n\n lastTransactionTimeTlv.SetTime(Timer::GetNow() - children[i].mLastHeard);\n\n SendAddressQueryResponse(targetTlv, mlIidTlv, &lastTransactionTimeTlv, aMessageInfo.GetPeerAddr());\n\n ExitNow();\n\n }\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 91, "score": 103960.66286684625 }, { "content": " Ip6::MessageInfo responseInfo;\n\n\n\n VerifyOrExit((message = Ip6::Udp::NewMessage(0)) != NULL, error = kThreadError_NoBufs);\n\n\n\n responseHeader.Init();\n\n responseHeader.SetVersion(1);\n\n responseHeader.SetType(Coap::Header::kTypeAcknowledgment);\n\n responseHeader.SetCode(Coap::Header::kCodeChanged);\n\n responseHeader.SetMessageId(aRequestHeader.GetMessageId());\n\n responseHeader.SetToken(aRequestHeader.GetToken(), aRequestHeader.GetTokenLength());\n\n responseHeader.Finalize();\n\n SuccessOrExit(error = message->Append(responseHeader.GetBytes(), responseHeader.GetLength()));\n\n\n\n memcpy(&responseInfo, &aRequestInfo, sizeof(responseInfo));\n\n memset(&responseInfo.mSockAddr, 0, sizeof(responseInfo.mSockAddr));\n\n SuccessOrExit(error = mCoapServer.SendMessage(*message, responseInfo));\n\n\n\n otLogInfoArp(\"Sent address notification acknowledgment\\n\");\n\n\n\nexit:\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 92, "score": 103959.98136486729 }, { "content": " memcmp(mMle.GetMeshLocal64()->GetIid(), mlIidTlv.GetIid(), 8))\n\n {\n\n // Target EID matches address and Mesh Local EID differs\n\n mNetif.RemoveUnicastAddress(*address);\n\n ExitNow();\n\n }\n\n }\n\n\n\n children = mMle.GetChildren(&numChildren);\n\n\n\n memcpy(&macAddr, mlIidTlv.GetIid(), sizeof(macAddr));\n\n macAddr.m8[0] ^= 0x2;\n\n\n\n for (int i = 0; i < Mle::kMaxChildren; i++)\n\n {\n\n if (children[i].mState != Neighbor::kStateValid || (children[i].mMode & Mle::ModeTlv::kModeFFD) != 0)\n\n {\n\n continue;\n\n }\n\n\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 93, "score": 103958.50357118623 }, { "content": "}\n\n\n\nvoid AddressResolver::HandleAddressNotification(Coap::Header &aHeader, Message &aMessage,\n\n const Ip6::MessageInfo &aMessageInfo)\n\n{\n\n ThreadTargetTlv targetTlv;\n\n ThreadMeshLocalEidTlv mlIidTlv;\n\n ThreadRloc16Tlv rloc16Tlv;\n\n\n\n VerifyOrExit(aHeader.GetType() == Coap::Header::kTypeConfirmable &&\n\n aHeader.GetCode() == Coap::Header::kCodePost, ;);\n\n\n\n otLogInfoArp(\"Received address notification from %04x\\n\", HostSwap16(aMessageInfo.GetPeerAddr().m16[7]));\n\n\n\n SuccessOrExit(ThreadTlv::GetTlv(aMessage, ThreadTlv::kTarget, sizeof(targetTlv), targetTlv));\n\n VerifyOrExit(targetTlv.IsValid(), ;);\n\n\n\n SuccessOrExit(ThreadTlv::GetTlv(aMessage, ThreadTlv::kMeshLocalEid, sizeof(mlIidTlv), mlIidTlv));\n\n VerifyOrExit(mlIidTlv.IsValid(), ;);\n\n\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 94, "score": 103957.87440603384 }, { "content": " for (size_t i = 0; i < sizeof(mCoapToken); i++)\n\n {\n\n mCoapToken[i] = otPlatRandomGet();\n\n }\n\n\n\n VerifyOrExit((message = Ip6::Udp::NewMessage(0)) != NULL, error = kThreadError_NoBufs);\n\n\n\n header.Init();\n\n header.SetVersion(1);\n\n header.SetType(Coap::Header::kTypeNonConfirmable);\n\n header.SetCode(Coap::Header::kCodePost);\n\n header.SetMessageId(++mCoapMessageId);\n\n header.SetToken(NULL, 0);\n\n header.AppendUriPathOptions(OPENTHREAD_URI_ADDRESS_ERROR);\n\n header.AppendContentFormatOption(Coap::Header::kApplicationOctetStream);\n\n header.Finalize();\n\n SuccessOrExit(error = message->Append(header.GetBytes(), header.GetLength()));\n\n SuccessOrExit(error = message->Append(&aTarget, sizeof(aTarget)));\n\n SuccessOrExit(error = message->Append(&aEid, sizeof(aEid)));\n\n\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 95, "score": 103957.33178874559 }, { "content": " */\n\n void Remove(uint8_t aRouterId);\n\n\n\n /**\n\n * This method returns the RLOC16 for a given EID, or initiates an Address Query if the mapping is not known.\n\n *\n\n * @param[in] aEid A reference to the EID.\n\n * @param[out] aRloc16 The RLOC16 corresponding to @p aEid.\n\n *\n\n * @retval kTheradError_None Successfully provided the RLOC16.\n\n * @retval kThreadError_AddressQuery Initiated an Address Query.\n\n *\n\n */\n\n ThreadError Resolve(const Ip6::Address &aEid, Mac::ShortAddress &aRloc16);\n\n\n\nprivate:\n\n enum\n\n {\n\n kCacheEntries = OPENTHREAD_CONFIG_ADDRESS_CACHE_ENTRIES,\n\n kStateUpdatePeriod = 1000u, ///< State update period in milliseconds.\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 96, "score": 103956.57721448313 }, { "content": "}\n\n\n\nvoid AddressResolver::HandleAddressQuery(void *aContext, Coap::Header &aHeader, Message &aMessage,\n\n const Ip6::MessageInfo &aMessageInfo)\n\n{\n\n AddressResolver *obj = reinterpret_cast<AddressResolver *>(aContext);\n\n obj->HandleAddressQuery(aHeader, aMessage, aMessageInfo);\n\n}\n\n\n\nvoid AddressResolver::HandleAddressQuery(Coap::Header &aHeader, Message &aMessage,\n\n const Ip6::MessageInfo &aMessageInfo)\n\n{\n\n ThreadTargetTlv targetTlv;\n\n ThreadMeshLocalEidTlv mlIidTlv;\n\n ThreadLastTransactionTimeTlv lastTransactionTimeTlv;\n\n Child *children;\n\n uint8_t numChildren;\n\n\n\n VerifyOrExit(aHeader.GetType() == Coap::Header::kTypeNonConfirmable &&\n\n aHeader.GetCode() == Coap::Header::kCodePost, ;);\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 97, "score": 103956.34494763383 }, { "content": " SendAddressQuery(aEid);\n\n error = kThreadError_AddressQuery;\n\n break;\n\n\n\n case Cache::kStateQuery:\n\n if (entry->mTimeout > 0)\n\n {\n\n error = kThreadError_AddressQuery;\n\n }\n\n else if (entry->mTimeout == 0 && entry->mRetryTimeout == 0)\n\n {\n\n entry->mTimeout = kAddressQueryTimeout;\n\n SendAddressQuery(aEid);\n\n error = kThreadError_AddressQuery;\n\n }\n\n else\n\n {\n\n error = kThreadError_Drop;\n\n }\n\n\n", "file_path": "src/core/thread/address_resolver.cpp", "rank": 98, "score": 103955.8436242316 }, { "content": "\n\n static void HandleAddressError(void *aContext, Coap::Header &aHeader,\n\n Message &aMessage, const Ip6::MessageInfo &aMessageInfo);\n\n void HandleAddressError(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo);\n\n\n\n static void HandleAddressQuery(void *aContext, Coap::Header &aHeader,\n\n Message &aMessage, const Ip6::MessageInfo &aMessageInfo);\n\n void HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo);\n\n\n\n static void HandleAddressNotification(void *aContext, Coap::Header &aHeader,\n\n Message &aMessage, const Ip6::MessageInfo &aMessageInfo);\n\n void HandleAddressNotification(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo);\n\n\n\n static void HandleDstUnreach(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo,\n\n const Ip6::IcmpHeader &aIcmpHeader);\n\n void HandleDstUnreach(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const Ip6::IcmpHeader &aIcmpHeader);\n\n\n\n static void HandleTimer(void *aContext);\n\n void HandleTimer(void);\n\n\n", "file_path": "src/core/thread/address_resolver.hpp", "rank": 99, "score": 103954.78050249818 } ]
C++
MUON/MUONgraphics/AliMUONPCBPainter.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
#include "AliMUONPCBPainter.h" #include "AliMUONManuPainter.h" #include "AliMUONContour.h" #include "AliMUONPainterHelper.h" #include "AliMUONVCalibParam.h" #include "AliMUONVTrackerData.h" #include "AliMpDEManager.h" #include "AliMpMotifPosition.h" #include "AliMpPCB.h" #include "AliMpPlaneType.h" #include "AliMpSlat.h" #include "AliLog.h" ClassImp(AliMUONPCBPainter) AliMUONPCBPainter::AliMUONPCBPainter(TRootIOCtor* ioCtor) : AliMUONVPainter(ioCtor), fDetElemId(-1), fPCBIndex(-1) { } AliMUONPCBPainter::AliMUONPCBPainter() : AliMUONVPainter(), fDetElemId(-1), fPCBIndex(-1) { } AliMUONPCBPainter::AliMUONPCBPainter(const AliMUONAttPainter& att, Int_t detElemId, Int_t pcbNumber) : AliMUONVPainter("PCB"), fDetElemId(detElemId), fPCBIndex(pcbNumber) { SetAttributes(att); AliMUONPainterHelper* h = AliMUONPainterHelper::Instance(); AliMp::PlaneType planeType = ( att.IsBendingPlane() ? AliMp::kBendingPlane : AliMp::kNonBendingPlane ); const AliMpSlat* slat = AliMUONPainterHelper::Instance()->GetSlat(fDetElemId,planeType); SetID(detElemId,pcbNumber); SetName(h->PCBName(pcbNumber)); SetPathName(h->PCBPathName(detElemId,pcbNumber)); AliMpPCB* pcb = slat->GetPCB(fPCBIndex); AliMUONContour* contour = h->GetContour(ContourName()); TObjArray contourArray; for ( Int_t imp = 0 ; imp < pcb->GetSize(); ++imp ) { AliMpMotifPosition* mp = pcb->GetMotifPosition(imp); AliMUONVPainter* painter = new AliMUONManuPainter(Attributes(),fDetElemId,mp->GetID()); Add(painter); if (!contour) { contourArray.Add(painter->Contour()); } } Double_t x,y,z; h->Local2Global(fDetElemId, pcb->X()-slat->GetPositionX(), pcb->Y()-slat->GetPositionY(), 0.0, x,y,z); if (!contour) { contour = h->MergeContours(contourArray,ContourName()); } SetContour(contour); } AliMUONPCBPainter::~AliMUONPCBPainter() { } AliMUONPCBPainter::AliMUONPCBPainter(const AliMUONPCBPainter& rhs) : AliMUONVPainter(rhs), fDetElemId(-1), fPCBIndex(-1) { rhs.Copy(*this); } AliMUONPCBPainter& AliMUONPCBPainter::operator=(const AliMUONPCBPainter& rhs) { if ( this != &rhs ) { rhs.Copy(*this); } return *this; } void AliMUONPCBPainter::ComputeDataRange(const AliMUONVTrackerData& data, Int_t dataIndex, Double_t& dataMin, Double_t& dataMax) const { dataMin = dataMax = data.PCB(fDetElemId, fPCBIndex,dataIndex); } void AliMUONPCBPainter::Copy(TObject& object) const { AliMUONVPainter::Copy((AliMUONVPainter&)(object)); ((AliMUONPCBPainter&)(object)).fDetElemId = fDetElemId; ((AliMUONPCBPainter&)(object)).fPCBIndex = fPCBIndex; } TString AliMUONPCBPainter::Describe(const AliMUONVTrackerData& data, Int_t dataIndex, Double_t, Double_t) { if (!data.HasPCB(fDetElemId,fPCBIndex)) return ""; Double_t value = data.PCB(fDetElemId,fPCBIndex,dataIndex); return AliMUONPainterHelper::Instance()->FormatValue(data.DimensionName(dataIndex).Data(),value); } Bool_t AliMUONPCBPainter::IsIncluded() const { return ( InteractiveReadOutConfig()->PCB(fDetElemId,fPCBIndex) > 0 ); } void AliMUONPCBPainter::PaintArea(const AliMUONVTrackerData& data, Int_t dataIndex, Double_t min, Double_t max) { if (!data.HasPCB(fDetElemId,fPCBIndex)) return; Double_t value = data.PCB(fDetElemId,fPCBIndex,dataIndex); if ( value >= AliMUONVCalibParam::InvalidFloatValue() ) return; Int_t color = AliMUONPainterHelper::Instance()->ColorFromValue(value,min,max); PaintArea(color); }
#include "AliMUONPCBPainter.h" #include "AliMUONManuPainter.h" #include "AliMUONContour.h" #include "AliMUONPainterHelper.h" #include "AliMUONVCalibParam.h" #include "AliMUONVTrackerData.h" #include "AliMpDEManager.h" #include "AliMpMotifPosition.h" #include "AliMpPCB.h" #include "AliMpPlaneType.h" #include "AliMpSlat.h" #include "AliLog.h" ClassImp(AliMUONPCBPainter) AliMUONPCBPainter::AliMUONPCBPainter(TRootIOCtor* ioCtor) : AliMUONVPainter(ioCtor), fDetElemId(-1), fPCBIndex(-1) { } AliMUONPCBPainter::AliMUONPCBPainter() : AliMUONVPainter(), fDetElemId(-1), fPCBIndex(-1) { } AliMUONPCBPainter::AliMUONPCBPainter(const AliMUONAttPainter& att, Int_t detElemId, Int_t pcbNumber) : AliMUONVPainter("PCB"), fDetElemId(detElemId), fPCBIndex(pcbNumber) { SetAttributes(att); AliMUONPainterHelper* h = AliMUONPainterHelper::Instance(); AliMp::PlaneType planeType = ( att.IsBendingPlane() ? AliMp::kBendingPlane : AliMp::kNonBendingPlane ); const AliMpSlat* slat = AliMUONPainterHelper::Instance()->GetSlat(fDetElemId,planeType); SetID(detElemId,pcbNumber); SetName(h->PCBName(pcbNumber)); SetPathName(h->PCBPathName(detElemId,pcbNumber)); AliMpPCB* pcb = slat->GetPCB(fPCBIndex); AliMUONContour* contour = h->GetContour(ContourName()); TObjArray contourArray; for ( Int_t imp = 0 ; imp < pcb->GetSize(); ++imp ) { AliMpMotifPosition* mp = pcb->GetMotifPosition(imp); AliMUONVPainter* painter = new AliMUONManuPainter(Attributes(),fDetElemId,mp->GetID()); Add(painter); if (!contour) { contourArray.Add(painter->Contour()); } } Double_t x,y,z;
; if (!contour) { contour = h->MergeContours(contourArray,ContourName()); } SetContour(contour); } AliMUONPCBPainter::~AliMUONPCBPainter() { } AliMUONPCBPainter::AliMUONPCBPainter(const AliMUONPCBPainter& rhs) : AliMUONVPainter(rhs), fDetElemId(-1), fPCBIndex(-1) { rhs.Copy(*this); } AliMUONPCBPainter& AliMUONPCBPainter::operator=(const AliMUONPCBPainter& rhs) { if ( this != &rhs ) { rhs.Copy(*this); } return *this; } void AliMUONPCBPainter::ComputeDataRange(const AliMUONVTrackerData& data, Int_t dataIndex, Double_t& dataMin, Double_t& dataMax) const { dataMin = dataMax = data.PCB(fDetElemId, fPCBIndex,dataIndex); } void AliMUONPCBPainter::Copy(TObject& object) const { AliMUONVPainter::Copy((AliMUONVPainter&)(object)); ((AliMUONPCBPainter&)(object)).fDetElemId = fDetElemId; ((AliMUONPCBPainter&)(object)).fPCBIndex = fPCBIndex; } TString AliMUONPCBPainter::Describe(const AliMUONVTrackerData& data, Int_t dataIndex, Double_t, Double_t) { if (!data.HasPCB(fDetElemId,fPCBIndex)) return ""; Double_t value = data.PCB(fDetElemId,fPCBIndex,dataIndex); return AliMUONPainterHelper::Instance()->FormatValue(data.DimensionName(dataIndex).Data(),value); } Bool_t AliMUONPCBPainter::IsIncluded() const { return ( InteractiveReadOutConfig()->PCB(fDetElemId,fPCBIndex) > 0 ); } void AliMUONPCBPainter::PaintArea(const AliMUONVTrackerData& data, Int_t dataIndex, Double_t min, Double_t max) { if (!data.HasPCB(fDetElemId,fPCBIndex)) return; Double_t value = data.PCB(fDetElemId,fPCBIndex,dataIndex); if ( value >= AliMUONVCalibParam::InvalidFloatValue() ) return; Int_t color = AliMUONPainterHelper::Instance()->ColorFromValue(value,min,max); PaintArea(color); }
h->Local2Global(fDetElemId, pcb->X()-slat->GetPositionX(), pcb->Y()-slat->GetPositionY(), 0.0, x,y,z)
call_expression
[ { "content": "class AliMpPCB;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpPCBPainter.h", "rank": 0, "score": 278175.9464289656 }, { "content": "class AliMpSlat;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpSlatPainter.h", "rank": 1, "score": 278174.1546947528 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 2, "score": 264430.56506290764 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/MUONmapping/AliMpSlatSegmentation.h", "rank": 3, "score": 259277.16579607318 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmapping/AliMpPCBPadIterator.h", "rank": 4, "score": 254384.2957201721 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/MUONgraphics/AliMUONPainterHelper.h", "rank": 5, "score": 240368.33029013552 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONgraphics/AliMUONPainterHelper.h", "rank": 6, "score": 240366.83742970304 }, { "content": "class AliMpPCBPainter : public AliMpVPainter\n\n{\n\npublic:\n\n AliMpPCBPainter(AliMpPCB* pcb);\n\n virtual ~AliMpPCBPainter();\n\n\n\n void Draw(Option_t* option);\n\n\n\n void Paint(Option_t* option);\n\n\n\n TVector2 GetDimensions() const;\n\n TVector2 GetPosition() const;\n\n\n\n private:\n\n /// Not implemented\n\n AliMpPCBPainter(const AliMpPCBPainter& right);\n\n /// Not implemented\n\n AliMpPCBPainter& operator = (const AliMpPCBPainter& right);\n\n\n\n AliMpPCB* fPCB; //!<! PCB to be plotted.\n\n\n\n ClassDef(AliMpPCBPainter,1) // A painter for a PCB of stations 3,4,5\n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONmpgraphics/AliMpPCBPainter.h", "rank": 7, "score": 234720.473310315 }, { "content": "class AliMpSlatPainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpSlatPainter();\n\n AliMpSlatPainter(const AliMpSlat* slat);\n\n virtual ~AliMpSlatPainter();\n\n\n\n TVector2 GetDimensions() const;\n\n\n\n TVector2 GetPosition() const;\n\n\n\n void Draw(Option_t* option);\n\n\n\n void Paint(Option_t* option);\n\n\n\n private:\n\n /// Not implemented\n\n AliMpSlatPainter(const AliMpSlatPainter& right);\n\n /// Not implemented\n\n AliMpSlatPainter& operator = (const AliMpSlatPainter& right);\n\n\n\n const AliMpSlat* fkSlat; //!<! pointer to the slat to be drawn\n\n\n\n ClassDef(AliMpSlatPainter,1) // A painter for a slat of stations 3,4,5\n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONmpgraphics/AliMpSlatPainter.h", "rank": 8, "score": 234719.34622992607 }, { "content": "class AliMpSlat;\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlatSegmentation.h", "rank": 9, "score": 217650.46522541248 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmapping/AliMpSlatPadIterator.h", "rank": 10, "score": 214685.71017554423 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/mapping/data/station345/flipPCB.h", "rank": 11, "score": 202099.47371030317 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/MUONmapping/AliMpTrigger.h", "rank": 12, "score": 202090.20745070712 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmapping/AliMpSegmentation.h", "rank": 13, "score": 202088.68602874433 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmapping/AliMpTrigger.h", "rank": 14, "score": 202088.68602874433 }, { "content": "class AliMpPCB : public TObject\n\n{\n\n public:\n\n\n\n AliMpPCB();\n\n /** Ctor. The sizes are given in mm.\n\n See full doc for the meaning of enveloppe parameters.\n\n */\n\n AliMpPCB(AliMpSlatMotifMap* motifMap,\n\n const char* id, Double_t padSizeX, Double_t padSizeY,\n\n Double_t enveloppeSizeX, Double_t enveloppeSizeY);\n\n \n\n AliMpPCB(const char* id, AliMpMotifSpecial* ms);\n\n \n\n AliMpPCB(const AliMpPCB& o);\n\n AliMpPCB& operator=(const AliMpPCB& o);\n\n\n\n virtual ~AliMpPCB();\n\n\n\n TObject* Clone(const char* newname=\"\") const;\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 15, "score": 200619.4666104194 }, { "content": "class AliMpSlat : public TObject\n\n{\n\n public:\n\n\n\n AliMpSlat(TRootIOCtor* ioCtor);\n\n AliMpSlat(const char* id, AliMp::PlaneType bendingOrNonBending);\n\n virtual ~AliMpSlat();\n\n\n\n /// Return x position\n\n Double_t GetPositionX() const { return fPositionX; }\n\n /// Return y position\n\n Double_t GetPositionY() const { return fPositionY; }\n\n \n\n const char* GetName() const;\n\n \n\n const char* GetID() const;\n\n\n\n void Add(const AliMpPCB& pcbType, const TArrayI& manuList);\n\n\n\n Double_t DX() const;\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 16, "score": 200617.82309104822 }, { "content": "/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n * See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n// $MpId: AliMpPCBPainter.h,v 1.7 2006/05/24 13:58:13 ivana Exp $\n\n\n\n/// \\ingroup mpgraphics\n\n/// \\class AliMpPCBPainter\n\n/// \\brief Class for drawing a PCB into canvas\n\n///\n\n// Author: Laurent Aphecetche\n\n\n\n#ifndef ALIMPPCBPAINTER_H\n\n#define ALIMPPCBPAINTER_H\n\n\n\n#include \"AliMpVPainter.h\"\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpPCBPainter.h", "rank": 17, "score": 198896.23792636566 }, { "content": "/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n * See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n// $MpId: AliMpSlatPainter.h,v 1.10 2006/05/24 13:58:13 ivana Exp $\n\n\n\n/// \\ingroup mpgraphics\n\n/// \\class AliMpSlatPainter\n\n/// \\brief Class for drawing a slat into canvas\n\n///\n\n// Author: Laurent Aphecetche\n\n\n\n#ifndef ALIMPSLATPAINTER_H\n\n#define ALIMPSLATPAINTER_H\n\n\n\n#ifndef ALI_MP_V_PAINTER_H\n\n# include \"AliMpVPainter.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpSlatPainter.h", "rank": 18, "score": 198896.0965947113 }, { "content": "class AliMUONContour;\n\n\n", "file_path": "MUON/MUONgraphics/AliMUONContourPainter.h", "rank": 19, "score": 198772.36019048808 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/MUONmapping/AliMpTriggerReader.h", "rank": 20, "score": 198743.749472236 }, { "content": "class AliMpPCB;\n", "file_path": "MUON/MUONmapping/AliMpSt345Reader.h", "rank": 21, "score": 198743.749472236 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmapping/AliMpTriggerReader.h", "rank": 22, "score": 198742.25661180352 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmapping/AliMpSt345Reader.h", "rank": 23, "score": 198742.25661180352 }, { "content": "class AliMpSlat;\n", "file_path": "MUON/MUONmpgraphics/AliMpDEVisu.h", "rank": 24, "score": 198742.25661180352 }, { "content": "class AliMpSlatMotifMap;\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 25, "score": 195578.84746264954 }, { "content": "class AliMpSlatSegmentation;\n\n\n", "file_path": "MUON/MUONmapping/AliMpPCBPadIterator.h", "rank": 26, "score": 190927.6859698033 }, { "content": " inline const EntryType &operator[](size_t i) const;\n", "file_path": "Vc/include/Vc/common/memorybase.h", "rank": 27, "score": 183995.50074769324 }, { "content": "class AliMUONContour;\n", "file_path": "MUON/MUONgraphics/AliMUONVPainter.h", "rank": 28, "score": 183477.57308309356 }, { "content": "class AliMUONContour;\n", "file_path": "MUON/MUONgraphics/AliMUONPainterHelper.h", "rank": 29, "score": 179863.9628174143 }, { "content": "class TObjArray;\n", "file_path": "MUON/MUONmpgraphics/AliMpIteratorPainter.h", "rank": 30, "score": 179769.8338001894 }, { "content": "class AliMpSlatMotifMap;\n\n\n\nconst char* NameIt(const TString& baseName);\n\n\n\nAliMpPCB* Duplicate(const AliMpPCB& src, AliMpSlatMotifMap& motifMap);\n\n\n\nvoid flipPCB(const char* srcName);\n\n\n\n#endif", "file_path": "MUON/mapping/data/station345/flipPCB.h", "rank": 31, "score": 176457.43699235687 }, { "content": "class AliMpMotifPainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpMotifPainter();\n\n AliMpMotifPainter(AliMpMotifType* motifType);\n\n AliMpMotifPainter(AliMpMotifPosition *motifPos);\n\n virtual ~AliMpMotifPainter();\n\n \n\n virtual void DumpObject(); //-MENU-\n\n virtual void Paint(Option_t *option);\n\n virtual TVector2 GetPosition() const;\n\n virtual TVector2 GetDimensions() const;\n\n\n\n private:\n\n /// Not implemented\n\n AliMpMotifPainter(const AliMpMotifPainter& right);\n\n /// Not implemented\n\n AliMpMotifPainter& operator = (const AliMpMotifPainter& right);\n\n\n\n void PaintContour(Option_t* option, Bool_t fill);\n\n\n\n AliMpMotifPosition *fMotifPos; ///< the motif to draw\n\n \n\n ClassDef(AliMpMotifPainter,1) // Motif painter\n\n};\n\n#endif //ALI_MP_MOTIF_PAINTER_H\n", "file_path": "MUON/MUONmpgraphics/AliMpMotifPainter.h", "rank": 32, "score": 163414.7603895825 }, { "content": "class AliMpRowPainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpRowPainter();\n\n AliMpRowPainter(AliMpRow *row);\n\n virtual ~AliMpRowPainter();\n\n \n\n virtual void DumpObject(); //-MENU-\n\n virtual void Draw(Option_t *option);\n\n virtual void Paint(Option_t *option);\n\n virtual TVector2 GetPosition() const;\n\n virtual TVector2 GetDimensions() const;\n\n\n\n private: \n\n /// Not implemented\n\n AliMpRowPainter(const AliMpRowPainter& right);\n\n /// Not implemented\n\n AliMpRowPainter& operator = (const AliMpRowPainter& right);\n\n\n\n AliMpRow *fRow; ///< the row to paint\n\n \n\n ClassDef(AliMpRowPainter,1) // Row painter\n\n};\n\n#endif //ALI_MP_ROW_PAINTER_H\n", "file_path": "MUON/MUONmpgraphics/AliMpRowPainter.h", "rank": 33, "score": 163414.7603895825 }, { "content": "class AliMpSectorPainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpSectorPainter();\n\n AliMpSectorPainter(AliMpSector *sector);\n\n virtual ~AliMpSectorPainter();\n\n \n\n virtual void Draw(Option_t* option);\n\n virtual void Paint(Option_t* /*option*/);\n\n virtual void DumpObject(); // -MENU-\n\n virtual TVector2 GetPosition() const;\n\n virtual TVector2 GetDimensions() const;\n\n\n\n private:\n\n /// Not implemented\n\n AliMpSectorPainter(const AliMpSectorPainter& right);\n\n /// Not implemented\n\n AliMpSectorPainter& operator = (const AliMpSectorPainter& right);\n\n\n\n AliMpSector *fSector; ///< the sector to draw\n\n\n\n ClassDef(AliMpSectorPainter,1) // Sector painter\n\n};\n\n#endif //ALI_MP_SECTOR_PAINTER_H\n", "file_path": "MUON/MUONmpgraphics/AliMpSectorPainter.h", "rank": 34, "score": 163414.7603895825 }, { "content": "class AliMpIteratorPainter : public AliMpVPainter\n\n{\n\npublic:\n\n AliMpIteratorPainter(AliMpVPadIterator* it);\n\n virtual ~AliMpIteratorPainter();\n\n \n\n void Draw(Option_t* option);\n\n void Paint(Option_t* option);\n\n \n\n TVector2 GetDimensions() const { return fDimensions; }\n\n TVector2 GetPosition() const { return fPosition; }\n\n\n\nprivate:\n\n /// Not implemented\n\n AliMpIteratorPainter();\n\n /// Not implemented\n\n AliMpIteratorPainter(const AliMpIteratorPainter&);\n\n /// Not implemented\n\n AliMpIteratorPainter& operator=(const AliMpIteratorPainter&);\n\n \n\n TObjArray* fPads; //!<! pads of the iterator\n\n TVector2 fPosition; //!<! position\n\n TVector2 fDimensions; //!<! dimension\n\n \n\n ClassDef(AliMpIteratorPainter,1) // Painter for a group of pads\n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONmpgraphics/AliMpIteratorPainter.h", "rank": 35, "score": 163414.7603895825 }, { "content": "class AliMpZonePainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpZonePainter();\n\n AliMpZonePainter(AliMpZone *zone);\n\n virtual ~AliMpZonePainter();\n\n \n\n virtual void DumpObject(); //-MENU-\n\n virtual void Draw(Option_t *option);\n\n virtual void Paint(Option_t *option);\n\n // get/set methods\n\n\n\n virtual TVector2 GetPosition() const;\n\n virtual TVector2 GetDimensions() const;\n\n virtual Int_t DistancetoPrimitive(Int_t x, Int_t y);\n\n\n\n private: \n\n /// Not implemented\n\n AliMpZonePainter(const AliMpZonePainter& right);\n\n /// Not implemented\n\n AliMpZonePainter& operator = (const AliMpZonePainter& right);\n\n\n\n AliMpZone *fZone; ///< the zone to draw\n\n\n\n ClassDef(AliMpZonePainter,1) // Zone painter\n\n};\n\n#endif //ALI_MP_ZONE_PAINTER_H\n", "file_path": "MUON/MUONmpgraphics/AliMpZonePainter.h", "rank": 36, "score": 163414.7603895825 }, { "content": "class AliMpSubZonePainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpSubZonePainter();\n\n AliMpSubZonePainter(AliMpSubZone *subZone);\n\n virtual ~AliMpSubZonePainter();\n\n \n\n virtual void DumpObject(); //-MENU-\n\n virtual void Draw(Option_t *option);\n\n virtual void Paint(Option_t *option);\n\n // get/set methods\n\n virtual TVector2 GetPosition() const;\n\n virtual TVector2 GetDimensions() const;\n\n virtual Int_t DistancetoPrimitive(Int_t x, Int_t y);\n\n\n\n private: \n\n /// Not implemented\n\n AliMpSubZonePainter(const AliMpSubZonePainter& right);\n\n /// Not implemented\n\n AliMpSubZonePainter& operator = (const AliMpSubZonePainter& right);\n\n\n\n AliMpSubZone *fSubZone; ///< the subzone to draw\n\n\n\n ClassDef(AliMpSubZonePainter,1) // SubZone painter\n\n};\n\n#endif //ALI_MP_SUB_ZONE_PAINTER_H\n", "file_path": "MUON/MUONmpgraphics/AliMpSubZonePainter.h", "rank": 37, "score": 159259.53618424773 }, { "content": "class AliMpRowSegmentPainter : public AliMpVPainter\n\n{\n\n public:\n\n AliMpRowSegmentPainter();\n\n AliMpRowSegmentPainter(AliMpVRowSegment *rowSegment);\n\n virtual ~AliMpRowSegmentPainter();\n\n \n\n virtual void DumpObject(); //-MENU-\n\n virtual void Draw(Option_t* option);\n\n virtual void Paint(Option_t* /*option*/);\n\n virtual TVector2 GetPosition() const;\n\n virtual TVector2 GetDimensions() const;\n\n\n\n private: \n\n /// Not implemented\n\n AliMpRowSegmentPainter(const AliMpRowSegmentPainter& right);\n\n /// Not implemented\n\n AliMpRowSegmentPainter& operator = (const AliMpRowSegmentPainter& right);\n\n\n\n AliMpVRowSegment *fRowSegment; ///< the row segment to draw\n\n\n\n ClassDef(AliMpRowSegmentPainter,1) // Row Segment painter\n\n};\n\n#endif //ALI_MP_ROW_SEGMENT_PAINTER_H\n", "file_path": "MUON/MUONmpgraphics/AliMpRowSegmentPainter.h", "rank": 38, "score": 159259.53618424773 }, { "content": "class AliMpSlatSegmentation : public AliMpVSegmentation\n\n{\n\n public:\n\n AliMpSlatSegmentation();\n\n AliMpSlatSegmentation(const AliMpSlat* slat, Bool_t own = false);\n\n virtual ~AliMpSlatSegmentation();\n\n\n\n virtual AliMpVPadIterator* CreateIterator(const AliMpArea& area) const;\n\n virtual AliMpVPadIterator* CreateIterator() const;\n\n\n\n virtual Int_t GetNeighbours(const AliMpPad& pad, TObjArray& neighbours,\n\n Bool_t includeSelf=kFALSE,\n\n Bool_t includeVoid=kFALSE) const;\n\n \n\n const char* GetName() const;\n\n \n\n Int_t MaxPadIndexX() const;\n\n Int_t MaxPadIndexY() const;\n\n Int_t NofPads() const;\n\n \n", "file_path": "MUON/MUONmapping/AliMpSlatSegmentation.h", "rank": 39, "score": 152998.86475975215 }, { "content": "class AliMUONAttPainter : public TObject\n\n{\n\npublic:\n\n \n\n /// Internal status bits\n\n enum EBits {\n\n kIsCathode0 = BIT(14),\n\n kIsCathode1 = BIT(15),\n\n kIsBendingPlane = BIT(16),\n\n kIsNonBendingPlane = BIT(17),\n\n kIsFrontView = BIT(18),\n\n kIsBackView = BIT(19),\n\n kIsCathodeAndPlaneMutuallyExclusive = BIT(20),\n\n kIsValid = BIT(21),\n\n kIsSinglePainter = BIT(22),\n\n kIsCathodeAndPlaneDisabled = BIT(23)\n\n };\n\n \n\n AliMUONAttPainter();\n\n virtual ~AliMUONAttPainter();\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainter.h", "rank": 40, "score": 147640.8152421612 }, { "content": "class AliMUONContourPainter : public TObject\n\n{\n\npublic:\n\n AliMUONContourPainter();\n\n virtual ~AliMUONContourPainter();\n\n \n\n using TObject::Paint;\n\n \n\n static void Paint(const AliMUONContour& contour, \n\n Int_t lineColor=1, Int_t lineStyle=1, \n\n Int_t fillColor=-1, Int_t fillStyle=1001);\n\n\n\n ClassDef(AliMUONContourPainter,1) // \n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONgraphics/AliMUONContourPainter.h", "rank": 41, "score": 147639.21773399287 }, { "content": "class AliMpVPainter : public TObject\n\n{\n\n public:\n\n AliMpVPainter();\n\n virtual ~AliMpVPainter();\n\n\n\n void DumpObject() const; // *MENU*\n\n /// Paint the associated object\n\n virtual void Paint(Option_t *option)=0;\n\n virtual TObject* Clone(const char* newname=\"\") const;\n\n virtual TObject* DrawClone(Option_t* option) const; // *MENU*\n\n\n\n //\n\n // get methods\n\n //\n\n /// Return the position inside the graphics pad\n\n TVector2 GetPadPosition() const {return fPadPosition;}\n\n /// Return the dimensions inside the graphics pad\n\n TVector2 GetPadDimensions() const {return fPadDimensions;}\n\n /// Return the color\n", "file_path": "MUON/MUONmpgraphics/AliMpVPainter.h", "rank": 42, "score": 147602.95086792452 }, { "content": "class AliMpPCBPadIterator : public AliMpVPadIterator\n\n{\n\npublic:\n\n AliMpPCBPadIterator(const AliMpSlat* slat, const AliMpArea& area);\n\n virtual ~AliMpPCBPadIterator();\n\n \n\n void First();\n\n void Next();\n\n Bool_t IsDone() const;\n\n AliMpPad CurrentItem() const;\n\n void Invalidate();\n\n \n\n void Print(Option_t* opt=\"\") const;\n\n \n\nprivate:\n\n /// Not implemented\n\n AliMpPCBPadIterator(const AliMpPCBPadIterator& right);\n\n /// Not implemented\n\n AliMpPCBPadIterator& operator = (const AliMpPCBPadIterator& right);\n\n \n", "file_path": "MUON/MUONmapping/AliMpPCBPadIterator.h", "rank": 43, "score": 146449.2575365213 }, { "content": "class AliMpSlatPadIterator : public AliMpVPadIterator\n\n{\n\n public:\n\n AliMpSlatPadIterator(); \n\n // Area position must be relative to bottom-left of slat.\n\n AliMpSlatPadIterator(const AliMpSlat* slat, const AliMpArea& area);\n\n virtual ~AliMpSlatPadIterator();\n\n\n\n void First();\n\n void Next();\n\n Bool_t IsDone() const;\n\n AliMpPad CurrentItem() const;\n\n void Invalidate();\n\n \n\n private:\n\n /// Not implemented\n\n AliMpSlatPadIterator(const AliMpSlatPadIterator&);\n\n /// Not implemented\n\n AliMpSlatPadIterator& operator=(const AliMpSlatPadIterator&);\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlatPadIterator.h", "rank": 44, "score": 146448.18536621096 }, { "content": "class AliMpSlatMotifMap : public TObject\n\n{\n\npublic:\n\n AliMpSlatMotifMap();\n\n virtual ~AliMpSlatMotifMap();\n\n \n\n AliMpVMotif* FindMotif(const TString& id) const;\n\n AliMpMotifType* FindMotifType(const TString& id) const;\n\n \n\n Bool_t AddMotif(AliMpVMotif* motif, Bool_t warn=kTRUE);\n\n Bool_t AddMotifType(AliMpMotifType* motifType, Bool_t warn=kTRUE);\n\n \n\n void Print(Option_t* opt=\"\") const;\n\n \n\n void Reset();\n\n \n\nprivate:\n\n /// Not implemented\n\n AliMpSlatMotifMap(const AliMpSlatMotifMap& rhs);\n\n /// Not implemented\n\n AliMpSlatMotifMap& operator=(const AliMpSlatMotifMap& rhs);\n\n\n\n TMap fMotifs; ///< collection of motifs\n\n TMap fMotifTypes; ///< collection of motifTypes\n\n \n\n ClassDef(AliMpSlatMotifMap,3) // Slat motif map \n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONmapping/AliMpSlatMotifMap.h", "rank": 45, "score": 142574.85489019577 }, { "content": "class AliMpMotifType;\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 46, "score": 139937.76517950627 }, { "content": "class AliMpMotifSpecial;\n\n\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 47, "score": 139937.76517950627 }, { "content": "class AliMpMotifPosition;\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 48, "score": 139937.76517950627 }, { "content": "class AliMpMotifPosition;\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 49, "score": 139936.80835428098 }, { "content": "class AliMpZone;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpZonePainter.h", "rank": 50, "score": 139927.08149978417 }, { "content": "class AliMpRow;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpRowPainter.h", "rank": 51, "score": 139927.08149978417 }, { "content": "class AliMpSector;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpSectorPainter.h", "rank": 52, "score": 139927.08149978417 }, { "content": "class AliMpSectorAreaHPadIterator : public AliMpVPadIterator\n\n{\n\n public:\n\n AliMpSectorAreaHPadIterator(const AliMpSectorSegmentation* segmentation, \n\n const AliMpArea& area);\n\n AliMpSectorAreaHPadIterator(const AliMpSectorAreaHPadIterator& src);\n\n AliMpSectorAreaHPadIterator();\n\n virtual ~AliMpSectorAreaHPadIterator();\n\n\n\n // operators\n\n AliMpSectorAreaHPadIterator& \n\n operator = (const AliMpSectorAreaHPadIterator& right);\n\n\n\n // methods\n\n virtual void First();\n\n virtual void Next();\n\n virtual Bool_t IsDone() const;\n\n virtual AliMpPad CurrentItem() const;\n\n virtual void Invalidate();\n\n\n", "file_path": "MUON/MUONmapping/AliMpSectorAreaHPadIterator.h", "rank": 53, "score": 138527.801952308 }, { "content": "class AliMUONContour;\n\n\n", "file_path": "MUON/MUONgraphics/AliMUONContourHandler.h", "rank": 54, "score": 138248.67072114768 }, { "content": "class AliMUONContour;\n", "file_path": "MUON/MUONgraphics/AliMUONContourMaker.h", "rank": 55, "score": 138248.67072114768 }, { "content": "/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n * See cxx source for full Copyright notice */\n\n\n\n// $Id$ \n\n// $MpId: AliMpPCB.h,v 1.9 2006/05/24 13:58:24 ivana Exp $ \n\n\n\n/// \\ingroup slat\n\n/// \\class AliMpPCB\n\n/// \\brief A PCB for station 3,4 or 5\n\n/// \n\n// Author: Laurent Aphecetche\n\n\n\n#ifndef ALIMPPCB_H\n\n#define ALIMPPCB_H\n\n\n\n#ifndef ALI_MP_VPAD_ITERATOR_H\n\n# include \"AliMpVPadIterator.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_AREA_H\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 56, "score": 136961.1117391558 }, { "content": "/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n * See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n// $MpId: AliMpSlat.h,v 1.8 2006/05/24 13:58:24 ivana Exp $\n\n\n\n/// \\ingroup slat\n\n/// \\class AliMpSlat\n\n/// \\brief A slat (building block of stations 3, 4 and 5)\n\n/// \n\n// Author: Laurent Aphecetche\n\n\n\n#ifndef ALI_MP_SLAT_H\n\n#define ALI_MP_SLAT_H\n\n\n\n#ifndef ALI_MP_PAD_H\n\n# include \"AliMpPad.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_V_SEGMENTATION_H\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 57, "score": 136946.81382128684 }, { "content": "# include \"AliMpVSegmentation.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_PLANE_TYPE_H\n\n# include \"AliMpPlaneType.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_EX_MAP_H\n\n #include \"AliMpExMap.h\"\n\n#endif\n\n\n\n#ifndef ROOT_TObject\n\n #include <TObject.h>\n\n#endif\n\n\n\n#ifndef ROOT_TString\n\n# include \"TString.h\"\n\n#endif\n\n\n\n#ifndef ROOT_TObjArray\n\n# include \"TObjArray.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 58, "score": 136939.16758486282 }, { "content": " TObjArray fPCBs; ///< array of AliMpPCB*\n\n Double_t fPositionX; ///< x Position of the slat center.\n\n Double_t fPositionY; ///< y Position of the slat center.\n\n Int_t fNofPads; ///< number of pads in this slat\n\n \n\n ClassDef(AliMpSlat,3) // A slat for stations 3,4,5\n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 59, "score": 136936.9982032011 }, { "content": " Double_t DY() const;\n\n\n\n /// Find the PCB containing the pad at location (ix,any iy).\n\n AliMpPCB* FindPCB(Int_t ix) const;\n\n\n\n /// Find the index of the PCB containing the pad at location ix.\n\n Int_t FindPCBIndex(Int_t ix) const;\n\n\n\n /// Find the index of the PCB containing a given manu\n\n Int_t FindPCBIndexByMotifPositionID(Int_t manuId) const;\n\n \n\n /// Find the PCB containing location (x,y).\n\n AliMpPCB* FindPCB(Double_t x, Double_t y) const;\n\n\n\n /// Find the index of the PCB containing the pad at location (x,y).\n\n Int_t FindPCBIndex(Double_t x, Double_t y) const;\n\n\n\n /// Returns the i-th PCB of this slat.\n\n AliMpPCB* GetPCB(Int_t i) const;\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 60, "score": 136935.82903399362 }, { "content": " TString fId; ///< PCB name\n\n Double_t fPadSizeX; ///< x-size of this PCB's pads (cm)\n\n Double_t fPadSizeY; ///< y-size of this PCB's pads (cm)\n\n Double_t fEnveloppeSizeX; ///< max x-size of this PCB (cm)\n\n Double_t fEnveloppeSizeY; ///< max y-size of this PCB (cm)\n\n Double_t fXoffset; ///< x-offset = x of first pad of this PCB (cm)\n\n Double_t fActiveXmin; ///< min x of an actual pad in this PCB (cm)\n\n Double_t fActiveXmax; ///< max x of an actual pad in this PCB (cm)\n\n Int_t fIxmin; ///< min pad index in x\n\n Int_t fIxmax; ///< max pad index in x\n\n Int_t fIymin; ///< min pad index in y\n\n Int_t fIymax; ///< max pad index in y\n\n TObjArray fMotifPositions; ///< array of motifs\n\n Int_t fNofPads; ///< number of pads in this PCB\n\n AliMpSlatMotifMap* fMotifMap; ///< to keep track of things to avoid duplications of motif and motiftypes, and get proper deletion\n\n \n\n ClassDef(AliMpPCB,3) // A PCB for Stations 3,4,5\n\n};\n\n\n\n#endif \n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 61, "score": 136933.68959882858 }, { "content": " Int_t GetNofPadsX() const;\n\n Int_t GetNofPadsY() const;\n\n\n\n Int_t Ixmin() const;\n\n Int_t Ixmax() const;\n\n \n\n Int_t Iymin() const;\n\n Int_t Iymax() const;\n\n \n\n const char* GetID() const;\n\n \n\n /// Return the number of pads in this PCB \n\n Int_t NofPads() const { return fNofPads; }\n\n \n\n /// Return the motif map\n\n AliMpSlatMotifMap* MotifMap() const { return fMotifMap; }\n\n \n\n void Save() const;\n\n \n\n private:\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 62, "score": 136932.09352469502 }, { "content": " AliMp::PlaneType PlaneType() const { return fPlaneType; }\n\n \n\n /// Return the number of pads in this slat\n\n Int_t NofPads() const { return fNofPads; }\n\n \n\n private:\n\n /// Not implemented\n\n AliMpSlat();\n\n /// Not implemented\n\n AliMpSlat(const AliMpSlat& rhs);\n\n /// Not implemented\n\n AliMpSlat& operator=(const AliMpSlat& rhs);\n\n\n\n TString fId; ///< The name of this slat, e.g. 112233N\n\n AliMp::PlaneType fPlaneType; ///< Whether it's bending or non-bending plane\n\n Double_t fDX; ///< Half-size in X (cm)\n\n Double_t fDY; ///< Half-size in Y (cm)\n\n Int_t fNofPadsX; ///< Actual number of pads in x direction\n\n Int_t fMaxNofPadsY; ///< Maximum number of pads in y direction\n\n mutable AliMpExMap fManuMap; ///< map of int to AliMpMotifPosition*\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 63, "score": 136930.91858821752 }, { "content": "# include \"AliMpArea.h\"\n\n#endif\n\n\n\n\n\n#ifndef ROOT_TObject\n\n# include \"TObject.h\"\n\n#endif\n\n\n\n#ifndef ROOT_TString\n\n# include \"TString.h\"\n\n#endif\n\n\n\n#ifndef ROOT_TArraI\n\n# include \"TArrayI.h\"\n\n#endif\n\n\n\n#ifndef ROOT_TObjArray\n\n# include \"TObjArray.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 64, "score": 136929.33605223196 }, { "content": "\n\n /** Duplicate this PCB. The copy has the manuids of its motifs changed \n\n according to the manuid vector, and its x-offset according to ix \n\n and x.\n\n */ \n\n AliMpPCB* Clone(const TArrayI& manuids,\n\n Int_t ixOffset, Double_t xOffset) const;\n\n\n\n void Copy(TObject& o) const;\n\n\n\n /** Add a motif to this PCB. (ix,iy) are the coordinates of one corner \n\n of the motif, in pad-units. Which corner depends on the sign(s) of (ix,iy):\n\n (ix>0,iy>0) : bottom-left corner\n\n (ix<0,iy>0) : bottom-right corner\n\n (ix<0,iy<0) : top-right corner\n\n (ix>0,iy<0) : top-left corner.\n\n */\n\n void Add(AliMpMotifType* motifType, Int_t ix, Int_t iy);\n\n\n\n AliMpArea Area() const;\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 65, "score": 136929.07752813827 }, { "content": " /// Returns the MotifPosition containing location (x,y).\n\n AliMpMotifPosition* FindMotifPosition(Double_t x, Double_t y) const;\n\n\n\n /// Returns the MotifPosition which id is manuid.\n\n AliMpMotifPosition* FindMotifPosition(Int_t manuid) const;\n\n\n\n /// Returns the MotifPosition containing the pad located at (ix,iy).\n\n AliMpMotifPosition* FindMotifPosition(Int_t ix, Int_t iy) const;\n\n\n\n /// Return the ids of the electronic cards (either manu or local board).\n\n void GetAllMotifPositionsIDs(TArrayI& ecn) const;\n\n \n\n /** Returns the max. number of pads in the x-direction contained in this slat.\n\n This is a max only as for e.g. non-bending slats, the y-dimension depends\n\n on the x-position.\n\n */\n\n Int_t GetMaxNofPadsY() const;\n\n \n\n /** Returns the max index useable in x-direction. \n\n Note that this can be different from GetNofPadsX()-1 for rounded slats.\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 66, "score": 136927.34160806995 }, { "content": " Double_t Ymin() const;\n\n Double_t Ymax() const;\n\n\n\n Double_t PadSizeX() const;\n\n Double_t PadSizeY() const;\n\n\n\n /** Returns the i-th motifPosition of this PCB.\n\n i : [0..GetSize()-1]\n\n */\n\n AliMpMotifPosition* GetMotifPosition(Int_t i) const;\n\n\n\n /// Returns the motifPosition which contains the pad at (ix,iy).\n\n AliMpMotifPosition* FindMotifPosition(Int_t ix, Int_t iy) const;\n\n\n\n /// Returns the motifPosition which contains the pad at (x,y).\n\n AliMpMotifPosition* FindMotifPosition(Double_t x, Double_t y) const;\n\n\n\n /// The number of motifs, aka manus.\n\n Int_t GetSize() const;\n\n\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 67, "score": 136926.85235078214 }, { "content": " */\n\n Int_t GetMaxPadIndexX() const;\n\n \n\n /// Return the number of electronic cards (either manu or local board).\n\n Int_t GetNofElectronicCards() const;\n\n \n\n /// Returns the number of pads in the x-direction contained in this slat.\n\n Int_t GetNofPadsX() const;\n\n \n\n /// Returns the number of PCBs of this slat.\n\n Int_t GetSize() const;\n\n \n\n void Print(Option_t* option=\"\") const;\n\n\n\n /** This is normally only used by triggerSlats, as for ST345 slats,\n\n the position is DX(),DY() simply.\n\n */\n\n void ForcePosition(Double_t x, Double_t y);\n\n \n\n /// Return the plane type\n", "file_path": "MUON/MUONmapping/AliMpSlat.h", "rank": 68, "score": 136920.59067273815 }, { "content": " \n\n void Print(Option_t* option = \"\") const;\n\n\n\n Bool_t HasMotifPositionID(Int_t manuId) const;\n\n \n\n Double_t ActiveDX() const;\n\n Double_t ActiveDY() const;\n\n\n\n Double_t DX() const;\n\n Double_t DY() const;\n\n\n\n Double_t X() const;\n\n Double_t Y() const;\n\n\n\n Double_t Xmin() const;\n\n Double_t Xmax() const;\n\n \n\n Double_t ActiveXmin() const;\n\n Double_t ActiveXmax() const;\n\n\n", "file_path": "MUON/MUONmapping/AliMpPCB.h", "rank": 69, "score": 136912.32432057956 }, { "content": "class AliMUONAttPainter;\n", "file_path": "MUON/MUONgraphics/AliMUONPainterHelper.h", "rank": 70, "score": 136776.49714664457 }, { "content": "class AliMUONContour;\n", "file_path": "MUON/MUONgraphics/AliMUONContourMakerTest.h", "rank": 71, "score": 136765.92159605812 }, { "content": "class AliMUONContour;\n\n\n", "file_path": "MUON/MUONgraphics/AliMUONManuContourMaker.h", "rank": 72, "score": 136765.92159605812 }, { "content": "class AliMpArea;\n", "file_path": "MUON/MUONmapping/AliMpPCBPadIterator.h", "rank": 73, "score": 136750.57431952187 }, { "content": "class AliMpSlatMotifMap;\n", "file_path": "MUON/MUONmapping/AliMpSegmentation.h", "rank": 74, "score": 136749.6444467487 }, { "content": "class AliMpMotifPosition;\n", "file_path": "MUON/MUONmapping/AliMpSlatSegmentation.h", "rank": 75, "score": 136749.6444467487 }, { "content": "class AliMpArea;\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlatPadIterator.h", "rank": 76, "score": 136749.6444467487 }, { "content": "class AliMpMotifType;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpMotifPainter.h", "rank": 77, "score": 136740.1915843809 }, { "content": "class AliMpVPainter;\n", "file_path": "MUON/MUONmpgraphics/AliMpDEVisu.h", "rank": 78, "score": 136740.1915843809 }, { "content": "class AliMpMotifPosition;\n", "file_path": "MUON/MUONmpgraphics/AliMpMotifPainter.h", "rank": 79, "score": 136740.1915843809 }, { "content": "class AliMUONAttPainterSelectorFrame : public TGHorizontalFrame\n\n{\n\npublic:\n\n AliMUONAttPainterSelectorFrame(TGWindow* p=0x0, UInt_t w=1, UInt_t h=1);\n\n virtual ~AliMUONAttPainterSelectorFrame();\n\n \n\n void Update(const AliMUONAttPainter& att);\n\n \n\n void Clicked(const AliMUONAttPainter* newValues); // *SIGNAL*\n\n \n\n void CathodeClicked(Int_t buttonId);\n\n \n\n void PlaneClicked(Int_t buttonId);\n\n \n\n void ViewClicked(Int_t buttonId);\n\n \n\nprivate:\n\n /// Not implemented\n\n AliMUONAttPainterSelectorFrame(const AliMUONAttPainterSelectorFrame& rhs);\n\n /// Not implemented\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainterSelectorFrame.h", "rank": 80, "score": 135652.66005706473 }, { "content": "class AliMUONAttPainter;\n", "file_path": "MUON/MUONgraphics/AliMUONPainterMasterFrame.h", "rank": 81, "score": 133736.5641694888 }, { "content": "class AliMpSlatMotifMap;\n", "file_path": "MUON/MUONmapping/AliMpSt345Reader.h", "rank": 82, "score": 133710.2203582974 }, { "content": "class AliMpSlatMotifMap;\n", "file_path": "MUON/MUONmapping/AliMpTriggerReader.h", "rank": 83, "score": 133710.2203582974 }, { "content": "class AliMpMotifType;\n", "file_path": "MUON/MUONmapping/AliMpSlatMotifMap.h", "rank": 84, "score": 133710.2203582974 }, { "content": "class AliMpVMotif;\n", "file_path": "MUON/MUONmapping/AliMpSlatMotifMap.h", "rank": 85, "score": 133710.2203582974 }, { "content": "class AliMpSubZone;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpSubZonePainter.h", "rank": 86, "score": 133701.0264749923 }, { "content": "class AliMpVPadIterator;\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpIteratorPainter.h", "rank": 87, "score": 133701.0264749923 }, { "content": "#ifndef ALIMUONATTPAINTER_H\n\n#define ALIMUONATTPAINTER_H\n\n\n\n/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n* See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n\n\n/// \\ingroup graphics\n\n/// \\class AliMUONAttPainter\n\n/// \\brief Basic attributes shared by all painters\n\n/// \n\n// Author Laurent Aphecetche, Subatech\n\n\n\n#ifndef ROOT_TObject\n\n# include \"TObject.h\"\n\n#endif\n\n#ifndef ROOT_TString\n\n# include \"TString.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainter.h", "rank": 88, "score": 132627.50440838 }, { "content": "#ifndef ALIMUONCONTOURPAINTER_H\n\n#define ALIMUONCONTOURPAINTER_H\n\n\n\n/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n* See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n\n\n/// \\ingroup graphics\n\n/// \\class AliMUONContourPainter\n\n/// \\brief Class to draw AliMUONContour objects\n\n/// \n\n// Author Laurent Aphecetche, Subatech\n\n\n\n#ifndef ROOT_TObject\n\n# include \"TObject.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONgraphics/AliMUONContourPainter.h", "rank": 89, "score": 132616.85633101067 }, { "content": "\n\n void SetCathodeAndPlaneMutuallyExclusive(Bool_t value);\n\n\n\n void SetValid(Bool_t value);\n\n\n\n void SetCathodeAndPlaneDisabled(Bool_t value);\n\n\n\nprivate:\n\n void SetName();\n\n\n\nprivate:\n\n TString fName; ///< name of the attributes\n\n\n\n ClassDef(AliMUONAttPainter,2) // Basic attributes of painters\n\n};\n\n\n\n#endif\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainter.h", "rank": 90, "score": 132603.69774529492 }, { "content": " /// Whether the painter is to be represented from front (as seen from IP)\n\n Bool_t IsFrontView() const { return TestBit(kIsFrontView); }\n\n \n\n /// Whether the painter is to be represented from back (as seen from IP)\n\n Bool_t IsBackView() const { return TestBit(kIsBackView); }\n\n \n\n\n\n /// Whether we represent attributes of a single painter (if false, means it's a painter group)\n\n Bool_t IsSinglePainter() const { return TestBit(kIsSinglePainter); }\n\n \n\n\n\n void Print(Option_t* opt=\"\") const;\n\n \n\n void SetCathode(Bool_t cath0, Bool_t cath1);\n\n\n\n void SetPlane(Bool_t bending, Bool_t nonBending);\n\n\n\n void SetSingle(Bool_t value);\n\n\n\n void SetViewPoint(Bool_t front, Bool_t back);\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainter.h", "rank": 91, "score": 132598.00768188614 }, { "content": "#ifndef ROOT_TString\n\n#include \"TString.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_V_SEGMENTATION_H\n\n#include \"AliMpVSegmentation.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_PAD_H\n\n#include \"AliMpPad.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlatSegmentation.h", "rank": 92, "score": 132593.2231301429 }, { "content": "/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n * See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n// $MpId: AliMpSlatSegmentation.h,v 1.12 2006/05/24 13:58:24 ivana Exp $\n\n\n\n/// \\ingroup slat\n\n/// \\class AliMpSlatSegmentation\n\n/// \\brief Implementation of AliMpVSegmentation for St345 slats.\n\n/// \n\n/// Note that integer indices start at (0,0) on the bottom-left of the slat,\n\n/// while floating point positions are relative to the center of the slat\n\n/// (where the slat is to be understood as N PCBs of fixed size = 40cm\n\n/// even if not all pads of a given PCBs are actually physically there).\n\n///\n\n/// \\author Laurent Aphecetche\n\n\n\n#ifndef ALI_MP_SLAT_SEGMENTATION_H\n\n#define ALI_MP_SLAT_SEGMENTATION_H\n\n\n", "file_path": "MUON/MUONmapping/AliMpSlatSegmentation.h", "rank": 93, "score": 132592.1694276391 }, { "content": "#ifndef ALIMPITERATORPAINTER_H\n\n#define ALIMPITERATORPAINTER_H\n\n\n\n/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n* See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n\n\n/// \\ingroup mpgraphics\n\n/// \\class AliMpIteratorPainter\n\n/// \\brief Painter for a group of pads defined by an iterator\n\n/// \n\n// Author Laurent Aphecetche\n\n\n\n#ifndef ALI_MP_V_PAINTER_H\n\n# include \"AliMpVPainter.h\"\n\n#endif\n\n\n\n#ifndef ROOT_TVector2\n\n# include \"TVector2.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpIteratorPainter.h", "rank": 94, "score": 132589.6694322039 }, { "content": "/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n * See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n// $MpId: AliMpVPainter.h,v 1.8 2006/05/24 13:58:13 ivana Exp $\n\n\n\n/// \\ingroup mpgraphics\n\n/// \\class AliMpVPainter\n\n/// \\brief Abstract base class for drawing objects into canvas\n\n///\n\n/// \\author David Guez, IPN Orsay\n\n\n\n#ifndef ALI_MP_V_PAINTER_H\n\n#define ALI_MP_V_PAINTER_H\n\n\n\n#include <TObject.h>\n\n#include <TVector2.h>\n\n\n", "file_path": "MUON/MUONmpgraphics/AliMpVPainter.h", "rank": 95, "score": 132589.37607637042 }, { "content": " \n\n /// Return our name\n\n virtual const char* GetName() const { return fName.Data(); }\n\n \n\n TString CathodeName() const;\n\n \n\n TString ViewPointName() const;\n\n\n\n TString PlaneName() const;\n\n \n\n /// Whether cathode & plane are disabled\n\n Bool_t IsCathodeAndPlaneDisabled() const { return TestBit(kIsCathodeAndPlaneDisabled); }\n\n \n\n /// Whether we are representing bending plane\n\n Bool_t IsBendingPlane() const { return TestBit(kIsBendingPlane); }\n\n \n\n /// Whether we are representing cathode 0\n\n Bool_t IsCathode0() const { return TestBit(kIsCathode0); }\n\n \n\n /// Whether we are representing cathode 1\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainter.h", "rank": 96, "score": 132588.2715651534 }, { "content": " Bool_t IsCathode1() const { return TestBit(kIsCathode1); }\n\n \n\n /// Whether we can select both cathode and plane\n\n Bool_t IsCathodeAndPlaneMutuallyExclusive() const { return TestBit(kIsCathodeAndPlaneMutuallyExclusive); }\n\n \n\n /// Whether we are defined by cathode\n\n Bool_t IsCathodeDefined() const { return IsCathode0() || IsCathode1(); }\n\n \n\n /// Whether we are representing non bending plane\n\n Bool_t IsNonBendingPlane() const { return TestBit(kIsNonBendingPlane); }\n\n \n\n /// Whether we are defined by plane\n\n Bool_t IsPlaneDefined() const { return IsBendingPlane() || IsNonBendingPlane(); }\n\n \n\n /// Whether we are valid\n\n Bool_t IsValid() const { return TestBit(kIsValid); }\n\n \n\n void Invert();\n\n \n\n\n", "file_path": "MUON/MUONgraphics/AliMUONAttPainter.h", "rank": 97, "score": 132588.2715651534 }, { "content": "#ifndef ALIMUONVPAINTER_H\n\n#define ALIMUONVPAINTER_H\n\n\n\n/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\n* See cxx source for full Copyright notice */\n\n\n\n// $Id$\n\n\n\n/// \\ingroup graphics\n\n/// \\class AliMUONVPainter\n\n/// \\brief Base class for a graphical object representing some part of the\n\n/// MUON tracking system\n\n/// \n\n// Author Laurent Aphecetche, Subatech\n\n\n\n#ifndef ALIMUONATTPAINTER_H\n\n# include \"AliMUONAttPainter.h\"\n\n#endif\n\n#ifndef ROOT_TQObject\n\n# include <TQObject.h>\n", "file_path": "MUON/MUONgraphics/AliMUONVPainter.h", "rank": 98, "score": 45.97334943628283 }, { "content": "#endif\n\n\n\n#ifndef ROOT_TVector2\n\n# include \"TVector2.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_PLANE_TYPE_H\n\n# include \"AliMpPlaneType.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_CATHOD_TYPE_H\n\n# include \"AliMpCathodType.h\"\n\n#endif\n\n\n\n#ifndef ALIMUONVPAINTER_H\n\n# include \"AliMUONVPainter.h\"\n\n#endif\n\n\n\n#ifndef ALI_MP_PAD_H\n\n# include \"AliMpPad.h\"\n\n#endif\n\n\n", "file_path": "MUON/MUONgraphics/AliMUONPainterHelper.h", "rank": 99, "score": 42.619541971163294 } ]